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
Should this be made `verbose` as it is being retried properly and may occur many times during the running of an application and bloat a log file?
public void onError(Throwable throwable) { Objects.requireNonNull(throwable, "'throwable' is required."); if (isRetryPending.get() && retryPolicy.calculateRetryDelay(throwable, retryAttempts.get()) != null) { logger.warning("Retry is already pending. Ignoring transient error.", throwable); return; } final int attemptsMade = retryAttempts.incrementAndGet(); final int attempts; final Duration retryInterval; if (((throwable instanceof AmqpException) && ((AmqpException) throwable).isTransient()) || (throwable instanceof IllegalStateException) || (throwable instanceof RejectedExecutionException)) { attempts = Math.min(attemptsMade, retryPolicy.getMaxRetries()); final Throwable throwableToUse = throwable instanceof AmqpException ? throwable : new AmqpException(true, "Non-AmqpException occurred upstream.", throwable, errorContext); retryInterval = retryPolicy.calculateRetryDelay(throwableToUse, attempts); } else { attempts = attemptsMade; retryInterval = retryPolicy.calculateRetryDelay(throwable, attempts); } if (retryInterval != null) { if (isRetryPending.getAndSet(true)) { retryAttempts.decrementAndGet(); return; } logger.info("Retry retrySubscription = Mono.delay(retryInterval).subscribe(i -> { if (isDisposed()) { logger.info("Retry } else { logger.info("Retry requestUpstream(); isRetryPending.set(false); } }); } else { logger.warning("Retry lastError = throwable; isDisposed.set(true); dispose(); synchronized (lock) { final ConcurrentLinkedDeque<ChannelSubscriber<T>> currentSubscribers = subscribers; subscribers = new ConcurrentLinkedDeque<>(); logger.info("Error in AMQP channel processor. Notifying {} subscribers.", currentSubscribers.size()); currentSubscribers.forEach(subscriber -> subscriber.onError(throwable)); } } }
logger.info("Retry
public void onError(Throwable throwable) { Objects.requireNonNull(throwable, "'throwable' is required."); if (isRetryPending.get() && retryPolicy.calculateRetryDelay(throwable, retryAttempts.get()) != null) { logger.warning("Retry is already pending. Ignoring transient error.", throwable); return; } final int attemptsMade = retryAttempts.incrementAndGet(); final int attempts; final Duration retryInterval; if (((throwable instanceof AmqpException) && ((AmqpException) throwable).isTransient()) || (throwable instanceof IllegalStateException) || (throwable instanceof RejectedExecutionException)) { attempts = Math.min(attemptsMade, retryPolicy.getMaxRetries()); final Throwable throwableToUse = throwable instanceof AmqpException ? throwable : new AmqpException(true, "Non-AmqpException occurred upstream.", throwable, errorContext); retryInterval = retryPolicy.calculateRetryDelay(throwableToUse, attempts); } else { attempts = attemptsMade; retryInterval = retryPolicy.calculateRetryDelay(throwable, attempts); } if (retryInterval != null) { if (isRetryPending.getAndSet(true)) { retryAttempts.decrementAndGet(); return; } logger.atInfo() .addKeyValue(RETRY_NUMBER_KEY, attempts) .addKeyValue(INTERVAL_KEY, retryInterval.toMillis()) .log("Transient error occurred. Retrying.", throwable); retrySubscription = Mono.delay(retryInterval).subscribe(i -> { if (isDisposed()) { logger.atInfo() .addKeyValue(RETRY_NUMBER_KEY, attempts) .log("Not requesting from upstream. Processor is disposed."); } else { logger.atInfo() .addKeyValue(RETRY_NUMBER_KEY, attempts) .log("Requesting from upstream."); requestUpstream(); isRetryPending.set(false); } }); } else { logger.atWarning() .addKeyValue(RETRY_NUMBER_KEY, attempts) .log("Retry attempts exhausted or exception was not retriable.", throwable); lastError = throwable; isDisposed.set(true); dispose(); synchronized (lock) { final ConcurrentLinkedDeque<ChannelSubscriber<T>> currentSubscribers = subscribers; subscribers = new ConcurrentLinkedDeque<>(); logger.info("Error in AMQP channel processor. Notifying {} subscribers.", currentSubscribers.size()); currentSubscribers.forEach(subscriber -> subscriber.onError(throwable)); } } }
class AmqpChannelProcessor<T> extends Mono<T> implements Processor<T, T>, CoreSubscriber<T>, Disposable { @SuppressWarnings("rawtypes") private static final AtomicReferenceFieldUpdater<AmqpChannelProcessor, Subscription> UPSTREAM = AtomicReferenceFieldUpdater.newUpdater(AmqpChannelProcessor.class, Subscription.class, "upstream"); private final ClientLogger logger; private final AtomicBoolean isDisposed = new AtomicBoolean(); private final AtomicBoolean isRequested = new AtomicBoolean(); private final AtomicBoolean isRetryPending = new AtomicBoolean(); private final AtomicInteger retryAttempts = new AtomicInteger(); private final Object lock = new Object(); private final AmqpRetryPolicy retryPolicy; private final Function<T, Flux<AmqpEndpointState>> endpointStatesFunction; private final AmqpErrorContext errorContext; private volatile Subscription upstream; private volatile ConcurrentLinkedDeque<ChannelSubscriber<T>> subscribers = new ConcurrentLinkedDeque<>(); private volatile Throwable lastError; private volatile T currentChannel; private volatile Disposable connectionSubscription; private volatile Disposable retrySubscription; public AmqpChannelProcessor(String fullyQualifiedNamespace, String entityPath, Function<T, Flux<AmqpEndpointState>> endpointStatesFunction, AmqpRetryPolicy retryPolicy, ClientLogger logger) { this.endpointStatesFunction = Objects.requireNonNull(endpointStatesFunction, "'endpointStates' cannot be null."); this.retryPolicy = Objects.requireNonNull(retryPolicy, "'retryPolicy' cannot be null."); /*Map<String, Object> loggingContext = new HashMap<>(); loggingContext.put(FULLY_QUALIFIED_NAMESPACE_KEY, Objects.requireNonNull(fullyQualifiedNamespace, "'fullyQualifiedNamespace' cannot be null.")); loggingContext.put(ENTITY_PATH_KEY, Objects.requireNonNull(entityPath, "'entityPath' cannot be null."));*/ this.logger = Objects.requireNonNull(logger, "'retryPolicy' cannot be null."); this.errorContext = new AmqpErrorContext(fullyQualifiedNamespace); } @Override public void onSubscribe(Subscription subscription) { if (Operators.setOnce(UPSTREAM, this, subscription)) { isRequested.set(true); subscription.request(1); } else { logger.warning("Processors can only be subscribed to once."); } } @Override public void onNext(T amqpChannel) { logger.info("Setting next AMQP channel."); Objects.requireNonNull(amqpChannel, "'amqpChannel' cannot be null."); final T oldChannel; final Disposable oldSubscription; synchronized (lock) { oldChannel = currentChannel; oldSubscription = connectionSubscription; currentChannel = amqpChannel; final ConcurrentLinkedDeque<ChannelSubscriber<T>> currentSubscribers = subscribers; logger.info("Next AMQP channel received, updating {} current subscribers", subscribers.size()); currentSubscribers.forEach(subscription -> subscription.onNext(amqpChannel)); connectionSubscription = endpointStatesFunction.apply(amqpChannel).subscribe( state -> { if (state == AmqpEndpointState.ACTIVE) { retryAttempts.set(0); logger.info("Channel is now active."); } }, error -> { setAndClearChannel(); onError(error); }, () -> { if (isDisposed()) { logger.info("Channel is disposed."); } else { logger.info("Channel is closed. Requesting upstream."); setAndClearChannel(); requestUpstream(); } }); } close(oldChannel); if (oldSubscription != null) { oldSubscription.dispose(); } isRequested.set(false); } /** * When downstream or upstream encounters an error, calculates whether to request another item upstream. * * @param throwable Exception to analyse. */ @Override @Override public void onComplete() { logger.info("Upstream connection publisher was completed. Terminating processor."); isDisposed.set(true); synchronized (lock) { final ConcurrentLinkedDeque<ChannelSubscriber<T>> currentSubscribers = subscribers; subscribers = new ConcurrentLinkedDeque<>(); logger.info("AMQP channel processor completed. Notifying {} subscribers.", currentSubscribers.size()); currentSubscribers.forEach(subscriber -> subscriber.onComplete()); } } @Override public void subscribe(CoreSubscriber<? super T> actual) { if (isDisposed()) { if (lastError != null) { actual.onSubscribe(Operators.emptySubscription()); actual.onError(lastError); } else { Operators.error(actual, logger.logExceptionAsError(new IllegalStateException("Cannot subscribe. Processor is already terminated."))); } return; } final ChannelSubscriber<T> subscriber = new ChannelSubscriber<T>(actual, this); actual.onSubscribe(subscriber); synchronized (lock) { if (currentChannel != null) { subscriber.complete(currentChannel); return; } } subscribers.add(subscriber); logger.atVerbose().addKeyValue("subscribers", subscribers.size()).log("Added a subscriber."); if (!isRetryPending.get()) { requestUpstream(); } } @Override public void dispose() { if (isDisposed.getAndSet(true)) { return; } if (retrySubscription != null && !retrySubscription.isDisposed()) { retrySubscription.dispose(); } onComplete(); synchronized (lock) { setAndClearChannel(); } } @Override public boolean isDisposed() { return isDisposed.get(); } private void requestUpstream() { if (currentChannel != null) { logger.verbose("Connection exists, not requesting another."); return; } else if (isDisposed()) { logger.verbose("Is already disposed."); return; } final Subscription subscription = UPSTREAM.get(this); if (subscription == null) { logger.warning("There is no upstream subscription."); return; } if (!isRequested.getAndSet(true)) { logger.info("Connection not requested, yet. Requesting one."); subscription.request(1); } } private void setAndClearChannel() { T oldChannel; synchronized (lock) { oldChannel = currentChannel; currentChannel = null; } close(oldChannel); } /** * Checks the current state of the channel for this channel and returns true if the channel is null or if this * processor is disposed. * * @return true if the current channel in the processor is null or if the processor is disposed */ public boolean isChannelClosed() { synchronized (lock) { return currentChannel == null || isDisposed(); } } private void close(T channel) { if (channel instanceof AsyncCloseable) { ((AsyncCloseable) channel).closeAsync().subscribe(); } else if (channel instanceof AutoCloseable) { try { ((AutoCloseable) channel).close(); } catch (Exception error) { logger.warning("Error occurred closing AutoCloseable channel.", error); } } else if (channel instanceof Disposable) { try { ((Disposable) channel).dispose(); } catch (Exception error) { logger.warning("Error occurred closing Disposable channel.", error); } } } /** * Represents the decorator-subscriber wrapping a downstream subscriber to AmqpChannelProcessor. * These are the subscribers waiting to receive a channel that is yet to be available in the AmqpChannelProcessor. * The AmqpChannelProcessor tracks a list of such waiting subscribers; once the processor receives * a result (channel, error or disposal) from it's upstream, each decorated-subscriber will be notified, * which removes itself from the tracking list, then propagates the notification to the wrapped subscriber. */ private static final class ChannelSubscriber<T> extends Operators.MonoSubscriber<T, T> { private final AmqpChannelProcessor<T> processor; private ChannelSubscriber(CoreSubscriber<? super T> actual, AmqpChannelProcessor<T> processor) { super(actual); this.processor = processor; } @Override public void cancel() { processor.subscribers.remove(this); super.cancel(); } @Override public void onComplete() { if (!isCancelled()) { processor.subscribers.remove(this); actual.onComplete(); } } @Override public void onNext(T channel) { if (!isCancelled()) { processor.subscribers.remove(this); super.complete(channel); } } @Override public void onError(Throwable throwable) { if (!isCancelled()) { processor.subscribers.remove(this); actual.onError(throwable); } else { Operators.onErrorDropped(throwable, currentContext()); } } } }
class AmqpChannelProcessor<T> extends Mono<T> implements Processor<T, T>, CoreSubscriber<T>, Disposable { @SuppressWarnings("rawtypes") private static final AtomicReferenceFieldUpdater<AmqpChannelProcessor, Subscription> UPSTREAM = AtomicReferenceFieldUpdater.newUpdater(AmqpChannelProcessor.class, Subscription.class, "upstream"); private static final String RETRY_NUMBER_KEY = "retry"; private final ClientLogger logger; private final AtomicBoolean isDisposed = new AtomicBoolean(); private final AtomicBoolean isRequested = new AtomicBoolean(); private final AtomicBoolean isRetryPending = new AtomicBoolean(); private final AtomicInteger retryAttempts = new AtomicInteger(); private final Object lock = new Object(); private final AmqpRetryPolicy retryPolicy; private final Function<T, Flux<AmqpEndpointState>> endpointStatesFunction; private final AmqpErrorContext errorContext; private volatile Subscription upstream; private volatile ConcurrentLinkedDeque<ChannelSubscriber<T>> subscribers = new ConcurrentLinkedDeque<>(); private volatile Throwable lastError; private volatile T currentChannel; private volatile Disposable connectionSubscription; private volatile Disposable retrySubscription; /** * @deprecated Use constructor overload that does not take {@link ClientLogger} */ @Deprecated public AmqpChannelProcessor(String fullyQualifiedNamespace, String entityPath, Function<T, Flux<AmqpEndpointState>> endpointStatesFunction, AmqpRetryPolicy retryPolicy, ClientLogger logger) { this.endpointStatesFunction = Objects.requireNonNull(endpointStatesFunction, "'endpointStates' cannot be null."); this.retryPolicy = Objects.requireNonNull(retryPolicy, "'retryPolicy' cannot be null."); this.logger = Objects.requireNonNull(logger, "'logger' cannot be null."); this.errorContext = new AmqpErrorContext(fullyQualifiedNamespace); } public AmqpChannelProcessor(String fullyQualifiedNamespace, Function<T, Flux<AmqpEndpointState>> endpointStatesFunction, AmqpRetryPolicy retryPolicy, Map<String, Object> loggingContext) { this.endpointStatesFunction = Objects.requireNonNull(endpointStatesFunction, "'endpointStates' cannot be null."); this.retryPolicy = Objects.requireNonNull(retryPolicy, "'retryPolicy' cannot be null."); this.logger = new ClientLogger(getClass(), Objects.requireNonNull(loggingContext, "'loggingContext' cannot be null.")); this.errorContext = new AmqpErrorContext(fullyQualifiedNamespace); } @Override public void onSubscribe(Subscription subscription) { if (Operators.setOnce(UPSTREAM, this, subscription)) { isRequested.set(true); subscription.request(1); } else { logger.warning("Processors can only be subscribed to once."); } } @Override public void onNext(T amqpChannel) { logger.info("Setting next AMQP channel."); Objects.requireNonNull(amqpChannel, "'amqpChannel' cannot be null."); final T oldChannel; final Disposable oldSubscription; synchronized (lock) { oldChannel = currentChannel; oldSubscription = connectionSubscription; currentChannel = amqpChannel; final ConcurrentLinkedDeque<ChannelSubscriber<T>> currentSubscribers = subscribers; logger.info("Next AMQP channel received, updating {} current subscribers", subscribers.size()); currentSubscribers.forEach(subscription -> subscription.onNext(amqpChannel)); connectionSubscription = endpointStatesFunction.apply(amqpChannel).subscribe( state -> { if (state == AmqpEndpointState.ACTIVE) { retryAttempts.set(0); logger.info("Channel is now active."); } }, error -> { setAndClearChannel(); onError(error); }, () -> { if (isDisposed()) { logger.info("Channel is disposed."); } else { logger.info("Channel is closed. Requesting upstream."); setAndClearChannel(); requestUpstream(); } }); } close(oldChannel); if (oldSubscription != null) { oldSubscription.dispose(); } isRequested.set(false); } /** * When downstream or upstream encounters an error, calculates whether to request another item upstream. * * @param throwable Exception to analyse. */ @Override @Override public void onComplete() { logger.info("Upstream connection publisher was completed. Terminating processor."); isDisposed.set(true); synchronized (lock) { final ConcurrentLinkedDeque<ChannelSubscriber<T>> currentSubscribers = subscribers; subscribers = new ConcurrentLinkedDeque<>(); logger.info("AMQP channel processor completed. Notifying {} subscribers.", currentSubscribers.size()); currentSubscribers.forEach(subscriber -> subscriber.onComplete()); } } @Override public void subscribe(CoreSubscriber<? super T> actual) { if (isDisposed()) { if (lastError != null) { actual.onSubscribe(Operators.emptySubscription()); actual.onError(lastError); } else { Operators.error(actual, logger.logExceptionAsError(new IllegalStateException("Cannot subscribe. Processor is already terminated."))); } return; } final ChannelSubscriber<T> subscriber = new ChannelSubscriber<T>(actual, this); actual.onSubscribe(subscriber); synchronized (lock) { if (currentChannel != null) { subscriber.complete(currentChannel); return; } } subscribers.add(subscriber); logger.atVerbose().addKeyValue("subscribers", subscribers.size()).log("Added a subscriber."); if (!isRetryPending.get()) { requestUpstream(); } } @Override public void dispose() { if (isDisposed.getAndSet(true)) { return; } if (retrySubscription != null && !retrySubscription.isDisposed()) { retrySubscription.dispose(); } onComplete(); synchronized (lock) { setAndClearChannel(); } } @Override public boolean isDisposed() { return isDisposed.get(); } private void requestUpstream() { if (currentChannel != null) { logger.verbose("Connection exists, not requesting another."); return; } else if (isDisposed()) { logger.verbose("Is already disposed."); return; } final Subscription subscription = UPSTREAM.get(this); if (subscription == null) { logger.warning("There is no upstream subscription."); return; } if (!isRequested.getAndSet(true)) { logger.info("Connection not requested, yet. Requesting one."); subscription.request(1); } } private void setAndClearChannel() { T oldChannel; synchronized (lock) { oldChannel = currentChannel; currentChannel = null; } close(oldChannel); } /** * Checks the current state of the channel for this channel and returns true if the channel is null or if this * processor is disposed. * * @return true if the current channel in the processor is null or if the processor is disposed */ public boolean isChannelClosed() { synchronized (lock) { return currentChannel == null || isDisposed(); } } private void close(T channel) { if (channel instanceof AsyncCloseable) { ((AsyncCloseable) channel).closeAsync().subscribe(); } else if (channel instanceof AutoCloseable) { try { ((AutoCloseable) channel).close(); } catch (Exception error) { logger.warning("Error occurred closing AutoCloseable channel.", error); } } else if (channel instanceof Disposable) { try { ((Disposable) channel).dispose(); } catch (Exception error) { logger.warning("Error occurred closing Disposable channel.", error); } } } /** * Represents the decorator-subscriber wrapping a downstream subscriber to AmqpChannelProcessor. * These are the subscribers waiting to receive a channel that is yet to be available in the AmqpChannelProcessor. * The AmqpChannelProcessor tracks a list of such waiting subscribers; once the processor receives * a result (channel, error or disposal) from it's upstream, each decorated-subscriber will be notified, * which removes itself from the tracking list, then propagates the notification to the wrapped subscriber. */ private static final class ChannelSubscriber<T> extends Operators.MonoSubscriber<T, T> { private final AmqpChannelProcessor<T> processor; private ChannelSubscriber(CoreSubscriber<? super T> actual, AmqpChannelProcessor<T> processor) { super(actual); this.processor = processor; } @Override public void cancel() { processor.subscribers.remove(this); super.cancel(); } @Override public void onComplete() { if (!isCancelled()) { processor.subscribers.remove(this); actual.onComplete(); } } @Override public void onNext(T channel) { if (!isCancelled()) { processor.subscribers.remove(this); super.complete(channel); } } @Override public void onError(Throwable throwable) { if (!isCancelled()) { processor.subscribers.remove(this); actual.onError(throwable); } else { Operators.onErrorDropped(throwable, currentContext()); } } } }
see above()
private void acquireChannel(final ChannelPromiseWithExpiryTime promise) { this.ensureInEventLoop(); if (this.isClosed()) { promise.setFailure(POOL_CLOSED_ON_ACQUIRE); return; } try { Channel candidate = this.pollChannel(); if (candidate != null) { doAcquireChannel(promise, candidate); return; } final int channelCount = this.channels(false); if (channelCount < this.maxChannels) { if (this.connecting.compareAndSet(false, true)) { final Promise<Channel> anotherPromise = this.newChannelPromiseForToBeEstablishedChannel(promise); final ChannelFuture future = this.bootstrap.clone().attr(POOL_KEY, this).connect(); if (future.isDone()) { this.safeNotifyChannelConnect(future, anotherPromise); } else { future.addListener(ignored -> this.safeNotifyChannelConnect(future, anotherPromise)); } return; } } else if (this.computeLoadFactor() > 0.90D) { long pendingRequestCountMin = Long.MAX_VALUE; for (Channel channel : this.availableChannels) { final RntbdRequestManager manager = channel.pipeline().get(RntbdRequestManager.class); if (manager == null) { logger.debug("Channel({} --> {}) closed", channel, this.remoteAddress()); } else { final long pendingRequestCount = manager.pendingRequestCount(); if (pendingRequestCount < pendingRequestCountMin && isChannelServiceable(channel)) { pendingRequestCountMin = pendingRequestCount; candidate = channel; } } } if (candidate != null && this.availableChannels.remove(candidate)) { this.doAcquireChannel(promise, candidate); return; } } else { for (Channel channel : this.availableChannels) { if (isChannelServiceable(channel)) { if (this.availableChannels.remove(channel)) { this.doAcquireChannel(promise, channel); return; } } } } this.addTaskToPendingAcquisitionQueue(promise); } catch (Throwable cause) { promise.tryFailure(cause); } }
logger.debug("Channel({} --> {}) closed", channel, this.remoteAddress());
private void acquireChannel(final ChannelPromiseWithExpiryTime promise) { this.ensureInEventLoop(); if (this.isClosed()) { promise.setFailure(POOL_CLOSED_ON_ACQUIRE); return; } try { Channel candidate = this.pollChannel(); if (candidate != null) { doAcquireChannel(promise, candidate); return; } final int channelCount = this.channels(false); if (channelCount < this.maxChannels) { if (this.connecting.compareAndSet(false, true)) { final Promise<Channel> anotherPromise = this.newChannelPromiseForToBeEstablishedChannel(promise); final ChannelFuture future = this.bootstrap.clone().attr(POOL_KEY, this).connect(); if (future.isDone()) { this.safeNotifyChannelConnect(future, anotherPromise); } else { future.addListener(ignored -> this.safeNotifyChannelConnect(future, anotherPromise)); } return; } } else if (this.computeLoadFactor() > 0.90D) { long pendingRequestCountMin = Long.MAX_VALUE; for (Channel channel : this.availableChannels) { final RntbdRequestManager manager = channel.pipeline().get(RntbdRequestManager.class); if (manager == null) { logger.debug("Channel({} --> {}) closed", channel, this.remoteAddress()); } else { final long pendingRequestCount = manager.pendingRequestCount(); if (pendingRequestCount < pendingRequestCountMin && isChannelServiceable(channel)) { pendingRequestCountMin = pendingRequestCount; candidate = channel; } } } if (candidate != null && this.availableChannels.remove(candidate)) { this.doAcquireChannel(promise, candidate); return; } } else { for (Channel channel : this.availableChannels) { if (isChannelServiceable(channel)) { if (this.availableChannels.remove(channel)) { this.doAcquireChannel(promise, channel); return; } } } } this.addTaskToPendingAcquisitionQueue(promise); } catch (Throwable cause) { promise.tryFailure(cause); } }
class and should be pulled up to RntbdServiceEndpoint or this.acquisitionTimeoutInNanos = config.connectionAcquisitionTimeoutInNanos(); this.allocatorMetric = config.allocator().metric(); this.maxChannels = config.maxChannelsPerEndpoint(); this.maxRequestsPerChannel = config.maxRequestsPerChannel(); this.maxPendingAcquisitions = Integer.MAX_VALUE; this.releaseHealthCheck = true; this.acquisitionTimeoutTask = acquisitionTimeoutInNanos <= 0 ? null : new AcquireTimeoutTask(this) { /** * Fails a request due to a channel acquisition timeout. * * @param task a {@link AcquireListener channel acquisition task} that has timed out. */ @Override public void onTimeout(AcquireListener task) { task.originalPromise.setFailure(ACQUISITION_TIMEOUT); } }
class and should be pulled up to RntbdServiceEndpoint or this.acquisitionTimeoutInNanos = config.connectionAcquisitionTimeoutInNanos(); this.allocatorMetric = config.allocator().metric(); this.maxChannels = config.maxChannelsPerEndpoint(); this.maxRequestsPerChannel = config.maxRequestsPerChannel(); this.maxPendingAcquisitions = Integer.MAX_VALUE; this.releaseHealthCheck = true; this.acquisitionTimeoutTask = acquisitionTimeoutInNanos <= 0 ? null : new AcquireTimeoutTask(this) { /** * Fails a request due to a channel acquisition timeout. * * @param task a {@link AcquireListener channel acquisition task} that has timed out. */ @Override public void onTimeout(AcquireListener task) { task.originalPromise.setFailure(ACQUISITION_TIMEOUT); } }
should decrease inside failFastRntbdRequestRecord.whenComplete?
public RntbdRequestRecord request(final RntbdRequestArgs args) { this.throwIfClosed(); int concurrentRequestSnapshot = this.concurrentRequests.incrementAndGet(); if (concurrentRequestSnapshot > this.maxConcurrentRequests) { try { return FailFastRntbdRequestRecord.createAndFailFast( args, concurrentRequestSnapshot, metrics, remoteAddress); } finally { concurrentRequests.decrementAndGet(); } } this.lastRequestNanoTime.set(args.nanoTimeCreated()); final RntbdRequestRecord record = this.write(args); record.whenComplete((response, error) -> { this.concurrentRequests.decrementAndGet(); this.metrics.markComplete(record); }); return record; }
concurrentRequests.decrementAndGet();
public RntbdRequestRecord request(final RntbdRequestArgs args) { this.throwIfClosed(); int concurrentRequestSnapshot = this.concurrentRequests.incrementAndGet(); if (concurrentRequestSnapshot > this.maxConcurrentRequests) { try { return FailFastRntbdRequestRecord.createAndFailFast( args, concurrentRequestSnapshot, metrics, remoteAddress); } finally { concurrentRequests.decrementAndGet(); } } this.lastRequestNanoTime.set(args.nanoTimeCreated()); final RntbdRequestRecord record = this.write(args); record.whenComplete((response, error) -> { this.concurrentRequests.decrementAndGet(); this.metrics.markComplete(record); }); return record; }
class RntbdServiceEndpoint implements RntbdEndpoint { private static final String TAG_NAME = RntbdServiceEndpoint.class.getSimpleName(); private static final long QUIET_PERIOD = 2_000_000_000L; private static final AtomicLong instanceCount = new AtomicLong(); private static final Logger logger = LoggerFactory.getLogger(RntbdServiceEndpoint.class); private static final AdaptiveRecvByteBufAllocator receiveBufferAllocator = new AdaptiveRecvByteBufAllocator(); private final RntbdClientChannelPool channelPool; private final AtomicBoolean closed; private final AtomicInteger concurrentRequests; private final long id; private final AtomicLong lastRequestNanoTime; private final RntbdMetrics metrics; private final Provider provider; private final SocketAddress remoteAddress; private final RntbdRequestTimer requestTimer; private final Tag tag; private final int maxConcurrentRequests; private RntbdServiceEndpoint( final Provider provider, final Config config, final NioEventLoopGroup group, final RntbdRequestTimer timer, final URI physicalAddress) { final Bootstrap bootstrap = new Bootstrap() .channel(NioSocketChannel.class) .group(group) .option(ChannelOption.ALLOCATOR, config.allocator()) .option(ChannelOption.AUTO_READ, true) .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, config.connectTimeoutInMillis()) .option(ChannelOption.RCVBUF_ALLOCATOR, receiveBufferAllocator) .option(ChannelOption.SO_KEEPALIVE, true) .remoteAddress(physicalAddress.getHost(), physicalAddress.getPort()); this.channelPool = new RntbdClientChannelPool(this, bootstrap, config); this.remoteAddress = bootstrap.config().remoteAddress(); this.concurrentRequests = new AtomicInteger(); this.lastRequestNanoTime = new AtomicLong(System.nanoTime()); this.closed = new AtomicBoolean(); this.requestTimer = timer; this.tag = Tag.of(TAG_NAME, RntbdMetrics.escape(this.remoteAddress.toString())); this.id = instanceCount.incrementAndGet(); this.provider = provider; this.metrics = new RntbdMetrics(provider.transportClient, this); this.maxConcurrentRequests = config.maxConcurrentRequestsPerEndpoint(); } /** * @return approximate number of acquired channels. */ @Override public int channelsAcquiredMetric() { return this.channelPool.channelsAcquiredMetrics(); } /** * @return approximate number of available channels. */ @Override public int channelsAvailableMetric() { return this.channelPool.channelsAvailableMetrics(); } @Override public int concurrentRequests() { return this.concurrentRequests.get(); } @Override public long id() { return this.id; } @Override public boolean isClosed() { return this.closed.get(); } public long lastRequestNanoTime() { return this.lastRequestNanoTime.get(); } @Override public SocketAddress remoteAddress() { return this.remoteAddress; } @Override public int requestQueueLength() { return this.channelPool.requestQueueLength(); } @Override public Tag tag() { return this.tag; } @Override public long usedDirectMemory() { return this.channelPool.usedDirectMemory(); } @Override public long usedHeapMemory() { return this.channelPool.usedHeapMemory(); } @Override public void close() { if (this.closed.compareAndSet(false, true)) { this.provider.evict(this); this.channelPool.close(); } } @Override public String toString() { return RntbdObjectMapper.toString(this); } private void ensureSuccessWhenReleasedToPool(Channel channel, Future<Void> released) { if (released.isSuccess()) { logger.debug("\n [{}]\n {}\n release succeeded", this, channel); } else { logger.debug("\n [{}]\n {}\n release failed due to {}", this, channel, released.cause()); } } private void releaseToPool(final Channel channel) { logger.debug("\n [{}]\n {}\n RELEASE", this, channel); final Future<Void> released = this.channelPool.release(channel); if (logger.isDebugEnabled()) { if (released.isDone()) { ensureSuccessWhenReleasedToPool(channel, released); } else { released.addListener(ignored -> ensureSuccessWhenReleasedToPool(channel, released)); } } } private void throwIfClosed() { checkState(!this.closed.get(), "%s is closed", this); } private RntbdRequestRecord write(final RntbdRequestArgs requestArgs) { final RntbdRequestRecord requestRecord = new AsyncRntbdRequestRecord(requestArgs, this.requestTimer); final Future<Channel> connectedChannel = this.channelPool.acquire(); logger.debug("\n [{}]\n {}\n WRITE WHEN CONNECTED {}", this, requestArgs, connectedChannel); if (connectedChannel.isDone()) { return writeWhenConnected(requestRecord, connectedChannel); } else { connectedChannel.addListener(ignored -> writeWhenConnected(requestRecord, connectedChannel)); } return requestRecord; } private RntbdRequestRecord writeWhenConnected( final RntbdRequestRecord requestRecord, final Future<? super Channel> connected) { if (connected.isSuccess()) { final Channel channel = (Channel) connected.getNow(); assert channel != null : "impossible"; this.releaseToPool(channel); channel.write(requestRecord.stage(RntbdRequestRecord.Stage.PIPELINED)); return requestRecord; } final RntbdRequestArgs requestArgs = requestRecord.args(); final UUID activityId = requestArgs.activityId(); final Throwable cause = connected.cause(); if (connected.isCancelled()) { logger.debug("\n [{}]\n {}\n write cancelled: {}", this, requestArgs, cause); requestRecord.cancel(true); } else { logger.debug("\n [{}]\n {}\n write failed due to {} ", this, requestArgs, cause); final String reason = cause.toString(); final GoneException goneException = new GoneException( lenientFormat("failed to establish connection to %s due to %s", this.remoteAddress, reason), cause instanceof Exception ? (Exception) cause : new IOException(reason, cause), ImmutableMap.of(HttpHeaders.ACTIVITY_ID, activityId.toString()), requestArgs.replicaPath() ); BridgeInternal.setRequestHeaders(goneException, requestArgs.serviceRequest().getHeaders()); requestRecord.completeExceptionally(goneException); } return requestRecord; } static final class JsonSerializer extends StdSerializer<RntbdServiceEndpoint> { private static final long serialVersionUID = -5764954918168771152L; public JsonSerializer() { super(RntbdServiceEndpoint.class); } @Override public void serialize(RntbdServiceEndpoint value, JsonGenerator generator, SerializerProvider provider) throws IOException { generator.writeStartObject(); generator.writeNumberField("id", value.id); generator.writeBooleanField("isClosed", value.isClosed()); generator.writeNumberField("concurrentRequests", value.concurrentRequests()); generator.writeStringField("remoteAddress", value.remoteAddress.toString()); generator.writeObjectField("channelPool", value.channelPool); generator.writeEndObject(); } } public static final class Provider implements RntbdEndpoint.Provider { private static final Logger logger = LoggerFactory.getLogger(Provider.class); private final AtomicBoolean closed; private final Config config; private final ConcurrentHashMap<String, RntbdEndpoint> endpoints; private final NioEventLoopGroup eventLoopGroup; private final AtomicInteger evictions; private final RntbdRequestTimer requestTimer; private final RntbdTransportClient transportClient; public Provider( final RntbdTransportClient transportClient, final Options options, final SslContext sslContext) { checkNotNull(transportClient, "expected non-null provider"); checkNotNull(options, "expected non-null options"); checkNotNull(sslContext, "expected non-null sslContext"); final DefaultThreadFactory threadFactory = new DefaultThreadFactory("cosmos-rntbd-nio", true); final LogLevel wireLogLevel; if (logger.isDebugEnabled()) { wireLogLevel = LogLevel.TRACE; } else { wireLogLevel = null; } this.transportClient = transportClient; this.config = new Config(options, sslContext, wireLogLevel); this.requestTimer = new RntbdRequestTimer( config.requestTimeoutInNanos(), config.requestTimerResolutionInNanos()); this.eventLoopGroup = new NioEventLoopGroup(options.threadCount(), threadFactory); this.endpoints = new ConcurrentHashMap<>(); this.evictions = new AtomicInteger(); this.closed = new AtomicBoolean(); } @Override public void close() { if (this.closed.compareAndSet(false, true)) { for (final RntbdEndpoint endpoint : this.endpoints.values()) { endpoint.close(); } this.eventLoopGroup.shutdownGracefully(QUIET_PERIOD, this.config.shutdownTimeoutInNanos(), NANOSECONDS) .addListener(future -> { this.requestTimer.close(); if (future.isSuccess()) { logger.debug("\n [{}]\n closed endpoints", this); return; } logger.error("\n [{}]\n failed to close endpoints due to ", this, future.cause()); }); return; } logger.debug("\n [{}]\n already closed", this); } @Override public Config config() { return this.config; } @Override public int count() { return this.endpoints.size(); } @Override public int evictions() { return this.evictions.get(); } @Override public RntbdEndpoint get(final URI physicalAddress) { return endpoints.computeIfAbsent(physicalAddress.getAuthority(), authority -> new RntbdServiceEndpoint( this, this.config, this.eventLoopGroup, this.requestTimer, physicalAddress)); } @Override public Stream<RntbdEndpoint> list() { return this.endpoints.values().stream(); } private void evict(final RntbdEndpoint endpoint) { if (this.endpoints.remove(endpoint.remoteAddress().toString()) != null) { this.evictions.incrementAndGet(); } } } }
class RntbdServiceEndpoint implements RntbdEndpoint { private static final String TAG_NAME = RntbdServiceEndpoint.class.getSimpleName(); private static final long QUIET_PERIOD = 2_000_000_000L; private static final AtomicLong instanceCount = new AtomicLong(); private static final Logger logger = LoggerFactory.getLogger(RntbdServiceEndpoint.class); private static final AdaptiveRecvByteBufAllocator receiveBufferAllocator = new AdaptiveRecvByteBufAllocator(); private final RntbdClientChannelPool channelPool; private final AtomicBoolean closed; private final AtomicInteger concurrentRequests; private final long id; private final AtomicLong lastRequestNanoTime; private final RntbdMetrics metrics; private final Provider provider; private final SocketAddress remoteAddress; private final RntbdRequestTimer requestTimer; private final Tag tag; private final int maxConcurrentRequests; private RntbdServiceEndpoint( final Provider provider, final Config config, final NioEventLoopGroup group, final RntbdRequestTimer timer, final URI physicalAddress) { final Bootstrap bootstrap = new Bootstrap() .channel(NioSocketChannel.class) .group(group) .option(ChannelOption.ALLOCATOR, config.allocator()) .option(ChannelOption.AUTO_READ, true) .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, config.connectTimeoutInMillis()) .option(ChannelOption.RCVBUF_ALLOCATOR, receiveBufferAllocator) .option(ChannelOption.SO_KEEPALIVE, true) .remoteAddress(physicalAddress.getHost(), physicalAddress.getPort()); this.channelPool = new RntbdClientChannelPool(this, bootstrap, config); this.remoteAddress = bootstrap.config().remoteAddress(); this.concurrentRequests = new AtomicInteger(); this.lastRequestNanoTime = new AtomicLong(System.nanoTime()); this.closed = new AtomicBoolean(); this.requestTimer = timer; this.tag = Tag.of(TAG_NAME, RntbdMetrics.escape(this.remoteAddress.toString())); this.id = instanceCount.incrementAndGet(); this.provider = provider; this.metrics = new RntbdMetrics(provider.transportClient, this); this.maxConcurrentRequests = config.maxConcurrentRequestsPerEndpoint(); } /** * @return approximate number of acquired channels. */ @Override public int channelsAcquiredMetric() { return this.channelPool.channelsAcquiredMetrics(); } /** * @return approximate number of available channels. */ @Override public int channelsAvailableMetric() { return this.channelPool.channelsAvailableMetrics(); } @Override public int concurrentRequests() { return this.concurrentRequests.get(); } @Override public long id() { return this.id; } @Override public boolean isClosed() { return this.closed.get(); } public long lastRequestNanoTime() { return this.lastRequestNanoTime.get(); } @Override public SocketAddress remoteAddress() { return this.remoteAddress; } @Override public int requestQueueLength() { return this.channelPool.requestQueueLength(); } @Override public Tag tag() { return this.tag; } @Override public long usedDirectMemory() { return this.channelPool.usedDirectMemory(); } @Override public long usedHeapMemory() { return this.channelPool.usedHeapMemory(); } @Override public void close() { if (this.closed.compareAndSet(false, true)) { this.provider.evict(this); this.channelPool.close(); } } @Override public String toString() { return RntbdObjectMapper.toString(this); } private void ensureSuccessWhenReleasedToPool(Channel channel, Future<Void> released) { if (released.isSuccess()) { logger.debug("\n [{}]\n {}\n release succeeded", this, channel); } else { logger.debug("\n [{}]\n {}\n release failed due to {}", this, channel, released.cause()); } } private void releaseToPool(final Channel channel) { logger.debug("\n [{}]\n {}\n RELEASE", this, channel); final Future<Void> released = this.channelPool.release(channel); if (logger.isDebugEnabled()) { if (released.isDone()) { ensureSuccessWhenReleasedToPool(channel, released); } else { released.addListener(ignored -> ensureSuccessWhenReleasedToPool(channel, released)); } } } private void throwIfClosed() { checkState(!this.closed.get(), "%s is closed", this); } private RntbdRequestRecord write(final RntbdRequestArgs requestArgs) { final RntbdRequestRecord requestRecord = new AsyncRntbdRequestRecord(requestArgs, this.requestTimer); final Future<Channel> connectedChannel = this.channelPool.acquire(); logger.debug("\n [{}]\n {}\n WRITE WHEN CONNECTED {}", this, requestArgs, connectedChannel); if (connectedChannel.isDone()) { return writeWhenConnected(requestRecord, connectedChannel); } else { connectedChannel.addListener(ignored -> writeWhenConnected(requestRecord, connectedChannel)); } return requestRecord; } private RntbdRequestRecord writeWhenConnected( final RntbdRequestRecord requestRecord, final Future<? super Channel> connected) { if (connected.isSuccess()) { final Channel channel = (Channel) connected.getNow(); assert channel != null : "impossible"; this.releaseToPool(channel); channel.write(requestRecord.stage(RntbdRequestRecord.Stage.PIPELINED)); return requestRecord; } final RntbdRequestArgs requestArgs = requestRecord.args(); final UUID activityId = requestArgs.activityId(); final Throwable cause = connected.cause(); if (connected.isCancelled()) { logger.debug("\n [{}]\n {}\n write cancelled: {}", this, requestArgs, cause); requestRecord.cancel(true); } else { logger.debug("\n [{}]\n {}\n write failed due to {} ", this, requestArgs, cause); final String reason = cause.toString(); final GoneException goneException = new GoneException( lenientFormat("failed to establish connection to %s due to %s", this.remoteAddress, reason), cause instanceof Exception ? (Exception) cause : new IOException(reason, cause), ImmutableMap.of(HttpHeaders.ACTIVITY_ID, activityId.toString()), requestArgs.replicaPath() ); BridgeInternal.setRequestHeaders(goneException, requestArgs.serviceRequest().getHeaders()); requestRecord.completeExceptionally(goneException); } return requestRecord; } static final class JsonSerializer extends StdSerializer<RntbdServiceEndpoint> { private static final long serialVersionUID = -5764954918168771152L; public JsonSerializer() { super(RntbdServiceEndpoint.class); } @Override public void serialize(RntbdServiceEndpoint value, JsonGenerator generator, SerializerProvider provider) throws IOException { generator.writeStartObject(); generator.writeNumberField("id", value.id); generator.writeBooleanField("isClosed", value.isClosed()); generator.writeNumberField("concurrentRequests", value.concurrentRequests()); generator.writeStringField("remoteAddress", value.remoteAddress.toString()); generator.writeObjectField("channelPool", value.channelPool); generator.writeEndObject(); } } public static final class Provider implements RntbdEndpoint.Provider { private static final Logger logger = LoggerFactory.getLogger(Provider.class); private final AtomicBoolean closed; private final Config config; private final ConcurrentHashMap<String, RntbdEndpoint> endpoints; private final NioEventLoopGroup eventLoopGroup; private final AtomicInteger evictions; private final RntbdRequestTimer requestTimer; private final RntbdTransportClient transportClient; public Provider( final RntbdTransportClient transportClient, final Options options, final SslContext sslContext) { checkNotNull(transportClient, "expected non-null provider"); checkNotNull(options, "expected non-null options"); checkNotNull(sslContext, "expected non-null sslContext"); final DefaultThreadFactory threadFactory = new DefaultThreadFactory("cosmos-rntbd-nio", true); final LogLevel wireLogLevel; if (logger.isDebugEnabled()) { wireLogLevel = LogLevel.TRACE; } else { wireLogLevel = null; } this.transportClient = transportClient; this.config = new Config(options, sslContext, wireLogLevel); this.requestTimer = new RntbdRequestTimer( config.requestTimeoutInNanos(), config.requestTimerResolutionInNanos()); this.eventLoopGroup = new NioEventLoopGroup(options.threadCount(), threadFactory); this.endpoints = new ConcurrentHashMap<>(); this.evictions = new AtomicInteger(); this.closed = new AtomicBoolean(); } @Override public void close() { if (this.closed.compareAndSet(false, true)) { for (final RntbdEndpoint endpoint : this.endpoints.values()) { endpoint.close(); } this.eventLoopGroup.shutdownGracefully(QUIET_PERIOD, this.config.shutdownTimeoutInNanos(), NANOSECONDS) .addListener(future -> { this.requestTimer.close(); if (future.isSuccess()) { logger.debug("\n [{}]\n closed endpoints", this); return; } logger.error("\n [{}]\n failed to close endpoints due to ", this, future.cause()); }); return; } logger.debug("\n [{}]\n already closed", this); } @Override public Config config() { return this.config; } @Override public int count() { return this.endpoints.size(); } @Override public int evictions() { return this.evictions.get(); } @Override public RntbdEndpoint get(final URI physicalAddress) { return endpoints.computeIfAbsent(physicalAddress.getAuthority(), authority -> new RntbdServiceEndpoint( this, this.config, this.eventLoopGroup, this.requestTimer, physicalAddress)); } @Override public Stream<RntbdEndpoint> list() { return this.endpoints.values().stream(); } private void evict(final RntbdEndpoint endpoint) { if (this.endpoints.remove(endpoint.remoteAddress().toString()) != null) { this.evictions.incrementAndGet(); } } } }
else if
private void logEndpoint(RntbdEndpoint endpoint) { int executorPoolSize = endpoint.executorTaskQueueMetrics(); if (this.logger.isDebugEnabled()) { logger.debug("RntbdEndpoint Identifier {}, Stat {}", getPoolId(endpoint), getPoolStat(endpoint)); } if (executorPoolSize > 5_000 || endpoint.requestQueueLength() > 5_000 || endpoint.gettingEstablishedConnectionsMetrics() > 0 || endpoint.channelsMetrics() > endpoint.maxChannels()) { if (this.logger.isWarnEnabled()) { logger.warn("RntbdEndpoint Identifier {}, Stat {}", getPoolId(endpoint), getPoolStat(endpoint)); } } }
if (executorPoolSize > 5_000 ||
private void logEndpoint(RntbdEndpoint endpoint) { if (this.logger.isWarnEnabled() && (endpoint.executorTaskQueueMetrics() > MAX_TASK_LIMIT || endpoint.requestQueueLength() > MAX_TASK_LIMIT || endpoint.gettingEstablishedConnectionsMetrics() > 0 || endpoint.channelsMetrics() > endpoint.maxChannels())) { logger.warn("RntbdEndpoint Identifier {}, Stat {}", getPoolId(endpoint), getPoolStat(endpoint)); } else if (this.logger.isDebugEnabled()) { logger.debug("RntbdEndpoint Identifier {}, Stat {}", getPoolId(endpoint), getPoolStat(endpoint)); } }
class RntbdEndpointMonitoringProvider { private final Logger logger = LoggerFactory.getLogger(RntbdEndpointMonitoringProvider.class); private static final EventExecutor monitoringRntbdChannelPool = new DefaultEventExecutor(new RntbdThreadFactory( "monitoring-rntbd-endpoints", true, Thread.MIN_PRIORITY)); private static final Duration MONITORING_PERIOD = Duration.ofSeconds(5); private final Provider provider; private ScheduledFuture<?> future; RntbdEndpointMonitoringProvider(Provider provider) { this.provider = provider; } synchronized void init() { logger.info("Starting RntbdClientChannelPoolMonitoringProvider ..."); this.future = this.monitoringRntbdChannelPool.scheduleAtFixedRate(() -> { logAllPools(); }, 0, MONITORING_PERIOD.toMillis(), TimeUnit.MILLISECONDS); } synchronized void shutdown() { logger.info("Shutting down RntbdClientChannelPoolMonitoringProvider ..."); this.future.cancel(false); this.future = null; } synchronized void logAllPools() { try { logger.debug("Total number of RntbdClientChannelPool [{}].", provider.endpoints.size()); for (RntbdEndpoint endpoint : provider.endpoints.values()) { logEndpoint(endpoint); } } catch (Exception e) { logger.error("monitoring unexpected failure", e); } } private String getPoolStat(RntbdEndpoint endpoint) { return "[ " + "poolTaskExecutorSize " + endpoint.executorTaskQueueMetrics() + ", lastRequestNanoTime " + Instant.now().minusNanos( System.nanoTime() - endpoint.lastRequestNanoTime()) + ", connecting " + endpoint.gettingEstablishedConnectionsMetrics() + ", acquiredChannel " + endpoint.channelsAcquiredMetric() + ", availableChannel " + endpoint.channelsAvailableMetric() + ", pendingAcquisitionSize " + endpoint.requestQueueLength() + ", closed " + endpoint.isClosed() + " ]"; } private String getPoolId(RntbdEndpoint endpoint) { if (endpoint == null) { return "null"; } return "[RntbdEndpoint" + ", id " + endpoint.id() + ", remoteAddress " + endpoint.remoteAddress() + ", creationTime " + endpoint.getCreatedTime() + ", hashCode " + endpoint.hashCode() + "]"; } }
class RntbdEndpointMonitoringProvider implements AutoCloseable { private final Logger logger = LoggerFactory.getLogger(RntbdEndpointMonitoringProvider.class); private static final EventExecutor monitoringRntbdChannelPool = new DefaultEventExecutor(new RntbdThreadFactory( "monitoring-rntbd-endpoints", true, Thread.MIN_PRIORITY)); private static final Duration MONITORING_PERIOD = Duration.ofSeconds(60); private final Provider provider; private final static int MAX_TASK_LIMIT = 5_000; private ScheduledFuture<?> future; RntbdEndpointMonitoringProvider(Provider provider) { this.provider = provider; } synchronized void init() { logger.info("Starting RntbdClientChannelPoolMonitoringProvider ..."); this.future = RntbdEndpointMonitoringProvider.monitoringRntbdChannelPool.scheduleAtFixedRate(() -> { logAllPools(); }, 0, MONITORING_PERIOD.toMillis(), TimeUnit.MILLISECONDS); } @Override public synchronized void close() { logger.info("Shutting down RntbdClientChannelPoolMonitoringProvider ..."); this.future.cancel(false); this.future = null; } synchronized void logAllPools() { try { logger.debug("Total number of RntbdClientChannelPool [{}].", provider.endpoints.size()); for (RntbdEndpoint endpoint : provider.endpoints.values()) { logEndpoint(endpoint); } } catch (Exception e) { logger.error("monitoring unexpected failure", e); } } private String getPoolStat(RntbdEndpoint endpoint) { return "[ " + "poolTaskExecutorSize " + endpoint.executorTaskQueueMetrics() + ", lastRequestNanoTime " + Instant.now().minusNanos( System.nanoTime() - endpoint.lastRequestNanoTime()) + ", connecting " + endpoint.gettingEstablishedConnectionsMetrics() + ", acquiredChannel " + endpoint.channelsAcquiredMetric() + ", availableChannel " + endpoint.channelsAvailableMetric() + ", pendingAcquisitionSize " + endpoint.requestQueueLength() + ", closed " + endpoint.isClosed() + " ]"; } private String getPoolId(RntbdEndpoint endpoint) { if (endpoint == null) { return "null"; } return "[RntbdEndpoint" + ", id " + endpoint.id() + ", remoteAddress " + endpoint.remoteAddress() + ", creationTime " + endpoint.getCreatedTime() + ", hashCode " + endpoint.hashCode() + "]"; } }
ah right. Thanks will fix.
private void logEndpoint(RntbdEndpoint endpoint) { int executorPoolSize = endpoint.executorTaskQueueMetrics(); if (this.logger.isDebugEnabled()) { logger.debug("RntbdEndpoint Identifier {}, Stat {}", getPoolId(endpoint), getPoolStat(endpoint)); } if (executorPoolSize > 5_000 || endpoint.requestQueueLength() > 5_000 || endpoint.gettingEstablishedConnectionsMetrics() > 0 || endpoint.channelsMetrics() > endpoint.maxChannels()) { if (this.logger.isWarnEnabled()) { logger.warn("RntbdEndpoint Identifier {}, Stat {}", getPoolId(endpoint), getPoolStat(endpoint)); } } }
if (executorPoolSize > 5_000 ||
private void logEndpoint(RntbdEndpoint endpoint) { if (this.logger.isWarnEnabled() && (endpoint.executorTaskQueueMetrics() > MAX_TASK_LIMIT || endpoint.requestQueueLength() > MAX_TASK_LIMIT || endpoint.gettingEstablishedConnectionsMetrics() > 0 || endpoint.channelsMetrics() > endpoint.maxChannels())) { logger.warn("RntbdEndpoint Identifier {}, Stat {}", getPoolId(endpoint), getPoolStat(endpoint)); } else if (this.logger.isDebugEnabled()) { logger.debug("RntbdEndpoint Identifier {}, Stat {}", getPoolId(endpoint), getPoolStat(endpoint)); } }
class RntbdEndpointMonitoringProvider { private final Logger logger = LoggerFactory.getLogger(RntbdEndpointMonitoringProvider.class); private static final EventExecutor monitoringRntbdChannelPool = new DefaultEventExecutor(new RntbdThreadFactory( "monitoring-rntbd-endpoints", true, Thread.MIN_PRIORITY)); private static final Duration MONITORING_PERIOD = Duration.ofSeconds(5); private final Provider provider; private ScheduledFuture<?> future; RntbdEndpointMonitoringProvider(Provider provider) { this.provider = provider; } synchronized void init() { logger.info("Starting RntbdClientChannelPoolMonitoringProvider ..."); this.future = this.monitoringRntbdChannelPool.scheduleAtFixedRate(() -> { logAllPools(); }, 0, MONITORING_PERIOD.toMillis(), TimeUnit.MILLISECONDS); } synchronized void shutdown() { logger.info("Shutting down RntbdClientChannelPoolMonitoringProvider ..."); this.future.cancel(false); this.future = null; } synchronized void logAllPools() { try { logger.debug("Total number of RntbdClientChannelPool [{}].", provider.endpoints.size()); for (RntbdEndpoint endpoint : provider.endpoints.values()) { logEndpoint(endpoint); } } catch (Exception e) { logger.error("monitoring unexpected failure", e); } } private String getPoolStat(RntbdEndpoint endpoint) { return "[ " + "poolTaskExecutorSize " + endpoint.executorTaskQueueMetrics() + ", lastRequestNanoTime " + Instant.now().minusNanos( System.nanoTime() - endpoint.lastRequestNanoTime()) + ", connecting " + endpoint.gettingEstablishedConnectionsMetrics() + ", acquiredChannel " + endpoint.channelsAcquiredMetric() + ", availableChannel " + endpoint.channelsAvailableMetric() + ", pendingAcquisitionSize " + endpoint.requestQueueLength() + ", closed " + endpoint.isClosed() + " ]"; } private String getPoolId(RntbdEndpoint endpoint) { if (endpoint == null) { return "null"; } return "[RntbdEndpoint" + ", id " + endpoint.id() + ", remoteAddress " + endpoint.remoteAddress() + ", creationTime " + endpoint.getCreatedTime() + ", hashCode " + endpoint.hashCode() + "]"; } }
class RntbdEndpointMonitoringProvider implements AutoCloseable { private final Logger logger = LoggerFactory.getLogger(RntbdEndpointMonitoringProvider.class); private static final EventExecutor monitoringRntbdChannelPool = new DefaultEventExecutor(new RntbdThreadFactory( "monitoring-rntbd-endpoints", true, Thread.MIN_PRIORITY)); private static final Duration MONITORING_PERIOD = Duration.ofSeconds(60); private final Provider provider; private final static int MAX_TASK_LIMIT = 5_000; private ScheduledFuture<?> future; RntbdEndpointMonitoringProvider(Provider provider) { this.provider = provider; } synchronized void init() { logger.info("Starting RntbdClientChannelPoolMonitoringProvider ..."); this.future = RntbdEndpointMonitoringProvider.monitoringRntbdChannelPool.scheduleAtFixedRate(() -> { logAllPools(); }, 0, MONITORING_PERIOD.toMillis(), TimeUnit.MILLISECONDS); } @Override public synchronized void close() { logger.info("Shutting down RntbdClientChannelPoolMonitoringProvider ..."); this.future.cancel(false); this.future = null; } synchronized void logAllPools() { try { logger.debug("Total number of RntbdClientChannelPool [{}].", provider.endpoints.size()); for (RntbdEndpoint endpoint : provider.endpoints.values()) { logEndpoint(endpoint); } } catch (Exception e) { logger.error("monitoring unexpected failure", e); } } private String getPoolStat(RntbdEndpoint endpoint) { return "[ " + "poolTaskExecutorSize " + endpoint.executorTaskQueueMetrics() + ", lastRequestNanoTime " + Instant.now().minusNanos( System.nanoTime() - endpoint.lastRequestNanoTime()) + ", connecting " + endpoint.gettingEstablishedConnectionsMetrics() + ", acquiredChannel " + endpoint.channelsAcquiredMetric() + ", availableChannel " + endpoint.channelsAvailableMetric() + ", pendingAcquisitionSize " + endpoint.requestQueueLength() + ", closed " + endpoint.isClosed() + " ]"; } private String getPoolId(RntbdEndpoint endpoint) { if (endpoint == null) { return "null"; } return "[RntbdEndpoint" + ", id " + endpoint.id() + ", remoteAddress " + endpoint.remoteAddress() + ", creationTime " + endpoint.getCreatedTime() + ", hashCode " + endpoint.hashCode() + "]"; } }
thanks addressed.
private void logEndpoint(RntbdEndpoint endpoint) { int executorPoolSize = endpoint.executorTaskQueueMetrics(); if (this.logger.isDebugEnabled()) { logger.debug("RntbdEndpoint Identifier {}, Stat {}", getPoolId(endpoint), getPoolStat(endpoint)); } if (executorPoolSize > 5_000 || endpoint.requestQueueLength() > 5_000 || endpoint.gettingEstablishedConnectionsMetrics() > 0 || endpoint.channelsMetrics() > endpoint.maxChannels()) { if (this.logger.isWarnEnabled()) { logger.warn("RntbdEndpoint Identifier {}, Stat {}", getPoolId(endpoint), getPoolStat(endpoint)); } } }
if (executorPoolSize > 5_000 ||
private void logEndpoint(RntbdEndpoint endpoint) { if (this.logger.isWarnEnabled() && (endpoint.executorTaskQueueMetrics() > MAX_TASK_LIMIT || endpoint.requestQueueLength() > MAX_TASK_LIMIT || endpoint.gettingEstablishedConnectionsMetrics() > 0 || endpoint.channelsMetrics() > endpoint.maxChannels())) { logger.warn("RntbdEndpoint Identifier {}, Stat {}", getPoolId(endpoint), getPoolStat(endpoint)); } else if (this.logger.isDebugEnabled()) { logger.debug("RntbdEndpoint Identifier {}, Stat {}", getPoolId(endpoint), getPoolStat(endpoint)); } }
class RntbdEndpointMonitoringProvider { private final Logger logger = LoggerFactory.getLogger(RntbdEndpointMonitoringProvider.class); private static final EventExecutor monitoringRntbdChannelPool = new DefaultEventExecutor(new RntbdThreadFactory( "monitoring-rntbd-endpoints", true, Thread.MIN_PRIORITY)); private static final Duration MONITORING_PERIOD = Duration.ofSeconds(5); private final Provider provider; private ScheduledFuture<?> future; RntbdEndpointMonitoringProvider(Provider provider) { this.provider = provider; } synchronized void init() { logger.info("Starting RntbdClientChannelPoolMonitoringProvider ..."); this.future = this.monitoringRntbdChannelPool.scheduleAtFixedRate(() -> { logAllPools(); }, 0, MONITORING_PERIOD.toMillis(), TimeUnit.MILLISECONDS); } synchronized void shutdown() { logger.info("Shutting down RntbdClientChannelPoolMonitoringProvider ..."); this.future.cancel(false); this.future = null; } synchronized void logAllPools() { try { logger.debug("Total number of RntbdClientChannelPool [{}].", provider.endpoints.size()); for (RntbdEndpoint endpoint : provider.endpoints.values()) { logEndpoint(endpoint); } } catch (Exception e) { logger.error("monitoring unexpected failure", e); } } private String getPoolStat(RntbdEndpoint endpoint) { return "[ " + "poolTaskExecutorSize " + endpoint.executorTaskQueueMetrics() + ", lastRequestNanoTime " + Instant.now().minusNanos( System.nanoTime() - endpoint.lastRequestNanoTime()) + ", connecting " + endpoint.gettingEstablishedConnectionsMetrics() + ", acquiredChannel " + endpoint.channelsAcquiredMetric() + ", availableChannel " + endpoint.channelsAvailableMetric() + ", pendingAcquisitionSize " + endpoint.requestQueueLength() + ", closed " + endpoint.isClosed() + " ]"; } private String getPoolId(RntbdEndpoint endpoint) { if (endpoint == null) { return "null"; } return "[RntbdEndpoint" + ", id " + endpoint.id() + ", remoteAddress " + endpoint.remoteAddress() + ", creationTime " + endpoint.getCreatedTime() + ", hashCode " + endpoint.hashCode() + "]"; } }
class RntbdEndpointMonitoringProvider implements AutoCloseable { private final Logger logger = LoggerFactory.getLogger(RntbdEndpointMonitoringProvider.class); private static final EventExecutor monitoringRntbdChannelPool = new DefaultEventExecutor(new RntbdThreadFactory( "monitoring-rntbd-endpoints", true, Thread.MIN_PRIORITY)); private static final Duration MONITORING_PERIOD = Duration.ofSeconds(60); private final Provider provider; private final static int MAX_TASK_LIMIT = 5_000; private ScheduledFuture<?> future; RntbdEndpointMonitoringProvider(Provider provider) { this.provider = provider; } synchronized void init() { logger.info("Starting RntbdClientChannelPoolMonitoringProvider ..."); this.future = RntbdEndpointMonitoringProvider.monitoringRntbdChannelPool.scheduleAtFixedRate(() -> { logAllPools(); }, 0, MONITORING_PERIOD.toMillis(), TimeUnit.MILLISECONDS); } @Override public synchronized void close() { logger.info("Shutting down RntbdClientChannelPoolMonitoringProvider ..."); this.future.cancel(false); this.future = null; } synchronized void logAllPools() { try { logger.debug("Total number of RntbdClientChannelPool [{}].", provider.endpoints.size()); for (RntbdEndpoint endpoint : provider.endpoints.values()) { logEndpoint(endpoint); } } catch (Exception e) { logger.error("monitoring unexpected failure", e); } } private String getPoolStat(RntbdEndpoint endpoint) { return "[ " + "poolTaskExecutorSize " + endpoint.executorTaskQueueMetrics() + ", lastRequestNanoTime " + Instant.now().minusNanos( System.nanoTime() - endpoint.lastRequestNanoTime()) + ", connecting " + endpoint.gettingEstablishedConnectionsMetrics() + ", acquiredChannel " + endpoint.channelsAcquiredMetric() + ", availableChannel " + endpoint.channelsAvailableMetric() + ", pendingAcquisitionSize " + endpoint.requestQueueLength() + ", closed " + endpoint.isClosed() + " ]"; } private String getPoolId(RntbdEndpoint endpoint) { if (endpoint == null) { return "null"; } return "[RntbdEndpoint" + ", id " + endpoint.id() + ", remoteAddress " + endpoint.remoteAddress() + ", creationTime " + endpoint.getCreatedTime() + ", hashCode " + endpoint.hashCode() + "]"; } }
This needs Javdocs
public TableClientBuilder() { policies = new ArrayList<>(); httpLogOptions = new HttpLogOptions(); }
httpLogOptions = new HttpLogOptions();
public TableClientBuilder() { policies = new ArrayList<>(); httpLogOptions = new HttpLogOptions(); }
class TableClientBuilder { private final ClientLogger logger = new ClientLogger(TableClientBuilder.class); private final SerializerAdapter serializerAdapter = new TablesJacksonSerializer(); private String tableName; private final List<HttpPipelinePolicy> policies; private Configuration configuration; private TokenCredential tokenCredential; private HttpClient httpClient; private String endpoint; private HttpLogOptions httpLogOptions; private HttpPipeline httpPipeline; private SasTokenCredential sasTokenCredential; private TablesServiceVersion version; private String accountName; private RequestRetryOptions retryOptions = new RequestRetryOptions(); /** * Sets the connection string to help build the client * * @param connectionString the connection string to the storage account * @return the TableClientBuilder */ public TableClientBuilder connectionString(String connectionString) { StorageConnectionString storageConnectionString = StorageConnectionString.create(connectionString, logger); StorageEndpoint endpoint = storageConnectionString.getTableEndpoint(); 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((TokenCredential) new TablesSharedKeyCredential(authSettings.getAccount().getName(), authSettings.getAccount().getAccessKey())); } else if (authSettings.getType() == StorageAuthenticationSettings.Type.SAS_TOKEN) { this.sasToken(authSettings.getSasToken()); } return this; } /** * Sets the table name to help build the client * * @param tableName name of the table for which the client is created for * @return the TableClientBuilder */ public TableClientBuilder tableName(String tableName) { this.tableName = tableName; return this; } /** * builds a sync tableClient * * @return a sync tableClient */ public TableClient buildClient() { return new TableClient(buildAsyncClient()); } /** * builds an async tableClient * * @return an aysnc tableClient */ public TableAsyncClient buildAsyncClient() { TablesServiceVersion serviceVersion = version != null ? version : TablesServiceVersion.getLatest(); HttpPipeline pipeline = (httpPipeline != null) ? httpPipeline : BuilderHelper.buildPipeline( (TablesSharedKeyCredential) tokenCredential, tokenCredential, sasTokenCredential, endpoint, retryOptions, httpLogOptions, httpClient, policies, configuration, logger); return new TableAsyncClient(tableName, pipeline, endpoint, serviceVersion, serializerAdapter); } /** * Sets the endpoint for the Azure Storage Table instance that the client will interact with. * * @param endpoint The URL of the Azure Storage Table instance to send service requests to and receive responses * from. * @return the updated TableClientBuilder object * @throws IllegalArgumentException If {@code endpoint} isn't a proper URL */ public TableClientBuilder endpoint(String endpoint) { try { new URL(endpoint); } catch (MalformedURLException ex) { throw logger.logExceptionAsWarning(new IllegalArgumentException("'endpoint' must be a valid URL")); } this.endpoint = endpoint; return this; } /** * Sets the HTTP pipeline to use for the service client. * * @param pipeline The HTTP pipeline to use for sending service requests and receiving responses. * @return The updated TableClientBuilder object. */ public TableClientBuilder pipeline(HttpPipeline pipeline) { if (this.httpPipeline != null && pipeline == null) { logger.info("HttpPipeline is being set to 'null' when it was previously configured."); } this.httpPipeline = pipeline; return this; } /** * Sets the SAS token used to authorize requests sent to the service. * * @param sasToken The SAS token to use for authenticating requests. * @return the updated BlobClientBuilder * @throws NullPointerException If {@code sasToken} is {@code null}. */ public TableClientBuilder sasToken(String sasToken) { this.sasTokenCredential = new SasTokenCredential(Objects.requireNonNull(sasToken, "'sasToken' cannot be null.")); this.tokenCredential = null; return this; } /** * Sets the configuration store that is used during construction of the service client. * <p> * The default configuration store is a clone of the {@link Configuration * configuration store}, use {@link Configuration * * @param configuration The configuration store used to * @return The updated TableClientBuilder object. */ public TableClientBuilder configuration(Configuration configuration) { this.configuration = configuration; return this; } /** * Sets the {@link TokenCredential} used to authenticate HTTP requests. * * @param credential TokenCredential used to authenticate HTTP requests. * @return The updated TableClientBuilder object. * @throws NullPointerException If {@code credential} is {@code null}. */ public TableClientBuilder credential(TokenCredential credential) { this.tokenCredential = Objects.requireNonNull(credential, "credential cannot be null."); return this; } /** * Sets the HTTP client to use for sending and receiving requests to and from the service. * * @param client The HTTP client to use for requests. * @return The updated TableClientBuilder object. */ public TableClientBuilder httpClient(HttpClient client) { if (this.httpClient != null && client == null) { logger.error("'httpClient' is being set to 'null' when it was previously configured."); } this.httpClient = client; return this; } /** * Sets the logging configuration for HTTP requests and responses. * * <p> If logLevel is not provided, default value of {@link HttpLogDetailLevel * * @param logOptions The logging configuration to use when sending and receiving HTTP requests/responses. * @return The updated TableClientBuilder object. */ public TableClientBuilder httpLogOptions(HttpLogOptions logOptions) { this.httpLogOptions = Objects.requireNonNull(logOptions, "'logOptions' cannot be null."); return this; } /** * Adds a policy to the set of existing policies that are executed after required policies. * * @param pipelinePolicy The retry policy for service requests. * @return The updated TableClientBuilder object. * @throws NullPointerException If {@code policy} is {@code null}. */ public TableClientBuilder addPolicy(HttpPipelinePolicy pipelinePolicy) { this.policies.add(Objects.requireNonNull(pipelinePolicy, "'pipelinePolicy' cannot be null")); return this; } /** * Sets the {@link TablesServiceVersion} that is used when making API requests. * * @param version {@link TablesServiceVersion} of the service to be used when making requests. * @return The updated TableClientBuilder object. */ public TableClientBuilder serviceVersion(TablesServiceVersion version) { this.version = version; return this; } /** * Sets the request retry options for all the requests made through the client. * * @param retryOptions {@link RequestRetryOptions}. * @return the updated TableServiceClientBuilder object * @throws NullPointerException If {@code retryOptions} is {@code null}. */ public TableClientBuilder retryOptions(RequestRetryOptions retryOptions) { this.retryOptions = Objects.requireNonNull(retryOptions, "'retryOptions' cannot be null."); return this; } }
class TableClientBuilder { private final ClientLogger logger = new ClientLogger(TableClientBuilder.class); private final SerializerAdapter serializerAdapter = new TablesJacksonSerializer(); private String tableName; private final List<HttpPipelinePolicy> policies; private Configuration configuration; private TokenCredential tokenCredential; private HttpClient httpClient; private String endpoint; private HttpLogOptions httpLogOptions; private HttpPipeline httpPipeline; private SasTokenCredential sasTokenCredential; private TablesServiceVersion version; private String accountName; private RequestRetryOptions retryOptions = new RequestRetryOptions(); /** * Create a new `TableClientBuilder` */ /** * Sets the connection string to help build the client * * @param connectionString the connection string to the storage account * @return the TableClientBuilder */ public TableClientBuilder connectionString(String connectionString) { StorageConnectionString storageConnectionString = StorageConnectionString.create(connectionString, logger); StorageEndpoint endpoint = storageConnectionString.getTableEndpoint(); 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((TokenCredential) new TablesSharedKeyCredential(authSettings.getAccount().getName(), authSettings.getAccount().getAccessKey())); } else if (authSettings.getType() == StorageAuthenticationSettings.Type.SAS_TOKEN) { this.sasToken(authSettings.getSasToken()); } return this; } /** * Sets the table name to help build the client * * @param tableName name of the table for which the client is created for * @return the TableClientBuilder */ public TableClientBuilder tableName(String tableName) { this.tableName = tableName; return this; } /** * builds a sync tableClient * * @return a sync tableClient */ public TableClient buildClient() { return new TableClient(buildAsyncClient()); } /** * builds an async tableClient * * @return an aysnc tableClient */ public TableAsyncClient buildAsyncClient() { TablesServiceVersion serviceVersion = version != null ? version : TablesServiceVersion.getLatest(); HttpPipeline pipeline = (httpPipeline != null) ? httpPipeline : BuilderHelper.buildPipeline( (TablesSharedKeyCredential) tokenCredential, tokenCredential, sasTokenCredential, endpoint, retryOptions, httpLogOptions, httpClient, policies, configuration, logger); return new TableAsyncClient(tableName, pipeline, endpoint, serviceVersion, serializerAdapter); } /** * Sets the endpoint for the Azure Storage Table instance that the client will interact with. * * @param endpoint The URL of the Azure Storage Table instance to send service requests to and receive responses * from. * @return the updated TableClientBuilder object * @throws IllegalArgumentException If {@code endpoint} isn't a proper URL */ public TableClientBuilder endpoint(String endpoint) { try { new URL(endpoint); } catch (MalformedURLException ex) { throw logger.logExceptionAsWarning(new IllegalArgumentException("'endpoint' must be a valid URL")); } this.endpoint = endpoint; return this; } /** * Sets the HTTP pipeline to use for the service client. * * @param pipeline The HTTP pipeline to use for sending service requests and receiving responses. * @return The updated TableClientBuilder object. */ public TableClientBuilder pipeline(HttpPipeline pipeline) { if (this.httpPipeline != null && pipeline == null) { logger.info("HttpPipeline is being set to 'null' when it was previously configured."); } this.httpPipeline = pipeline; return this; } /** * Sets the SAS token used to authorize requests sent to the service. * * @param sasToken The SAS token to use for authenticating requests. * @return the updated BlobClientBuilder * @throws NullPointerException If {@code sasToken} is {@code null}. */ public TableClientBuilder sasToken(String sasToken) { this.sasTokenCredential = new SasTokenCredential(Objects.requireNonNull(sasToken, "'sasToken' cannot be null.")); this.tokenCredential = null; return this; } /** * Sets the configuration store that is used during construction of the service client. * <p> * The default configuration store is a clone of the {@link Configuration * configuration store}, use {@link Configuration * * @param configuration The configuration store used to * @return The updated TableClientBuilder object. */ public TableClientBuilder configuration(Configuration configuration) { this.configuration = configuration; return this; } /** * Sets the {@link TokenCredential} used to authenticate HTTP requests. * * @param credential TokenCredential used to authenticate HTTP requests. * @return The updated TableClientBuilder object. * @throws NullPointerException If {@code credential} is {@code null}. */ public TableClientBuilder credential(TokenCredential credential) { this.tokenCredential = Objects.requireNonNull(credential, "credential cannot be null."); return this; } /** * Sets the HTTP client to use for sending and receiving requests to and from the service. * * @param client The HTTP client to use for requests. * @return The updated TableClientBuilder object. */ public TableClientBuilder httpClient(HttpClient client) { if (this.httpClient != null && client == null) { logger.error("'httpClient' is being set to 'null' when it was previously configured."); } this.httpClient = client; return this; } /** * Sets the logging configuration for HTTP requests and responses. * * <p> If logLevel is not provided, default value of {@link HttpLogDetailLevel * * @param logOptions The logging configuration to use when sending and receiving HTTP requests/responses. * @return The updated TableClientBuilder object. */ public TableClientBuilder httpLogOptions(HttpLogOptions logOptions) { this.httpLogOptions = Objects.requireNonNull(logOptions, "'logOptions' cannot be null."); return this; } /** * Adds a policy to the set of existing policies that are executed after required policies. * * @param pipelinePolicy The retry policy for service requests. * @return The updated TableClientBuilder object. * @throws NullPointerException If {@code policy} is {@code null}. */ public TableClientBuilder addPolicy(HttpPipelinePolicy pipelinePolicy) { this.policies.add(Objects.requireNonNull(pipelinePolicy, "'pipelinePolicy' cannot be null")); return this; } /** * Sets the {@link TablesServiceVersion} that is used when making API requests. * * @param version {@link TablesServiceVersion} of the service to be used when making requests. * @return The updated TableClientBuilder object. */ public TableClientBuilder serviceVersion(TablesServiceVersion version) { this.version = version; return this; } /** * Sets the request retry options for all the requests made through the client. * * @param retryOptions {@link RequestRetryOptions}. * @return the updated TableServiceClientBuilder object * @throws NullPointerException If {@code retryOptions} is {@code null}. */ public TableClientBuilder retryOptions(RequestRetryOptions retryOptions) { this.retryOptions = Objects.requireNonNull(retryOptions, "'retryOptions' cannot be null."); return this; } }
NIT : This should be `final`
public Mono<StoreResponse> invokeStoreAsync(final Uri addressUri, final RxDocumentServiceRequest request) { checkNotNull(addressUri, "expected non-null address"); checkNotNull(request, "expected non-null request"); this.throwIfClosed(); final URI address = addressUri.getURI(); final RntbdRequestArgs requestArgs = new RntbdRequestArgs(request, address); final RntbdEndpoint endpoint = this.endpointProvider.get(address); final RntbdRequestRecord record = endpoint.request(requestArgs); Context reactorContext = Context.of(KEY_ON_ERROR_DROPPED, onErrorDropHookWithReduceLogLevel); final Mono<StoreResponse> result = Mono.fromFuture(record.whenComplete((response, throwable) -> { record.stage(RntbdRequestRecord.Stage.COMPLETED); if (request.requestContext.cosmosDiagnostics == null) { request.requestContext.cosmosDiagnostics = BridgeInternal.createCosmosDiagnostics(); } if (response != null) { RequestTimeline timeline = record.takeTimelineSnapshot(); response.setRequestTimeline(timeline); } })).onErrorMap(throwable -> { Throwable error = throwable instanceof CompletionException ? throwable.getCause() : throwable; if (!(error instanceof CosmosException)) { String unexpectedError = RntbdObjectMapper.toJson(error); reportIssue(logger, endpoint, "request completed with an unexpected {}: \\{\"record\":{},\"error\":{}}", error.getClass(), record, unexpectedError); error = new GoneException( lenientFormat("an unexpected %s occurred: %s", unexpectedError), address.toString()); } return error; }); return result.doFinally(signalType -> { if (signalType != SignalType.CANCEL) { return; } result.subscribe( response -> { if (logger.isDebugEnabled()) { logger.debug( "received response to cancelled request: {\"request\":{},\"response\":{\"type\":{}," + "\"value\":{}}}}", RntbdObjectMapper.toJson(record), response.getClass().getSimpleName(), RntbdObjectMapper.toJson(response)); } }, throwable -> { if (logger.isDebugEnabled()) { logger.debug( "received response to cancelled request: {\"request\":{},\"response\":{\"type\":{}," + "\"value\":{}}}", RntbdObjectMapper.toJson(record), throwable.getClass().getSimpleName(), RntbdObjectMapper.toJson(throwable)); } }); }).subscriberContext(reactorContext);
Context reactorContext = Context.of(KEY_ON_ERROR_DROPPED, onErrorDropHookWithReduceLogLevel);
public Mono<StoreResponse> invokeStoreAsync(final Uri addressUri, final RxDocumentServiceRequest request) { checkNotNull(addressUri, "expected non-null address"); checkNotNull(request, "expected non-null request"); this.throwIfClosed(); final URI address = addressUri.getURI(); final RntbdRequestArgs requestArgs = new RntbdRequestArgs(request, address); final RntbdEndpoint endpoint = this.endpointProvider.get(address); final RntbdRequestRecord record = endpoint.request(requestArgs); final Context reactorContext = Context.of(KEY_ON_ERROR_DROPPED, onErrorDropHookWithReduceLogLevel); final Mono<StoreResponse> result = Mono.fromFuture(record.whenComplete((response, throwable) -> { record.stage(RntbdRequestRecord.Stage.COMPLETED); if (request.requestContext.cosmosDiagnostics == null) { request.requestContext.cosmosDiagnostics = BridgeInternal.createCosmosDiagnostics(); } if (response != null) { RequestTimeline timeline = record.takeTimelineSnapshot(); response.setRequestTimeline(timeline); } })).onErrorMap(throwable -> { Throwable error = throwable instanceof CompletionException ? throwable.getCause() : throwable; if (!(error instanceof CosmosException)) { String unexpectedError = RntbdObjectMapper.toJson(error); reportIssue(logger, endpoint, "request completed with an unexpected {}: \\{\"record\":{},\"error\":{}}", error.getClass(), record, unexpectedError); error = new GoneException( lenientFormat("an unexpected %s occurred: %s", unexpectedError), address.toString()); } return error; }); return result.doFinally(signalType -> { if (signalType != SignalType.CANCEL) { return; } result.subscribe( response -> { if (logger.isDebugEnabled()) { logger.debug( "received response to cancelled request: {\"request\":{},\"response\":{\"type\":{}," + "\"value\":{}}}}", RntbdObjectMapper.toJson(record), response.getClass().getSimpleName(), RntbdObjectMapper.toJson(response)); } }, throwable -> { if (logger.isDebugEnabled()) { logger.debug( "received response to cancelled request: {\"request\":{},\"response\":{\"type\":{}," + "\"value\":{}}}", RntbdObjectMapper.toJson(record), throwable.getClass().getSimpleName(), RntbdObjectMapper.toJson(throwable)); } }); }
class RntbdTransportClient extends TransportClient { private static final String TAG_NAME = RntbdTransportClient.class.getSimpleName(); private static final AtomicLong instanceCount = new AtomicLong(); private static final Logger logger = LoggerFactory.getLogger(RntbdTransportClient.class); /** * A key that can be used to store a sequence-specific {@link Hooks * hook in a {@link Context}, as a {@link Consumer Consumer&lt;Throwable&gt;}. */ private static final String KEY_ON_ERROR_DROPPED = "reactor.onErrorDropped.local"; /** * This lambda gets injected into the local Reactor Context to react tot he onErrorDropped event and * log the throwable with DEBUG level instead of the ERROR level used in the default hook. * This is safe here because we guarantee resource clean-up with the doFinally-lambda */ private static final Consumer<? super Throwable> onErrorDropHookWithReduceLogLevel = throwable -> { if (logger.isDebugEnabled()) { logger.debug( "Extra error - on error dropped - operator called :", throwable); } }; private final AtomicBoolean closed = new AtomicBoolean(); private final RntbdEndpoint.Provider endpointProvider; private final long id; private final Tag tag; RntbdTransportClient(final RntbdEndpoint.Provider endpointProvider) { this.endpointProvider = endpointProvider; this.id = instanceCount.incrementAndGet(); this.tag = RntbdTransportClient.tag(this.id); } RntbdTransportClient(final Options options, final SslContext sslContext) { this.endpointProvider = new RntbdServiceEndpoint.Provider(this, options, sslContext); this.id = instanceCount.incrementAndGet(); this.tag = RntbdTransportClient.tag(this.id); } RntbdTransportClient(final Configs configs, final ConnectionPolicy connectionPolicy, final UserAgentContainer userAgent) { this(new Options.Builder(connectionPolicy).userAgent(userAgent).build(), configs.getSslContext()); } public boolean isClosed() { return this.closed.get(); } @Override public void close() { if (this.closed.compareAndSet(false, true)) { logger.debug("close {}", this); this.endpointProvider.close(); return; } logger.debug("already closed {}", this); } public int endpointCount() { return this.endpointProvider.count(); } public int endpointEvictionCount() { return this.endpointProvider.evictions(); } public long id() { return this.id; } @Override ).subscriberContext(reactorContext); }
class RntbdTransportClient extends TransportClient { private static final String TAG_NAME = RntbdTransportClient.class.getSimpleName(); private static final AtomicLong instanceCount = new AtomicLong(); private static final Logger logger = LoggerFactory.getLogger(RntbdTransportClient.class); /** * A key that can be used to store a sequence-specific {@link Hooks * hook in a {@link Context}, as a {@link Consumer Consumer&lt;Throwable&gt;}. */ private static final String KEY_ON_ERROR_DROPPED = "reactor.onErrorDropped.local"; /** * This lambda gets injected into the local Reactor Context to react tot he onErrorDropped event and * log the throwable with DEBUG level instead of the ERROR level used in the default hook. * This is safe here because we guarantee resource clean-up with the doFinally-lambda */ private static final Consumer<? super Throwable> onErrorDropHookWithReduceLogLevel = throwable -> { if (logger.isDebugEnabled()) { logger.debug( "Extra error - on error dropped - operator called :", throwable); } }; private final AtomicBoolean closed = new AtomicBoolean(); private final RntbdEndpoint.Provider endpointProvider; private final long id; private final Tag tag; RntbdTransportClient(final RntbdEndpoint.Provider endpointProvider) { this.endpointProvider = endpointProvider; this.id = instanceCount.incrementAndGet(); this.tag = RntbdTransportClient.tag(this.id); } RntbdTransportClient(final Options options, final SslContext sslContext) { this.endpointProvider = new RntbdServiceEndpoint.Provider(this, options, sslContext); this.id = instanceCount.incrementAndGet(); this.tag = RntbdTransportClient.tag(this.id); } RntbdTransportClient(final Configs configs, final ConnectionPolicy connectionPolicy, final UserAgentContainer userAgent) { this(new Options.Builder(connectionPolicy).userAgent(userAgent).build(), configs.getSslContext()); } public boolean isClosed() { return this.closed.get(); } @Override public void close() { if (this.closed.compareAndSet(false, true)) { logger.debug("close {}", this); this.endpointProvider.close(); return; } logger.debug("already closed {}", this); } public int endpointCount() { return this.endpointProvider.count(); } public int endpointEvictionCount() { return this.endpointProvider.evictions(); } public long id() { return this.id; } @Override ).subscriberContext(reactorContext); }
Fixed
public Mono<StoreResponse> invokeStoreAsync(final Uri addressUri, final RxDocumentServiceRequest request) { checkNotNull(addressUri, "expected non-null address"); checkNotNull(request, "expected non-null request"); this.throwIfClosed(); final URI address = addressUri.getURI(); final RntbdRequestArgs requestArgs = new RntbdRequestArgs(request, address); final RntbdEndpoint endpoint = this.endpointProvider.get(address); final RntbdRequestRecord record = endpoint.request(requestArgs); Context reactorContext = Context.of(KEY_ON_ERROR_DROPPED, onErrorDropHookWithReduceLogLevel); final Mono<StoreResponse> result = Mono.fromFuture(record.whenComplete((response, throwable) -> { record.stage(RntbdRequestRecord.Stage.COMPLETED); if (request.requestContext.cosmosDiagnostics == null) { request.requestContext.cosmosDiagnostics = BridgeInternal.createCosmosDiagnostics(); } if (response != null) { RequestTimeline timeline = record.takeTimelineSnapshot(); response.setRequestTimeline(timeline); } })).onErrorMap(throwable -> { Throwable error = throwable instanceof CompletionException ? throwable.getCause() : throwable; if (!(error instanceof CosmosException)) { String unexpectedError = RntbdObjectMapper.toJson(error); reportIssue(logger, endpoint, "request completed with an unexpected {}: \\{\"record\":{},\"error\":{}}", error.getClass(), record, unexpectedError); error = new GoneException( lenientFormat("an unexpected %s occurred: %s", unexpectedError), address.toString()); } return error; }); return result.doFinally(signalType -> { if (signalType != SignalType.CANCEL) { return; } result.subscribe( response -> { if (logger.isDebugEnabled()) { logger.debug( "received response to cancelled request: {\"request\":{},\"response\":{\"type\":{}," + "\"value\":{}}}}", RntbdObjectMapper.toJson(record), response.getClass().getSimpleName(), RntbdObjectMapper.toJson(response)); } }, throwable -> { if (logger.isDebugEnabled()) { logger.debug( "received response to cancelled request: {\"request\":{},\"response\":{\"type\":{}," + "\"value\":{}}}", RntbdObjectMapper.toJson(record), throwable.getClass().getSimpleName(), RntbdObjectMapper.toJson(throwable)); } }); }).subscriberContext(reactorContext);
Context reactorContext = Context.of(KEY_ON_ERROR_DROPPED, onErrorDropHookWithReduceLogLevel);
public Mono<StoreResponse> invokeStoreAsync(final Uri addressUri, final RxDocumentServiceRequest request) { checkNotNull(addressUri, "expected non-null address"); checkNotNull(request, "expected non-null request"); this.throwIfClosed(); final URI address = addressUri.getURI(); final RntbdRequestArgs requestArgs = new RntbdRequestArgs(request, address); final RntbdEndpoint endpoint = this.endpointProvider.get(address); final RntbdRequestRecord record = endpoint.request(requestArgs); final Context reactorContext = Context.of(KEY_ON_ERROR_DROPPED, onErrorDropHookWithReduceLogLevel); final Mono<StoreResponse> result = Mono.fromFuture(record.whenComplete((response, throwable) -> { record.stage(RntbdRequestRecord.Stage.COMPLETED); if (request.requestContext.cosmosDiagnostics == null) { request.requestContext.cosmosDiagnostics = BridgeInternal.createCosmosDiagnostics(); } if (response != null) { RequestTimeline timeline = record.takeTimelineSnapshot(); response.setRequestTimeline(timeline); } })).onErrorMap(throwable -> { Throwable error = throwable instanceof CompletionException ? throwable.getCause() : throwable; if (!(error instanceof CosmosException)) { String unexpectedError = RntbdObjectMapper.toJson(error); reportIssue(logger, endpoint, "request completed with an unexpected {}: \\{\"record\":{},\"error\":{}}", error.getClass(), record, unexpectedError); error = new GoneException( lenientFormat("an unexpected %s occurred: %s", unexpectedError), address.toString()); } return error; }); return result.doFinally(signalType -> { if (signalType != SignalType.CANCEL) { return; } result.subscribe( response -> { if (logger.isDebugEnabled()) { logger.debug( "received response to cancelled request: {\"request\":{},\"response\":{\"type\":{}," + "\"value\":{}}}}", RntbdObjectMapper.toJson(record), response.getClass().getSimpleName(), RntbdObjectMapper.toJson(response)); } }, throwable -> { if (logger.isDebugEnabled()) { logger.debug( "received response to cancelled request: {\"request\":{},\"response\":{\"type\":{}," + "\"value\":{}}}", RntbdObjectMapper.toJson(record), throwable.getClass().getSimpleName(), RntbdObjectMapper.toJson(throwable)); } }); }
class RntbdTransportClient extends TransportClient { private static final String TAG_NAME = RntbdTransportClient.class.getSimpleName(); private static final AtomicLong instanceCount = new AtomicLong(); private static final Logger logger = LoggerFactory.getLogger(RntbdTransportClient.class); /** * A key that can be used to store a sequence-specific {@link Hooks * hook in a {@link Context}, as a {@link Consumer Consumer&lt;Throwable&gt;}. */ private static final String KEY_ON_ERROR_DROPPED = "reactor.onErrorDropped.local"; /** * This lambda gets injected into the local Reactor Context to react tot he onErrorDropped event and * log the throwable with DEBUG level instead of the ERROR level used in the default hook. * This is safe here because we guarantee resource clean-up with the doFinally-lambda */ private static final Consumer<? super Throwable> onErrorDropHookWithReduceLogLevel = throwable -> { if (logger.isDebugEnabled()) { logger.debug( "Extra error - on error dropped - operator called :", throwable); } }; private final AtomicBoolean closed = new AtomicBoolean(); private final RntbdEndpoint.Provider endpointProvider; private final long id; private final Tag tag; RntbdTransportClient(final RntbdEndpoint.Provider endpointProvider) { this.endpointProvider = endpointProvider; this.id = instanceCount.incrementAndGet(); this.tag = RntbdTransportClient.tag(this.id); } RntbdTransportClient(final Options options, final SslContext sslContext) { this.endpointProvider = new RntbdServiceEndpoint.Provider(this, options, sslContext); this.id = instanceCount.incrementAndGet(); this.tag = RntbdTransportClient.tag(this.id); } RntbdTransportClient(final Configs configs, final ConnectionPolicy connectionPolicy, final UserAgentContainer userAgent) { this(new Options.Builder(connectionPolicy).userAgent(userAgent).build(), configs.getSslContext()); } public boolean isClosed() { return this.closed.get(); } @Override public void close() { if (this.closed.compareAndSet(false, true)) { logger.debug("close {}", this); this.endpointProvider.close(); return; } logger.debug("already closed {}", this); } public int endpointCount() { return this.endpointProvider.count(); } public int endpointEvictionCount() { return this.endpointProvider.evictions(); } public long id() { return this.id; } @Override ).subscriberContext(reactorContext); }
class RntbdTransportClient extends TransportClient { private static final String TAG_NAME = RntbdTransportClient.class.getSimpleName(); private static final AtomicLong instanceCount = new AtomicLong(); private static final Logger logger = LoggerFactory.getLogger(RntbdTransportClient.class); /** * A key that can be used to store a sequence-specific {@link Hooks * hook in a {@link Context}, as a {@link Consumer Consumer&lt;Throwable&gt;}. */ private static final String KEY_ON_ERROR_DROPPED = "reactor.onErrorDropped.local"; /** * This lambda gets injected into the local Reactor Context to react tot he onErrorDropped event and * log the throwable with DEBUG level instead of the ERROR level used in the default hook. * This is safe here because we guarantee resource clean-up with the doFinally-lambda */ private static final Consumer<? super Throwable> onErrorDropHookWithReduceLogLevel = throwable -> { if (logger.isDebugEnabled()) { logger.debug( "Extra error - on error dropped - operator called :", throwable); } }; private final AtomicBoolean closed = new AtomicBoolean(); private final RntbdEndpoint.Provider endpointProvider; private final long id; private final Tag tag; RntbdTransportClient(final RntbdEndpoint.Provider endpointProvider) { this.endpointProvider = endpointProvider; this.id = instanceCount.incrementAndGet(); this.tag = RntbdTransportClient.tag(this.id); } RntbdTransportClient(final Options options, final SslContext sslContext) { this.endpointProvider = new RntbdServiceEndpoint.Provider(this, options, sslContext); this.id = instanceCount.incrementAndGet(); this.tag = RntbdTransportClient.tag(this.id); } RntbdTransportClient(final Configs configs, final ConnectionPolicy connectionPolicy, final UserAgentContainer userAgent) { this(new Options.Builder(connectionPolicy).userAgent(userAgent).build(), configs.getSslContext()); } public boolean isClosed() { return this.closed.get(); } @Override public void close() { if (this.closed.compareAndSet(false, true)) { logger.debug("close {}", this); this.endpointProvider.close(); return; } logger.debug("already closed {}", this); } public int endpointCount() { return this.endpointProvider.count(); } public int endpointEvictionCount() { return this.endpointProvider.evictions(); } public long id() { return this.id; } @Override ).subscriberContext(reactorContext); }
Validate that these are not needed in V7.0 SDK.
void unpackAttributes(Map<String, Object> attributes) { this.enabled = (Boolean) attributes.get("enabled"); this.notBefore = epochToOffsetDateTime(attributes.get("nbf")); this.expiresOn = epochToOffsetDateTime(attributes.get("exp")); this.createdOn = epochToOffsetDateTime(attributes.get("created")); this.updatedOn = epochToOffsetDateTime(attributes.get("updated")); this.recoveryLevel = (String) attributes.get("recoveryLevel"); this.recoverableDays = (Integer) attributes.get("recoverableDays"); }
this.recoveryLevel = (String) attributes.get("recoveryLevel");
void unpackAttributes(Map<String, Object> attributes) { this.enabled = (Boolean) attributes.get("enabled"); this.notBefore = epochToOffsetDateTime(attributes.get("nbf")); this.expiresOn = epochToOffsetDateTime(attributes.get("exp")); this.createdOn = epochToOffsetDateTime(attributes.get("created")); this.updatedOn = epochToOffsetDateTime(attributes.get("updated")); this.recoveryLevel = (String) attributes.get("recoveryLevel"); this.recoverableDays = (Integer) attributes.get("recoverableDays"); }
class KeyProperties { /** * Determines whether the object is enabled. */ Boolean enabled; /** * Not before date in UTC. */ OffsetDateTime notBefore; /** * The key version. */ String version; /** * Expiry date in UTC. */ OffsetDateTime expiresOn; /** * Creation time in UTC. */ private OffsetDateTime createdOn; /** * Last updated time in UTC. */ private OffsetDateTime updatedOn; /** * Reflects the deletion recovery level currently in effect for keys in * the current vault. If it contains 'Purgeable', the key can be * permanently deleted by a privileged user; otherwise, only the system can * purge the key, at the end of the retention interval. Possible values * include: 'Purgeable', 'Recoverable+Purgeable', 'Recoverable', * 'Recoverable+ProtectedSubscription'. */ private String recoveryLevel; /** * The key name. */ String name; /** * Key identifier. */ @JsonProperty(value = "kid") String id; /** * Application specific metadata in the form of key-value pairs. */ @JsonProperty(value = "tags") private Map<String, String> tags; /** * True if the key's lifetime is managed by key vault. If this is a key * backing a certificate, then managed will be true. */ @JsonProperty(value = "managed", access = JsonProperty.Access.WRITE_ONLY) private Boolean managed; /** * The number of days a key is retained before being deleted for a soft delete-enabled Key Vault. */ @JsonProperty(value = "recoverableDays", access = JsonProperty.Access.WRITE_ONLY) private Integer recoverableDays; /** * Gets the number of days a key is retained before being deleted for a soft delete-enabled Key Vault. * @return the recoverable days. */ public Integer getRecoverableDays() { return recoverableDays; } /** * Get the recoveryLevel value. * * @return the recoveryLevel value */ public String getRecoveryLevel() { return this.recoveryLevel; } /** * Get the key name. * * @return the name of the key. */ public String getName() { return this.name; } /** * Get the enabled value. * * @return the enabled value */ public Boolean isEnabled() { return this.enabled; } /** * Set the enabled value. * * @param enabled The enabled value to set * @return the updated KeyProperties object itself. */ public KeyProperties setEnabled(Boolean enabled) { this.enabled = enabled; return this; } /** * Get the notBefore UTC time. * * @return the notBefore UTC time. */ public OffsetDateTime getNotBefore() { return notBefore; } /** * Set the {@link OffsetDateTime notBefore} UTC time. * * @param notBefore The notBefore UTC time to set * @return the updated KeyProperties object itself. */ public KeyProperties setNotBefore(OffsetDateTime notBefore) { this.notBefore = notBefore; return this; } /** * Get the Key Expiry time in UTC. * * @return the expires UTC time. */ public OffsetDateTime getExpiresOn() { return this.expiresOn; } /** * Set the {@link OffsetDateTime expires} UTC time. * * @param expiresOn The expiry time to set for the key. * @return the updated KeyProperties object itself. */ public KeyProperties setExpiresOn(OffsetDateTime expiresOn) { this.expiresOn = expiresOn; return this; } /** * Get the the UTC time at which key was created. * * @return the created UTC time. */ public OffsetDateTime getCreatedOn() { return createdOn; } /** * Get the UTC time at which key was last updated. * * @return the last updated UTC time. */ public OffsetDateTime getUpdatedOn() { return updatedOn; } /** * Get the key identifier. * * @return the key identifier. */ public String getId() { return this.id; } /** * Get the tags associated with the key. * * @return the value of the tags. */ public Map<String, String> getTags() { return this.tags; } /** * Set the tags to be associated with the key. * * @param tags The tags to set * @return the updated KeyProperties object itself. */ public KeyProperties setTags(Map<String, String> tags) { this.tags = tags; return this; } /** * Get the managed value. * * @return the managed value */ public Boolean isManaged() { return this.managed; } /** * Get the version of the key. * * @return the version of the key. */ public String getVersion() { return this.version; } /** * Unpacks the attributes JSON response and updates the variables in the Key Attributes object. Uses Lazy Update to * set values for variables id, contentType, and id as these variables are part of main JSON body and not attributes * JSON body when the key response comes from list keys operations. * * @param attributes The key value mapping of the key attributes */ @JsonProperty("attributes") @SuppressWarnings("unchecked") private OffsetDateTime epochToOffsetDateTime(Object epochValue) { if (epochValue != null) { Instant instant = Instant.ofEpochMilli(((Number) epochValue).longValue() * 1000L); return OffsetDateTime.ofInstant(instant, ZoneOffset.UTC); } return null; } Object lazyValueSelection(Object input1, Object input2) { if (input1 == null) { return input2; } return input1; } @JsonProperty(value = "kid") void unpackId(String keyId) { if (keyId != null && keyId.length() > 0) { this.id = keyId; try { URL url = new URL(keyId); String[] tokens = url.getPath().split("/"); this.name = (tokens.length >= 3 ? tokens[2] : null); this.version = (tokens.length >= 4 ? tokens[3] : null); } catch (MalformedURLException e) { e.printStackTrace(); } } } List<KeyOperation> getKeyOperations(List<String> jsonWebKeyOps) { List<KeyOperation> output = new ArrayList<>(); for (String keyOp : jsonWebKeyOps) { output.add(KeyOperation.fromString(keyOp)); } return output; } @SuppressWarnings("unchecked") JsonWebKey createKeyMaterialFromJson(Map<String, Object> key) { JsonWebKey outputKey = new JsonWebKey() .setY(decode((String) key.get("y"))) .setX(decode((String) key.get("x"))) .setCurveName(KeyCurveName.fromString((String) key.get("crv"))) .setKeyOps(getKeyOperations((List<String>) key.get("key_ops"))) .setT(decode((String) key.get("key_hsm"))) .setK(decode((String) key.get("k"))) .setQ(decode((String) key.get("q"))) .setP(decode((String) key.get("p"))) .setQi(decode((String) key.get("qi"))) .setDq(decode((String) key.get("dq"))) .setDp(decode((String) key.get("dp"))) .setD(decode((String) key.get("d"))) .setE(decode((String) key.get("e"))) .setN(decode((String) key.get("n"))) .setKeyType(KeyType.fromString((String) key.get("kty"))) .setId((String) key.get("kid")); unpackId((String) key.get("kid")); return outputKey; } void setManaged(boolean managed) { this.managed = managed; } private byte[] decode(String in) { if (in != null) { return Base64.getUrlDecoder().decode(in); } return null; } }
class KeyProperties { /** * Determines whether the object is enabled. */ Boolean enabled; /** * Not before date in UTC. */ OffsetDateTime notBefore; /** * The key version. */ String version; /** * Expiry date in UTC. */ OffsetDateTime expiresOn; /** * Creation time in UTC. */ private OffsetDateTime createdOn; /** * Last updated time in UTC. */ private OffsetDateTime updatedOn; /** * Reflects the deletion recovery level currently in effect for keys in * the current vault. If it contains 'Purgeable', the key can be * permanently deleted by a privileged user; otherwise, only the system can * purge the key, at the end of the retention interval. Possible values * include: 'Purgeable', 'Recoverable+Purgeable', 'Recoverable', * 'Recoverable+ProtectedSubscription'. */ private String recoveryLevel; /** * The key name. */ String name; /** * Key identifier. */ @JsonProperty(value = "kid") String id; /** * Application specific metadata in the form of key-value pairs. */ @JsonProperty(value = "tags") private Map<String, String> tags; /** * True if the key's lifetime is managed by key vault. If this is a key * backing a certificate, then managed will be true. */ @JsonProperty(value = "managed", access = JsonProperty.Access.WRITE_ONLY) private Boolean managed; /** * The number of days a key is retained before being deleted for a soft delete-enabled Key Vault. */ @JsonProperty(value = "recoverableDays", access = JsonProperty.Access.WRITE_ONLY) private Integer recoverableDays; /** * Gets the number of days a key is retained before being deleted for a soft delete-enabled Key Vault. * @return the recoverable days. */ public Integer getRecoverableDays() { return recoverableDays; } /** * Get the recoveryLevel value. * * @return the recoveryLevel value */ public String getRecoveryLevel() { return this.recoveryLevel; } /** * Get the key name. * * @return the name of the key. */ public String getName() { return this.name; } /** * Get the enabled value. * * @return the enabled value */ public Boolean isEnabled() { return this.enabled; } /** * Set the enabled value. * * @param enabled The enabled value to set * @return the updated KeyProperties object itself. */ public KeyProperties setEnabled(Boolean enabled) { this.enabled = enabled; return this; } /** * Get the notBefore UTC time. * * @return the notBefore UTC time. */ public OffsetDateTime getNotBefore() { return notBefore; } /** * Set the {@link OffsetDateTime notBefore} UTC time. * * @param notBefore The notBefore UTC time to set * @return the updated KeyProperties object itself. */ public KeyProperties setNotBefore(OffsetDateTime notBefore) { this.notBefore = notBefore; return this; } /** * Get the Key Expiry time in UTC. * * @return the expires UTC time. */ public OffsetDateTime getExpiresOn() { return this.expiresOn; } /** * Set the {@link OffsetDateTime expires} UTC time. * * @param expiresOn The expiry time to set for the key. * @return the updated KeyProperties object itself. */ public KeyProperties setExpiresOn(OffsetDateTime expiresOn) { this.expiresOn = expiresOn; return this; } /** * Get the the UTC time at which key was created. * * @return the created UTC time. */ public OffsetDateTime getCreatedOn() { return createdOn; } /** * Get the UTC time at which key was last updated. * * @return the last updated UTC time. */ public OffsetDateTime getUpdatedOn() { return updatedOn; } /** * Get the key identifier. * * @return the key identifier. */ public String getId() { return this.id; } /** * Get the tags associated with the key. * * @return the value of the tags. */ public Map<String, String> getTags() { return this.tags; } /** * Set the tags to be associated with the key. * * @param tags The tags to set * @return the updated KeyProperties object itself. */ public KeyProperties setTags(Map<String, String> tags) { this.tags = tags; return this; } /** * Get the managed value. * * @return the managed value */ public Boolean isManaged() { return this.managed; } /** * Get the version of the key. * * @return the version of the key. */ public String getVersion() { return this.version; } /** * Unpacks the attributes JSON response and updates the variables in the Key Attributes object. Uses Lazy Update to * set values for variables id, contentType, and id as these variables are part of main JSON body and not attributes * JSON body when the key response comes from list keys operations. * * @param attributes The key value mapping of the key attributes */ @JsonProperty("attributes") @SuppressWarnings("unchecked") private OffsetDateTime epochToOffsetDateTime(Object epochValue) { if (epochValue != null) { Instant instant = Instant.ofEpochMilli(((Number) epochValue).longValue() * 1000L); return OffsetDateTime.ofInstant(instant, ZoneOffset.UTC); } return null; } Object lazyValueSelection(Object input1, Object input2) { if (input1 == null) { return input2; } return input1; } @JsonProperty(value = "kid") void unpackId(String keyId) { if (keyId != null && keyId.length() > 0) { this.id = keyId; try { URL url = new URL(keyId); String[] tokens = url.getPath().split("/"); this.name = (tokens.length >= 3 ? tokens[2] : null); this.version = (tokens.length >= 4 ? tokens[3] : null); } catch (MalformedURLException e) { e.printStackTrace(); } } } List<KeyOperation> getKeyOperations(List<String> jsonWebKeyOps) { List<KeyOperation> output = new ArrayList<>(); for (String keyOp : jsonWebKeyOps) { output.add(KeyOperation.fromString(keyOp)); } return output; } @SuppressWarnings("unchecked") JsonWebKey createKeyMaterialFromJson(Map<String, Object> key) { JsonWebKey outputKey = new JsonWebKey() .setY(decode((String) key.get("y"))) .setX(decode((String) key.get("x"))) .setCurveName(KeyCurveName.fromString((String) key.get("crv"))) .setKeyOps(getKeyOperations((List<String>) key.get("key_ops"))) .setT(decode((String) key.get("key_hsm"))) .setK(decode((String) key.get("k"))) .setQ(decode((String) key.get("q"))) .setP(decode((String) key.get("p"))) .setQi(decode((String) key.get("qi"))) .setDq(decode((String) key.get("dq"))) .setDp(decode((String) key.get("dp"))) .setD(decode((String) key.get("d"))) .setE(decode((String) key.get("e"))) .setN(decode((String) key.get("n"))) .setKeyType(KeyType.fromString((String) key.get("kty"))) .setId((String) key.get("kid")); unpackId((String) key.get("kid")); return outputKey; } void setManaged(boolean managed) { this.managed = managed; } private byte[] decode(String in) { if (in != null) { return Base64.getUrlDecoder().decode(in); } return null; } }
`tags` are only a part of the `KeyBundle` object definition (mapped to the `KeyVaultKey` model) in the Swagger for service version 7.0, they are not included in `KeyAttributes` (mapped to the `KeyProperties` model).
void unpackAttributes(Map<String, Object> attributes) { this.enabled = (Boolean) attributes.get("enabled"); this.notBefore = epochToOffsetDateTime(attributes.get("nbf")); this.expiresOn = epochToOffsetDateTime(attributes.get("exp")); this.createdOn = epochToOffsetDateTime(attributes.get("created")); this.updatedOn = epochToOffsetDateTime(attributes.get("updated")); this.recoveryLevel = (String) attributes.get("recoveryLevel"); this.recoverableDays = (Integer) attributes.get("recoverableDays"); }
this.recoveryLevel = (String) attributes.get("recoveryLevel");
void unpackAttributes(Map<String, Object> attributes) { this.enabled = (Boolean) attributes.get("enabled"); this.notBefore = epochToOffsetDateTime(attributes.get("nbf")); this.expiresOn = epochToOffsetDateTime(attributes.get("exp")); this.createdOn = epochToOffsetDateTime(attributes.get("created")); this.updatedOn = epochToOffsetDateTime(attributes.get("updated")); this.recoveryLevel = (String) attributes.get("recoveryLevel"); this.recoverableDays = (Integer) attributes.get("recoverableDays"); }
class KeyProperties { /** * Determines whether the object is enabled. */ Boolean enabled; /** * Not before date in UTC. */ OffsetDateTime notBefore; /** * The key version. */ String version; /** * Expiry date in UTC. */ OffsetDateTime expiresOn; /** * Creation time in UTC. */ private OffsetDateTime createdOn; /** * Last updated time in UTC. */ private OffsetDateTime updatedOn; /** * Reflects the deletion recovery level currently in effect for keys in * the current vault. If it contains 'Purgeable', the key can be * permanently deleted by a privileged user; otherwise, only the system can * purge the key, at the end of the retention interval. Possible values * include: 'Purgeable', 'Recoverable+Purgeable', 'Recoverable', * 'Recoverable+ProtectedSubscription'. */ private String recoveryLevel; /** * The key name. */ String name; /** * Key identifier. */ @JsonProperty(value = "kid") String id; /** * Application specific metadata in the form of key-value pairs. */ @JsonProperty(value = "tags") private Map<String, String> tags; /** * True if the key's lifetime is managed by key vault. If this is a key * backing a certificate, then managed will be true. */ @JsonProperty(value = "managed", access = JsonProperty.Access.WRITE_ONLY) private Boolean managed; /** * The number of days a key is retained before being deleted for a soft delete-enabled Key Vault. */ @JsonProperty(value = "recoverableDays", access = JsonProperty.Access.WRITE_ONLY) private Integer recoverableDays; /** * Gets the number of days a key is retained before being deleted for a soft delete-enabled Key Vault. * @return the recoverable days. */ public Integer getRecoverableDays() { return recoverableDays; } /** * Get the recoveryLevel value. * * @return the recoveryLevel value */ public String getRecoveryLevel() { return this.recoveryLevel; } /** * Get the key name. * * @return the name of the key. */ public String getName() { return this.name; } /** * Get the enabled value. * * @return the enabled value */ public Boolean isEnabled() { return this.enabled; } /** * Set the enabled value. * * @param enabled The enabled value to set * @return the updated KeyProperties object itself. */ public KeyProperties setEnabled(Boolean enabled) { this.enabled = enabled; return this; } /** * Get the notBefore UTC time. * * @return the notBefore UTC time. */ public OffsetDateTime getNotBefore() { return notBefore; } /** * Set the {@link OffsetDateTime notBefore} UTC time. * * @param notBefore The notBefore UTC time to set * @return the updated KeyProperties object itself. */ public KeyProperties setNotBefore(OffsetDateTime notBefore) { this.notBefore = notBefore; return this; } /** * Get the Key Expiry time in UTC. * * @return the expires UTC time. */ public OffsetDateTime getExpiresOn() { return this.expiresOn; } /** * Set the {@link OffsetDateTime expires} UTC time. * * @param expiresOn The expiry time to set for the key. * @return the updated KeyProperties object itself. */ public KeyProperties setExpiresOn(OffsetDateTime expiresOn) { this.expiresOn = expiresOn; return this; } /** * Get the the UTC time at which key was created. * * @return the created UTC time. */ public OffsetDateTime getCreatedOn() { return createdOn; } /** * Get the UTC time at which key was last updated. * * @return the last updated UTC time. */ public OffsetDateTime getUpdatedOn() { return updatedOn; } /** * Get the key identifier. * * @return the key identifier. */ public String getId() { return this.id; } /** * Get the tags associated with the key. * * @return the value of the tags. */ public Map<String, String> getTags() { return this.tags; } /** * Set the tags to be associated with the key. * * @param tags The tags to set * @return the updated KeyProperties object itself. */ public KeyProperties setTags(Map<String, String> tags) { this.tags = tags; return this; } /** * Get the managed value. * * @return the managed value */ public Boolean isManaged() { return this.managed; } /** * Get the version of the key. * * @return the version of the key. */ public String getVersion() { return this.version; } /** * Unpacks the attributes JSON response and updates the variables in the Key Attributes object. Uses Lazy Update to * set values for variables id, contentType, and id as these variables are part of main JSON body and not attributes * JSON body when the key response comes from list keys operations. * * @param attributes The key value mapping of the key attributes */ @JsonProperty("attributes") @SuppressWarnings("unchecked") private OffsetDateTime epochToOffsetDateTime(Object epochValue) { if (epochValue != null) { Instant instant = Instant.ofEpochMilli(((Number) epochValue).longValue() * 1000L); return OffsetDateTime.ofInstant(instant, ZoneOffset.UTC); } return null; } Object lazyValueSelection(Object input1, Object input2) { if (input1 == null) { return input2; } return input1; } @JsonProperty(value = "kid") void unpackId(String keyId) { if (keyId != null && keyId.length() > 0) { this.id = keyId; try { URL url = new URL(keyId); String[] tokens = url.getPath().split("/"); this.name = (tokens.length >= 3 ? tokens[2] : null); this.version = (tokens.length >= 4 ? tokens[3] : null); } catch (MalformedURLException e) { e.printStackTrace(); } } } List<KeyOperation> getKeyOperations(List<String> jsonWebKeyOps) { List<KeyOperation> output = new ArrayList<>(); for (String keyOp : jsonWebKeyOps) { output.add(KeyOperation.fromString(keyOp)); } return output; } @SuppressWarnings("unchecked") JsonWebKey createKeyMaterialFromJson(Map<String, Object> key) { JsonWebKey outputKey = new JsonWebKey() .setY(decode((String) key.get("y"))) .setX(decode((String) key.get("x"))) .setCurveName(KeyCurveName.fromString((String) key.get("crv"))) .setKeyOps(getKeyOperations((List<String>) key.get("key_ops"))) .setT(decode((String) key.get("key_hsm"))) .setK(decode((String) key.get("k"))) .setQ(decode((String) key.get("q"))) .setP(decode((String) key.get("p"))) .setQi(decode((String) key.get("qi"))) .setDq(decode((String) key.get("dq"))) .setDp(decode((String) key.get("dp"))) .setD(decode((String) key.get("d"))) .setE(decode((String) key.get("e"))) .setN(decode((String) key.get("n"))) .setKeyType(KeyType.fromString((String) key.get("kty"))) .setId((String) key.get("kid")); unpackId((String) key.get("kid")); return outputKey; } void setManaged(boolean managed) { this.managed = managed; } private byte[] decode(String in) { if (in != null) { return Base64.getUrlDecoder().decode(in); } return null; } }
class KeyProperties { /** * Determines whether the object is enabled. */ Boolean enabled; /** * Not before date in UTC. */ OffsetDateTime notBefore; /** * The key version. */ String version; /** * Expiry date in UTC. */ OffsetDateTime expiresOn; /** * Creation time in UTC. */ private OffsetDateTime createdOn; /** * Last updated time in UTC. */ private OffsetDateTime updatedOn; /** * Reflects the deletion recovery level currently in effect for keys in * the current vault. If it contains 'Purgeable', the key can be * permanently deleted by a privileged user; otherwise, only the system can * purge the key, at the end of the retention interval. Possible values * include: 'Purgeable', 'Recoverable+Purgeable', 'Recoverable', * 'Recoverable+ProtectedSubscription'. */ private String recoveryLevel; /** * The key name. */ String name; /** * Key identifier. */ @JsonProperty(value = "kid") String id; /** * Application specific metadata in the form of key-value pairs. */ @JsonProperty(value = "tags") private Map<String, String> tags; /** * True if the key's lifetime is managed by key vault. If this is a key * backing a certificate, then managed will be true. */ @JsonProperty(value = "managed", access = JsonProperty.Access.WRITE_ONLY) private Boolean managed; /** * The number of days a key is retained before being deleted for a soft delete-enabled Key Vault. */ @JsonProperty(value = "recoverableDays", access = JsonProperty.Access.WRITE_ONLY) private Integer recoverableDays; /** * Gets the number of days a key is retained before being deleted for a soft delete-enabled Key Vault. * @return the recoverable days. */ public Integer getRecoverableDays() { return recoverableDays; } /** * Get the recoveryLevel value. * * @return the recoveryLevel value */ public String getRecoveryLevel() { return this.recoveryLevel; } /** * Get the key name. * * @return the name of the key. */ public String getName() { return this.name; } /** * Get the enabled value. * * @return the enabled value */ public Boolean isEnabled() { return this.enabled; } /** * Set the enabled value. * * @param enabled The enabled value to set * @return the updated KeyProperties object itself. */ public KeyProperties setEnabled(Boolean enabled) { this.enabled = enabled; return this; } /** * Get the notBefore UTC time. * * @return the notBefore UTC time. */ public OffsetDateTime getNotBefore() { return notBefore; } /** * Set the {@link OffsetDateTime notBefore} UTC time. * * @param notBefore The notBefore UTC time to set * @return the updated KeyProperties object itself. */ public KeyProperties setNotBefore(OffsetDateTime notBefore) { this.notBefore = notBefore; return this; } /** * Get the Key Expiry time in UTC. * * @return the expires UTC time. */ public OffsetDateTime getExpiresOn() { return this.expiresOn; } /** * Set the {@link OffsetDateTime expires} UTC time. * * @param expiresOn The expiry time to set for the key. * @return the updated KeyProperties object itself. */ public KeyProperties setExpiresOn(OffsetDateTime expiresOn) { this.expiresOn = expiresOn; return this; } /** * Get the the UTC time at which key was created. * * @return the created UTC time. */ public OffsetDateTime getCreatedOn() { return createdOn; } /** * Get the UTC time at which key was last updated. * * @return the last updated UTC time. */ public OffsetDateTime getUpdatedOn() { return updatedOn; } /** * Get the key identifier. * * @return the key identifier. */ public String getId() { return this.id; } /** * Get the tags associated with the key. * * @return the value of the tags. */ public Map<String, String> getTags() { return this.tags; } /** * Set the tags to be associated with the key. * * @param tags The tags to set * @return the updated KeyProperties object itself. */ public KeyProperties setTags(Map<String, String> tags) { this.tags = tags; return this; } /** * Get the managed value. * * @return the managed value */ public Boolean isManaged() { return this.managed; } /** * Get the version of the key. * * @return the version of the key. */ public String getVersion() { return this.version; } /** * Unpacks the attributes JSON response and updates the variables in the Key Attributes object. Uses Lazy Update to * set values for variables id, contentType, and id as these variables are part of main JSON body and not attributes * JSON body when the key response comes from list keys operations. * * @param attributes The key value mapping of the key attributes */ @JsonProperty("attributes") @SuppressWarnings("unchecked") private OffsetDateTime epochToOffsetDateTime(Object epochValue) { if (epochValue != null) { Instant instant = Instant.ofEpochMilli(((Number) epochValue).longValue() * 1000L); return OffsetDateTime.ofInstant(instant, ZoneOffset.UTC); } return null; } Object lazyValueSelection(Object input1, Object input2) { if (input1 == null) { return input2; } return input1; } @JsonProperty(value = "kid") void unpackId(String keyId) { if (keyId != null && keyId.length() > 0) { this.id = keyId; try { URL url = new URL(keyId); String[] tokens = url.getPath().split("/"); this.name = (tokens.length >= 3 ? tokens[2] : null); this.version = (tokens.length >= 4 ? tokens[3] : null); } catch (MalformedURLException e) { e.printStackTrace(); } } } List<KeyOperation> getKeyOperations(List<String> jsonWebKeyOps) { List<KeyOperation> output = new ArrayList<>(); for (String keyOp : jsonWebKeyOps) { output.add(KeyOperation.fromString(keyOp)); } return output; } @SuppressWarnings("unchecked") JsonWebKey createKeyMaterialFromJson(Map<String, Object> key) { JsonWebKey outputKey = new JsonWebKey() .setY(decode((String) key.get("y"))) .setX(decode((String) key.get("x"))) .setCurveName(KeyCurveName.fromString((String) key.get("crv"))) .setKeyOps(getKeyOperations((List<String>) key.get("key_ops"))) .setT(decode((String) key.get("key_hsm"))) .setK(decode((String) key.get("k"))) .setQ(decode((String) key.get("q"))) .setP(decode((String) key.get("p"))) .setQi(decode((String) key.get("qi"))) .setDq(decode((String) key.get("dq"))) .setDp(decode((String) key.get("dp"))) .setD(decode((String) key.get("d"))) .setE(decode((String) key.get("e"))) .setN(decode((String) key.get("n"))) .setKeyType(KeyType.fromString((String) key.get("kty"))) .setId((String) key.get("kid")); unpackId((String) key.get("kid")); return outputKey; } void setManaged(boolean managed) { this.managed = managed; } private byte[] decode(String in) { if (in != null) { return Base64.getUrlDecoder().decode(in); } return null; } }
It looks there is already existing `StorageAccountSkuType.STANDARD_GRS`.
public Mono<FunctionApp> createAsync() { if (this.isInCreateMode()) { if (inner().serverFarmId() == null) { withNewConsumptionPlan(); } if (currentStorageAccount == null && storageAccountToSet == null && storageAccountCreatable == null) { withNewStorageAccount( this.manager().sdkContext().randomResourceName(name(), 20), StorageAccountSkuType.fromSkuName(com.azure.resourcemanager.storage.models.SkuName.STANDARD_GRS)); } } return super.createAsync(); }
StorageAccountSkuType.fromSkuName(com.azure.resourcemanager.storage.models.SkuName.STANDARD_GRS));
public Mono<FunctionApp> createAsync() { if (this.isInCreateMode()) { if (inner().serverFarmId() == null) { withNewConsumptionPlan(); } if (currentStorageAccount == null && storageAccountToSet == null && storageAccountCreatable == null) { withNewStorageAccount( this.manager().sdkContext().randomResourceName(name(), 20), StorageAccountSkuType.STANDARD_GRS); } } return super.createAsync(); }
class FunctionAppImpl extends AppServiceBaseImpl< FunctionApp, FunctionAppImpl, FunctionApp.DefinitionStages.WithCreate, FunctionApp.Update> implements FunctionApp, FunctionApp.Definition, FunctionApp.DefinitionStages.NewAppServicePlanWithGroup, FunctionApp.DefinitionStages.ExistingLinuxPlanWithGroup, FunctionApp.Update { private final ClientLogger logger = new ClientLogger(getClass()); private static final String SETTING_FUNCTIONS_WORKER_RUNTIME = "FUNCTIONS_WORKER_RUNTIME"; private static final String SETTING_FUNCTIONS_EXTENSION_VERSION = "FUNCTIONS_EXTENSION_VERSION"; 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 final FunctionAppKeyService functionAppKeyService; private FunctionService functionService; private FunctionDeploymentSlots deploymentSlots; private String functionAppKeyServiceHost; private String functionServiceHost; FunctionAppImpl( final String name, SiteInner innerObject, SiteConfigResourceInner siteConfig, SiteLogsConfigInner logConfig, AppServiceManager manager) { super(name, innerObject, siteConfig, logConfig, manager); functionAppKeyServiceHost = manager.environment().getResourceManagerEndpoint(); functionAppKeyService = RestProxy.create(FunctionAppKeyService.class, manager.httpPipeline()); 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, new AzureJacksonAdapter()); } } @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<Indexable> submitAppSettings() { if (storageAccountCreatable != null && this.taskResult(storageAccountCreatable.key()) != null) { storageAccountToSet = this.taskResult(storageAccountCreatable.key()); } if (storageAccountToSet == null) { return super.submitAppSettings(); } else { return Flux .concat( storageAccountToSet .getKeysAsync() .map(storageAccountKeys -> storageAccountKeys.get(0)) .zipWith( this.manager().appServicePlans().getByIdAsync(this.appServicePlanId()), (StorageAccountKey storageAccountKey, AppServicePlan appServicePlan) -> { String connectionString = com.azure.resourcemanager.resources.fluentcore.utils.Utils .getStorageConnectionString(storageAccountToSet.name(), storageAccountKey.value(), manager().environment()); addAppSettingIfNotModified(SETTING_WEB_JOBS_STORAGE, connectionString); addAppSettingIfNotModified(SETTING_WEB_JOBS_DASHBOARD, connectionString); if (OperatingSystem.WINDOWS.equals(operatingSystem()) && (appServicePlan == null || isConsumptionOrPremiumAppServicePlan(appServicePlan.pricingTier()))) { addAppSettingIfNotModified( SETTING_WEBSITE_CONTENTAZUREFILECONNECTIONSTRING, connectionString); addAppSettingIfNotModified( SETTING_WEBSITE_CONTENTSHARE, this.manager().sdkContext().randomResourceName(name(), 32)); } return FunctionAppImpl.super.submitAppSettings(); })) .last() .then( Mono .fromCallable( () -> { currentStorageAccount = storageAccountToSet; storageAccountToSet = null; storageAccountCreatable = null; return this; })); } } @Override public OperatingSystem operatingSystem() { return (inner().reserved() == null || !inner().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.BASIC.toString()) || description.tier().equalsIgnoreCase(SkuName.STANDARD.toString()) || description.tier().equalsIgnoreCase(SkuName.PREMIUM.toString()) || description.tier().equalsIgnoreCase(SkuName.PREMIUM_V2.toString())) { return withWebAppAlwaysOn(true); } else { return withWebAppAlwaysOn(false); } } @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).withGeneralPurposeAccountKind().withSku(sku); } else { storageAccountCreatable = storageDefine .withExistingResourceGroup(resourceGroupName()) .withGeneralPurposeAccountKind() .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) { inner().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(); return super.withPrivateRegistryImage(imageAndTag, serverUrl); } @Override protected void cleanUpContainerSettings() { if (siteConfig != null && siteConfig.linuxFxVersion() != null) { siteConfig.withLinuxFxVersion(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.inner().reserved() == null || !appServicePlan.inner().reserved()) ? OperatingSystem.WINDOWS : OperatingSystem.LINUX; } @Override public StorageAccount storageAccount() { return currentStorageAccount; } @Override public String getMasterKey() { return getMasterKeyAsync().block(); } @Override public Mono<String> getMasterKeyAsync() { return FluxUtil .withContext( context -> functionAppKeyService .listKeys( functionAppKeyServiceHost, resourceGroupName(), name(), manager().subscriptionId(), "2019-08-01")) .map(ListKeysResult::getMasterKey) .subscriberContext( context -> context.putAll(FluxUtil.toReactorContext(this.manager().inner().getContext()))); } @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() .inner() .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 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) { return kuduClient.zipDeployAsync(zipFile); } @Override public void zipDeploy(InputStream zipFile) { zipDeployAsync(zipFile).block(); } @Override @Override public Mono<Void> afterPostRunAsync(final boolean isGroupFaulted) { if (!isGroupFaulted) { initializeFunctionService(); } return super.afterPostRunAsync(isGroupFaulted); } private static class ListKeysResult { @JsonProperty("masterKey") private String masterKey; @JsonProperty("functionKeys") private Map<String, String> functionKeys; @JsonProperty("systemKeys") private Map<String, String> systemKeys; public String getMasterKey() { return masterKey; } } @Host("{$host}") @ServiceInterface(name = "FunctionAppKeyService") private interface FunctionAppKeyService { @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.appservice.WebApps listKeys" }) @Post( "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Web/sites/{name}" + "/host/default/listkeys") Mono<ListKeysResult> listKeys( @HostParam("$host") String host, @PathParam("resourceGroupName") String resourceGroupName, @PathParam("name") String name, @PathParam("subscriptionId") String subscriptionId, @QueryParam("api-version") String apiVersion); } @Host("{$host}") @ServiceInterface(name = "FunctionService") private interface FunctionService { @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.appservice.WebApps listFunctionKeys" }) @Get("admin/functions/{name}/keys") Mono<FunctionKeyListResult> listFunctionKeys( @HostParam("$host") String host, @PathParam("name") String functionName); @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.appservice.WebApps addFunctionKey" }) @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({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.appservice.WebApps generateFunctionKey" }) @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", "x-ms-logging-context: com.microsoft.azure.management.appservice.WebApps deleteFunctionKey" }) @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", "x-ms-logging-context: com.microsoft.azure.management.appservice.WebApps ping" }) @Post("admin/host/ping") Mono<Void> ping(@HostParam("$host") String host); @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.appservice.WebApps getHostStatus" }) @Get("admin/host/status") Mono<Void> getHostStatus(@HostParam("$host") String host); @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.appservice.WebApps triggerFunction" }) @Post("admin/functions/{name}") Mono<Void> triggerFunction( @HostParam("$host") String host, @PathParam("name") String functionName, @BodyParam("application/json") Object payload); } private static class FunctionKeyListResult { @JsonProperty("keys") private List<NameValuePair> keys; } /* private static final class FunctionCredential implements TokenCredential { private final FunctionAppImpl functionApp; private FunctionCredential(FunctionAppImpl functionApp) { this.functionApp = functionApp; } @Override public Mono<AccessToken> getToken(TokenRequestContext request) { return functionApp.manager().inner().getWebApps() .getFunctionsAdminTokenAsync(functionApp.resourceGroupName(), functionApp.name()) .map(token -> { String jwt = new String(Base64.getUrlDecoder().decode(token.split("\\.")[1])); Pattern pattern = Pattern.compile("\"exp\": *([0-9]+),"); Matcher matcher = pattern.matcher(jwt); matcher.find(); long expire = Long.parseLong(matcher.group(1)); return new AccessToken(token, OffsetDateTime.ofInstant( Instant.ofEpochMilli(expire), ZoneOffset.UTC)); }); } } */ }
class FunctionAppImpl extends AppServiceBaseImpl< FunctionApp, FunctionAppImpl, FunctionApp.DefinitionStages.WithCreate, FunctionApp.Update> implements FunctionApp, FunctionApp.Definition, FunctionApp.DefinitionStages.NewAppServicePlanWithGroup, FunctionApp.DefinitionStages.ExistingLinuxPlanWithGroup, FunctionApp.Update { private final ClientLogger logger = new ClientLogger(getClass()); private static final String SETTING_FUNCTIONS_WORKER_RUNTIME = "FUNCTIONS_WORKER_RUNTIME"; private static final String SETTING_FUNCTIONS_EXTENSION_VERSION = "FUNCTIONS_EXTENSION_VERSION"; 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 final FunctionAppKeyService functionAppKeyService; private FunctionService functionService; private FunctionDeploymentSlots deploymentSlots; private String functionAppKeyServiceHost; private String functionServiceHost; FunctionAppImpl( final String name, SiteInner innerObject, SiteConfigResourceInner siteConfig, SiteLogsConfigInner logConfig, AppServiceManager manager) { super(name, innerObject, siteConfig, logConfig, manager); functionAppKeyServiceHost = manager.environment().getResourceManagerEndpoint(); functionAppKeyService = RestProxy.create(FunctionAppKeyService.class, manager.httpPipeline()); 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, new AzureJacksonAdapter()); } } @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<Indexable> submitAppSettings() { if (storageAccountCreatable != null && this.taskResult(storageAccountCreatable.key()) != null) { storageAccountToSet = this.taskResult(storageAccountCreatable.key()); } if (storageAccountToSet == null) { return super.submitAppSettings(); } else { return Flux .concat( storageAccountToSet .getKeysAsync() .map(storageAccountKeys -> storageAccountKeys.get(0)) .zipWith( this.manager().appServicePlans().getByIdAsync(this.appServicePlanId()), (StorageAccountKey storageAccountKey, AppServicePlan appServicePlan) -> { String connectionString = com.azure.resourcemanager.resources.fluentcore.utils.Utils .getStorageConnectionString(storageAccountToSet.name(), storageAccountKey.value(), manager().environment()); addAppSettingIfNotModified(SETTING_WEB_JOBS_STORAGE, connectionString); addAppSettingIfNotModified(SETTING_WEB_JOBS_DASHBOARD, connectionString); if (OperatingSystem.WINDOWS.equals(operatingSystem()) && (appServicePlan == null || isConsumptionOrPremiumAppServicePlan(appServicePlan.pricingTier()))) { addAppSettingIfNotModified( SETTING_WEBSITE_CONTENTAZUREFILECONNECTIONSTRING, connectionString); addAppSettingIfNotModified( SETTING_WEBSITE_CONTENTSHARE, this.manager().sdkContext().randomResourceName(name(), 32)); } return FunctionAppImpl.super.submitAppSettings(); })) .last() .then( Mono .fromCallable( () -> { currentStorageAccount = storageAccountToSet; storageAccountToSet = null; storageAccountCreatable = null; return this; })); } } @Override public OperatingSystem operatingSystem() { return (inner().reserved() == null || !inner().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.BASIC.toString()) || description.tier().equalsIgnoreCase(SkuName.STANDARD.toString()) || description.tier().equalsIgnoreCase(SkuName.PREMIUM.toString()) || description.tier().equalsIgnoreCase(SkuName.PREMIUM_V2.toString())) { return withWebAppAlwaysOn(true); } else { return withWebAppAlwaysOn(false); } } @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).withGeneralPurposeAccountKind().withSku(sku); } else { storageAccountCreatable = storageDefine .withExistingResourceGroup(resourceGroupName()) .withGeneralPurposeAccountKind() .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) { inner().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(); return super.withPrivateRegistryImage(imageAndTag, serverUrl); } @Override protected void cleanUpContainerSettings() { if (siteConfig != null && siteConfig.linuxFxVersion() != null) { siteConfig.withLinuxFxVersion(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.inner().reserved() == null || !appServicePlan.inner().reserved()) ? OperatingSystem.WINDOWS : OperatingSystem.LINUX; } @Override public StorageAccount storageAccount() { return currentStorageAccount; } @Override public String getMasterKey() { return getMasterKeyAsync().block(); } @Override public Mono<String> getMasterKeyAsync() { return FluxUtil .withContext( context -> functionAppKeyService .listKeys( functionAppKeyServiceHost, resourceGroupName(), name(), manager().subscriptionId(), "2019-08-01")) .map(ListKeysResult::getMasterKey) .subscriberContext( context -> context.putAll(FluxUtil.toReactorContext(this.manager().inner().getContext()))); } @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() .inner() .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 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) { return kuduClient.zipDeployAsync(zipFile); } @Override public void zipDeploy(InputStream zipFile) { zipDeployAsync(zipFile).block(); } @Override @Override public Mono<Void> afterPostRunAsync(final boolean isGroupFaulted) { if (!isGroupFaulted) { initializeFunctionService(); } return super.afterPostRunAsync(isGroupFaulted); } private static class ListKeysResult { @JsonProperty("masterKey") private String masterKey; @JsonProperty("functionKeys") private Map<String, String> functionKeys; @JsonProperty("systemKeys") private Map<String, String> systemKeys; public String getMasterKey() { return masterKey; } } @Host("{$host}") @ServiceInterface(name = "FunctionAppKeyService") private interface FunctionAppKeyService { @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.appservice.WebApps listKeys" }) @Post( "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Web/sites/{name}" + "/host/default/listkeys") Mono<ListKeysResult> listKeys( @HostParam("$host") String host, @PathParam("resourceGroupName") String resourceGroupName, @PathParam("name") String name, @PathParam("subscriptionId") String subscriptionId, @QueryParam("api-version") String apiVersion); } @Host("{$host}") @ServiceInterface(name = "FunctionService") private interface FunctionService { @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.appservice.WebApps listFunctionKeys" }) @Get("admin/functions/{name}/keys") Mono<FunctionKeyListResult> listFunctionKeys( @HostParam("$host") String host, @PathParam("name") String functionName); @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.appservice.WebApps addFunctionKey" }) @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({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.appservice.WebApps generateFunctionKey" }) @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", "x-ms-logging-context: com.microsoft.azure.management.appservice.WebApps deleteFunctionKey" }) @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", "x-ms-logging-context: com.microsoft.azure.management.appservice.WebApps ping" }) @Post("admin/host/ping") Mono<Void> ping(@HostParam("$host") String host); @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.appservice.WebApps getHostStatus" }) @Get("admin/host/status") Mono<Void> getHostStatus(@HostParam("$host") String host); @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.appservice.WebApps triggerFunction" }) @Post("admin/functions/{name}") Mono<Void> triggerFunction( @HostParam("$host") String host, @PathParam("name") String functionName, @BodyParam("application/json") Object payload); } private static class FunctionKeyListResult { @JsonProperty("keys") private List<NameValuePair> keys; } /* private static final class FunctionCredential implements TokenCredential { private final FunctionAppImpl functionApp; private FunctionCredential(FunctionAppImpl functionApp) { this.functionApp = functionApp; } @Override public Mono<AccessToken> getToken(TokenRequestContext request) { return functionApp.manager().inner().getWebApps() .getFunctionsAdminTokenAsync(functionApp.resourceGroupName(), functionApp.name()) .map(token -> { String jwt = new String(Base64.getUrlDecoder().decode(token.split("\\.")[1])); Pattern pattern = Pattern.compile("\"exp\": *([0-9]+),"); Matcher matcher = pattern.matcher(jwt); matcher.find(); long expire = Long.parseLong(matcher.group(1)); return new AccessToken(token, OffsetDateTime.ofInstant( Instant.ofEpochMilli(expire), ZoneOffset.UTC)); }); } } */ }
Maybe better same change for tests and samples.
public void canSetStorageAccountForUnmanagedDisk() { final String storageName = generateRandomResourceName("st", 14); StorageAccount storageAccount = storageManager .storageAccounts() .define(storageName) .withRegion(region) .withNewResourceGroup(rgName) .withSku(StorageAccountSkuType.fromSkuName(SkuName.PREMIUM_LRS)) .create(); VirtualMachine virtualMachine = computeManager .virtualMachines() .define(vmName) .withRegion(region) .withExistingResourceGroup(rgName) .withNewPrimaryNetwork("10.0.0.0/28") .withPrimaryPrivateIPAddressDynamic() .withoutPrimaryPublicIPAddress() .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) .withRootUsername("Foo12") .withRootPassword(password()) .withUnmanagedDisks() .defineUnmanagedDataDisk("disk1") .withNewVhd(100) .withLun(2) .storeAt(storageAccount.name(), "diskvhds", "datadisk1vhd.vhd") .attach() .defineUnmanagedDataDisk("disk2") .withNewVhd(100) .withLun(3) .storeAt(storageAccount.name(), "diskvhds", "datadisk2vhd.vhd") .attach() .withSize(VirtualMachineSizeTypes.STANDARD_DS2_V2) .withOSDiskCaching(CachingTypes.READ_WRITE) .create(); Map<Integer, VirtualMachineUnmanagedDataDisk> unmanagedDataDisks = virtualMachine.unmanagedDataDisks(); Assertions.assertNotNull(unmanagedDataDisks); Assertions.assertEquals(2, unmanagedDataDisks.size()); VirtualMachineUnmanagedDataDisk firstUnmanagedDataDisk = unmanagedDataDisks.get(2); Assertions.assertNotNull(firstUnmanagedDataDisk); VirtualMachineUnmanagedDataDisk secondUnmanagedDataDisk = unmanagedDataDisks.get(3); Assertions.assertNotNull(secondUnmanagedDataDisk); String createdVhdUri1 = firstUnmanagedDataDisk.vhdUri(); String createdVhdUri2 = secondUnmanagedDataDisk.vhdUri(); Assertions.assertNotNull(createdVhdUri1); Assertions.assertNotNull(createdVhdUri2); computeManager.virtualMachines().deleteById(virtualMachine.id()); virtualMachine = computeManager .virtualMachines() .define(vmName) .withRegion(region) .withExistingResourceGroup(rgName) .withNewPrimaryNetwork("10.0.0.0/28") .withPrimaryPrivateIPAddressDynamic() .withoutPrimaryPublicIPAddress() .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) .withRootUsername("Foo12") .withRootPassword(password()) .withUnmanagedDisks() .withExistingUnmanagedDataDisk(storageAccount.name(), "diskvhds", "datadisk1vhd.vhd") .withSize(VirtualMachineSizeTypes.STANDARD_DS2_V2) .create(); virtualMachine = computeManager.virtualMachines().getById(virtualMachine.id()); unmanagedDataDisks = virtualMachine.unmanagedDataDisks(); Assertions.assertNotNull(unmanagedDataDisks); Assertions.assertEquals(1, unmanagedDataDisks.size()); firstUnmanagedDataDisk = null; for (VirtualMachineUnmanagedDataDisk unmanagedDisk : unmanagedDataDisks.values()) { firstUnmanagedDataDisk = unmanagedDisk; break; } Assertions.assertNotNull(firstUnmanagedDataDisk.vhdUri()); Assertions.assertTrue(firstUnmanagedDataDisk.vhdUri().equalsIgnoreCase(createdVhdUri1)); virtualMachine .update() .withExistingUnmanagedDataDisk(storageAccount.name(), "diskvhds", "datadisk2vhd.vhd") .apply(); virtualMachine = computeManager.virtualMachines().getById(virtualMachine.id()); unmanagedDataDisks = virtualMachine.unmanagedDataDisks(); Assertions.assertNotNull(unmanagedDataDisks); Assertions.assertEquals(2, unmanagedDataDisks.size()); }
.withSku(StorageAccountSkuType.fromSkuName(SkuName.PREMIUM_LRS))
public void canSetStorageAccountForUnmanagedDisk() { final String storageName = generateRandomResourceName("st", 14); StorageAccount storageAccount = storageManager .storageAccounts() .define(storageName) .withRegion(region) .withNewResourceGroup(rgName) .withSku(StorageAccountSkuType.PREMIUM_LRS) .create(); VirtualMachine virtualMachine = computeManager .virtualMachines() .define(vmName) .withRegion(region) .withExistingResourceGroup(rgName) .withNewPrimaryNetwork("10.0.0.0/28") .withPrimaryPrivateIPAddressDynamic() .withoutPrimaryPublicIPAddress() .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) .withRootUsername("Foo12") .withRootPassword(password()) .withUnmanagedDisks() .defineUnmanagedDataDisk("disk1") .withNewVhd(100) .withLun(2) .storeAt(storageAccount.name(), "diskvhds", "datadisk1vhd.vhd") .attach() .defineUnmanagedDataDisk("disk2") .withNewVhd(100) .withLun(3) .storeAt(storageAccount.name(), "diskvhds", "datadisk2vhd.vhd") .attach() .withSize(VirtualMachineSizeTypes.STANDARD_DS2_V2) .withOSDiskCaching(CachingTypes.READ_WRITE) .create(); Map<Integer, VirtualMachineUnmanagedDataDisk> unmanagedDataDisks = virtualMachine.unmanagedDataDisks(); Assertions.assertNotNull(unmanagedDataDisks); Assertions.assertEquals(2, unmanagedDataDisks.size()); VirtualMachineUnmanagedDataDisk firstUnmanagedDataDisk = unmanagedDataDisks.get(2); Assertions.assertNotNull(firstUnmanagedDataDisk); VirtualMachineUnmanagedDataDisk secondUnmanagedDataDisk = unmanagedDataDisks.get(3); Assertions.assertNotNull(secondUnmanagedDataDisk); String createdVhdUri1 = firstUnmanagedDataDisk.vhdUri(); String createdVhdUri2 = secondUnmanagedDataDisk.vhdUri(); Assertions.assertNotNull(createdVhdUri1); Assertions.assertNotNull(createdVhdUri2); computeManager.virtualMachines().deleteById(virtualMachine.id()); virtualMachine = computeManager .virtualMachines() .define(vmName) .withRegion(region) .withExistingResourceGroup(rgName) .withNewPrimaryNetwork("10.0.0.0/28") .withPrimaryPrivateIPAddressDynamic() .withoutPrimaryPublicIPAddress() .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) .withRootUsername("Foo12") .withRootPassword(password()) .withUnmanagedDisks() .withExistingUnmanagedDataDisk(storageAccount.name(), "diskvhds", "datadisk1vhd.vhd") .withSize(VirtualMachineSizeTypes.STANDARD_DS2_V2) .create(); virtualMachine = computeManager.virtualMachines().getById(virtualMachine.id()); unmanagedDataDisks = virtualMachine.unmanagedDataDisks(); Assertions.assertNotNull(unmanagedDataDisks); Assertions.assertEquals(1, unmanagedDataDisks.size()); firstUnmanagedDataDisk = null; for (VirtualMachineUnmanagedDataDisk unmanagedDisk : unmanagedDataDisks.values()) { firstUnmanagedDataDisk = unmanagedDisk; break; } Assertions.assertNotNull(firstUnmanagedDataDisk.vhdUri()); Assertions.assertTrue(firstUnmanagedDataDisk.vhdUri().equalsIgnoreCase(createdVhdUri1)); virtualMachine .update() .withExistingUnmanagedDataDisk(storageAccount.name(), "diskvhds", "datadisk2vhd.vhd") .apply(); virtualMachine = computeManager.virtualMachines().getById(virtualMachine.id()); unmanagedDataDisks = virtualMachine.unmanagedDataDisks(); Assertions.assertNotNull(unmanagedDataDisks); Assertions.assertEquals(2, unmanagedDataDisks.size()); }
class VirtualMachineOperationsTests extends ComputeManagementTest { private String rgName = ""; private String rgName2 = ""; private final Region region = Region.US_EAST; private final Region regionProxPlacementGroup = Region.US_WEST_CENTRAL; private final Region regionProxPlacementGroup2 = Region.US_SOUTH_CENTRAL; private final String vmName = "javavm"; private final String proxGroupName = "testproxgroup1"; private final String proxGroupName2 = "testproxgroup2"; private final String availabilitySetName = "availset1"; private final String availabilitySetName2 = "availset2"; private final ProximityPlacementGroupType proxGroupType = ProximityPlacementGroupType.STANDARD; @Override protected void initializeClients(HttpPipeline httpPipeline, AzureProfile profile) { rgName = generateRandomResourceName("javacsmrg", 15); rgName2 = generateRandomResourceName("javacsmrg2", 15); super.initializeClients(httpPipeline, profile); } @Override protected void cleanUpResources() { resourceManager.resourceGroups().beginDeleteByName(rgName); } @Test public void canCreateVirtualMachineWithNetworking() throws Exception { NetworkSecurityGroup nsg = this .networkManager .networkSecurityGroups() .define("nsg") .withRegion(region) .withNewResourceGroup(rgName) .defineRule("rule1") .allowInbound() .fromAnyAddress() .fromPort(80) .toAnyAddress() .toPort(80) .withProtocol(SecurityRuleProtocol.TCP) .attach() .create(); Creatable<Network> networkDefinition = this .networkManager .networks() .define("network1") .withRegion(region) .withNewResourceGroup(rgName) .withAddressSpace("10.0.0.0/28") .defineSubnet("subnet1") .withAddressPrefix("10.0.0.0/29") .withExistingNetworkSecurityGroup(nsg) .attach(); VirtualMachine vm = computeManager .virtualMachines() .define(vmName) .withRegion(region) .withNewResourceGroup(rgName) .withNewPrimaryNetwork(networkDefinition) .withPrimaryPrivateIPAddressDynamic() .withoutPrimaryPublicIPAddress() .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) .withRootUsername("Foo12") .withRootPassword(password()) .create(); NetworkInterface primaryNic = vm.getPrimaryNetworkInterface(); Assertions.assertNotNull(primaryNic); NicIpConfiguration primaryIpConfig = primaryNic.primaryIPConfiguration(); Assertions.assertNotNull(primaryIpConfig); Assertions.assertNotNull(primaryIpConfig.networkId()); Network network = primaryIpConfig.getNetwork(); Assertions.assertNotNull(primaryIpConfig.subnetName()); Subnet subnet = network.subnets().get(primaryIpConfig.subnetName()); Assertions.assertNotNull(subnet); nsg = subnet.getNetworkSecurityGroup(); Assertions.assertNotNull(nsg); Assertions.assertEquals("nsg", nsg.name()); Assertions.assertEquals(1, nsg.securityRules().size()); nsg = primaryIpConfig.getNetworkSecurityGroup(); Assertions.assertEquals("nsg", nsg.name()); } @Test public void canCreateVirtualMachine() throws Exception { computeManager .virtualMachines() .define(vmName) .withRegion(region) .withNewResourceGroup(rgName) .withNewPrimaryNetwork("10.0.0.0/28") .withPrimaryPrivateIPAddressDynamic() .withoutPrimaryPublicIPAddress() .withPopularWindowsImage(KnownWindowsVirtualMachineImage.WINDOWS_SERVER_2012_R2_DATACENTER) .withAdminUsername("Foo12") .withAdminPassword(password()) .withUnmanagedDisks() .withSize(VirtualMachineSizeTypes.STANDARD_D3) .withOSDiskCaching(CachingTypes.READ_WRITE) .withOSDiskName("javatest") .withLicenseType("Windows_Server") .create(); VirtualMachine foundVM = null; PagedIterable<VirtualMachine> vms = computeManager.virtualMachines().listByResourceGroup(rgName); for (VirtualMachine vm1 : vms) { if (vm1.name().equals(vmName)) { foundVM = vm1; break; } } Assertions.assertNotNull(foundVM); Assertions.assertEquals(region, foundVM.region()); foundVM = computeManager.virtualMachines().getByResourceGroup(rgName, vmName); Assertions.assertNotNull(foundVM); Assertions.assertEquals(region, foundVM.region()); Assertions.assertEquals("Windows_Server", foundVM.licenseType()); PowerState powerState = foundVM.powerState(); Assertions.assertEquals(powerState, PowerState.RUNNING); VirtualMachineInstanceView instanceView = foundVM.instanceView(); Assertions.assertNotNull(instanceView); Assertions.assertNotNull(instanceView.statuses().size() > 0); computeManager.virtualMachines().deleteById(foundVM.id()); } @Test public void canCreateVirtualMachineSyncPoll() throws Exception { final long defaultDelayInMillis = 10 * 1000; Accepted<VirtualMachine> acceptedVirtualMachine = computeManager .virtualMachines() .define(vmName) .withRegion(region) .withNewResourceGroup(rgName) .withNewPrimaryNetwork("10.0.0.0/28") .withPrimaryPrivateIPAddressDynamic() .withoutPrimaryPublicIPAddress() .withPopularWindowsImage(KnownWindowsVirtualMachineImage.WINDOWS_SERVER_2016_DATACENTER) .withAdminUsername("Foo12") .withAdminPassword(password()) .withUnmanagedDisks() .withSize(VirtualMachineSizeTypes.STANDARD_D3) .withOSDiskCaching(CachingTypes.READ_WRITE) .withOSDiskName("javatest") .withLicenseType("Windows_Server") .beginCreate(); VirtualMachine createdVirtualMachine = acceptedVirtualMachine.getActivationResponse().getValue(); Assertions.assertNotEquals("Succeeded", createdVirtualMachine.provisioningState()); LongRunningOperationStatus pollStatus = acceptedVirtualMachine.getActivationResponse().getStatus(); long delayInMills = acceptedVirtualMachine.getActivationResponse().getRetryAfter() == null ? defaultDelayInMillis : acceptedVirtualMachine.getActivationResponse().getRetryAfter().toMillis(); while (!pollStatus.isComplete()) { SdkContext.sleep(delayInMills); PollResponse<?> pollResponse = acceptedVirtualMachine.getSyncPoller().poll(); pollStatus = pollResponse.getStatus(); delayInMills = pollResponse.getRetryAfter() == null ? defaultDelayInMillis : pollResponse.getRetryAfter().toMillis(); } Assertions.assertEquals(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, pollStatus); VirtualMachine virtualMachine = acceptedVirtualMachine.getFinalResult(); Assertions.assertEquals("Succeeded", virtualMachine.provisioningState()); Accepted<Void> acceptedDelete = computeManager.virtualMachines() .beginDeleteByResourceGroup(virtualMachine.resourceGroupName(), virtualMachine.name()); pollStatus = acceptedDelete.getActivationResponse().getStatus(); delayInMills = acceptedDelete.getActivationResponse().getRetryAfter() == null ? defaultDelayInMillis : (int) acceptedDelete.getActivationResponse().getRetryAfter().toMillis(); while (!pollStatus.isComplete()) { SdkContext.sleep(delayInMills); PollResponse<?> pollResponse = acceptedDelete.getSyncPoller().poll(); pollStatus = pollResponse.getStatus(); delayInMills = pollResponse.getRetryAfter() == null ? defaultDelayInMillis : (int) pollResponse.getRetryAfter().toMillis(); } boolean deleted = false; try { computeManager.virtualMachines().getById(virtualMachine.id()); } catch (ManagementException e) { if (e.getResponse().getStatusCode() == 404 && ("NotFound".equals(e.getValue().getCode()) || "ResourceNotFound".equals(e.getValue().getCode()))) { deleted = true; } } Assertions.assertTrue(deleted); } @Test public void canCreateUpdatePriorityAndPrice() throws Exception { computeManager .virtualMachines() .define(vmName) .withRegion(region) .withNewResourceGroup(rgName) .withNewPrimaryNetwork("10.0.0.0/28") .withPrimaryPrivateIPAddressDynamic() .withoutPrimaryPublicIPAddress() .withPopularWindowsImage(KnownWindowsVirtualMachineImage.WINDOWS_SERVER_2016_DATACENTER) .withAdminUsername("Foo12") .withAdminPassword(password()) .withUnmanagedDisks() .withSize(VirtualMachineSizeTypes.STANDARD_A2) .withOSDiskCaching(CachingTypes.READ_WRITE) .withOSDiskName("javatest") .withLowPriority(VirtualMachineEvictionPolicyTypes.DEALLOCATE) .withMaxPrice(1000.0) .withLicenseType("Windows_Server") .create(); VirtualMachine foundVM = null; PagedIterable<VirtualMachine> vms = computeManager.virtualMachines().listByResourceGroup(rgName); for (VirtualMachine vm1 : vms) { if (vm1.name().equals(vmName)) { foundVM = vm1; break; } } Assertions.assertNotNull(foundVM); Assertions.assertEquals(region, foundVM.region()); foundVM = computeManager.virtualMachines().getByResourceGroup(rgName, vmName); Assertions.assertNotNull(foundVM); Assertions.assertEquals(region, foundVM.region()); Assertions.assertEquals("Windows_Server", foundVM.licenseType()); Assertions.assertEquals((Double) 1000.0, foundVM.billingProfile().maxPrice()); Assertions.assertEquals(VirtualMachineEvictionPolicyTypes.DEALLOCATE, foundVM.evictionPolicy()); try { foundVM.update().withMaxPrice(1500.0).apply(); Assertions.assertEquals((Double) 1500.0, foundVM.billingProfile().maxPrice()); Assertions.fail(); } catch (ManagementException e) { } foundVM.deallocate(); foundVM.update().withMaxPrice(2000.0).apply(); foundVM.start(); Assertions.assertEquals((Double) 2000.0, foundVM.billingProfile().maxPrice()); foundVM = foundVM.update().withPriority(VirtualMachinePriorityTypes.SPOT).apply(); Assertions.assertEquals(VirtualMachinePriorityTypes.SPOT, foundVM.priority()); foundVM = foundVM.update().withPriority(VirtualMachinePriorityTypes.LOW).apply(); Assertions.assertEquals(VirtualMachinePriorityTypes.LOW, foundVM.priority()); try { foundVM.update().withPriority(VirtualMachinePriorityTypes.REGULAR).apply(); Assertions.assertEquals(VirtualMachinePriorityTypes.REGULAR, foundVM.priority()); Assertions.fail(); } catch (ManagementException e) { } computeManager.virtualMachines().deleteById(foundVM.id()); } @Test public void cannotUpdateProximityPlacementGroupForVirtualMachine() throws Exception { AvailabilitySet setCreated = computeManager .availabilitySets() .define(availabilitySetName) .withRegion(regionProxPlacementGroup) .withNewResourceGroup(rgName) .withNewProximityPlacementGroup(proxGroupName, proxGroupType) .create(); Assertions.assertEquals(availabilitySetName, setCreated.name()); Assertions.assertNotNull(setCreated.proximityPlacementGroup()); Assertions.assertEquals(proxGroupType, setCreated.proximityPlacementGroup().proximityPlacementGroupType()); Assertions.assertNotNull(setCreated.proximityPlacementGroup().availabilitySetIds()); Assertions.assertFalse(setCreated.proximityPlacementGroup().availabilitySetIds().isEmpty()); Assertions .assertTrue( setCreated.id().equalsIgnoreCase(setCreated.proximityPlacementGroup().availabilitySetIds().get(0))); Assertions.assertEquals(setCreated.regionName(), setCreated.proximityPlacementGroup().location()); AvailabilitySet setCreated2 = computeManager .availabilitySets() .define(availabilitySetName2) .withRegion(regionProxPlacementGroup2) .withNewResourceGroup(rgName2) .withNewProximityPlacementGroup(proxGroupName2, proxGroupType) .create(); Assertions.assertEquals(availabilitySetName2, setCreated2.name()); Assertions.assertNotNull(setCreated2.proximityPlacementGroup()); Assertions.assertEquals(proxGroupType, setCreated2.proximityPlacementGroup().proximityPlacementGroupType()); Assertions.assertNotNull(setCreated2.proximityPlacementGroup().availabilitySetIds()); Assertions.assertFalse(setCreated2.proximityPlacementGroup().availabilitySetIds().isEmpty()); Assertions .assertTrue( setCreated2.id().equalsIgnoreCase(setCreated2.proximityPlacementGroup().availabilitySetIds().get(0))); Assertions.assertEquals(setCreated2.regionName(), setCreated2.proximityPlacementGroup().location()); computeManager .virtualMachines() .define(vmName) .withRegion(regionProxPlacementGroup) .withExistingResourceGroup(rgName) .withNewPrimaryNetwork("10.0.0.0/28") .withPrimaryPrivateIPAddressDynamic() .withoutPrimaryPublicIPAddress() .withProximityPlacementGroup(setCreated.proximityPlacementGroup().id()) .withPopularWindowsImage(KnownWindowsVirtualMachineImage.WINDOWS_SERVER_2019_DATACENTER) .withAdminUsername("Foo12") .withAdminPassword(password()) .withUnmanagedDisks() .withSize(VirtualMachineSizeTypes.STANDARD_DS3_V2) .withOSDiskCaching(CachingTypes.READ_WRITE) .withOSDiskName("javatest") .withLicenseType("Windows_Server") .create(); VirtualMachine foundVM = null; PagedIterable<VirtualMachine> vms = computeManager.virtualMachines().listByResourceGroup(rgName); for (VirtualMachine vm1 : vms) { if (vm1.name().equals(vmName)) { foundVM = vm1; break; } } Assertions.assertNotNull(foundVM); Assertions.assertEquals(regionProxPlacementGroup, foundVM.region()); foundVM = computeManager.virtualMachines().getByResourceGroup(rgName, vmName); Assertions.assertNotNull(foundVM); Assertions.assertEquals(regionProxPlacementGroup, foundVM.region()); Assertions.assertEquals("Windows_Server", foundVM.licenseType()); PowerState powerState = foundVM.powerState(); Assertions.assertEquals(powerState, PowerState.RUNNING); VirtualMachineInstanceView instanceView = foundVM.instanceView(); Assertions.assertNotNull(instanceView); Assertions.assertNotNull(instanceView.statuses().size() > 0); Assertions.assertNotNull(foundVM.proximityPlacementGroup()); Assertions.assertEquals(proxGroupType, foundVM.proximityPlacementGroup().proximityPlacementGroupType()); Assertions.assertNotNull(foundVM.proximityPlacementGroup().availabilitySetIds()); Assertions.assertFalse(foundVM.proximityPlacementGroup().availabilitySetIds().isEmpty()); Assertions .assertTrue( setCreated.id().equalsIgnoreCase(foundVM.proximityPlacementGroup().availabilitySetIds().get(0))); Assertions.assertNotNull(foundVM.proximityPlacementGroup().virtualMachineIds()); Assertions.assertFalse(foundVM.proximityPlacementGroup().virtualMachineIds().isEmpty()); Assertions .assertTrue(foundVM.id().equalsIgnoreCase(setCreated.proximityPlacementGroup().virtualMachineIds().get(0))); try { VirtualMachine updatedVm = foundVM.update().withProximityPlacementGroup(setCreated2.proximityPlacementGroup().id()).apply(); } catch (ManagementException clEx) { Assertions .assertTrue( clEx .getMessage() .contains( "Updating proximity placement group of VM javavm is not allowed while the VM is running." + " Please stop/deallocate the VM and retry the operation.")); } computeManager.virtualMachines().deleteById(foundVM.id()); computeManager.availabilitySets().deleteById(setCreated.id()); } @Test public void canCreateVirtualMachinesAndAvailabilitySetInSameProximityPlacementGroup() throws Exception { AvailabilitySet setCreated = computeManager .availabilitySets() .define(availabilitySetName) .withRegion(regionProxPlacementGroup) .withNewResourceGroup(rgName) .withNewProximityPlacementGroup(proxGroupName, proxGroupType) .create(); Assertions.assertEquals(availabilitySetName, setCreated.name()); Assertions.assertNotNull(setCreated.proximityPlacementGroup()); Assertions.assertEquals(proxGroupType, setCreated.proximityPlacementGroup().proximityPlacementGroupType()); Assertions.assertNotNull(setCreated.proximityPlacementGroup().availabilitySetIds()); Assertions.assertFalse(setCreated.proximityPlacementGroup().availabilitySetIds().isEmpty()); Assertions .assertTrue( setCreated.id().equalsIgnoreCase(setCreated.proximityPlacementGroup().availabilitySetIds().get(0))); Assertions.assertEquals(setCreated.regionName(), setCreated.proximityPlacementGroup().location()); computeManager .virtualMachines() .define(vmName) .withRegion(regionProxPlacementGroup) .withExistingResourceGroup(rgName) .withNewPrimaryNetwork("10.0.0.0/28") .withPrimaryPrivateIPAddressDynamic() .withoutPrimaryPublicIPAddress() .withProximityPlacementGroup(setCreated.proximityPlacementGroup().id()) .withPopularWindowsImage(KnownWindowsVirtualMachineImage.WINDOWS_SERVER_2019_DATACENTER) .withAdminUsername("Foo12") .withAdminPassword(password()) .withUnmanagedDisks() .withSize(VirtualMachineSizeTypes.STANDARD_DS3_V2) .withOSDiskCaching(CachingTypes.READ_WRITE) .withOSDiskName("javatest") .withLicenseType("Windows_Server") .create(); VirtualMachine foundVM = null; PagedIterable<VirtualMachine> vms = computeManager.virtualMachines().listByResourceGroup(rgName); for (VirtualMachine vm1 : vms) { if (vm1.name().equals(vmName)) { foundVM = vm1; break; } } Assertions.assertNotNull(foundVM); Assertions.assertEquals(regionProxPlacementGroup, foundVM.region()); foundVM = computeManager.virtualMachines().getByResourceGroup(rgName, vmName); Assertions.assertNotNull(foundVM); Assertions.assertEquals(regionProxPlacementGroup, foundVM.region()); Assertions.assertEquals("Windows_Server", foundVM.licenseType()); PowerState powerState = foundVM.powerState(); Assertions.assertEquals(powerState, PowerState.RUNNING); VirtualMachineInstanceView instanceView = foundVM.instanceView(); Assertions.assertNotNull(instanceView); Assertions.assertNotNull(instanceView.statuses().size() > 0); Assertions.assertNotNull(foundVM.proximityPlacementGroup()); Assertions.assertEquals(proxGroupType, foundVM.proximityPlacementGroup().proximityPlacementGroupType()); Assertions.assertNotNull(foundVM.proximityPlacementGroup().availabilitySetIds()); Assertions.assertFalse(foundVM.proximityPlacementGroup().availabilitySetIds().isEmpty()); Assertions .assertTrue( setCreated.id().equalsIgnoreCase(foundVM.proximityPlacementGroup().availabilitySetIds().get(0))); Assertions.assertNotNull(foundVM.proximityPlacementGroup().virtualMachineIds()); Assertions.assertFalse(foundVM.proximityPlacementGroup().virtualMachineIds().isEmpty()); Assertions .assertTrue(foundVM.id().equalsIgnoreCase(setCreated.proximityPlacementGroup().virtualMachineIds().get(0))); VirtualMachine updatedVm = foundVM.update().withoutProximityPlacementGroup().apply(); Assertions.assertNotNull(updatedVm.proximityPlacementGroup()); Assertions.assertEquals(proxGroupType, updatedVm.proximityPlacementGroup().proximityPlacementGroupType()); Assertions.assertNotNull(updatedVm.proximityPlacementGroup().availabilitySetIds()); Assertions.assertFalse(updatedVm.proximityPlacementGroup().availabilitySetIds().isEmpty()); Assertions .assertTrue( setCreated.id().equalsIgnoreCase(updatedVm.proximityPlacementGroup().availabilitySetIds().get(0))); computeManager.virtualMachines().deleteById(foundVM.id()); computeManager.availabilitySets().deleteById(setCreated.id()); } @Test public void canCreateVirtualMachinesAndRelatedResourcesInParallel() throws Exception { String vmNamePrefix = "vmz"; String publicIpNamePrefix = generateRandomResourceName("pip-", 15); String networkNamePrefix = generateRandomResourceName("vnet-", 15); int count = 5; CreatablesInfo creatablesInfo = prepareCreatableVirtualMachines(region, vmNamePrefix, networkNamePrefix, publicIpNamePrefix, count); List<Creatable<VirtualMachine>> virtualMachineCreatables = creatablesInfo.virtualMachineCreatables; List<String> networkCreatableKeys = creatablesInfo.networkCreatableKeys; List<String> publicIpCreatableKeys = creatablesInfo.publicIpCreatableKeys; CreatedResources<VirtualMachine> createdVirtualMachines = computeManager.virtualMachines().create(virtualMachineCreatables); Assertions.assertTrue(createdVirtualMachines.size() == count); Set<String> virtualMachineNames = new HashSet<>(); for (int i = 0; i < count; i++) { virtualMachineNames.add(String.format("%s-%d", vmNamePrefix, i)); } for (VirtualMachine virtualMachine : createdVirtualMachines.values()) { Assertions.assertTrue(virtualMachineNames.contains(virtualMachine.name())); Assertions.assertNotNull(virtualMachine.id()); } Set<String> networkNames = new HashSet<>(); for (int i = 0; i < count; i++) { networkNames.add(String.format("%s-%d", networkNamePrefix, i)); } for (String networkCreatableKey : networkCreatableKeys) { Network createdNetwork = (Network) createdVirtualMachines.createdRelatedResource(networkCreatableKey); Assertions.assertNotNull(createdNetwork); Assertions.assertTrue(networkNames.contains(createdNetwork.name())); } Set<String> publicIPAddressNames = new HashSet<>(); for (int i = 0; i < count; i++) { publicIPAddressNames.add(String.format("%s-%d", publicIpNamePrefix, i)); } for (String publicIpCreatableKey : publicIpCreatableKeys) { PublicIpAddress createdPublicIpAddress = (PublicIpAddress) createdVirtualMachines.createdRelatedResource(publicIpCreatableKey); Assertions.assertNotNull(createdPublicIpAddress); Assertions.assertTrue(publicIPAddressNames.contains(createdPublicIpAddress.name())); } } @Test public void canStreamParallelCreatedVirtualMachinesAndRelatedResources() throws Exception { String vmNamePrefix = "vmz"; String publicIpNamePrefix = generateRandomResourceName("pip-", 15); String networkNamePrefix = generateRandomResourceName("vnet-", 15); int count = 5; final Set<String> virtualMachineNames = new HashSet<>(); for (int i = 0; i < count; i++) { virtualMachineNames.add(String.format("%s-%d", vmNamePrefix, i)); } final Set<String> networkNames = new HashSet<>(); for (int i = 0; i < count; i++) { networkNames.add(String.format("%s-%d", networkNamePrefix, i)); } final Set<String> publicIPAddressNames = new HashSet<>(); for (int i = 0; i < count; i++) { publicIPAddressNames.add(String.format("%s-%d", publicIpNamePrefix, i)); } final CreatablesInfo creatablesInfo = prepareCreatableVirtualMachines(region, vmNamePrefix, networkNamePrefix, publicIpNamePrefix, count); final AtomicInteger resourceCount = new AtomicInteger(0); List<Creatable<VirtualMachine>> virtualMachineCreatables = creatablesInfo.virtualMachineCreatables; computeManager .virtualMachines() .createAsync(virtualMachineCreatables) .map( createdResource -> { if (createdResource instanceof Resource) { Resource resource = (Resource) createdResource; System.out.println("Created: " + resource.id()); if (resource instanceof VirtualMachine) { VirtualMachine virtualMachine = (VirtualMachine) resource; Assertions.assertTrue(virtualMachineNames.contains(virtualMachine.name())); Assertions.assertNotNull(virtualMachine.id()); } else if (resource instanceof Network) { Network network = (Network) resource; Assertions.assertTrue(networkNames.contains(network.name())); Assertions.assertNotNull(network.id()); } else if (resource instanceof PublicIpAddress) { PublicIpAddress publicIPAddress = (PublicIpAddress) resource; Assertions.assertTrue(publicIPAddressNames.contains(publicIPAddress.name())); Assertions.assertNotNull(publicIPAddress.id()); } } resourceCount.incrementAndGet(); return createdResource; }) .blockLast(); networkNames.forEach(name -> { Assertions.assertNotNull(networkManager.networks().getByResourceGroup(rgName, name)); }); publicIPAddressNames.forEach(name -> { Assertions.assertNotNull(networkManager.publicIpAddresses().getByResourceGroup(rgName, name)); }); Assertions.assertEquals(1, storageManager.storageAccounts().listByResourceGroup(rgName).stream().count()); Assertions.assertEquals(count, networkManager.networkInterfaces().listByResourceGroup(rgName).stream().count()); Assertions.assertEquals(count, resourceCount.get()); } @Test @Test public void canUpdateTagsOnVM() { 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("firstuser") .withRootPassword("afh123RVS!") .withSize(VirtualMachineSizeTypes.STANDARD_D3_V2) .create(); virtualMachine.update().withTag("test", "testValue").apply(); Assertions.assertEquals("testValue", virtualMachine.inner().tags().get("test")); Map<String, String> testTags = new HashMap<String, String>(); testTags.put("testTag", "testValue"); virtualMachine.update().withTags(testTags).apply(); Assertions.assertEquals(testTags, virtualMachine.inner().tags()); } @Test public void canRunScriptOnVM() { 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("firstuser") .withRootPassword("afh123RVS!") .create(); List<String> installGit = new ArrayList<>(); installGit.add("sudo apt-get update"); installGit.add("sudo apt-get install -y git"); RunCommandResult runResult = virtualMachine.runShellScript(installGit, new ArrayList<RunCommandInputParameter>()); Assertions.assertNotNull(runResult); Assertions.assertNotNull(runResult.value()); Assertions.assertTrue(runResult.value().size() > 0); } @Test public void canPerformSimulateEvictionOnSpotVirtualMachine() { 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("firstuser") .withRootPassword("afh123RVS!") .withSpotPriority(VirtualMachineEvictionPolicyTypes.DEALLOCATE) .withSize(VirtualMachineSizeTypes.STANDARD_D2_V3) .create(); Assertions.assertNotNull(virtualMachine.osDiskStorageAccountType()); Assertions.assertTrue(virtualMachine.osDiskSize() > 0); Disk disk = computeManager.disks().getById(virtualMachine.osDiskId()); Assertions.assertNotNull(disk); Assertions.assertEquals(DiskState.ATTACHED, disk.inner().diskState()); virtualMachine.simulateEviction(); SdkContext.sleep(30 * 60 * 1000); virtualMachine = computeManager.virtualMachines().getById(virtualMachine.id()); Assertions.assertNotNull(virtualMachine); Assertions.assertNull(virtualMachine.osDiskStorageAccountType()); Assertions.assertTrue(virtualMachine.osDiskSize() == 0); disk = computeManager.disks().getById(virtualMachine.osDiskId()); Assertions.assertEquals(DiskState.RESERVED, disk.inner().diskState()); } private CreatablesInfo prepareCreatableVirtualMachines( Region region, String vmNamePrefix, String networkNamePrefix, String publicIpNamePrefix, int vmCount) { Creatable<ResourceGroup> resourceGroupCreatable = resourceManager.resourceGroups().define(rgName).withRegion(region); Creatable<StorageAccount> storageAccountCreatable = storageManager .storageAccounts() .define(generateRandomResourceName("stg", 20)) .withRegion(region) .withNewResourceGroup(resourceGroupCreatable); List<String> networkCreatableKeys = new ArrayList<>(); List<String> publicIpCreatableKeys = new ArrayList<>(); List<Creatable<VirtualMachine>> virtualMachineCreatables = new ArrayList<>(); for (int i = 0; i < vmCount; i++) { Creatable<Network> networkCreatable = networkManager .networks() .define(String.format("%s-%d", networkNamePrefix, i)) .withRegion(region) .withNewResourceGroup(resourceGroupCreatable) .withAddressSpace("10.0.0.0/28"); networkCreatableKeys.add(networkCreatable.key()); Creatable<PublicIpAddress> publicIPAddressCreatable = networkManager .publicIpAddresses() .define(String.format("%s-%d", publicIpNamePrefix, i)) .withRegion(region) .withNewResourceGroup(resourceGroupCreatable); publicIpCreatableKeys.add(publicIPAddressCreatable.key()); Creatable<VirtualMachine> virtualMachineCreatable = computeManager .virtualMachines() .define(String.format("%s-%d", vmNamePrefix, i)) .withRegion(region) .withNewResourceGroup(resourceGroupCreatable) .withNewPrimaryNetwork(networkCreatable) .withPrimaryPrivateIPAddressDynamic() .withNewPrimaryPublicIPAddress(publicIPAddressCreatable) .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) .withRootUsername("tirekicker") .withRootPassword("BaR@12! .withUnmanagedDisks() .withNewStorageAccount(storageAccountCreatable); virtualMachineCreatables.add(virtualMachineCreatable); } CreatablesInfo creatablesInfo = new CreatablesInfo(); creatablesInfo.virtualMachineCreatables = virtualMachineCreatables; creatablesInfo.networkCreatableKeys = networkCreatableKeys; creatablesInfo.publicIpCreatableKeys = publicIpCreatableKeys; return creatablesInfo; } class CreatablesInfo { private List<Creatable<VirtualMachine>> virtualMachineCreatables; List<String> networkCreatableKeys; List<String> publicIpCreatableKeys; } }
class VirtualMachineOperationsTests extends ComputeManagementTest { private String rgName = ""; private String rgName2 = ""; private final Region region = Region.US_EAST; private final Region regionProxPlacementGroup = Region.US_WEST_CENTRAL; private final Region regionProxPlacementGroup2 = Region.US_SOUTH_CENTRAL; private final String vmName = "javavm"; private final String proxGroupName = "testproxgroup1"; private final String proxGroupName2 = "testproxgroup2"; private final String availabilitySetName = "availset1"; private final String availabilitySetName2 = "availset2"; private final ProximityPlacementGroupType proxGroupType = ProximityPlacementGroupType.STANDARD; @Override protected void initializeClients(HttpPipeline httpPipeline, AzureProfile profile) { rgName = generateRandomResourceName("javacsmrg", 15); rgName2 = generateRandomResourceName("javacsmrg2", 15); super.initializeClients(httpPipeline, profile); } @Override protected void cleanUpResources() { resourceManager.resourceGroups().beginDeleteByName(rgName); } @Test public void canCreateVirtualMachineWithNetworking() throws Exception { NetworkSecurityGroup nsg = this .networkManager .networkSecurityGroups() .define("nsg") .withRegion(region) .withNewResourceGroup(rgName) .defineRule("rule1") .allowInbound() .fromAnyAddress() .fromPort(80) .toAnyAddress() .toPort(80) .withProtocol(SecurityRuleProtocol.TCP) .attach() .create(); Creatable<Network> networkDefinition = this .networkManager .networks() .define("network1") .withRegion(region) .withNewResourceGroup(rgName) .withAddressSpace("10.0.0.0/28") .defineSubnet("subnet1") .withAddressPrefix("10.0.0.0/29") .withExistingNetworkSecurityGroup(nsg) .attach(); VirtualMachine vm = computeManager .virtualMachines() .define(vmName) .withRegion(region) .withNewResourceGroup(rgName) .withNewPrimaryNetwork(networkDefinition) .withPrimaryPrivateIPAddressDynamic() .withoutPrimaryPublicIPAddress() .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) .withRootUsername("Foo12") .withRootPassword(password()) .create(); NetworkInterface primaryNic = vm.getPrimaryNetworkInterface(); Assertions.assertNotNull(primaryNic); NicIpConfiguration primaryIpConfig = primaryNic.primaryIPConfiguration(); Assertions.assertNotNull(primaryIpConfig); Assertions.assertNotNull(primaryIpConfig.networkId()); Network network = primaryIpConfig.getNetwork(); Assertions.assertNotNull(primaryIpConfig.subnetName()); Subnet subnet = network.subnets().get(primaryIpConfig.subnetName()); Assertions.assertNotNull(subnet); nsg = subnet.getNetworkSecurityGroup(); Assertions.assertNotNull(nsg); Assertions.assertEquals("nsg", nsg.name()); Assertions.assertEquals(1, nsg.securityRules().size()); nsg = primaryIpConfig.getNetworkSecurityGroup(); Assertions.assertEquals("nsg", nsg.name()); } @Test public void canCreateVirtualMachine() throws Exception { computeManager .virtualMachines() .define(vmName) .withRegion(region) .withNewResourceGroup(rgName) .withNewPrimaryNetwork("10.0.0.0/28") .withPrimaryPrivateIPAddressDynamic() .withoutPrimaryPublicIPAddress() .withPopularWindowsImage(KnownWindowsVirtualMachineImage.WINDOWS_SERVER_2012_R2_DATACENTER) .withAdminUsername("Foo12") .withAdminPassword(password()) .withUnmanagedDisks() .withSize(VirtualMachineSizeTypes.STANDARD_D3) .withOSDiskCaching(CachingTypes.READ_WRITE) .withOSDiskName("javatest") .withLicenseType("Windows_Server") .create(); VirtualMachine foundVM = null; PagedIterable<VirtualMachine> vms = computeManager.virtualMachines().listByResourceGroup(rgName); for (VirtualMachine vm1 : vms) { if (vm1.name().equals(vmName)) { foundVM = vm1; break; } } Assertions.assertNotNull(foundVM); Assertions.assertEquals(region, foundVM.region()); foundVM = computeManager.virtualMachines().getByResourceGroup(rgName, vmName); Assertions.assertNotNull(foundVM); Assertions.assertEquals(region, foundVM.region()); Assertions.assertEquals("Windows_Server", foundVM.licenseType()); PowerState powerState = foundVM.powerState(); Assertions.assertEquals(powerState, PowerState.RUNNING); VirtualMachineInstanceView instanceView = foundVM.instanceView(); Assertions.assertNotNull(instanceView); Assertions.assertNotNull(instanceView.statuses().size() > 0); computeManager.virtualMachines().deleteById(foundVM.id()); } @Test public void canCreateVirtualMachineSyncPoll() throws Exception { final long defaultDelayInMillis = 10 * 1000; Accepted<VirtualMachine> acceptedVirtualMachine = computeManager .virtualMachines() .define(vmName) .withRegion(region) .withNewResourceGroup(rgName) .withNewPrimaryNetwork("10.0.0.0/28") .withPrimaryPrivateIPAddressDynamic() .withoutPrimaryPublicIPAddress() .withPopularWindowsImage(KnownWindowsVirtualMachineImage.WINDOWS_SERVER_2016_DATACENTER) .withAdminUsername("Foo12") .withAdminPassword(password()) .withUnmanagedDisks() .withSize(VirtualMachineSizeTypes.STANDARD_D3) .withOSDiskCaching(CachingTypes.READ_WRITE) .withOSDiskName("javatest") .withLicenseType("Windows_Server") .beginCreate(); VirtualMachine createdVirtualMachine = acceptedVirtualMachine.getActivationResponse().getValue(); Assertions.assertNotEquals("Succeeded", createdVirtualMachine.provisioningState()); LongRunningOperationStatus pollStatus = acceptedVirtualMachine.getActivationResponse().getStatus(); long delayInMills = acceptedVirtualMachine.getActivationResponse().getRetryAfter() == null ? defaultDelayInMillis : acceptedVirtualMachine.getActivationResponse().getRetryAfter().toMillis(); while (!pollStatus.isComplete()) { SdkContext.sleep(delayInMills); PollResponse<?> pollResponse = acceptedVirtualMachine.getSyncPoller().poll(); pollStatus = pollResponse.getStatus(); delayInMills = pollResponse.getRetryAfter() == null ? defaultDelayInMillis : pollResponse.getRetryAfter().toMillis(); } Assertions.assertEquals(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, pollStatus); VirtualMachine virtualMachine = acceptedVirtualMachine.getFinalResult(); Assertions.assertEquals("Succeeded", virtualMachine.provisioningState()); Accepted<Void> acceptedDelete = computeManager.virtualMachines() .beginDeleteByResourceGroup(virtualMachine.resourceGroupName(), virtualMachine.name()); pollStatus = acceptedDelete.getActivationResponse().getStatus(); delayInMills = acceptedDelete.getActivationResponse().getRetryAfter() == null ? defaultDelayInMillis : (int) acceptedDelete.getActivationResponse().getRetryAfter().toMillis(); while (!pollStatus.isComplete()) { SdkContext.sleep(delayInMills); PollResponse<?> pollResponse = acceptedDelete.getSyncPoller().poll(); pollStatus = pollResponse.getStatus(); delayInMills = pollResponse.getRetryAfter() == null ? defaultDelayInMillis : (int) pollResponse.getRetryAfter().toMillis(); } boolean deleted = false; try { computeManager.virtualMachines().getById(virtualMachine.id()); } catch (ManagementException e) { if (e.getResponse().getStatusCode() == 404 && ("NotFound".equals(e.getValue().getCode()) || "ResourceNotFound".equals(e.getValue().getCode()))) { deleted = true; } } Assertions.assertTrue(deleted); } @Test public void canCreateUpdatePriorityAndPrice() throws Exception { computeManager .virtualMachines() .define(vmName) .withRegion(region) .withNewResourceGroup(rgName) .withNewPrimaryNetwork("10.0.0.0/28") .withPrimaryPrivateIPAddressDynamic() .withoutPrimaryPublicIPAddress() .withPopularWindowsImage(KnownWindowsVirtualMachineImage.WINDOWS_SERVER_2016_DATACENTER) .withAdminUsername("Foo12") .withAdminPassword(password()) .withUnmanagedDisks() .withSize(VirtualMachineSizeTypes.STANDARD_A2) .withOSDiskCaching(CachingTypes.READ_WRITE) .withOSDiskName("javatest") .withLowPriority(VirtualMachineEvictionPolicyTypes.DEALLOCATE) .withMaxPrice(1000.0) .withLicenseType("Windows_Server") .create(); VirtualMachine foundVM = null; PagedIterable<VirtualMachine> vms = computeManager.virtualMachines().listByResourceGroup(rgName); for (VirtualMachine vm1 : vms) { if (vm1.name().equals(vmName)) { foundVM = vm1; break; } } Assertions.assertNotNull(foundVM); Assertions.assertEquals(region, foundVM.region()); foundVM = computeManager.virtualMachines().getByResourceGroup(rgName, vmName); Assertions.assertNotNull(foundVM); Assertions.assertEquals(region, foundVM.region()); Assertions.assertEquals("Windows_Server", foundVM.licenseType()); Assertions.assertEquals((Double) 1000.0, foundVM.billingProfile().maxPrice()); Assertions.assertEquals(VirtualMachineEvictionPolicyTypes.DEALLOCATE, foundVM.evictionPolicy()); try { foundVM.update().withMaxPrice(1500.0).apply(); Assertions.assertEquals((Double) 1500.0, foundVM.billingProfile().maxPrice()); Assertions.fail(); } catch (ManagementException e) { } foundVM.deallocate(); foundVM.update().withMaxPrice(2000.0).apply(); foundVM.start(); Assertions.assertEquals((Double) 2000.0, foundVM.billingProfile().maxPrice()); foundVM = foundVM.update().withPriority(VirtualMachinePriorityTypes.SPOT).apply(); Assertions.assertEquals(VirtualMachinePriorityTypes.SPOT, foundVM.priority()); foundVM = foundVM.update().withPriority(VirtualMachinePriorityTypes.LOW).apply(); Assertions.assertEquals(VirtualMachinePriorityTypes.LOW, foundVM.priority()); try { foundVM.update().withPriority(VirtualMachinePriorityTypes.REGULAR).apply(); Assertions.assertEquals(VirtualMachinePriorityTypes.REGULAR, foundVM.priority()); Assertions.fail(); } catch (ManagementException e) { } computeManager.virtualMachines().deleteById(foundVM.id()); } @Test public void cannotUpdateProximityPlacementGroupForVirtualMachine() throws Exception { AvailabilitySet setCreated = computeManager .availabilitySets() .define(availabilitySetName) .withRegion(regionProxPlacementGroup) .withNewResourceGroup(rgName) .withNewProximityPlacementGroup(proxGroupName, proxGroupType) .create(); Assertions.assertEquals(availabilitySetName, setCreated.name()); Assertions.assertNotNull(setCreated.proximityPlacementGroup()); Assertions.assertEquals(proxGroupType, setCreated.proximityPlacementGroup().proximityPlacementGroupType()); Assertions.assertNotNull(setCreated.proximityPlacementGroup().availabilitySetIds()); Assertions.assertFalse(setCreated.proximityPlacementGroup().availabilitySetIds().isEmpty()); Assertions .assertTrue( setCreated.id().equalsIgnoreCase(setCreated.proximityPlacementGroup().availabilitySetIds().get(0))); Assertions.assertEquals(setCreated.regionName(), setCreated.proximityPlacementGroup().location()); AvailabilitySet setCreated2 = computeManager .availabilitySets() .define(availabilitySetName2) .withRegion(regionProxPlacementGroup2) .withNewResourceGroup(rgName2) .withNewProximityPlacementGroup(proxGroupName2, proxGroupType) .create(); Assertions.assertEquals(availabilitySetName2, setCreated2.name()); Assertions.assertNotNull(setCreated2.proximityPlacementGroup()); Assertions.assertEquals(proxGroupType, setCreated2.proximityPlacementGroup().proximityPlacementGroupType()); Assertions.assertNotNull(setCreated2.proximityPlacementGroup().availabilitySetIds()); Assertions.assertFalse(setCreated2.proximityPlacementGroup().availabilitySetIds().isEmpty()); Assertions .assertTrue( setCreated2.id().equalsIgnoreCase(setCreated2.proximityPlacementGroup().availabilitySetIds().get(0))); Assertions.assertEquals(setCreated2.regionName(), setCreated2.proximityPlacementGroup().location()); computeManager .virtualMachines() .define(vmName) .withRegion(regionProxPlacementGroup) .withExistingResourceGroup(rgName) .withNewPrimaryNetwork("10.0.0.0/28") .withPrimaryPrivateIPAddressDynamic() .withoutPrimaryPublicIPAddress() .withProximityPlacementGroup(setCreated.proximityPlacementGroup().id()) .withPopularWindowsImage(KnownWindowsVirtualMachineImage.WINDOWS_SERVER_2019_DATACENTER) .withAdminUsername("Foo12") .withAdminPassword(password()) .withUnmanagedDisks() .withSize(VirtualMachineSizeTypes.STANDARD_DS3_V2) .withOSDiskCaching(CachingTypes.READ_WRITE) .withOSDiskName("javatest") .withLicenseType("Windows_Server") .create(); VirtualMachine foundVM = null; PagedIterable<VirtualMachine> vms = computeManager.virtualMachines().listByResourceGroup(rgName); for (VirtualMachine vm1 : vms) { if (vm1.name().equals(vmName)) { foundVM = vm1; break; } } Assertions.assertNotNull(foundVM); Assertions.assertEquals(regionProxPlacementGroup, foundVM.region()); foundVM = computeManager.virtualMachines().getByResourceGroup(rgName, vmName); Assertions.assertNotNull(foundVM); Assertions.assertEquals(regionProxPlacementGroup, foundVM.region()); Assertions.assertEquals("Windows_Server", foundVM.licenseType()); PowerState powerState = foundVM.powerState(); Assertions.assertEquals(powerState, PowerState.RUNNING); VirtualMachineInstanceView instanceView = foundVM.instanceView(); Assertions.assertNotNull(instanceView); Assertions.assertNotNull(instanceView.statuses().size() > 0); Assertions.assertNotNull(foundVM.proximityPlacementGroup()); Assertions.assertEquals(proxGroupType, foundVM.proximityPlacementGroup().proximityPlacementGroupType()); Assertions.assertNotNull(foundVM.proximityPlacementGroup().availabilitySetIds()); Assertions.assertFalse(foundVM.proximityPlacementGroup().availabilitySetIds().isEmpty()); Assertions .assertTrue( setCreated.id().equalsIgnoreCase(foundVM.proximityPlacementGroup().availabilitySetIds().get(0))); Assertions.assertNotNull(foundVM.proximityPlacementGroup().virtualMachineIds()); Assertions.assertFalse(foundVM.proximityPlacementGroup().virtualMachineIds().isEmpty()); Assertions .assertTrue(foundVM.id().equalsIgnoreCase(setCreated.proximityPlacementGroup().virtualMachineIds().get(0))); try { VirtualMachine updatedVm = foundVM.update().withProximityPlacementGroup(setCreated2.proximityPlacementGroup().id()).apply(); } catch (ManagementException clEx) { Assertions .assertTrue( clEx .getMessage() .contains( "Updating proximity placement group of VM javavm is not allowed while the VM is running." + " Please stop/deallocate the VM and retry the operation.")); } computeManager.virtualMachines().deleteById(foundVM.id()); computeManager.availabilitySets().deleteById(setCreated.id()); } @Test public void canCreateVirtualMachinesAndAvailabilitySetInSameProximityPlacementGroup() throws Exception { AvailabilitySet setCreated = computeManager .availabilitySets() .define(availabilitySetName) .withRegion(regionProxPlacementGroup) .withNewResourceGroup(rgName) .withNewProximityPlacementGroup(proxGroupName, proxGroupType) .create(); Assertions.assertEquals(availabilitySetName, setCreated.name()); Assertions.assertNotNull(setCreated.proximityPlacementGroup()); Assertions.assertEquals(proxGroupType, setCreated.proximityPlacementGroup().proximityPlacementGroupType()); Assertions.assertNotNull(setCreated.proximityPlacementGroup().availabilitySetIds()); Assertions.assertFalse(setCreated.proximityPlacementGroup().availabilitySetIds().isEmpty()); Assertions .assertTrue( setCreated.id().equalsIgnoreCase(setCreated.proximityPlacementGroup().availabilitySetIds().get(0))); Assertions.assertEquals(setCreated.regionName(), setCreated.proximityPlacementGroup().location()); computeManager .virtualMachines() .define(vmName) .withRegion(regionProxPlacementGroup) .withExistingResourceGroup(rgName) .withNewPrimaryNetwork("10.0.0.0/28") .withPrimaryPrivateIPAddressDynamic() .withoutPrimaryPublicIPAddress() .withProximityPlacementGroup(setCreated.proximityPlacementGroup().id()) .withPopularWindowsImage(KnownWindowsVirtualMachineImage.WINDOWS_SERVER_2019_DATACENTER) .withAdminUsername("Foo12") .withAdminPassword(password()) .withUnmanagedDisks() .withSize(VirtualMachineSizeTypes.STANDARD_DS3_V2) .withOSDiskCaching(CachingTypes.READ_WRITE) .withOSDiskName("javatest") .withLicenseType("Windows_Server") .create(); VirtualMachine foundVM = null; PagedIterable<VirtualMachine> vms = computeManager.virtualMachines().listByResourceGroup(rgName); for (VirtualMachine vm1 : vms) { if (vm1.name().equals(vmName)) { foundVM = vm1; break; } } Assertions.assertNotNull(foundVM); Assertions.assertEquals(regionProxPlacementGroup, foundVM.region()); foundVM = computeManager.virtualMachines().getByResourceGroup(rgName, vmName); Assertions.assertNotNull(foundVM); Assertions.assertEquals(regionProxPlacementGroup, foundVM.region()); Assertions.assertEquals("Windows_Server", foundVM.licenseType()); PowerState powerState = foundVM.powerState(); Assertions.assertEquals(powerState, PowerState.RUNNING); VirtualMachineInstanceView instanceView = foundVM.instanceView(); Assertions.assertNotNull(instanceView); Assertions.assertNotNull(instanceView.statuses().size() > 0); Assertions.assertNotNull(foundVM.proximityPlacementGroup()); Assertions.assertEquals(proxGroupType, foundVM.proximityPlacementGroup().proximityPlacementGroupType()); Assertions.assertNotNull(foundVM.proximityPlacementGroup().availabilitySetIds()); Assertions.assertFalse(foundVM.proximityPlacementGroup().availabilitySetIds().isEmpty()); Assertions .assertTrue( setCreated.id().equalsIgnoreCase(foundVM.proximityPlacementGroup().availabilitySetIds().get(0))); Assertions.assertNotNull(foundVM.proximityPlacementGroup().virtualMachineIds()); Assertions.assertFalse(foundVM.proximityPlacementGroup().virtualMachineIds().isEmpty()); Assertions .assertTrue(foundVM.id().equalsIgnoreCase(setCreated.proximityPlacementGroup().virtualMachineIds().get(0))); VirtualMachine updatedVm = foundVM.update().withoutProximityPlacementGroup().apply(); Assertions.assertNotNull(updatedVm.proximityPlacementGroup()); Assertions.assertEquals(proxGroupType, updatedVm.proximityPlacementGroup().proximityPlacementGroupType()); Assertions.assertNotNull(updatedVm.proximityPlacementGroup().availabilitySetIds()); Assertions.assertFalse(updatedVm.proximityPlacementGroup().availabilitySetIds().isEmpty()); Assertions .assertTrue( setCreated.id().equalsIgnoreCase(updatedVm.proximityPlacementGroup().availabilitySetIds().get(0))); computeManager.virtualMachines().deleteById(foundVM.id()); computeManager.availabilitySets().deleteById(setCreated.id()); } @Test public void canCreateVirtualMachinesAndRelatedResourcesInParallel() throws Exception { String vmNamePrefix = "vmz"; String publicIpNamePrefix = generateRandomResourceName("pip-", 15); String networkNamePrefix = generateRandomResourceName("vnet-", 15); int count = 5; CreatablesInfo creatablesInfo = prepareCreatableVirtualMachines(region, vmNamePrefix, networkNamePrefix, publicIpNamePrefix, count); List<Creatable<VirtualMachine>> virtualMachineCreatables = creatablesInfo.virtualMachineCreatables; List<String> networkCreatableKeys = creatablesInfo.networkCreatableKeys; List<String> publicIpCreatableKeys = creatablesInfo.publicIpCreatableKeys; CreatedResources<VirtualMachine> createdVirtualMachines = computeManager.virtualMachines().create(virtualMachineCreatables); Assertions.assertTrue(createdVirtualMachines.size() == count); Set<String> virtualMachineNames = new HashSet<>(); for (int i = 0; i < count; i++) { virtualMachineNames.add(String.format("%s-%d", vmNamePrefix, i)); } for (VirtualMachine virtualMachine : createdVirtualMachines.values()) { Assertions.assertTrue(virtualMachineNames.contains(virtualMachine.name())); Assertions.assertNotNull(virtualMachine.id()); } Set<String> networkNames = new HashSet<>(); for (int i = 0; i < count; i++) { networkNames.add(String.format("%s-%d", networkNamePrefix, i)); } for (String networkCreatableKey : networkCreatableKeys) { Network createdNetwork = (Network) createdVirtualMachines.createdRelatedResource(networkCreatableKey); Assertions.assertNotNull(createdNetwork); Assertions.assertTrue(networkNames.contains(createdNetwork.name())); } Set<String> publicIPAddressNames = new HashSet<>(); for (int i = 0; i < count; i++) { publicIPAddressNames.add(String.format("%s-%d", publicIpNamePrefix, i)); } for (String publicIpCreatableKey : publicIpCreatableKeys) { PublicIpAddress createdPublicIpAddress = (PublicIpAddress) createdVirtualMachines.createdRelatedResource(publicIpCreatableKey); Assertions.assertNotNull(createdPublicIpAddress); Assertions.assertTrue(publicIPAddressNames.contains(createdPublicIpAddress.name())); } } @Test public void canStreamParallelCreatedVirtualMachinesAndRelatedResources() throws Exception { String vmNamePrefix = "vmz"; String publicIpNamePrefix = generateRandomResourceName("pip-", 15); String networkNamePrefix = generateRandomResourceName("vnet-", 15); int count = 5; final Set<String> virtualMachineNames = new HashSet<>(); for (int i = 0; i < count; i++) { virtualMachineNames.add(String.format("%s-%d", vmNamePrefix, i)); } final Set<String> networkNames = new HashSet<>(); for (int i = 0; i < count; i++) { networkNames.add(String.format("%s-%d", networkNamePrefix, i)); } final Set<String> publicIPAddressNames = new HashSet<>(); for (int i = 0; i < count; i++) { publicIPAddressNames.add(String.format("%s-%d", publicIpNamePrefix, i)); } final CreatablesInfo creatablesInfo = prepareCreatableVirtualMachines(region, vmNamePrefix, networkNamePrefix, publicIpNamePrefix, count); final AtomicInteger resourceCount = new AtomicInteger(0); List<Creatable<VirtualMachine>> virtualMachineCreatables = creatablesInfo.virtualMachineCreatables; computeManager .virtualMachines() .createAsync(virtualMachineCreatables) .map( createdResource -> { if (createdResource instanceof Resource) { Resource resource = (Resource) createdResource; System.out.println("Created: " + resource.id()); if (resource instanceof VirtualMachine) { VirtualMachine virtualMachine = (VirtualMachine) resource; Assertions.assertTrue(virtualMachineNames.contains(virtualMachine.name())); Assertions.assertNotNull(virtualMachine.id()); } else if (resource instanceof Network) { Network network = (Network) resource; Assertions.assertTrue(networkNames.contains(network.name())); Assertions.assertNotNull(network.id()); } else if (resource instanceof PublicIpAddress) { PublicIpAddress publicIPAddress = (PublicIpAddress) resource; Assertions.assertTrue(publicIPAddressNames.contains(publicIPAddress.name())); Assertions.assertNotNull(publicIPAddress.id()); } } resourceCount.incrementAndGet(); return createdResource; }) .blockLast(); networkNames.forEach(name -> { Assertions.assertNotNull(networkManager.networks().getByResourceGroup(rgName, name)); }); publicIPAddressNames.forEach(name -> { Assertions.assertNotNull(networkManager.publicIpAddresses().getByResourceGroup(rgName, name)); }); Assertions.assertEquals(1, storageManager.storageAccounts().listByResourceGroup(rgName).stream().count()); Assertions.assertEquals(count, networkManager.networkInterfaces().listByResourceGroup(rgName).stream().count()); Assertions.assertEquals(count, resourceCount.get()); } @Test @Test public void canUpdateTagsOnVM() { 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("firstuser") .withRootPassword("afh123RVS!") .withSize(VirtualMachineSizeTypes.STANDARD_D3_V2) .create(); virtualMachine.update().withTag("test", "testValue").apply(); Assertions.assertEquals("testValue", virtualMachine.inner().tags().get("test")); Map<String, String> testTags = new HashMap<String, String>(); testTags.put("testTag", "testValue"); virtualMachine.update().withTags(testTags).apply(); Assertions.assertEquals(testTags, virtualMachine.inner().tags()); } @Test public void canRunScriptOnVM() { 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("firstuser") .withRootPassword("afh123RVS!") .create(); List<String> installGit = new ArrayList<>(); installGit.add("sudo apt-get update"); installGit.add("sudo apt-get install -y git"); RunCommandResult runResult = virtualMachine.runShellScript(installGit, new ArrayList<RunCommandInputParameter>()); Assertions.assertNotNull(runResult); Assertions.assertNotNull(runResult.value()); Assertions.assertTrue(runResult.value().size() > 0); } @Test public void canPerformSimulateEvictionOnSpotVirtualMachine() { 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("firstuser") .withRootPassword("afh123RVS!") .withSpotPriority(VirtualMachineEvictionPolicyTypes.DEALLOCATE) .withSize(VirtualMachineSizeTypes.STANDARD_D2_V3) .create(); Assertions.assertNotNull(virtualMachine.osDiskStorageAccountType()); Assertions.assertTrue(virtualMachine.osDiskSize() > 0); Disk disk = computeManager.disks().getById(virtualMachine.osDiskId()); Assertions.assertNotNull(disk); Assertions.assertEquals(DiskState.ATTACHED, disk.inner().diskState()); virtualMachine.simulateEviction(); SdkContext.sleep(30 * 60 * 1000); virtualMachine = computeManager.virtualMachines().getById(virtualMachine.id()); Assertions.assertNotNull(virtualMachine); Assertions.assertNull(virtualMachine.osDiskStorageAccountType()); Assertions.assertTrue(virtualMachine.osDiskSize() == 0); disk = computeManager.disks().getById(virtualMachine.osDiskId()); Assertions.assertEquals(DiskState.RESERVED, disk.inner().diskState()); } private CreatablesInfo prepareCreatableVirtualMachines( Region region, String vmNamePrefix, String networkNamePrefix, String publicIpNamePrefix, int vmCount) { Creatable<ResourceGroup> resourceGroupCreatable = resourceManager.resourceGroups().define(rgName).withRegion(region); Creatable<StorageAccount> storageAccountCreatable = storageManager .storageAccounts() .define(generateRandomResourceName("stg", 20)) .withRegion(region) .withNewResourceGroup(resourceGroupCreatable); List<String> networkCreatableKeys = new ArrayList<>(); List<String> publicIpCreatableKeys = new ArrayList<>(); List<Creatable<VirtualMachine>> virtualMachineCreatables = new ArrayList<>(); for (int i = 0; i < vmCount; i++) { Creatable<Network> networkCreatable = networkManager .networks() .define(String.format("%s-%d", networkNamePrefix, i)) .withRegion(region) .withNewResourceGroup(resourceGroupCreatable) .withAddressSpace("10.0.0.0/28"); networkCreatableKeys.add(networkCreatable.key()); Creatable<PublicIpAddress> publicIPAddressCreatable = networkManager .publicIpAddresses() .define(String.format("%s-%d", publicIpNamePrefix, i)) .withRegion(region) .withNewResourceGroup(resourceGroupCreatable); publicIpCreatableKeys.add(publicIPAddressCreatable.key()); Creatable<VirtualMachine> virtualMachineCreatable = computeManager .virtualMachines() .define(String.format("%s-%d", vmNamePrefix, i)) .withRegion(region) .withNewResourceGroup(resourceGroupCreatable) .withNewPrimaryNetwork(networkCreatable) .withPrimaryPrivateIPAddressDynamic() .withNewPrimaryPublicIPAddress(publicIPAddressCreatable) .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) .withRootUsername("tirekicker") .withRootPassword("BaR@12! .withUnmanagedDisks() .withNewStorageAccount(storageAccountCreatable); virtualMachineCreatables.add(virtualMachineCreatable); } CreatablesInfo creatablesInfo = new CreatablesInfo(); creatablesInfo.virtualMachineCreatables = virtualMachineCreatables; creatablesInfo.networkCreatableKeys = networkCreatableKeys; creatablesInfo.publicIpCreatableKeys = publicIpCreatableKeys; return creatablesInfo; } class CreatablesInfo { private List<Creatable<VirtualMachine>> virtualMachineCreatables; List<String> networkCreatableKeys; List<String> publicIpCreatableKeys; } }
getActiveDirectoryEndpoint
public static void main(String[] args) { try { final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); final TokenCredential credential = new DefaultAzureCredentialBuilder() .authorityHost(profile.getEnvironment().getResourceManagerEndpoint()) .build(); Azure azure = Azure .configure() .withLogLevel(HttpLogDetailLevel.BASIC) .authenticate(credential, profile) .withDefaultSubscription(); System.out.println("Selected subscription: " + azure.subscriptionId()); runSample(azure, Configuration.getGlobalConfiguration().get(Configuration.PROPERTY_AZURE_CLIENT_ID)); } catch (Exception e) { System.out.println(e.getMessage()); e.printStackTrace(); } }
.authorityHost(profile.getEnvironment().getResourceManagerEndpoint())
public static void main(String[] args) { try { final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); final TokenCredential credential = new DefaultAzureCredentialBuilder() .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); Azure azure = Azure .configure() .withLogLevel(HttpLogDetailLevel.BASIC) .authenticate(credential, profile) .withDefaultSubscription(); System.out.println("Selected subscription: " + azure.subscriptionId()); runSample(azure, Configuration.getGlobalConfiguration().get(Configuration.PROPERTY_AZURE_CLIENT_ID)); } catch (Exception e) { System.out.println(e.getMessage()); e.printStackTrace(); } }
class ManageSpringCloud { private static final String PIGGYMETRICS_TAR_GZ_URL = "https: private static final String SPRING_CLOUD_SERVICE_PRINCIPAL = "03b39d0f-4213-4864-a245-b1476ec03169"; /** * Main function which runs the actual sample. * @param azure instance of the azure client * @param clientId the aad client id in azure instance * @return true if sample runs successfully * @throws IllegalStateException unexcepted state */ public static boolean runSample(Azure azure, String clientId) throws IOException, KeyStoreException, CertificateException, NoSuchAlgorithmException { final String rgName = azure.sdkContext().randomResourceName("rg", 24); final String serviceName = azure.sdkContext().randomResourceName("service", 24); final Region region = Region.US_EAST; final String domainName = azure.sdkContext().randomResourceName("jsdkdemo-", 20) + ".com"; final String certOrderName = azure.sdkContext().randomResourceName("cert", 15); final String vaultName = azure.sdkContext().randomResourceName("vault", 15); final String certName = azure.sdkContext().randomResourceName("cert", 15); try { azure.resourceGroups().define(rgName) .withRegion(region) .create(); System.out.printf("Creating spring cloud service %s in resource group %s ...%n", serviceName, rgName); SpringService service = azure.springServices().define(serviceName) .withRegion(region) .withExistingResourceGroup(rgName) .create(); System.out.printf("Created spring cloud service %s%n", service.name()); Utils.print(service); File gzFile = new File("piggymetrics.tar.gz"); if (!gzFile.exists()) { HttpURLConnection connection = (HttpURLConnection) new URL(PIGGYMETRICS_TAR_GZ_URL).openConnection(); connection.connect(); try (InputStream inputStream = connection.getInputStream(); OutputStream outputStream = new FileOutputStream(gzFile)) { IOUtils.copy(inputStream, outputStream); } connection.disconnect(); } System.out.printf("Creating spring cloud app gateway in resource group %s ...%n", rgName); SpringApp gateway = service.apps().define("gateway") .defineActiveDeployment("default") .withSourceCodeTarGzFile(gzFile) .withTargetModule("gateway") .attach() .withDefaultPublicEndpoint() .withHttpsOnly() .create(); System.out.println("Created spring cloud service gateway"); Utils.print(gateway); System.out.printf("Creating spring cloud app auth-service in resource group %s ...%n", rgName); SpringApp authService = service.apps().define("auth-service") .defineActiveDeployment("default") .withSourceCodeTarGzFile(gzFile) .withTargetModule("auth-service") .attach() .create(); System.out.println("Created spring cloud service auth-service"); Utils.print(authService); System.out.printf("Creating spring cloud app account-service in resource group %s ...%n", rgName); SpringApp accountService = service.apps().define("account-service") .defineActiveDeployment("default") .withSourceCodeTarGzFile(gzFile) .withTargetModule("account-service") .attach() .create(); System.out.println("Created spring cloud service account-service"); Utils.print(accountService); System.out.println("Purchasing a domain " + domainName + "..."); AppServiceDomain domain = azure.appServiceDomains().define(domainName) .withExistingResourceGroup(rgName) .defineRegistrantContact() .withFirstName("Jon") .withLastName("Doe") .withEmail("jondoe@contoso.com") .withAddressLine1("123 4th Ave") .withCity("Redmond") .withStateOrProvince("WA") .withCountry(CountryIsoCode.UNITED_STATES) .withPostalCode("98052") .withPhoneCountryCode(CountryPhoneCode.UNITED_STATES) .withPhoneNumber("4258828080") .attach() .withDomainPrivacyEnabled(true) .withAutoRenewEnabled(false) .create(); System.out.println("Purchased domain " + domain.name()); Utils.print(domain); DnsZone dnsZone = azure.dnsZones().getById(domain.dnsZoneId()); gateway.refresh(); System.out.printf("Updating dns with CNAME ssl.%s to %s%n", domainName, gateway.fqdn()); dnsZone.update() .withCNameRecordSet("ssl", gateway.fqdn()) .apply(); System.out.printf("Purchasing a certificate for *.%s and save to %s in key vault named %s ...%n", domainName, certOrderName, vaultName); AppServiceCertificateOrder certificateOrder = azure.appServiceCertificateOrders().define(certOrderName) .withExistingResourceGroup(rgName) .withHostName(String.format("*.%s", domainName)) .withWildcardSku() .withDomainVerification(domain) .withNewKeyVault(vaultName, region) .withAutoRenew(true) .create(); System.out.printf("Purchased certificate: *.%s ...%n", domain.name()); Utils.print(certificateOrder); System.out.printf("Updating key vault %s with access from %s, %s%n", vaultName, clientId, SPRING_CLOUD_SERVICE_PRINCIPAL); Vault vault = azure.vaults().getByResourceGroup(rgName, vaultName); vault.update() .defineAccessPolicy() .forServicePrincipal(clientId) .allowSecretAllPermissions() .allowCertificateAllPermissions() .attach() .defineAccessPolicy() .forServicePrincipal(SPRING_CLOUD_SERVICE_PRINCIPAL) .allowCertificatePermissions(CertificatePermissions.GET, CertificatePermissions.LIST) .allowSecretPermissions(SecretPermissions.GET, SecretPermissions.LIST) .attach() .apply(); System.out.printf("Updated key vault %s%n", vault.name()); Utils.print(vault); Secret secret = vault.secrets().getByName(certOrderName); byte[] certificate = Base64.getDecoder().decode(secret.value()); String thumbprint = secret.tags().get("Thumbprint"); if (thumbprint == null || thumbprint.isEmpty()) { KeyStore store = KeyStore.getInstance("PKCS12"); store.load(new ByteArrayInputStream(certificate), null); String alias = Collections.list(store.aliases()).get(0); thumbprint = DatatypeConverter.printHexBinary(MessageDigest.getInstance("SHA-1").digest(store.getCertificate(alias).getEncoded())); } System.out.printf("Get certificate: %s%n", secret.value()); System.out.printf("Certificate Thumbprint: %s%n", thumbprint); CertificateClient certificateClient = new CertificateClientBuilder() .vaultUrl(vault.vaultUri()) .pipeline(service.manager().httpPipeline()) .buildClient(); System.out.printf("Uploading certificate to %s in key vault ...%n", certName); certificateClient.importCertificate( new ImportCertificateOptions(certName, certificate) .setEnabled(true) ); System.out.println("Updating Spring Cloud Service with certificate ..."); service.update() .withCertificate(certName, vault.vaultUri(), certName) .apply(); System.out.printf("Updating Spring Cloud App with domain ssl.%s ...%n", domainName); gateway.update() .withCustomDomain(String.format("ssl.%s", domainName), thumbprint) .apply(); System.out.printf("Successfully expose domain ssl.%s%n", domainName); return true; } finally { try { System.out.println("Delete Resource Group: " + rgName); azure.resourceGroups().beginDeleteByName(rgName); } catch (NullPointerException npe) { System.out.println("Did not create any resources in Azure. No clean up is necessary"); } catch (Exception g) { g.printStackTrace(); } } } /** * Main entry point. * @param args the parameters */ public static void extraTarGzSource(File folder, URL url) throws IOException { HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.connect(); try (TarArchiveInputStream inputStream = new TarArchiveInputStream(new GzipCompressorInputStream(connection.getInputStream()))) { TarArchiveEntry entry; while ((entry = inputStream.getNextTarEntry()) != null) { if (entry.isDirectory()) { continue; } File file = new File(folder, entry.getName()); File parent = file.getParentFile(); if (parent.exists() || parent.mkdirs()) { try (OutputStream outputStream = new FileOutputStream(file)) { IOUtils.copy(inputStream, outputStream); } } else { throw new IllegalStateException("Cannot create directory: " + parent.getAbsolutePath()); } } } finally { connection.disconnect(); } } }
class ManageSpringCloud { private static final String PIGGYMETRICS_TAR_GZ_URL = "https: private static final String SPRING_CLOUD_SERVICE_PRINCIPAL = "03b39d0f-4213-4864-a245-b1476ec03169"; /** * Main function which runs the actual sample. * @param azure instance of the azure client * @param clientId the aad client id in azure instance * @return true if sample runs successfully * @throws IllegalStateException unexcepted state */ public static boolean runSample(Azure azure, String clientId) throws IOException, KeyStoreException, CertificateException, NoSuchAlgorithmException { final String rgName = azure.sdkContext().randomResourceName("rg", 24); final String serviceName = azure.sdkContext().randomResourceName("service", 24); final Region region = Region.US_EAST; final String domainName = azure.sdkContext().randomResourceName("jsdkdemo-", 20) + ".com"; final String certOrderName = azure.sdkContext().randomResourceName("cert", 15); final String vaultName = azure.sdkContext().randomResourceName("vault", 15); final String certName = azure.sdkContext().randomResourceName("cert", 15); try { azure.resourceGroups().define(rgName) .withRegion(region) .create(); System.out.printf("Creating spring cloud service %s in resource group %s ...%n", serviceName, rgName); SpringService service = azure.springServices().define(serviceName) .withRegion(region) .withExistingResourceGroup(rgName) .create(); System.out.printf("Created spring cloud service %s%n", service.name()); Utils.print(service); File gzFile = new File("piggymetrics.tar.gz"); if (!gzFile.exists()) { HttpURLConnection connection = (HttpURLConnection) new URL(PIGGYMETRICS_TAR_GZ_URL).openConnection(); connection.connect(); try (InputStream inputStream = connection.getInputStream(); OutputStream outputStream = new FileOutputStream(gzFile)) { IOUtils.copy(inputStream, outputStream); } connection.disconnect(); } System.out.printf("Creating spring cloud app gateway in resource group %s ...%n", rgName); SpringApp gateway = service.apps().define("gateway") .defineActiveDeployment("default") .withSourceCodeTarGzFile(gzFile) .withTargetModule("gateway") .attach() .withDefaultPublicEndpoint() .withHttpsOnly() .create(); System.out.println("Created spring cloud service gateway"); Utils.print(gateway); System.out.printf("Creating spring cloud app auth-service in resource group %s ...%n", rgName); SpringApp authService = service.apps().define("auth-service") .defineActiveDeployment("default") .withSourceCodeTarGzFile(gzFile) .withTargetModule("auth-service") .attach() .create(); System.out.println("Created spring cloud service auth-service"); Utils.print(authService); System.out.printf("Creating spring cloud app account-service in resource group %s ...%n", rgName); SpringApp accountService = service.apps().define("account-service") .defineActiveDeployment("default") .withSourceCodeTarGzFile(gzFile) .withTargetModule("account-service") .attach() .create(); System.out.println("Created spring cloud service account-service"); Utils.print(accountService); System.out.println("Purchasing a domain " + domainName + "..."); AppServiceDomain domain = azure.appServiceDomains().define(domainName) .withExistingResourceGroup(rgName) .defineRegistrantContact() .withFirstName("Jon") .withLastName("Doe") .withEmail("jondoe@contoso.com") .withAddressLine1("123 4th Ave") .withCity("Redmond") .withStateOrProvince("WA") .withCountry(CountryIsoCode.UNITED_STATES) .withPostalCode("98052") .withPhoneCountryCode(CountryPhoneCode.UNITED_STATES) .withPhoneNumber("4258828080") .attach() .withDomainPrivacyEnabled(true) .withAutoRenewEnabled(false) .create(); System.out.println("Purchased domain " + domain.name()); Utils.print(domain); DnsZone dnsZone = azure.dnsZones().getById(domain.dnsZoneId()); gateway.refresh(); System.out.printf("Updating dns with CNAME ssl.%s to %s%n", domainName, gateway.fqdn()); dnsZone.update() .withCNameRecordSet("ssl", gateway.fqdn()) .apply(); System.out.printf("Purchasing a certificate for *.%s and save to %s in key vault named %s ...%n", domainName, certOrderName, vaultName); AppServiceCertificateOrder certificateOrder = azure.appServiceCertificateOrders().define(certOrderName) .withExistingResourceGroup(rgName) .withHostName(String.format("*.%s", domainName)) .withWildcardSku() .withDomainVerification(domain) .withNewKeyVault(vaultName, region) .withAutoRenew(true) .create(); System.out.printf("Purchased certificate: *.%s ...%n", domain.name()); Utils.print(certificateOrder); System.out.printf("Updating key vault %s with access from %s, %s%n", vaultName, clientId, SPRING_CLOUD_SERVICE_PRINCIPAL); Vault vault = azure.vaults().getByResourceGroup(rgName, vaultName); vault.update() .defineAccessPolicy() .forServicePrincipal(clientId) .allowSecretAllPermissions() .allowCertificateAllPermissions() .attach() .defineAccessPolicy() .forServicePrincipal(SPRING_CLOUD_SERVICE_PRINCIPAL) .allowCertificatePermissions(CertificatePermissions.GET, CertificatePermissions.LIST) .allowSecretPermissions(SecretPermissions.GET, SecretPermissions.LIST) .attach() .apply(); System.out.printf("Updated key vault %s%n", vault.name()); Utils.print(vault); Secret secret = vault.secrets().getByName(certOrderName); byte[] certificate = Base64.getDecoder().decode(secret.value()); String thumbprint = secret.tags().get("Thumbprint"); if (thumbprint == null || thumbprint.isEmpty()) { KeyStore store = KeyStore.getInstance("PKCS12"); store.load(new ByteArrayInputStream(certificate), null); String alias = Collections.list(store.aliases()).get(0); thumbprint = DatatypeConverter.printHexBinary(MessageDigest.getInstance("SHA-1").digest(store.getCertificate(alias).getEncoded())); } System.out.printf("Get certificate: %s%n", secret.value()); System.out.printf("Certificate Thumbprint: %s%n", thumbprint); CertificateClient certificateClient = new CertificateClientBuilder() .vaultUrl(vault.vaultUri()) .pipeline(service.manager().httpPipeline()) .buildClient(); System.out.printf("Uploading certificate to %s in key vault ...%n", certName); certificateClient.importCertificate( new ImportCertificateOptions(certName, certificate) .setEnabled(true) ); System.out.println("Updating Spring Cloud Service with certificate ..."); service.update() .withCertificate(certName, vault.vaultUri(), certName) .apply(); System.out.printf("Updating Spring Cloud App with domain ssl.%s ...%n", domainName); gateway.update() .withCustomDomain(String.format("ssl.%s", domainName), thumbprint) .apply(); System.out.printf("Successfully expose domain ssl.%s%n", domainName); return true; } finally { try { System.out.println("Delete Resource Group: " + rgName); azure.resourceGroups().beginDeleteByName(rgName); } catch (NullPointerException npe) { System.out.println("Did not create any resources in Azure. No clean up is necessary"); } catch (Exception g) { g.printStackTrace(); } } } /** * Main entry point. * @param args the parameters */ public static void extraTarGzSource(File folder, URL url) throws IOException { HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.connect(); try (TarArchiveInputStream inputStream = new TarArchiveInputStream(new GzipCompressorInputStream(connection.getInputStream()))) { TarArchiveEntry entry; while ((entry = inputStream.getNextTarEntry()) != null) { if (entry.isDirectory()) { continue; } File file = new File(folder, entry.getName()); File parent = file.getParentFile(); if (parent.exists() || parent.mkdirs()) { try (OutputStream outputStream = new FileOutputStream(file)) { IOUtils.copy(inputStream, outputStream); } } else { throw new IllegalStateException("Cannot create directory: " + parent.getAbsolutePath()); } } } finally { connection.disconnect(); } } }
Remove here.
public static void main(String[] args) { try { final Region region = Region.US_WEST_CENTRAL; final String usage = "Usage: mvn clean compile exec:java -Dexec.args=\"<subscription-id> <rg-name> <client-id>\""; if (args.length < 2) { throw new IllegalArgumentException(usage); } final String subscriptionId = args[0]; final String resourceGroupName = args[1]; final String clientId = args[2]; final String linuxVMName = "yourVirtualMachineName"; final String userName = "tirekicker"; final String password = Utils.password(); ManagedIdentityCredential credential = new ManagedIdentityCredentialBuilder() .clientId(clientId) .build(); AzureProfile profile = new AzureProfile(null, subscriptionId, AzureEnvironment.AZURE); Azure azure = Azure.configure() .withLogLevel(HttpLogDetailLevel.BASIC) .authenticate(credential, profile) .withSubscription(subscriptionId); System.out.println("Selected subscription: " + azure.subscriptionId()); System.out.println("Creating a Linux VM using ManagedIdentityCredential."); VirtualMachine virtualMachine = azure.virtualMachines() .define(linuxVMName) .withRegion(region) .withExistingResourceGroup(resourceGroupName) .withNewPrimaryNetwork("10.0.0.0/28") .withPrimaryPrivateIPAddressDynamic() .withoutPrimaryPublicIPAddress() .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) .withRootUsername(userName) .withRootPassword(password) .create(); System.out.println("Created virtual machine using ManagedIdentityCredential."); Utils.print(virtualMachine); } catch (Exception e) { System.out.println(e.getMessage()); e.printStackTrace(); } }
}
public static void main(String[] args) { final Region region = Region.US_WEST_CENTRAL; final String usage = "Usage: mvn clean compile exec:java -Dexec.args=\"<subscription-id> <rg-name> [<client-id>]\""; if (args.length < 2) { throw new IllegalArgumentException(usage); } final String subscriptionId = args[0]; final String resourceGroupName = args[1]; final String clientId = args.length > 2 ? args[2] : null; final String linuxVMName = "yourVirtualMachineName"; final String userName = "tirekicker"; final String password = Utils.password(); ManagedIdentityCredential credential = new ManagedIdentityCredentialBuilder() .clientId(clientId) .build(); AzureProfile profile = new AzureProfile(null, subscriptionId, AzureEnvironment.AZURE); Azure azure = Azure.configure() .withLogLevel(HttpLogDetailLevel.BASIC) .authenticate(credential, profile) .withSubscription(subscriptionId); System.out.println("Selected subscription: " + azure.subscriptionId()); System.out.println("Creating a Linux VM using ManagedIdentityCredential."); VirtualMachine virtualMachine = azure.virtualMachines() .define(linuxVMName) .withRegion(region) .withExistingResourceGroup(resourceGroupName) .withNewPrimaryNetwork("10.0.0.0/28") .withPrimaryPrivateIPAddressDynamic() .withoutPrimaryPublicIPAddress() .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) .withRootUsername(userName) .withRootPassword(password) .create(); System.out.println("Created virtual machine using ManagedIdentityCredential."); Utils.print(virtualMachine); System.out.println("Deleting resource group: " + resourceGroupName); azure.resourceGroups().deleteByName(resourceGroupName); System.out.println("Deleted resource group: " + resourceGroupName); }
class ManageVirtualMachineFromMSIEnabledVirtualMachine { /** * Main entry point. * * @param args the parameters */ private ManageVirtualMachineFromMSIEnabledVirtualMachine() { } }
class ManageVirtualMachineFromMSIEnabledVirtualMachine { /** * Main entry point. * * @param args the parameters */ private ManageVirtualMachineFromMSIEnabledVirtualMachine() { } }
removed.
public static void main(String[] args) { try { final Region region = Region.US_WEST_CENTRAL; final String usage = "Usage: mvn clean compile exec:java -Dexec.args=\"<subscription-id> <rg-name> <client-id>\""; if (args.length < 2) { throw new IllegalArgumentException(usage); } final String subscriptionId = args[0]; final String resourceGroupName = args[1]; final String clientId = args[2]; final String linuxVMName = "yourVirtualMachineName"; final String userName = "tirekicker"; final String password = Utils.password(); ManagedIdentityCredential credential = new ManagedIdentityCredentialBuilder() .clientId(clientId) .build(); AzureProfile profile = new AzureProfile(null, subscriptionId, AzureEnvironment.AZURE); Azure azure = Azure.configure() .withLogLevel(HttpLogDetailLevel.BASIC) .authenticate(credential, profile) .withSubscription(subscriptionId); System.out.println("Selected subscription: " + azure.subscriptionId()); System.out.println("Creating a Linux VM using ManagedIdentityCredential."); VirtualMachine virtualMachine = azure.virtualMachines() .define(linuxVMName) .withRegion(region) .withExistingResourceGroup(resourceGroupName) .withNewPrimaryNetwork("10.0.0.0/28") .withPrimaryPrivateIPAddressDynamic() .withoutPrimaryPublicIPAddress() .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) .withRootUsername(userName) .withRootPassword(password) .create(); System.out.println("Created virtual machine using ManagedIdentityCredential."); Utils.print(virtualMachine); } catch (Exception e) { System.out.println(e.getMessage()); e.printStackTrace(); } }
}
public static void main(String[] args) { final Region region = Region.US_WEST_CENTRAL; final String usage = "Usage: mvn clean compile exec:java -Dexec.args=\"<subscription-id> <rg-name> [<client-id>]\""; if (args.length < 2) { throw new IllegalArgumentException(usage); } final String subscriptionId = args[0]; final String resourceGroupName = args[1]; final String clientId = args.length > 2 ? args[2] : null; final String linuxVMName = "yourVirtualMachineName"; final String userName = "tirekicker"; final String password = Utils.password(); ManagedIdentityCredential credential = new ManagedIdentityCredentialBuilder() .clientId(clientId) .build(); AzureProfile profile = new AzureProfile(null, subscriptionId, AzureEnvironment.AZURE); Azure azure = Azure.configure() .withLogLevel(HttpLogDetailLevel.BASIC) .authenticate(credential, profile) .withSubscription(subscriptionId); System.out.println("Selected subscription: " + azure.subscriptionId()); System.out.println("Creating a Linux VM using ManagedIdentityCredential."); VirtualMachine virtualMachine = azure.virtualMachines() .define(linuxVMName) .withRegion(region) .withExistingResourceGroup(resourceGroupName) .withNewPrimaryNetwork("10.0.0.0/28") .withPrimaryPrivateIPAddressDynamic() .withoutPrimaryPublicIPAddress() .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) .withRootUsername(userName) .withRootPassword(password) .create(); System.out.println("Created virtual machine using ManagedIdentityCredential."); Utils.print(virtualMachine); System.out.println("Deleting resource group: " + resourceGroupName); azure.resourceGroups().deleteByName(resourceGroupName); System.out.println("Deleted resource group: " + resourceGroupName); }
class ManageVirtualMachineFromMSIEnabledVirtualMachine { /** * Main entry point. * * @param args the parameters */ private ManageVirtualMachineFromMSIEnabledVirtualMachine() { } }
class ManageVirtualMachineFromMSIEnabledVirtualMachine { /** * Main entry point. * * @param args the parameters */ private ManageVirtualMachineFromMSIEnabledVirtualMachine() { } }
(not required for beta.1) we don't need log handling, this is all hack to transport logs over spans, and not official OpenTelemetry (which will support Logs separately in the future)
private void export(SpanData span, List<TelemetryItem> telemetryItems) { Span.Kind kind = span.getKind(); String instrumentationName = span.getInstrumentationLibraryInfo().getName(); Matcher matcher = COMPONENT_PATTERN.matcher(instrumentationName); String stdComponent = matcher.matches() ? matcher.group(1) : null; if ("jms".equals(stdComponent) && !span.getParentSpanId().isValid() && kind == Span.Kind.CLIENT) { return; } if (kind == Span.Kind.INTERNAL) { if (span.getName().equals("log.message")) { exportLogSpan(span, telemetryItems); } else if (!span.getParentSpanId().isValid()) { exportRequest(stdComponent, span, telemetryItems); } else if (span.getName().equals("EventHubs.message")) { exportRemoteDependency(stdComponent, span, false, telemetryItems); } else { exportRemoteDependency(stdComponent, span, true, telemetryItems); } } else if (kind == Span.Kind.CLIENT || kind == Span.Kind.PRODUCER) { exportRemoteDependency(stdComponent, span, false, telemetryItems); } else if (kind == Span.Kind.SERVER || kind == Span.Kind.CONSUMER) { exportRequest(stdComponent, span, telemetryItems); } else { throw new UnsupportedOperationException(kind.name()); } }
exportLogSpan(span, telemetryItems);
private void export(SpanData span, List<TelemetryItem> telemetryItems) { Span.Kind kind = span.getKind(); String instrumentationName = span.getInstrumentationLibraryInfo().getName(); Matcher matcher = COMPONENT_PATTERN.matcher(instrumentationName); String stdComponent = matcher.matches() ? matcher.group(1) : null; if ("jms".equals(stdComponent) && !span.getParentSpanId().isValid() && kind == Span.Kind.CLIENT) { return; } if (kind == Span.Kind.INTERNAL) { if (!span.getParentSpanId().isValid()) { exportRequest(stdComponent, span, telemetryItems); } else if (span.getName().equals("EventHubs.message")) { exportRemoteDependency(stdComponent, span, false, telemetryItems); } else { exportRemoteDependency(stdComponent, span, true, telemetryItems); } } else if (kind == Span.Kind.CLIENT || kind == Span.Kind.PRODUCER) { exportRemoteDependency(stdComponent, span, false, telemetryItems); } else if (kind == Span.Kind.SERVER || kind == Span.Kind.CONSUMER) { exportRequest(stdComponent, span, telemetryItems); } else { throw new UnsupportedOperationException(kind.name()); } }
class AzureMonitorExporter implements SpanExporter { private static final Pattern COMPONENT_PATTERN = Pattern .compile("io\\.opentelemetry\\.auto\\.([^0-9]*)(-[0-9.]*)?"); private static final Set<String> SQL_DB_SYSTEMS; static { Set<String> dbSystems = new HashSet<>(); dbSystems.add("db2"); dbSystems.add("derby"); dbSystems.add("mariadb"); dbSystems.add("mssql"); dbSystems.add("mysql"); dbSystems.add("oracle"); dbSystems.add("postgresql"); dbSystems.add("sqlite"); dbSystems.add("other_sql"); dbSystems.add("hsqldb"); dbSystems.add("h2"); SQL_DB_SYSTEMS = Collections.unmodifiableSet(dbSystems); } private final MonitorExporterClient client; private final ClientLogger logger = new ClientLogger(AzureMonitorExporter.class); private final String instrumentationKey; private final String telemetryItemNamePrefix; /** * Creates an instance of exporter that is configured with given exporter client that sends telemetry events to * Application Insights resource identified by the instrumentation key. * * @param client The client used to send data to Azure Monitor. * @param instrumentationKey The instrumentation key of Application Insights resource. */ AzureMonitorExporter(MonitorExporterClient client, String instrumentationKey) { this.client = client; this.instrumentationKey = instrumentationKey; this.telemetryItemNamePrefix = "Microsoft.ApplicationInsights." + instrumentationKey + "."; } /** * {@inheritDoc} */ @Override public CompletableResultCode export(Collection<SpanData> spans) { try { List<TelemetryItem> telemetryItems = new ArrayList<>(); for (SpanData span : spans) { logger.verbose("exporting span: {}", span); export(span, telemetryItems); } client.export(telemetryItems); return CompletableResultCode.ofSuccess(); } catch (Throwable t) { logger.error(t.getMessage(), t); return CompletableResultCode.ofFailure(); } } /** * {@inheritDoc} */ @Override public CompletableResultCode flush() { return CompletableResultCode.ofSuccess(); } /** * {@inheritDoc} */ @Override public CompletableResultCode shutdown() { return CompletableResultCode.ofSuccess(); } private void exportLogSpan(SpanData span, List<TelemetryItem> telemetryItems) { Map<String, AttributeValue> attributes = getAttributesCopy(span.getAttributes()); String message = removeAttributeString(attributes, "message"); String level = removeAttributeString(attributes, "level"); String loggerName = removeAttributeString(attributes, "loggerName"); String errorStack = removeAttributeString(attributes, "error.stack"); Double samplingPercentage = removeAiSamplingPercentage(attributes); if (errorStack == null) { trackTrace(message, span.getStartEpochNanos(), level, loggerName, span.getTraceId(), span.getParentSpanId(), samplingPercentage, attributes, telemetryItems); } else { trackTraceAsException(message, span.getStartEpochNanos(), level, loggerName, errorStack, span.getTraceId(), span.getParentSpanId(), samplingPercentage, attributes, telemetryItems); } } private void trackTrace(String message, long timeEpochNanos, String level, String loggerName, TraceId traceId, SpanId parentSpanId, Double samplingPercentage, Map<String, AttributeValue> attributes, List<TelemetryItem> telemetryItems) { TelemetryItem telemetryItem = new TelemetryItem(); MessageData messageData = new MessageData(); MonitorBase monitorBase = new MonitorBase(); telemetryItem.setTags(new HashMap<>()); telemetryItem.setName(telemetryItemNamePrefix + "Message"); telemetryItem.setVersion(1); telemetryItem.setInstrumentationKey(instrumentationKey); telemetryItem.setData(monitorBase); messageData.setProperties(new HashMap<>()); messageData.setVersion(2); monitorBase.setBaseType("MessageData"); monitorBase.setBaseData(messageData); messageData.setSeverityLevel(toSeverityLevel(level)); messageData.setMessage(message); if (parentSpanId.isValid()) { telemetryItem.getTags().put(ContextTagKeys.AI_OPERATION_ID.toString(), traceId.toLowerBase16()); telemetryItem.getTags().put(ContextTagKeys.AI_OPERATION_PARENT_ID.toString(), parentSpanId.toLowerBase16()); } setProperties(messageData.getProperties(), timeEpochNanos, level, loggerName, attributes); telemetryItem.setSampleRate(samplingPercentage.floatValue()); telemetryItems.add(telemetryItem); } private static void setProperties(Map<String, String> properties, long timeEpochNanos, String level, String loggerName, Map<String, AttributeValue> attributes) { if (level != null) { properties.put("SourceType", "Logger"); properties.put("LoggingLevel", level); } if (loggerName != null) { properties.put("LoggerName", loggerName); } if (attributes != null) { for (Map.Entry<String, AttributeValue> entry : attributes.entrySet()) { AttributeValue av = entry.getValue(); String stringValue = null; switch (av.getType()) { case STRING: stringValue = av.getStringValue(); break; case BOOLEAN: stringValue = String.valueOf(av.getBooleanValue()); break; case LONG: stringValue = String.valueOf(av.getLongValue()); break; case DOUBLE: stringValue = String.valueOf(av.getDoubleValue()); break; case STRING_ARRAY: stringValue = String.valueOf(av.getStringArrayValue()); break; case BOOLEAN_ARRAY: stringValue = String.valueOf(av.getBooleanArrayValue()); break; case LONG_ARRAY: stringValue = String.valueOf(av.getLongArrayValue()); break; case DOUBLE_ARRAY: stringValue = String.valueOf(av.getDoubleArrayValue()); break; } if (stringValue != null) { properties.put(entry.getKey(), stringValue); } } } } private void trackTraceAsException(String message, long timeEpochNanos, String level, String loggerName, String errorStack, TraceId traceId, SpanId parentSpanId, Double samplingPercentage, Map<String, AttributeValue> attributes, List<TelemetryItem> telemetryItems) { TelemetryItem telemetryItem = new TelemetryItem(); TelemetryExceptionData exceptionData = new TelemetryExceptionData(); MonitorBase monitorBase = new MonitorBase(); telemetryItem.setTags(new HashMap<>()); telemetryItem.setName(telemetryItemNamePrefix + "Exception"); telemetryItem.setVersion(1); telemetryItem.setInstrumentationKey(instrumentationKey); telemetryItem.setData(monitorBase); exceptionData.setProperties(new HashMap<>()); exceptionData.setVersion(2); monitorBase.setBaseType("ExceptionData"); monitorBase.setBaseData(exceptionData); if (parentSpanId.isValid()) { telemetryItem.getTags().put(ContextTagKeys.AI_OPERATION_ID.toString(), traceId.toLowerBase16()); telemetryItem.getTags().put(ContextTagKeys.AI_OPERATION_PARENT_ID.toString(), parentSpanId.toLowerBase16()); } exceptionData.setExceptions(minimalParse(errorStack)); exceptionData.setSeverityLevel(toSeverityLevel(level)); exceptionData.getProperties().put("Logger Message", message); setProperties(exceptionData.getProperties(), timeEpochNanos, level, loggerName, attributes); telemetryItem.setSampleRate(samplingPercentage.floatValue()); telemetryItems.add(telemetryItem); } private static List<TelemetryExceptionDetails> minimalParse(String errorStack) { TelemetryExceptionDetails details = new TelemetryExceptionDetails(); String line = errorStack.split("\n")[0]; int index = line.indexOf(": "); if (index != -1) { details.setTypeName(line.substring(0, index)); details.setMessage(line.substring(index + 2)); } else { details.setTypeName(line); } details.setStack(errorStack); return Arrays.asList(details); } private void exportRemoteDependency(String stdComponent, SpanData span, boolean inProc, List<TelemetryItem> telemetryItems) { TelemetryItem telemetryItem = new TelemetryItem(); RemoteDependencyData remoteDependencyData = new RemoteDependencyData(); MonitorBase monitorBase = new MonitorBase(); telemetryItem.setTags(new HashMap<>()); telemetryItem.setName(telemetryItemNamePrefix + "RemoteDependency"); telemetryItem.setVersion(1); telemetryItem.setInstrumentationKey(instrumentationKey); telemetryItem.setData(monitorBase); remoteDependencyData.setProperties(new HashMap<>()); remoteDependencyData.setVersion(2); monitorBase.setBaseType("RemoteDependencyData"); monitorBase.setBaseData(remoteDependencyData); addLinks(remoteDependencyData.getProperties(), span.getLinks()); remoteDependencyData.setName(span.getName()); span.getInstrumentationLibraryInfo().getName(); Map<String, AttributeValue> attributes = getAttributesCopy(span.getAttributes()); if (inProc) { remoteDependencyData.setType("InProc"); } else { if (attributes.containsKey("http.method")) { applyHttpRequestSpan(attributes, remoteDependencyData); } else if (attributes.containsKey(SemanticAttributes.DB_SYSTEM.key())) { applyDatabaseQuerySpan(attributes, remoteDependencyData, stdComponent); } else if (span.getName().equals("EventHubs.send")) { remoteDependencyData.setType("Microsoft.EventHub"); String peerAddress = removeAttributeString(attributes, "peer.address"); String destination = removeAttributeString(attributes, "message_bus.destination"); remoteDependencyData.setTarget(peerAddress + "/" + destination); } else if (span.getName().equals("EventHubs.message")) { String peerAddress = removeAttributeString(attributes, "peer.address"); String destination = removeAttributeString(attributes, "message_bus.destination"); if (peerAddress != null) { remoteDependencyData.setTarget(peerAddress + "/" + destination); } remoteDependencyData.setType("Microsoft.EventHub"); } else if ("kafka-clients".equals(stdComponent)) { remoteDependencyData.setType("Kafka"); remoteDependencyData.setTarget(span.getName()); } else if ("jms".equals(stdComponent)) { remoteDependencyData.setType("JMS"); remoteDependencyData.setTarget(span.getName()); } } remoteDependencyData.setId(span.getSpanId().toLowerBase16()); telemetryItem.getTags().put(ContextTagKeys.AI_OPERATION_ID.toString(), span.getTraceId().toLowerBase16()); SpanId parentSpanId = span.getParentSpanId(); if (parentSpanId.isValid()) { telemetryItem.getTags().put(ContextTagKeys.AI_OPERATION_PARENT_ID.toString(), parentSpanId.toLowerBase16()); } telemetryItem.setTime(getFormattedTime(span.getStartEpochNanos())); remoteDependencyData.setDuration(getFormattedDuration(Duration.ofNanos(span.getEndEpochNanos() - span.getStartEpochNanos()))); remoteDependencyData.setSuccess(span.getStatus().isOk()); String description = span.getStatus().getDescription(); if (description != null) { remoteDependencyData.getProperties().put("statusDescription", description); } Double samplingPercentage = removeAiSamplingPercentage(attributes); if (stdComponent == null) { addExtraAttributes(remoteDependencyData.getProperties(), attributes); } telemetryItem.setSampleRate(samplingPercentage.floatValue()); telemetryItems.add(telemetryItem); exportEvents(span, samplingPercentage, telemetryItems); } private void applyDatabaseQuerySpan(Map<String, AttributeValue> attributes, RemoteDependencyData rd, String component) { String type = removeAttributeString(attributes, SemanticAttributes.DB_SYSTEM.key()); if (SQL_DB_SYSTEMS.contains(type)) { type = "SQL"; } rd.setType(type); rd.setData(removeAttributeString(attributes, SemanticAttributes.DB_STATEMENT.key())); String dbUrl = removeAttributeString(attributes, SemanticAttributes.DB_CONNECTION_STRING.key()); if (dbUrl == null) { rd.setTarget(type); } else { String dbInstance = removeAttributeString(attributes, SemanticAttributes.DB_NAME.key()); if (dbInstance != null) { dbUrl += " | " + dbInstance; } if ("jdbc".equals(component)) { rd.setTarget("jdbc:" + dbUrl); } else { rd.setTarget(dbUrl); } } } private void applyHttpRequestSpan(Map<String, AttributeValue> attributes, RemoteDependencyData remoteDependencyData) { remoteDependencyData.setType("Http (tracked component)"); String method = removeAttributeString(attributes, SemanticAttributes.HTTP_METHOD.key()); String url = removeAttributeString(attributes, SemanticAttributes.HTTP_URL.key()); AttributeValue httpStatusCode = attributes.remove(SemanticAttributes.HTTP_STATUS_CODE.key()); if (httpStatusCode != null && httpStatusCode.getType() == AttributeValue.Type.LONG) { long statusCode = httpStatusCode.getLongValue(); remoteDependencyData.setResultCode(Long.toString(statusCode)); } if (url != null) { try { URI uriObject = new URI(url); String target = createTarget(uriObject); remoteDependencyData.setTarget(target); String path = uriObject.getPath(); if (CoreUtils.isNullOrEmpty(path)) { remoteDependencyData.setName(method + " /"); } else { remoteDependencyData.setName(method + " " + path); } } catch (URISyntaxException e) { logger.error(e.getMessage()); } } } private void exportRequest(String stdComponent, SpanData span, List<TelemetryItem> telemetryItems) { TelemetryItem telemetryItem = new TelemetryItem(); RequestData requestData = new RequestData(); MonitorBase monitorBase = new MonitorBase(); telemetryItem.setTags(new HashMap<>()); telemetryItem.setName(telemetryItemNamePrefix + "Request"); telemetryItem.setVersion(1); telemetryItem.setInstrumentationKey(instrumentationKey); telemetryItem.setData(monitorBase); requestData.setProperties(new HashMap<>()); requestData.setVersion(2); monitorBase.setBaseType("RequestData"); monitorBase.setBaseData(requestData); Map<String, AttributeValue> attributes = getAttributesCopy(span.getAttributes()); if ("kafka-clients".equals(stdComponent)) { requestData.setSource(span.getName()); } else if ("jms".equals(stdComponent)) { requestData.setSource(span.getName()); } addLinks(requestData.getProperties(), span.getLinks()); AttributeValue httpStatusCode = attributes.remove(SemanticAttributes.HTTP_STATUS_CODE.key()); if (isNonNullLong(httpStatusCode)) { requestData.setResponseCode(Long.toString(httpStatusCode.getLongValue())); } String httpUrl = removeAttributeString(attributes, SemanticAttributes.HTTP_URL.key()); if (httpUrl != null) { requestData.setUrl(httpUrl); } String httpMethod = removeAttributeString(attributes, SemanticAttributes.HTTP_METHOD.key()); String name = span.getName(); if (httpMethod != null && name.startsWith("/")) { name = httpMethod + " " + name; } requestData.setName(name); telemetryItem.getTags().put(ContextTagKeys.AI_OPERATION_NAME.toString(), name); if (span.getName().equals("EventHubs.process")) { String peerAddress = removeAttributeString(attributes, "peer.address"); String destination = removeAttributeString(attributes, "message_bus.destination"); requestData.setSource(peerAddress + "/" + destination); } requestData.setId(span.getSpanId().toLowerBase16()); telemetryItem.getTags().put(ContextTagKeys.AI_OPERATION_ID.toString(), span.getTraceId().toLowerBase16()); String aiLegacyParentId = span.getTraceState().get("ai-legacy-parent-id"); if (aiLegacyParentId != null) { telemetryItem.getTags().put(ContextTagKeys.AI_OPERATION_PARENT_ID.toString(), aiLegacyParentId); String aiLegacyOperationId = span.getTraceState().get("ai-legacy-operation-id"); if (aiLegacyOperationId != null) { telemetryItem.getTags().putIfAbsent("ai_legacyRootID", aiLegacyOperationId); } } else { SpanId parentSpanId = span.getParentSpanId(); if (parentSpanId.isValid()) { telemetryItem.getTags().put(ContextTagKeys.AI_OPERATION_PARENT_ID.toString(), parentSpanId.toLowerBase16()); } } long startEpochNanos = span.getStartEpochNanos(); telemetryItem.setTime(getFormattedTime(startEpochNanos)); Duration duration = Duration.ofNanos(span.getEndEpochNanos() - startEpochNanos); requestData.setDuration(getFormattedDuration(duration)); requestData.setSuccess(span.getStatus().isOk()); String description = span.getStatus().getDescription(); if (description != null) { requestData.getProperties().put("statusDescription", description); } Double samplingPercentage = removeAiSamplingPercentage(attributes); if (stdComponent == null) { addExtraAttributes(requestData.getProperties(), attributes); } telemetryItem.setSampleRate(samplingPercentage.floatValue()); telemetryItems.add(telemetryItem); exportEvents(span, samplingPercentage, telemetryItems); } private void exportEvents(SpanData span, Double samplingPercentage, List<TelemetryItem> telemetryItems) { boolean foundException = false; for (SpanData.Event event : span.getEvents()) { TelemetryItem telemetryItem = new TelemetryItem(); TelemetryEventData eventData = new TelemetryEventData(); MonitorBase monitorBase = new MonitorBase(); telemetryItem.setTags(new HashMap<>()); telemetryItem.setName(telemetryItemNamePrefix + "Event"); telemetryItem.setVersion(1); telemetryItem.setInstrumentationKey(instrumentationKey); telemetryItem.setData(monitorBase); eventData.setProperties(new HashMap<>()); eventData.setVersion(2); monitorBase.setBaseType("EventData"); monitorBase.setBaseData(eventData); eventData.setName(event.getName()); String operationId = span.getTraceId().toLowerBase16(); telemetryItem.getTags().put(ContextTagKeys.AI_OPERATION_ID.toString(), operationId); telemetryItem.getTags().put(ContextTagKeys.AI_OPERATION_PARENT_ID.toString(), span.getParentSpanId().toLowerBase16()); telemetryItem.setTime(getFormattedTime(event.getEpochNanos())); addExtraAttributes(eventData.getProperties(), event.getAttributes()); if (event.getAttributes().get(SemanticAttributes.EXCEPTION_TYPE.key()) != null || event.getAttributes().get(SemanticAttributes.EXCEPTION_MESSAGE.key()) != null) { if (!foundException) { AttributeValue stacktrace = event.getAttributes().get(SemanticAttributes.EXCEPTION_STACKTRACE.key()); if (stacktrace != null) { trackException(stacktrace.getStringValue(), span, operationId, span.getSpanId().toLowerBase16(), samplingPercentage, telemetryItems); } } foundException = true; } else { telemetryItem.setSampleRate(samplingPercentage.floatValue()); telemetryItems.add(telemetryItem); } } } private void trackException(String errorStack, SpanData span, String operationId, String id, Double samplingPercentage, List<TelemetryItem> telemetryItems) { TelemetryItem telemetryItem = new TelemetryItem(); TelemetryExceptionData exceptionData = new TelemetryExceptionData(); MonitorBase monitorBase = new MonitorBase(); telemetryItem.setTags(new HashMap<>()); telemetryItem.setName(telemetryItemNamePrefix + "Exception"); telemetryItem.setVersion(1); telemetryItem.setInstrumentationKey(instrumentationKey); telemetryItem.setData(monitorBase); exceptionData.setProperties(new HashMap<>()); exceptionData.setVersion(2); monitorBase.setBaseType("ExceptionData"); monitorBase.setBaseData(exceptionData); telemetryItem.getTags().put(ContextTagKeys.AI_OPERATION_ID.toString(), operationId); telemetryItem.getTags().put(ContextTagKeys.AI_OPERATION_PARENT_ID.toString(), id); telemetryItem.setTime(getFormattedTime(span.getEndEpochNanos())); telemetryItem.setSampleRate(samplingPercentage.floatValue()); exceptionData.setExceptions(minimalParse(errorStack)); telemetryItems.add(telemetryItem); } private static String getFormattedDuration(Duration duration) { return duration.toDays() + "." + duration.toHours() + ":" + duration.toMinutes() + ":" + duration.getSeconds() + "." + duration.toMillis(); } private static String getFormattedTime(long epochNanos) { return Instant.ofEpochMilli(NANOSECONDS.toMillis(epochNanos)) .atOffset(ZoneOffset.UTC) .format(DateTimeFormatter.ISO_DATE_TIME); } private boolean isNonNullLong(AttributeValue attributeValue) { return attributeValue != null && attributeValue.getType() == AttributeValue.Type.LONG; } private Map<String, AttributeValue> getAttributesCopy(ReadableAttributes attributes) { final Map<String, AttributeValue> copy = new HashMap<>(); attributes.forEach(new ReadableKeyValuePairs.KeyValueConsumer<AttributeValue>() { @Override public void consume(String key, AttributeValue value) { copy.put(key, value); } }); return copy; } private static void addLinks(Map<String, String> properties, List<SpanData.Link> links) { if (links.isEmpty()) { return; } StringBuilder sb = new StringBuilder(); sb.append("["); boolean first = true; for (SpanData.Link link : links) { if (!first) { sb.append(","); } sb.append("{\"operation_Id\":\""); sb.append(link.getContext().getTraceId().toLowerBase16()); sb.append("\",\"id\":\""); sb.append(link.getContext().getSpanId().toLowerBase16()); sb.append("\"}"); first = false; } sb.append("]"); properties.put("_MS.links", sb.toString()); } private static String removeAttributeString(Map<String, AttributeValue> attributes, String attributeName) { AttributeValue attributeValue = attributes.remove(attributeName); if (attributeValue == null) { return null; } else if (attributeValue.getType() == AttributeValue.Type.STRING) { return attributeValue.getStringValue(); } else { return null; } } private static Double removeAttributeDouble(Map<String, AttributeValue> attributes, String attributeName) { AttributeValue attributeValue = attributes.remove(attributeName); if (attributeValue == null) { return null; } else if (attributeValue.getType() == AttributeValue.Type.DOUBLE) { return attributeValue.getDoubleValue(); } else { return null; } } private static String createTarget(URI uriObject) { String target = uriObject.getHost(); if (uriObject.getPort() != 80 && uriObject.getPort() != 443 && uriObject.getPort() != -1) { target += ":" + uriObject.getPort(); } return target; } private static String getStringValue(AttributeValue value) { switch (value.getType()) { case STRING: return value.getStringValue(); case BOOLEAN: return Boolean.toString(value.getBooleanValue()); case LONG: return Long.toString(value.getLongValue()); case DOUBLE: return Double.toString(value.getDoubleValue()); case STRING_ARRAY: return join(value.getStringArrayValue()); case BOOLEAN_ARRAY: return join(value.getBooleanArrayValue()); case LONG_ARRAY: return join(value.getLongArrayValue()); case DOUBLE_ARRAY: return join(value.getDoubleArrayValue()); default: return null; } } private static <T> String join(List<T> values) { StringBuilder sb = new StringBuilder(); if (CoreUtils.isNullOrEmpty(values)) { return sb.toString(); } for (int i = 0; i < values.size() - 1; i++) { sb.append(values.get(i)); sb.append(", "); } sb.append(values.get(values.size() - 1)); return sb.toString(); } private static SeverityLevel toSeverityLevel(String level) { if (level == null) { return null; } switch (level) { case "FATAL": return SeverityLevel.CRITICAL; case "ERROR": case "SEVERE": return SeverityLevel.ERROR; case "WARN": case "WARNING": return SeverityLevel.WARNING; case "INFO": return SeverityLevel.INFORMATION; case "DEBUG": case "TRACE": case "CONFIG": case "FINE": case "FINER": case "FINEST": case "ALL": return SeverityLevel.VERBOSE; default: return SeverityLevel.VERBOSE; } } private static Double removeAiSamplingPercentage(Map<String, AttributeValue> attributes) { return removeAttributeDouble(attributes, "ai.sampling.percentage"); } private static void addExtraAttributes(Map<String, String> properties, Map<String, AttributeValue> attributes) { for (Map.Entry<String, AttributeValue> entry : attributes.entrySet()) { String value = getStringValue(entry.getValue()); if (value != null) { properties.put(entry.getKey(), value); } } } private static void addExtraAttributes(final Map<String, String> properties, Attributes attributes) { attributes.forEach(new ReadableKeyValuePairs.KeyValueConsumer<AttributeValue>() { @Override public void consume(String key, AttributeValue value) { String val = getStringValue(value); if (val != null) { properties.put(key, val); } } }); } }
class AzureMonitorExporter implements SpanExporter { private static final Pattern COMPONENT_PATTERN = Pattern .compile("io\\.opentelemetry\\.auto\\.([^0-9]*)(-[0-9.]*)?"); private static final Set<String> SQL_DB_SYSTEMS; static { Set<String> dbSystems = new HashSet<>(); dbSystems.add("db2"); dbSystems.add("derby"); dbSystems.add("mariadb"); dbSystems.add("mssql"); dbSystems.add("mysql"); dbSystems.add("oracle"); dbSystems.add("postgresql"); dbSystems.add("sqlite"); dbSystems.add("other_sql"); dbSystems.add("hsqldb"); dbSystems.add("h2"); SQL_DB_SYSTEMS = Collections.unmodifiableSet(dbSystems); } private final MonitorExporterClient client; private final ClientLogger logger = new ClientLogger(AzureMonitorExporter.class); private final String instrumentationKey; private final String telemetryItemNamePrefix; /** * Creates an instance of exporter that is configured with given exporter client that sends telemetry events to * Application Insights resource identified by the instrumentation key. * * @param client The client used to send data to Azure Monitor. * @param instrumentationKey The instrumentation key of Application Insights resource. */ AzureMonitorExporter(MonitorExporterClient client, String instrumentationKey) { this.client = client; this.instrumentationKey = instrumentationKey; String formattedInstrumentationKey = instrumentationKey.replaceAll("-", ""); this.telemetryItemNamePrefix = "Microsoft.ApplicationInsights." + formattedInstrumentationKey + "."; } /** * {@inheritDoc} */ @Override public CompletableResultCode export(Collection<SpanData> spans) { try { List<TelemetryItem> telemetryItems = new ArrayList<>(); for (SpanData span : spans) { logger.verbose("exporting span: {}", span); export(span, telemetryItems); } client.export(telemetryItems); return CompletableResultCode.ofSuccess(); } catch (Throwable t) { logger.error(t.getMessage(), t); return CompletableResultCode.ofFailure(); } } /** * {@inheritDoc} */ @Override public CompletableResultCode flush() { return CompletableResultCode.ofSuccess(); } /** * {@inheritDoc} */ @Override public CompletableResultCode shutdown() { return CompletableResultCode.ofSuccess(); } private static void setProperties(Map<String, String> properties, long timeEpochNanos, String level, String loggerName, Map<String, AttributeValue> attributes) { if (level != null) { properties.put("SourceType", "Logger"); properties.put("LoggingLevel", level); } if (loggerName != null) { properties.put("LoggerName", loggerName); } if (attributes != null) { for (Map.Entry<String, AttributeValue> entry : attributes.entrySet()) { AttributeValue av = entry.getValue(); String stringValue = null; switch (av.getType()) { case STRING: stringValue = av.getStringValue(); break; case BOOLEAN: stringValue = String.valueOf(av.getBooleanValue()); break; case LONG: stringValue = String.valueOf(av.getLongValue()); break; case DOUBLE: stringValue = String.valueOf(av.getDoubleValue()); break; case STRING_ARRAY: stringValue = String.valueOf(av.getStringArrayValue()); break; case BOOLEAN_ARRAY: stringValue = String.valueOf(av.getBooleanArrayValue()); break; case LONG_ARRAY: stringValue = String.valueOf(av.getLongArrayValue()); break; case DOUBLE_ARRAY: stringValue = String.valueOf(av.getDoubleArrayValue()); break; } if (stringValue != null) { properties.put(entry.getKey(), stringValue); } } } } private static List<TelemetryExceptionDetails> minimalParse(String errorStack) { TelemetryExceptionDetails details = new TelemetryExceptionDetails(); String line = errorStack.split("\n")[0]; int index = line.indexOf(": "); if (index != -1) { details.setTypeName(line.substring(0, index)); details.setMessage(line.substring(index + 2)); } else { details.setTypeName(line); } details.setStack(errorStack); return Arrays.asList(details); } private void exportRemoteDependency(String stdComponent, SpanData span, boolean inProc, List<TelemetryItem> telemetryItems) { TelemetryItem telemetryItem = new TelemetryItem(); RemoteDependencyData remoteDependencyData = new RemoteDependencyData(); MonitorBase monitorBase = new MonitorBase(); telemetryItem.setTags(new HashMap<>()); telemetryItem.setName(telemetryItemNamePrefix + "RemoteDependency"); telemetryItem.setVersion(1); telemetryItem.setInstrumentationKey(instrumentationKey); telemetryItem.setData(monitorBase); remoteDependencyData.setProperties(new HashMap<>()); remoteDependencyData.setVersion(2); monitorBase.setBaseType("RemoteDependencyData"); monitorBase.setBaseData(remoteDependencyData); addLinks(remoteDependencyData.getProperties(), span.getLinks()); remoteDependencyData.setName(span.getName()); span.getInstrumentationLibraryInfo().getName(); Map<String, AttributeValue> attributes = getAttributesCopy(span.getAttributes()); if (inProc) { remoteDependencyData.setType("InProc"); } else { if (attributes.containsKey("http.method")) { applyHttpRequestSpan(attributes, remoteDependencyData); } else if (attributes.containsKey(SemanticAttributes.DB_SYSTEM.key())) { applyDatabaseQuerySpan(attributes, remoteDependencyData, stdComponent); } else if (span.getName().equals("EventHubs.send")) { remoteDependencyData.setType("Microsoft.EventHub"); String peerAddress = removeAttributeString(attributes, "peer.address"); String destination = removeAttributeString(attributes, "message_bus.destination"); remoteDependencyData.setTarget(peerAddress + "/" + destination); } else if (span.getName().equals("EventHubs.message")) { String peerAddress = removeAttributeString(attributes, "peer.address"); String destination = removeAttributeString(attributes, "message_bus.destination"); if (peerAddress != null) { remoteDependencyData.setTarget(peerAddress + "/" + destination); } remoteDependencyData.setType("Microsoft.EventHub"); } else if ("kafka-clients".equals(stdComponent)) { remoteDependencyData.setType("Kafka"); remoteDependencyData.setTarget(span.getName()); } else if ("jms".equals(stdComponent)) { remoteDependencyData.setType("JMS"); remoteDependencyData.setTarget(span.getName()); } } remoteDependencyData.setId(span.getSpanId().toLowerBase16()); telemetryItem.getTags().put(ContextTagKeys.AI_OPERATION_ID.toString(), span.getTraceId().toLowerBase16()); SpanId parentSpanId = span.getParentSpanId(); if (parentSpanId.isValid()) { telemetryItem.getTags().put(ContextTagKeys.AI_OPERATION_PARENT_ID.toString(), parentSpanId.toLowerBase16()); } telemetryItem.setTime(getFormattedTime(span.getStartEpochNanos())); remoteDependencyData.setDuration(getFormattedDuration(Duration.ofNanos(span.getEndEpochNanos() - span.getStartEpochNanos()))); remoteDependencyData.setSuccess(span.getStatus().isOk()); String description = span.getStatus().getDescription(); if (description != null) { remoteDependencyData.getProperties().put("statusDescription", description); } Double samplingPercentage = removeAiSamplingPercentage(attributes); if (stdComponent == null) { addExtraAttributes(remoteDependencyData.getProperties(), attributes); } telemetryItem.setSampleRate(samplingPercentage.floatValue()); telemetryItems.add(telemetryItem); exportEvents(span, samplingPercentage, telemetryItems); } private void applyDatabaseQuerySpan(Map<String, AttributeValue> attributes, RemoteDependencyData rd, String component) { String type = removeAttributeString(attributes, SemanticAttributes.DB_SYSTEM.key()); if (SQL_DB_SYSTEMS.contains(type)) { type = "SQL"; } rd.setType(type); rd.setData(removeAttributeString(attributes, SemanticAttributes.DB_STATEMENT.key())); String dbUrl = removeAttributeString(attributes, SemanticAttributes.DB_CONNECTION_STRING.key()); if (dbUrl == null) { rd.setTarget(type); } else { String dbInstance = removeAttributeString(attributes, SemanticAttributes.DB_NAME.key()); if (dbInstance != null) { dbUrl += " | " + dbInstance; } if ("jdbc".equals(component)) { rd.setTarget("jdbc:" + dbUrl); } else { rd.setTarget(dbUrl); } } } private void applyHttpRequestSpan(Map<String, AttributeValue> attributes, RemoteDependencyData remoteDependencyData) { remoteDependencyData.setType("Http (tracked component)"); String method = removeAttributeString(attributes, SemanticAttributes.HTTP_METHOD.key()); String url = removeAttributeString(attributes, SemanticAttributes.HTTP_URL.key()); AttributeValue httpStatusCode = attributes.remove(SemanticAttributes.HTTP_STATUS_CODE.key()); if (httpStatusCode != null && httpStatusCode.getType() == AttributeValue.Type.LONG) { long statusCode = httpStatusCode.getLongValue(); remoteDependencyData.setResultCode(Long.toString(statusCode)); } if (url != null) { try { URI uriObject = new URI(url); String target = createTarget(uriObject); remoteDependencyData.setTarget(target); String path = uriObject.getPath(); if (CoreUtils.isNullOrEmpty(path)) { remoteDependencyData.setName(method + " /"); } else { remoteDependencyData.setName(method + " " + path); } } catch (URISyntaxException e) { logger.error(e.getMessage()); } } } private void exportRequest(String stdComponent, SpanData span, List<TelemetryItem> telemetryItems) { TelemetryItem telemetryItem = new TelemetryItem(); RequestData requestData = new RequestData(); MonitorBase monitorBase = new MonitorBase(); telemetryItem.setTags(new HashMap<>()); telemetryItem.setName(telemetryItemNamePrefix + "Request"); telemetryItem.setVersion(1); telemetryItem.setInstrumentationKey(instrumentationKey); telemetryItem.setData(monitorBase); requestData.setProperties(new HashMap<>()); requestData.setVersion(2); monitorBase.setBaseType("RequestData"); monitorBase.setBaseData(requestData); Map<String, AttributeValue> attributes = getAttributesCopy(span.getAttributes()); if ("kafka-clients".equals(stdComponent)) { requestData.setSource(span.getName()); } else if ("jms".equals(stdComponent)) { requestData.setSource(span.getName()); } addLinks(requestData.getProperties(), span.getLinks()); AttributeValue httpStatusCode = attributes.remove(SemanticAttributes.HTTP_STATUS_CODE.key()); if (isNonNullLong(httpStatusCode)) { requestData.setResponseCode(Long.toString(httpStatusCode.getLongValue())); } String httpUrl = removeAttributeString(attributes, SemanticAttributes.HTTP_URL.key()); if (httpUrl != null) { requestData.setUrl(httpUrl); } String httpMethod = removeAttributeString(attributes, SemanticAttributes.HTTP_METHOD.key()); String name = span.getName(); if (httpMethod != null && name.startsWith("/")) { name = httpMethod + " " + name; } requestData.setName(name); telemetryItem.getTags().put(ContextTagKeys.AI_OPERATION_NAME.toString(), name); if (span.getName().equals("EventHubs.process")) { String peerAddress = removeAttributeString(attributes, "peer.address"); String destination = removeAttributeString(attributes, "message_bus.destination"); requestData.setSource(peerAddress + "/" + destination); } requestData.setId(span.getSpanId().toLowerBase16()); telemetryItem.getTags().put(ContextTagKeys.AI_OPERATION_ID.toString(), span.getTraceId().toLowerBase16()); String aiLegacyParentId = span.getTraceState().get("ai-legacy-parent-id"); if (aiLegacyParentId != null) { telemetryItem.getTags().put(ContextTagKeys.AI_OPERATION_PARENT_ID.toString(), aiLegacyParentId); String aiLegacyOperationId = span.getTraceState().get("ai-legacy-operation-id"); if (aiLegacyOperationId != null) { telemetryItem.getTags().putIfAbsent("ai_legacyRootID", aiLegacyOperationId); } } else { SpanId parentSpanId = span.getParentSpanId(); if (parentSpanId.isValid()) { telemetryItem.getTags().put(ContextTagKeys.AI_OPERATION_PARENT_ID.toString(), parentSpanId.toLowerBase16()); } } long startEpochNanos = span.getStartEpochNanos(); telemetryItem.setTime(getFormattedTime(startEpochNanos)); Duration duration = Duration.ofNanos(span.getEndEpochNanos() - startEpochNanos); requestData.setDuration(getFormattedDuration(duration)); requestData.setSuccess(span.getStatus().isOk()); String description = span.getStatus().getDescription(); if (description != null) { requestData.getProperties().put("statusDescription", description); } Double samplingPercentage = removeAiSamplingPercentage(attributes); if (stdComponent == null) { addExtraAttributes(requestData.getProperties(), attributes); } telemetryItem.setSampleRate(samplingPercentage.floatValue()); telemetryItems.add(telemetryItem); exportEvents(span, samplingPercentage, telemetryItems); } private void exportEvents(SpanData span, Double samplingPercentage, List<TelemetryItem> telemetryItems) { boolean foundException = false; for (SpanData.Event event : span.getEvents()) { TelemetryItem telemetryItem = new TelemetryItem(); TelemetryEventData eventData = new TelemetryEventData(); MonitorBase monitorBase = new MonitorBase(); telemetryItem.setTags(new HashMap<>()); telemetryItem.setName(telemetryItemNamePrefix + "Event"); telemetryItem.setVersion(1); telemetryItem.setInstrumentationKey(instrumentationKey); telemetryItem.setData(monitorBase); eventData.setProperties(new HashMap<>()); eventData.setVersion(2); monitorBase.setBaseType("EventData"); monitorBase.setBaseData(eventData); eventData.setName(event.getName()); String operationId = span.getTraceId().toLowerBase16(); telemetryItem.getTags().put(ContextTagKeys.AI_OPERATION_ID.toString(), operationId); telemetryItem.getTags().put(ContextTagKeys.AI_OPERATION_PARENT_ID.toString(), span.getParentSpanId().toLowerBase16()); telemetryItem.setTime(getFormattedTime(event.getEpochNanos())); addExtraAttributes(eventData.getProperties(), event.getAttributes()); if (event.getAttributes().get(SemanticAttributes.EXCEPTION_TYPE.key()) != null || event.getAttributes().get(SemanticAttributes.EXCEPTION_MESSAGE.key()) != null) { if (!foundException) { AttributeValue stacktrace = event.getAttributes().get(SemanticAttributes.EXCEPTION_STACKTRACE.key()); if (stacktrace != null) { trackException(stacktrace.getStringValue(), span, operationId, span.getSpanId().toLowerBase16(), samplingPercentage, telemetryItems); } } foundException = true; } else { telemetryItem.setSampleRate(samplingPercentage.floatValue()); telemetryItems.add(telemetryItem); } } } private void trackException(String errorStack, SpanData span, String operationId, String id, Double samplingPercentage, List<TelemetryItem> telemetryItems) { TelemetryItem telemetryItem = new TelemetryItem(); TelemetryExceptionData exceptionData = new TelemetryExceptionData(); MonitorBase monitorBase = new MonitorBase(); telemetryItem.setTags(new HashMap<>()); telemetryItem.setName(telemetryItemNamePrefix + "Exception"); telemetryItem.setVersion(1); telemetryItem.setInstrumentationKey(instrumentationKey); telemetryItem.setData(monitorBase); exceptionData.setProperties(new HashMap<>()); exceptionData.setVersion(2); monitorBase.setBaseType("ExceptionData"); monitorBase.setBaseData(exceptionData); telemetryItem.getTags().put(ContextTagKeys.AI_OPERATION_ID.toString(), operationId); telemetryItem.getTags().put(ContextTagKeys.AI_OPERATION_PARENT_ID.toString(), id); telemetryItem.setTime(getFormattedTime(span.getEndEpochNanos())); telemetryItem.setSampleRate(samplingPercentage.floatValue()); exceptionData.setExceptions(minimalParse(errorStack)); telemetryItems.add(telemetryItem); } private static String getFormattedDuration(Duration duration) { return duration.toDays() + "." + duration.toHours() + ":" + duration.toMinutes() + ":" + duration.getSeconds() + "." + duration.toMillis(); } private static String getFormattedTime(long epochNanos) { return Instant.ofEpochMilli(NANOSECONDS.toMillis(epochNanos)) .atOffset(ZoneOffset.UTC) .format(DateTimeFormatter.ISO_DATE_TIME); } private boolean isNonNullLong(AttributeValue attributeValue) { return attributeValue != null && attributeValue.getType() == AttributeValue.Type.LONG; } private Map<String, AttributeValue> getAttributesCopy(ReadableAttributes attributes) { final Map<String, AttributeValue> copy = new HashMap<>(); attributes.forEach(new ReadableKeyValuePairs.KeyValueConsumer<AttributeValue>() { @Override public void consume(String key, AttributeValue value) { copy.put(key, value); } }); return copy; } private static void addLinks(Map<String, String> properties, List<SpanData.Link> links) { if (links.isEmpty()) { return; } StringBuilder sb = new StringBuilder(); sb.append("["); boolean first = true; for (SpanData.Link link : links) { if (!first) { sb.append(","); } sb.append("{\"operation_Id\":\""); sb.append(link.getContext().getTraceId().toLowerBase16()); sb.append("\",\"id\":\""); sb.append(link.getContext().getSpanId().toLowerBase16()); sb.append("\"}"); first = false; } sb.append("]"); properties.put("_MS.links", sb.toString()); } private static String removeAttributeString(Map<String, AttributeValue> attributes, String attributeName) { AttributeValue attributeValue = attributes.remove(attributeName); if (attributeValue == null) { return null; } else if (attributeValue.getType() == AttributeValue.Type.STRING) { return attributeValue.getStringValue(); } else { return null; } } private static Double removeAttributeDouble(Map<String, AttributeValue> attributes, String attributeName) { AttributeValue attributeValue = attributes.remove(attributeName); if (attributeValue == null) { return null; } else if (attributeValue.getType() == AttributeValue.Type.DOUBLE) { return attributeValue.getDoubleValue(); } else { return null; } } private static String createTarget(URI uriObject) { String target = uriObject.getHost(); if (uriObject.getPort() != 80 && uriObject.getPort() != 443 && uriObject.getPort() != -1) { target += ":" + uriObject.getPort(); } return target; } private static String getStringValue(AttributeValue value) { switch (value.getType()) { case STRING: return value.getStringValue(); case BOOLEAN: return Boolean.toString(value.getBooleanValue()); case LONG: return Long.toString(value.getLongValue()); case DOUBLE: return Double.toString(value.getDoubleValue()); case STRING_ARRAY: return join(value.getStringArrayValue()); case BOOLEAN_ARRAY: return join(value.getBooleanArrayValue()); case LONG_ARRAY: return join(value.getLongArrayValue()); case DOUBLE_ARRAY: return join(value.getDoubleArrayValue()); default: return null; } } private static <T> String join(List<T> values) { StringBuilder sb = new StringBuilder(); if (CoreUtils.isNullOrEmpty(values)) { return sb.toString(); } for (int i = 0; i < values.size() - 1; i++) { sb.append(values.get(i)); sb.append(", "); } sb.append(values.get(values.size() - 1)); return sb.toString(); } private static Double removeAiSamplingPercentage(Map<String, AttributeValue> attributes) { return removeAttributeDouble(attributes, "ai.sampling.percentage"); } private static void addExtraAttributes(Map<String, String> properties, Map<String, AttributeValue> attributes) { for (Map.Entry<String, AttributeValue> entry : attributes.entrySet()) { String value = getStringValue(entry.getValue()); if (value != null) { properties.put(entry.getKey(), value); } } } private static void addExtraAttributes(final Map<String, String> properties, Attributes attributes) { attributes.forEach(new ReadableKeyValuePairs.KeyValueConsumer<AttributeValue>() { @Override public void consume(String key, AttributeValue value) { String val = getStringValue(value); if (val != null) { properties.put(key, val); } } }); } }
TODO for GA, probably need to publish an OpenTelemetry Sampler as part of this package that implements ApplicationInsights's sampling algorithm
private void exportRemoteDependency(String stdComponent, SpanData span, boolean inProc, List<TelemetryItem> telemetryItems) { TelemetryItem telemetryItem = new TelemetryItem(); RemoteDependencyData remoteDependencyData = new RemoteDependencyData(); MonitorBase monitorBase = new MonitorBase(); telemetryItem.setTags(new HashMap<>()); telemetryItem.setName(telemetryItemNamePrefix + "RemoteDependency"); telemetryItem.setVersion(1); telemetryItem.setInstrumentationKey(instrumentationKey); telemetryItem.setData(monitorBase); remoteDependencyData.setProperties(new HashMap<>()); remoteDependencyData.setVersion(2); monitorBase.setBaseType("RemoteDependencyData"); monitorBase.setBaseData(remoteDependencyData); addLinks(remoteDependencyData.getProperties(), span.getLinks()); remoteDependencyData.setName(span.getName()); span.getInstrumentationLibraryInfo().getName(); Map<String, AttributeValue> attributes = getAttributesCopy(span.getAttributes()); if (inProc) { remoteDependencyData.setType("InProc"); } else { if (attributes.containsKey("http.method")) { applyHttpRequestSpan(attributes, remoteDependencyData); } else if (attributes.containsKey(SemanticAttributes.DB_SYSTEM.key())) { applyDatabaseQuerySpan(attributes, remoteDependencyData, stdComponent); } else if (span.getName().equals("EventHubs.send")) { remoteDependencyData.setType("Microsoft.EventHub"); String peerAddress = removeAttributeString(attributes, "peer.address"); String destination = removeAttributeString(attributes, "message_bus.destination"); remoteDependencyData.setTarget(peerAddress + "/" + destination); } else if (span.getName().equals("EventHubs.message")) { String peerAddress = removeAttributeString(attributes, "peer.address"); String destination = removeAttributeString(attributes, "message_bus.destination"); if (peerAddress != null) { remoteDependencyData.setTarget(peerAddress + "/" + destination); } remoteDependencyData.setType("Microsoft.EventHub"); } else if ("kafka-clients".equals(stdComponent)) { remoteDependencyData.setType("Kafka"); remoteDependencyData.setTarget(span.getName()); } else if ("jms".equals(stdComponent)) { remoteDependencyData.setType("JMS"); remoteDependencyData.setTarget(span.getName()); } } remoteDependencyData.setId(span.getSpanId().toLowerBase16()); telemetryItem.getTags().put(ContextTagKeys.AI_OPERATION_ID.toString(), span.getTraceId().toLowerBase16()); SpanId parentSpanId = span.getParentSpanId(); if (parentSpanId.isValid()) { telemetryItem.getTags().put(ContextTagKeys.AI_OPERATION_PARENT_ID.toString(), parentSpanId.toLowerBase16()); } telemetryItem.setTime(getFormattedTime(span.getStartEpochNanos())); remoteDependencyData.setDuration(getFormattedDuration(Duration.ofNanos(span.getEndEpochNanos() - span.getStartEpochNanos()))); remoteDependencyData.setSuccess(span.getStatus().isOk()); String description = span.getStatus().getDescription(); if (description != null) { remoteDependencyData.getProperties().put("statusDescription", description); } Double samplingPercentage = removeAiSamplingPercentage(attributes); if (stdComponent == null) { addExtraAttributes(remoteDependencyData.getProperties(), attributes); } telemetryItem.setSampleRate(samplingPercentage.floatValue()); telemetryItems.add(telemetryItem); exportEvents(span, samplingPercentage, telemetryItems); }
Double samplingPercentage = removeAiSamplingPercentage(attributes);
private void exportRemoteDependency(String stdComponent, SpanData span, boolean inProc, List<TelemetryItem> telemetryItems) { TelemetryItem telemetryItem = new TelemetryItem(); RemoteDependencyData remoteDependencyData = new RemoteDependencyData(); MonitorBase monitorBase = new MonitorBase(); telemetryItem.setTags(new HashMap<>()); telemetryItem.setName(telemetryItemNamePrefix + "RemoteDependency"); telemetryItem.setVersion(1); telemetryItem.setInstrumentationKey(instrumentationKey); telemetryItem.setData(monitorBase); remoteDependencyData.setProperties(new HashMap<>()); remoteDependencyData.setVersion(2); monitorBase.setBaseType("RemoteDependencyData"); monitorBase.setBaseData(remoteDependencyData); addLinks(remoteDependencyData.getProperties(), span.getLinks()); remoteDependencyData.setName(span.getName()); span.getInstrumentationLibraryInfo().getName(); Map<String, AttributeValue> attributes = getAttributesCopy(span.getAttributes()); if (inProc) { remoteDependencyData.setType("InProc"); } else { if (attributes.containsKey("http.method")) { applyHttpRequestSpan(attributes, remoteDependencyData); } else if (attributes.containsKey(SemanticAttributes.DB_SYSTEM.key())) { applyDatabaseQuerySpan(attributes, remoteDependencyData, stdComponent); } else if (span.getName().equals("EventHubs.send")) { remoteDependencyData.setType("Microsoft.EventHub"); String peerAddress = removeAttributeString(attributes, "peer.address"); String destination = removeAttributeString(attributes, "message_bus.destination"); remoteDependencyData.setTarget(peerAddress + "/" + destination); } else if (span.getName().equals("EventHubs.message")) { String peerAddress = removeAttributeString(attributes, "peer.address"); String destination = removeAttributeString(attributes, "message_bus.destination"); if (peerAddress != null) { remoteDependencyData.setTarget(peerAddress + "/" + destination); } remoteDependencyData.setType("Microsoft.EventHub"); } else if ("kafka-clients".equals(stdComponent)) { remoteDependencyData.setType("Kafka"); remoteDependencyData.setTarget(span.getName()); } else if ("jms".equals(stdComponent)) { remoteDependencyData.setType("JMS"); remoteDependencyData.setTarget(span.getName()); } } remoteDependencyData.setId(span.getSpanId().toLowerBase16()); telemetryItem.getTags().put(ContextTagKeys.AI_OPERATION_ID.toString(), span.getTraceId().toLowerBase16()); SpanId parentSpanId = span.getParentSpanId(); if (parentSpanId.isValid()) { telemetryItem.getTags().put(ContextTagKeys.AI_OPERATION_PARENT_ID.toString(), parentSpanId.toLowerBase16()); } telemetryItem.setTime(getFormattedTime(span.getStartEpochNanos())); remoteDependencyData.setDuration(getFormattedDuration(Duration.ofNanos(span.getEndEpochNanos() - span.getStartEpochNanos()))); remoteDependencyData.setSuccess(span.getStatus().isOk()); String description = span.getStatus().getDescription(); if (description != null) { remoteDependencyData.getProperties().put("statusDescription", description); } Double samplingPercentage = removeAiSamplingPercentage(attributes); if (stdComponent == null) { addExtraAttributes(remoteDependencyData.getProperties(), attributes); } telemetryItem.setSampleRate(samplingPercentage.floatValue()); telemetryItems.add(telemetryItem); exportEvents(span, samplingPercentage, telemetryItems); }
class AzureMonitorExporter implements SpanExporter { private static final Pattern COMPONENT_PATTERN = Pattern .compile("io\\.opentelemetry\\.auto\\.([^0-9]*)(-[0-9.]*)?"); private static final Set<String> SQL_DB_SYSTEMS; static { Set<String> dbSystems = new HashSet<>(); dbSystems.add("db2"); dbSystems.add("derby"); dbSystems.add("mariadb"); dbSystems.add("mssql"); dbSystems.add("mysql"); dbSystems.add("oracle"); dbSystems.add("postgresql"); dbSystems.add("sqlite"); dbSystems.add("other_sql"); dbSystems.add("hsqldb"); dbSystems.add("h2"); SQL_DB_SYSTEMS = Collections.unmodifiableSet(dbSystems); } private final MonitorExporterClient client; private final ClientLogger logger = new ClientLogger(AzureMonitorExporter.class); private final String instrumentationKey; private final String telemetryItemNamePrefix; /** * Creates an instance of exporter that is configured with given exporter client that sends telemetry events to * Application Insights resource identified by the instrumentation key. * * @param client The client used to send data to Azure Monitor. * @param instrumentationKey The instrumentation key of Application Insights resource. */ AzureMonitorExporter(MonitorExporterClient client, String instrumentationKey) { this.client = client; this.instrumentationKey = instrumentationKey; this.telemetryItemNamePrefix = "Microsoft.ApplicationInsights." + instrumentationKey + "."; } /** * {@inheritDoc} */ @Override public CompletableResultCode export(Collection<SpanData> spans) { try { List<TelemetryItem> telemetryItems = new ArrayList<>(); for (SpanData span : spans) { logger.verbose("exporting span: {}", span); export(span, telemetryItems); } client.export(telemetryItems); return CompletableResultCode.ofSuccess(); } catch (Throwable t) { logger.error(t.getMessage(), t); return CompletableResultCode.ofFailure(); } } /** * {@inheritDoc} */ @Override public CompletableResultCode flush() { return CompletableResultCode.ofSuccess(); } /** * {@inheritDoc} */ @Override public CompletableResultCode shutdown() { return CompletableResultCode.ofSuccess(); } private void export(SpanData span, List<TelemetryItem> telemetryItems) { Span.Kind kind = span.getKind(); String instrumentationName = span.getInstrumentationLibraryInfo().getName(); Matcher matcher = COMPONENT_PATTERN.matcher(instrumentationName); String stdComponent = matcher.matches() ? matcher.group(1) : null; if ("jms".equals(stdComponent) && !span.getParentSpanId().isValid() && kind == Span.Kind.CLIENT) { return; } if (kind == Span.Kind.INTERNAL) { if (span.getName().equals("log.message")) { exportLogSpan(span, telemetryItems); } else if (!span.getParentSpanId().isValid()) { exportRequest(stdComponent, span, telemetryItems); } else if (span.getName().equals("EventHubs.message")) { exportRemoteDependency(stdComponent, span, false, telemetryItems); } else { exportRemoteDependency(stdComponent, span, true, telemetryItems); } } else if (kind == Span.Kind.CLIENT || kind == Span.Kind.PRODUCER) { exportRemoteDependency(stdComponent, span, false, telemetryItems); } else if (kind == Span.Kind.SERVER || kind == Span.Kind.CONSUMER) { exportRequest(stdComponent, span, telemetryItems); } else { throw new UnsupportedOperationException(kind.name()); } } private void exportLogSpan(SpanData span, List<TelemetryItem> telemetryItems) { Map<String, AttributeValue> attributes = getAttributesCopy(span.getAttributes()); String message = removeAttributeString(attributes, "message"); String level = removeAttributeString(attributes, "level"); String loggerName = removeAttributeString(attributes, "loggerName"); String errorStack = removeAttributeString(attributes, "error.stack"); Double samplingPercentage = removeAiSamplingPercentage(attributes); if (errorStack == null) { trackTrace(message, span.getStartEpochNanos(), level, loggerName, span.getTraceId(), span.getParentSpanId(), samplingPercentage, attributes, telemetryItems); } else { trackTraceAsException(message, span.getStartEpochNanos(), level, loggerName, errorStack, span.getTraceId(), span.getParentSpanId(), samplingPercentage, attributes, telemetryItems); } } private void trackTrace(String message, long timeEpochNanos, String level, String loggerName, TraceId traceId, SpanId parentSpanId, Double samplingPercentage, Map<String, AttributeValue> attributes, List<TelemetryItem> telemetryItems) { TelemetryItem telemetryItem = new TelemetryItem(); MessageData messageData = new MessageData(); MonitorBase monitorBase = new MonitorBase(); telemetryItem.setTags(new HashMap<>()); telemetryItem.setName(telemetryItemNamePrefix + "Message"); telemetryItem.setVersion(1); telemetryItem.setInstrumentationKey(instrumentationKey); telemetryItem.setData(monitorBase); messageData.setProperties(new HashMap<>()); messageData.setVersion(2); monitorBase.setBaseType("MessageData"); monitorBase.setBaseData(messageData); messageData.setSeverityLevel(toSeverityLevel(level)); messageData.setMessage(message); if (parentSpanId.isValid()) { telemetryItem.getTags().put(ContextTagKeys.AI_OPERATION_ID.toString(), traceId.toLowerBase16()); telemetryItem.getTags().put(ContextTagKeys.AI_OPERATION_PARENT_ID.toString(), parentSpanId.toLowerBase16()); } setProperties(messageData.getProperties(), timeEpochNanos, level, loggerName, attributes); telemetryItem.setSampleRate(samplingPercentage.floatValue()); telemetryItems.add(telemetryItem); } private static void setProperties(Map<String, String> properties, long timeEpochNanos, String level, String loggerName, Map<String, AttributeValue> attributes) { if (level != null) { properties.put("SourceType", "Logger"); properties.put("LoggingLevel", level); } if (loggerName != null) { properties.put("LoggerName", loggerName); } if (attributes != null) { for (Map.Entry<String, AttributeValue> entry : attributes.entrySet()) { AttributeValue av = entry.getValue(); String stringValue = null; switch (av.getType()) { case STRING: stringValue = av.getStringValue(); break; case BOOLEAN: stringValue = String.valueOf(av.getBooleanValue()); break; case LONG: stringValue = String.valueOf(av.getLongValue()); break; case DOUBLE: stringValue = String.valueOf(av.getDoubleValue()); break; case STRING_ARRAY: stringValue = String.valueOf(av.getStringArrayValue()); break; case BOOLEAN_ARRAY: stringValue = String.valueOf(av.getBooleanArrayValue()); break; case LONG_ARRAY: stringValue = String.valueOf(av.getLongArrayValue()); break; case DOUBLE_ARRAY: stringValue = String.valueOf(av.getDoubleArrayValue()); break; } if (stringValue != null) { properties.put(entry.getKey(), stringValue); } } } } private void trackTraceAsException(String message, long timeEpochNanos, String level, String loggerName, String errorStack, TraceId traceId, SpanId parentSpanId, Double samplingPercentage, Map<String, AttributeValue> attributes, List<TelemetryItem> telemetryItems) { TelemetryItem telemetryItem = new TelemetryItem(); TelemetryExceptionData exceptionData = new TelemetryExceptionData(); MonitorBase monitorBase = new MonitorBase(); telemetryItem.setTags(new HashMap<>()); telemetryItem.setName(telemetryItemNamePrefix + "Exception"); telemetryItem.setVersion(1); telemetryItem.setInstrumentationKey(instrumentationKey); telemetryItem.setData(monitorBase); exceptionData.setProperties(new HashMap<>()); exceptionData.setVersion(2); monitorBase.setBaseType("ExceptionData"); monitorBase.setBaseData(exceptionData); if (parentSpanId.isValid()) { telemetryItem.getTags().put(ContextTagKeys.AI_OPERATION_ID.toString(), traceId.toLowerBase16()); telemetryItem.getTags().put(ContextTagKeys.AI_OPERATION_PARENT_ID.toString(), parentSpanId.toLowerBase16()); } exceptionData.setExceptions(minimalParse(errorStack)); exceptionData.setSeverityLevel(toSeverityLevel(level)); exceptionData.getProperties().put("Logger Message", message); setProperties(exceptionData.getProperties(), timeEpochNanos, level, loggerName, attributes); telemetryItem.setSampleRate(samplingPercentage.floatValue()); telemetryItems.add(telemetryItem); } private static List<TelemetryExceptionDetails> minimalParse(String errorStack) { TelemetryExceptionDetails details = new TelemetryExceptionDetails(); String line = errorStack.split("\n")[0]; int index = line.indexOf(": "); if (index != -1) { details.setTypeName(line.substring(0, index)); details.setMessage(line.substring(index + 2)); } else { details.setTypeName(line); } details.setStack(errorStack); return Arrays.asList(details); } private void applyDatabaseQuerySpan(Map<String, AttributeValue> attributes, RemoteDependencyData rd, String component) { String type = removeAttributeString(attributes, SemanticAttributes.DB_SYSTEM.key()); if (SQL_DB_SYSTEMS.contains(type)) { type = "SQL"; } rd.setType(type); rd.setData(removeAttributeString(attributes, SemanticAttributes.DB_STATEMENT.key())); String dbUrl = removeAttributeString(attributes, SemanticAttributes.DB_CONNECTION_STRING.key()); if (dbUrl == null) { rd.setTarget(type); } else { String dbInstance = removeAttributeString(attributes, SemanticAttributes.DB_NAME.key()); if (dbInstance != null) { dbUrl += " | " + dbInstance; } if ("jdbc".equals(component)) { rd.setTarget("jdbc:" + dbUrl); } else { rd.setTarget(dbUrl); } } } private void applyHttpRequestSpan(Map<String, AttributeValue> attributes, RemoteDependencyData remoteDependencyData) { remoteDependencyData.setType("Http (tracked component)"); String method = removeAttributeString(attributes, SemanticAttributes.HTTP_METHOD.key()); String url = removeAttributeString(attributes, SemanticAttributes.HTTP_URL.key()); AttributeValue httpStatusCode = attributes.remove(SemanticAttributes.HTTP_STATUS_CODE.key()); if (httpStatusCode != null && httpStatusCode.getType() == AttributeValue.Type.LONG) { long statusCode = httpStatusCode.getLongValue(); remoteDependencyData.setResultCode(Long.toString(statusCode)); } if (url != null) { try { URI uriObject = new URI(url); String target = createTarget(uriObject); remoteDependencyData.setTarget(target); String path = uriObject.getPath(); if (CoreUtils.isNullOrEmpty(path)) { remoteDependencyData.setName(method + " /"); } else { remoteDependencyData.setName(method + " " + path); } } catch (URISyntaxException e) { logger.error(e.getMessage()); } } } private void exportRequest(String stdComponent, SpanData span, List<TelemetryItem> telemetryItems) { TelemetryItem telemetryItem = new TelemetryItem(); RequestData requestData = new RequestData(); MonitorBase monitorBase = new MonitorBase(); telemetryItem.setTags(new HashMap<>()); telemetryItem.setName(telemetryItemNamePrefix + "Request"); telemetryItem.setVersion(1); telemetryItem.setInstrumentationKey(instrumentationKey); telemetryItem.setData(monitorBase); requestData.setProperties(new HashMap<>()); requestData.setVersion(2); monitorBase.setBaseType("RequestData"); monitorBase.setBaseData(requestData); Map<String, AttributeValue> attributes = getAttributesCopy(span.getAttributes()); if ("kafka-clients".equals(stdComponent)) { requestData.setSource(span.getName()); } else if ("jms".equals(stdComponent)) { requestData.setSource(span.getName()); } addLinks(requestData.getProperties(), span.getLinks()); AttributeValue httpStatusCode = attributes.remove(SemanticAttributes.HTTP_STATUS_CODE.key()); if (isNonNullLong(httpStatusCode)) { requestData.setResponseCode(Long.toString(httpStatusCode.getLongValue())); } String httpUrl = removeAttributeString(attributes, SemanticAttributes.HTTP_URL.key()); if (httpUrl != null) { requestData.setUrl(httpUrl); } String httpMethod = removeAttributeString(attributes, SemanticAttributes.HTTP_METHOD.key()); String name = span.getName(); if (httpMethod != null && name.startsWith("/")) { name = httpMethod + " " + name; } requestData.setName(name); telemetryItem.getTags().put(ContextTagKeys.AI_OPERATION_NAME.toString(), name); if (span.getName().equals("EventHubs.process")) { String peerAddress = removeAttributeString(attributes, "peer.address"); String destination = removeAttributeString(attributes, "message_bus.destination"); requestData.setSource(peerAddress + "/" + destination); } requestData.setId(span.getSpanId().toLowerBase16()); telemetryItem.getTags().put(ContextTagKeys.AI_OPERATION_ID.toString(), span.getTraceId().toLowerBase16()); String aiLegacyParentId = span.getTraceState().get("ai-legacy-parent-id"); if (aiLegacyParentId != null) { telemetryItem.getTags().put(ContextTagKeys.AI_OPERATION_PARENT_ID.toString(), aiLegacyParentId); String aiLegacyOperationId = span.getTraceState().get("ai-legacy-operation-id"); if (aiLegacyOperationId != null) { telemetryItem.getTags().putIfAbsent("ai_legacyRootID", aiLegacyOperationId); } } else { SpanId parentSpanId = span.getParentSpanId(); if (parentSpanId.isValid()) { telemetryItem.getTags().put(ContextTagKeys.AI_OPERATION_PARENT_ID.toString(), parentSpanId.toLowerBase16()); } } long startEpochNanos = span.getStartEpochNanos(); telemetryItem.setTime(getFormattedTime(startEpochNanos)); Duration duration = Duration.ofNanos(span.getEndEpochNanos() - startEpochNanos); requestData.setDuration(getFormattedDuration(duration)); requestData.setSuccess(span.getStatus().isOk()); String description = span.getStatus().getDescription(); if (description != null) { requestData.getProperties().put("statusDescription", description); } Double samplingPercentage = removeAiSamplingPercentage(attributes); if (stdComponent == null) { addExtraAttributes(requestData.getProperties(), attributes); } telemetryItem.setSampleRate(samplingPercentage.floatValue()); telemetryItems.add(telemetryItem); exportEvents(span, samplingPercentage, telemetryItems); } private void exportEvents(SpanData span, Double samplingPercentage, List<TelemetryItem> telemetryItems) { boolean foundException = false; for (SpanData.Event event : span.getEvents()) { TelemetryItem telemetryItem = new TelemetryItem(); TelemetryEventData eventData = new TelemetryEventData(); MonitorBase monitorBase = new MonitorBase(); telemetryItem.setTags(new HashMap<>()); telemetryItem.setName(telemetryItemNamePrefix + "Event"); telemetryItem.setVersion(1); telemetryItem.setInstrumentationKey(instrumentationKey); telemetryItem.setData(monitorBase); eventData.setProperties(new HashMap<>()); eventData.setVersion(2); monitorBase.setBaseType("EventData"); monitorBase.setBaseData(eventData); eventData.setName(event.getName()); String operationId = span.getTraceId().toLowerBase16(); telemetryItem.getTags().put(ContextTagKeys.AI_OPERATION_ID.toString(), operationId); telemetryItem.getTags().put(ContextTagKeys.AI_OPERATION_PARENT_ID.toString(), span.getParentSpanId().toLowerBase16()); telemetryItem.setTime(getFormattedTime(event.getEpochNanos())); addExtraAttributes(eventData.getProperties(), event.getAttributes()); if (event.getAttributes().get(SemanticAttributes.EXCEPTION_TYPE.key()) != null || event.getAttributes().get(SemanticAttributes.EXCEPTION_MESSAGE.key()) != null) { if (!foundException) { AttributeValue stacktrace = event.getAttributes().get(SemanticAttributes.EXCEPTION_STACKTRACE.key()); if (stacktrace != null) { trackException(stacktrace.getStringValue(), span, operationId, span.getSpanId().toLowerBase16(), samplingPercentage, telemetryItems); } } foundException = true; } else { telemetryItem.setSampleRate(samplingPercentage.floatValue()); telemetryItems.add(telemetryItem); } } } private void trackException(String errorStack, SpanData span, String operationId, String id, Double samplingPercentage, List<TelemetryItem> telemetryItems) { TelemetryItem telemetryItem = new TelemetryItem(); TelemetryExceptionData exceptionData = new TelemetryExceptionData(); MonitorBase monitorBase = new MonitorBase(); telemetryItem.setTags(new HashMap<>()); telemetryItem.setName(telemetryItemNamePrefix + "Exception"); telemetryItem.setVersion(1); telemetryItem.setInstrumentationKey(instrumentationKey); telemetryItem.setData(monitorBase); exceptionData.setProperties(new HashMap<>()); exceptionData.setVersion(2); monitorBase.setBaseType("ExceptionData"); monitorBase.setBaseData(exceptionData); telemetryItem.getTags().put(ContextTagKeys.AI_OPERATION_ID.toString(), operationId); telemetryItem.getTags().put(ContextTagKeys.AI_OPERATION_PARENT_ID.toString(), id); telemetryItem.setTime(getFormattedTime(span.getEndEpochNanos())); telemetryItem.setSampleRate(samplingPercentage.floatValue()); exceptionData.setExceptions(minimalParse(errorStack)); telemetryItems.add(telemetryItem); } private static String getFormattedDuration(Duration duration) { return duration.toDays() + "." + duration.toHours() + ":" + duration.toMinutes() + ":" + duration.getSeconds() + "." + duration.toMillis(); } private static String getFormattedTime(long epochNanos) { return Instant.ofEpochMilli(NANOSECONDS.toMillis(epochNanos)) .atOffset(ZoneOffset.UTC) .format(DateTimeFormatter.ISO_DATE_TIME); } private boolean isNonNullLong(AttributeValue attributeValue) { return attributeValue != null && attributeValue.getType() == AttributeValue.Type.LONG; } private Map<String, AttributeValue> getAttributesCopy(ReadableAttributes attributes) { final Map<String, AttributeValue> copy = new HashMap<>(); attributes.forEach(new ReadableKeyValuePairs.KeyValueConsumer<AttributeValue>() { @Override public void consume(String key, AttributeValue value) { copy.put(key, value); } }); return copy; } private static void addLinks(Map<String, String> properties, List<SpanData.Link> links) { if (links.isEmpty()) { return; } StringBuilder sb = new StringBuilder(); sb.append("["); boolean first = true; for (SpanData.Link link : links) { if (!first) { sb.append(","); } sb.append("{\"operation_Id\":\""); sb.append(link.getContext().getTraceId().toLowerBase16()); sb.append("\",\"id\":\""); sb.append(link.getContext().getSpanId().toLowerBase16()); sb.append("\"}"); first = false; } sb.append("]"); properties.put("_MS.links", sb.toString()); } private static String removeAttributeString(Map<String, AttributeValue> attributes, String attributeName) { AttributeValue attributeValue = attributes.remove(attributeName); if (attributeValue == null) { return null; } else if (attributeValue.getType() == AttributeValue.Type.STRING) { return attributeValue.getStringValue(); } else { return null; } } private static Double removeAttributeDouble(Map<String, AttributeValue> attributes, String attributeName) { AttributeValue attributeValue = attributes.remove(attributeName); if (attributeValue == null) { return null; } else if (attributeValue.getType() == AttributeValue.Type.DOUBLE) { return attributeValue.getDoubleValue(); } else { return null; } } private static String createTarget(URI uriObject) { String target = uriObject.getHost(); if (uriObject.getPort() != 80 && uriObject.getPort() != 443 && uriObject.getPort() != -1) { target += ":" + uriObject.getPort(); } return target; } private static String getStringValue(AttributeValue value) { switch (value.getType()) { case STRING: return value.getStringValue(); case BOOLEAN: return Boolean.toString(value.getBooleanValue()); case LONG: return Long.toString(value.getLongValue()); case DOUBLE: return Double.toString(value.getDoubleValue()); case STRING_ARRAY: return join(value.getStringArrayValue()); case BOOLEAN_ARRAY: return join(value.getBooleanArrayValue()); case LONG_ARRAY: return join(value.getLongArrayValue()); case DOUBLE_ARRAY: return join(value.getDoubleArrayValue()); default: return null; } } private static <T> String join(List<T> values) { StringBuilder sb = new StringBuilder(); if (CoreUtils.isNullOrEmpty(values)) { return sb.toString(); } for (int i = 0; i < values.size() - 1; i++) { sb.append(values.get(i)); sb.append(", "); } sb.append(values.get(values.size() - 1)); return sb.toString(); } private static SeverityLevel toSeverityLevel(String level) { if (level == null) { return null; } switch (level) { case "FATAL": return SeverityLevel.CRITICAL; case "ERROR": case "SEVERE": return SeverityLevel.ERROR; case "WARN": case "WARNING": return SeverityLevel.WARNING; case "INFO": return SeverityLevel.INFORMATION; case "DEBUG": case "TRACE": case "CONFIG": case "FINE": case "FINER": case "FINEST": case "ALL": return SeverityLevel.VERBOSE; default: return SeverityLevel.VERBOSE; } } private static Double removeAiSamplingPercentage(Map<String, AttributeValue> attributes) { return removeAttributeDouble(attributes, "ai.sampling.percentage"); } private static void addExtraAttributes(Map<String, String> properties, Map<String, AttributeValue> attributes) { for (Map.Entry<String, AttributeValue> entry : attributes.entrySet()) { String value = getStringValue(entry.getValue()); if (value != null) { properties.put(entry.getKey(), value); } } } private static void addExtraAttributes(final Map<String, String> properties, Attributes attributes) { attributes.forEach(new ReadableKeyValuePairs.KeyValueConsumer<AttributeValue>() { @Override public void consume(String key, AttributeValue value) { String val = getStringValue(value); if (val != null) { properties.put(key, val); } } }); } }
class AzureMonitorExporter implements SpanExporter { private static final Pattern COMPONENT_PATTERN = Pattern .compile("io\\.opentelemetry\\.auto\\.([^0-9]*)(-[0-9.]*)?"); private static final Set<String> SQL_DB_SYSTEMS; static { Set<String> dbSystems = new HashSet<>(); dbSystems.add("db2"); dbSystems.add("derby"); dbSystems.add("mariadb"); dbSystems.add("mssql"); dbSystems.add("mysql"); dbSystems.add("oracle"); dbSystems.add("postgresql"); dbSystems.add("sqlite"); dbSystems.add("other_sql"); dbSystems.add("hsqldb"); dbSystems.add("h2"); SQL_DB_SYSTEMS = Collections.unmodifiableSet(dbSystems); } private final MonitorExporterClient client; private final ClientLogger logger = new ClientLogger(AzureMonitorExporter.class); private final String instrumentationKey; private final String telemetryItemNamePrefix; /** * Creates an instance of exporter that is configured with given exporter client that sends telemetry events to * Application Insights resource identified by the instrumentation key. * * @param client The client used to send data to Azure Monitor. * @param instrumentationKey The instrumentation key of Application Insights resource. */ AzureMonitorExporter(MonitorExporterClient client, String instrumentationKey) { this.client = client; this.instrumentationKey = instrumentationKey; String formattedInstrumentationKey = instrumentationKey.replaceAll("-", ""); this.telemetryItemNamePrefix = "Microsoft.ApplicationInsights." + formattedInstrumentationKey + "."; } /** * {@inheritDoc} */ @Override public CompletableResultCode export(Collection<SpanData> spans) { try { List<TelemetryItem> telemetryItems = new ArrayList<>(); for (SpanData span : spans) { logger.verbose("exporting span: {}", span); export(span, telemetryItems); } client.export(telemetryItems); return CompletableResultCode.ofSuccess(); } catch (Throwable t) { logger.error(t.getMessage(), t); return CompletableResultCode.ofFailure(); } } /** * {@inheritDoc} */ @Override public CompletableResultCode flush() { return CompletableResultCode.ofSuccess(); } /** * {@inheritDoc} */ @Override public CompletableResultCode shutdown() { return CompletableResultCode.ofSuccess(); } private void export(SpanData span, List<TelemetryItem> telemetryItems) { Span.Kind kind = span.getKind(); String instrumentationName = span.getInstrumentationLibraryInfo().getName(); Matcher matcher = COMPONENT_PATTERN.matcher(instrumentationName); String stdComponent = matcher.matches() ? matcher.group(1) : null; if ("jms".equals(stdComponent) && !span.getParentSpanId().isValid() && kind == Span.Kind.CLIENT) { return; } if (kind == Span.Kind.INTERNAL) { if (!span.getParentSpanId().isValid()) { exportRequest(stdComponent, span, telemetryItems); } else if (span.getName().equals("EventHubs.message")) { exportRemoteDependency(stdComponent, span, false, telemetryItems); } else { exportRemoteDependency(stdComponent, span, true, telemetryItems); } } else if (kind == Span.Kind.CLIENT || kind == Span.Kind.PRODUCER) { exportRemoteDependency(stdComponent, span, false, telemetryItems); } else if (kind == Span.Kind.SERVER || kind == Span.Kind.CONSUMER) { exportRequest(stdComponent, span, telemetryItems); } else { throw new UnsupportedOperationException(kind.name()); } } private static void setProperties(Map<String, String> properties, long timeEpochNanos, String level, String loggerName, Map<String, AttributeValue> attributes) { if (level != null) { properties.put("SourceType", "Logger"); properties.put("LoggingLevel", level); } if (loggerName != null) { properties.put("LoggerName", loggerName); } if (attributes != null) { for (Map.Entry<String, AttributeValue> entry : attributes.entrySet()) { AttributeValue av = entry.getValue(); String stringValue = null; switch (av.getType()) { case STRING: stringValue = av.getStringValue(); break; case BOOLEAN: stringValue = String.valueOf(av.getBooleanValue()); break; case LONG: stringValue = String.valueOf(av.getLongValue()); break; case DOUBLE: stringValue = String.valueOf(av.getDoubleValue()); break; case STRING_ARRAY: stringValue = String.valueOf(av.getStringArrayValue()); break; case BOOLEAN_ARRAY: stringValue = String.valueOf(av.getBooleanArrayValue()); break; case LONG_ARRAY: stringValue = String.valueOf(av.getLongArrayValue()); break; case DOUBLE_ARRAY: stringValue = String.valueOf(av.getDoubleArrayValue()); break; } if (stringValue != null) { properties.put(entry.getKey(), stringValue); } } } } private static List<TelemetryExceptionDetails> minimalParse(String errorStack) { TelemetryExceptionDetails details = new TelemetryExceptionDetails(); String line = errorStack.split("\n")[0]; int index = line.indexOf(": "); if (index != -1) { details.setTypeName(line.substring(0, index)); details.setMessage(line.substring(index + 2)); } else { details.setTypeName(line); } details.setStack(errorStack); return Arrays.asList(details); } private void applyDatabaseQuerySpan(Map<String, AttributeValue> attributes, RemoteDependencyData rd, String component) { String type = removeAttributeString(attributes, SemanticAttributes.DB_SYSTEM.key()); if (SQL_DB_SYSTEMS.contains(type)) { type = "SQL"; } rd.setType(type); rd.setData(removeAttributeString(attributes, SemanticAttributes.DB_STATEMENT.key())); String dbUrl = removeAttributeString(attributes, SemanticAttributes.DB_CONNECTION_STRING.key()); if (dbUrl == null) { rd.setTarget(type); } else { String dbInstance = removeAttributeString(attributes, SemanticAttributes.DB_NAME.key()); if (dbInstance != null) { dbUrl += " | " + dbInstance; } if ("jdbc".equals(component)) { rd.setTarget("jdbc:" + dbUrl); } else { rd.setTarget(dbUrl); } } } private void applyHttpRequestSpan(Map<String, AttributeValue> attributes, RemoteDependencyData remoteDependencyData) { remoteDependencyData.setType("Http (tracked component)"); String method = removeAttributeString(attributes, SemanticAttributes.HTTP_METHOD.key()); String url = removeAttributeString(attributes, SemanticAttributes.HTTP_URL.key()); AttributeValue httpStatusCode = attributes.remove(SemanticAttributes.HTTP_STATUS_CODE.key()); if (httpStatusCode != null && httpStatusCode.getType() == AttributeValue.Type.LONG) { long statusCode = httpStatusCode.getLongValue(); remoteDependencyData.setResultCode(Long.toString(statusCode)); } if (url != null) { try { URI uriObject = new URI(url); String target = createTarget(uriObject); remoteDependencyData.setTarget(target); String path = uriObject.getPath(); if (CoreUtils.isNullOrEmpty(path)) { remoteDependencyData.setName(method + " /"); } else { remoteDependencyData.setName(method + " " + path); } } catch (URISyntaxException e) { logger.error(e.getMessage()); } } } private void exportRequest(String stdComponent, SpanData span, List<TelemetryItem> telemetryItems) { TelemetryItem telemetryItem = new TelemetryItem(); RequestData requestData = new RequestData(); MonitorBase monitorBase = new MonitorBase(); telemetryItem.setTags(new HashMap<>()); telemetryItem.setName(telemetryItemNamePrefix + "Request"); telemetryItem.setVersion(1); telemetryItem.setInstrumentationKey(instrumentationKey); telemetryItem.setData(monitorBase); requestData.setProperties(new HashMap<>()); requestData.setVersion(2); monitorBase.setBaseType("RequestData"); monitorBase.setBaseData(requestData); Map<String, AttributeValue> attributes = getAttributesCopy(span.getAttributes()); if ("kafka-clients".equals(stdComponent)) { requestData.setSource(span.getName()); } else if ("jms".equals(stdComponent)) { requestData.setSource(span.getName()); } addLinks(requestData.getProperties(), span.getLinks()); AttributeValue httpStatusCode = attributes.remove(SemanticAttributes.HTTP_STATUS_CODE.key()); if (isNonNullLong(httpStatusCode)) { requestData.setResponseCode(Long.toString(httpStatusCode.getLongValue())); } String httpUrl = removeAttributeString(attributes, SemanticAttributes.HTTP_URL.key()); if (httpUrl != null) { requestData.setUrl(httpUrl); } String httpMethod = removeAttributeString(attributes, SemanticAttributes.HTTP_METHOD.key()); String name = span.getName(); if (httpMethod != null && name.startsWith("/")) { name = httpMethod + " " + name; } requestData.setName(name); telemetryItem.getTags().put(ContextTagKeys.AI_OPERATION_NAME.toString(), name); if (span.getName().equals("EventHubs.process")) { String peerAddress = removeAttributeString(attributes, "peer.address"); String destination = removeAttributeString(attributes, "message_bus.destination"); requestData.setSource(peerAddress + "/" + destination); } requestData.setId(span.getSpanId().toLowerBase16()); telemetryItem.getTags().put(ContextTagKeys.AI_OPERATION_ID.toString(), span.getTraceId().toLowerBase16()); String aiLegacyParentId = span.getTraceState().get("ai-legacy-parent-id"); if (aiLegacyParentId != null) { telemetryItem.getTags().put(ContextTagKeys.AI_OPERATION_PARENT_ID.toString(), aiLegacyParentId); String aiLegacyOperationId = span.getTraceState().get("ai-legacy-operation-id"); if (aiLegacyOperationId != null) { telemetryItem.getTags().putIfAbsent("ai_legacyRootID", aiLegacyOperationId); } } else { SpanId parentSpanId = span.getParentSpanId(); if (parentSpanId.isValid()) { telemetryItem.getTags().put(ContextTagKeys.AI_OPERATION_PARENT_ID.toString(), parentSpanId.toLowerBase16()); } } long startEpochNanos = span.getStartEpochNanos(); telemetryItem.setTime(getFormattedTime(startEpochNanos)); Duration duration = Duration.ofNanos(span.getEndEpochNanos() - startEpochNanos); requestData.setDuration(getFormattedDuration(duration)); requestData.setSuccess(span.getStatus().isOk()); String description = span.getStatus().getDescription(); if (description != null) { requestData.getProperties().put("statusDescription", description); } Double samplingPercentage = removeAiSamplingPercentage(attributes); if (stdComponent == null) { addExtraAttributes(requestData.getProperties(), attributes); } telemetryItem.setSampleRate(samplingPercentage.floatValue()); telemetryItems.add(telemetryItem); exportEvents(span, samplingPercentage, telemetryItems); } private void exportEvents(SpanData span, Double samplingPercentage, List<TelemetryItem> telemetryItems) { boolean foundException = false; for (SpanData.Event event : span.getEvents()) { TelemetryItem telemetryItem = new TelemetryItem(); TelemetryEventData eventData = new TelemetryEventData(); MonitorBase monitorBase = new MonitorBase(); telemetryItem.setTags(new HashMap<>()); telemetryItem.setName(telemetryItemNamePrefix + "Event"); telemetryItem.setVersion(1); telemetryItem.setInstrumentationKey(instrumentationKey); telemetryItem.setData(monitorBase); eventData.setProperties(new HashMap<>()); eventData.setVersion(2); monitorBase.setBaseType("EventData"); monitorBase.setBaseData(eventData); eventData.setName(event.getName()); String operationId = span.getTraceId().toLowerBase16(); telemetryItem.getTags().put(ContextTagKeys.AI_OPERATION_ID.toString(), operationId); telemetryItem.getTags().put(ContextTagKeys.AI_OPERATION_PARENT_ID.toString(), span.getParentSpanId().toLowerBase16()); telemetryItem.setTime(getFormattedTime(event.getEpochNanos())); addExtraAttributes(eventData.getProperties(), event.getAttributes()); if (event.getAttributes().get(SemanticAttributes.EXCEPTION_TYPE.key()) != null || event.getAttributes().get(SemanticAttributes.EXCEPTION_MESSAGE.key()) != null) { if (!foundException) { AttributeValue stacktrace = event.getAttributes().get(SemanticAttributes.EXCEPTION_STACKTRACE.key()); if (stacktrace != null) { trackException(stacktrace.getStringValue(), span, operationId, span.getSpanId().toLowerBase16(), samplingPercentage, telemetryItems); } } foundException = true; } else { telemetryItem.setSampleRate(samplingPercentage.floatValue()); telemetryItems.add(telemetryItem); } } } private void trackException(String errorStack, SpanData span, String operationId, String id, Double samplingPercentage, List<TelemetryItem> telemetryItems) { TelemetryItem telemetryItem = new TelemetryItem(); TelemetryExceptionData exceptionData = new TelemetryExceptionData(); MonitorBase monitorBase = new MonitorBase(); telemetryItem.setTags(new HashMap<>()); telemetryItem.setName(telemetryItemNamePrefix + "Exception"); telemetryItem.setVersion(1); telemetryItem.setInstrumentationKey(instrumentationKey); telemetryItem.setData(monitorBase); exceptionData.setProperties(new HashMap<>()); exceptionData.setVersion(2); monitorBase.setBaseType("ExceptionData"); monitorBase.setBaseData(exceptionData); telemetryItem.getTags().put(ContextTagKeys.AI_OPERATION_ID.toString(), operationId); telemetryItem.getTags().put(ContextTagKeys.AI_OPERATION_PARENT_ID.toString(), id); telemetryItem.setTime(getFormattedTime(span.getEndEpochNanos())); telemetryItem.setSampleRate(samplingPercentage.floatValue()); exceptionData.setExceptions(minimalParse(errorStack)); telemetryItems.add(telemetryItem); } private static String getFormattedDuration(Duration duration) { return duration.toDays() + "." + duration.toHours() + ":" + duration.toMinutes() + ":" + duration.getSeconds() + "." + duration.toMillis(); } private static String getFormattedTime(long epochNanos) { return Instant.ofEpochMilli(NANOSECONDS.toMillis(epochNanos)) .atOffset(ZoneOffset.UTC) .format(DateTimeFormatter.ISO_DATE_TIME); } private boolean isNonNullLong(AttributeValue attributeValue) { return attributeValue != null && attributeValue.getType() == AttributeValue.Type.LONG; } private Map<String, AttributeValue> getAttributesCopy(ReadableAttributes attributes) { final Map<String, AttributeValue> copy = new HashMap<>(); attributes.forEach(new ReadableKeyValuePairs.KeyValueConsumer<AttributeValue>() { @Override public void consume(String key, AttributeValue value) { copy.put(key, value); } }); return copy; } private static void addLinks(Map<String, String> properties, List<SpanData.Link> links) { if (links.isEmpty()) { return; } StringBuilder sb = new StringBuilder(); sb.append("["); boolean first = true; for (SpanData.Link link : links) { if (!first) { sb.append(","); } sb.append("{\"operation_Id\":\""); sb.append(link.getContext().getTraceId().toLowerBase16()); sb.append("\",\"id\":\""); sb.append(link.getContext().getSpanId().toLowerBase16()); sb.append("\"}"); first = false; } sb.append("]"); properties.put("_MS.links", sb.toString()); } private static String removeAttributeString(Map<String, AttributeValue> attributes, String attributeName) { AttributeValue attributeValue = attributes.remove(attributeName); if (attributeValue == null) { return null; } else if (attributeValue.getType() == AttributeValue.Type.STRING) { return attributeValue.getStringValue(); } else { return null; } } private static Double removeAttributeDouble(Map<String, AttributeValue> attributes, String attributeName) { AttributeValue attributeValue = attributes.remove(attributeName); if (attributeValue == null) { return null; } else if (attributeValue.getType() == AttributeValue.Type.DOUBLE) { return attributeValue.getDoubleValue(); } else { return null; } } private static String createTarget(URI uriObject) { String target = uriObject.getHost(); if (uriObject.getPort() != 80 && uriObject.getPort() != 443 && uriObject.getPort() != -1) { target += ":" + uriObject.getPort(); } return target; } private static String getStringValue(AttributeValue value) { switch (value.getType()) { case STRING: return value.getStringValue(); case BOOLEAN: return Boolean.toString(value.getBooleanValue()); case LONG: return Long.toString(value.getLongValue()); case DOUBLE: return Double.toString(value.getDoubleValue()); case STRING_ARRAY: return join(value.getStringArrayValue()); case BOOLEAN_ARRAY: return join(value.getBooleanArrayValue()); case LONG_ARRAY: return join(value.getLongArrayValue()); case DOUBLE_ARRAY: return join(value.getDoubleArrayValue()); default: return null; } } private static <T> String join(List<T> values) { StringBuilder sb = new StringBuilder(); if (CoreUtils.isNullOrEmpty(values)) { return sb.toString(); } for (int i = 0; i < values.size() - 1; i++) { sb.append(values.get(i)); sb.append(", "); } sb.append(values.get(values.size() - 1)); return sb.toString(); } private static Double removeAiSamplingPercentage(Map<String, AttributeValue> attributes) { return removeAttributeDouble(attributes, "ai.sampling.percentage"); } private static void addExtraAttributes(Map<String, String> properties, Map<String, AttributeValue> attributes) { for (Map.Entry<String, AttributeValue> entry : attributes.entrySet()) { String value = getStringValue(entry.getValue()); if (value != null) { properties.put(entry.getKey(), value); } } } private static void addExtraAttributes(final Map<String, String> properties, Attributes attributes) { attributes.forEach(new ReadableKeyValuePairs.KeyValueConsumer<AttributeValue>() { @Override public void consume(String key, AttributeValue value) { String val = getStringValue(value); if (val != null) { properties.put(key, val); } } }); } }
TODO do we want to provide a legacy Application Insights propagator?
private void exportRequest(String stdComponent, SpanData span, List<TelemetryItem> telemetryItems) { TelemetryItem telemetryItem = new TelemetryItem(); RequestData requestData = new RequestData(); MonitorBase monitorBase = new MonitorBase(); telemetryItem.setTags(new HashMap<>()); telemetryItem.setName(telemetryItemNamePrefix + "Request"); telemetryItem.setVersion(1); telemetryItem.setInstrumentationKey(instrumentationKey); telemetryItem.setData(monitorBase); requestData.setProperties(new HashMap<>()); requestData.setVersion(2); monitorBase.setBaseType("RequestData"); monitorBase.setBaseData(requestData); Map<String, AttributeValue> attributes = getAttributesCopy(span.getAttributes()); if ("kafka-clients".equals(stdComponent)) { requestData.setSource(span.getName()); } else if ("jms".equals(stdComponent)) { requestData.setSource(span.getName()); } addLinks(requestData.getProperties(), span.getLinks()); AttributeValue httpStatusCode = attributes.remove(SemanticAttributes.HTTP_STATUS_CODE.key()); if (isNonNullLong(httpStatusCode)) { requestData.setResponseCode(Long.toString(httpStatusCode.getLongValue())); } String httpUrl = removeAttributeString(attributes, SemanticAttributes.HTTP_URL.key()); if (httpUrl != null) { requestData.setUrl(httpUrl); } String httpMethod = removeAttributeString(attributes, SemanticAttributes.HTTP_METHOD.key()); String name = span.getName(); if (httpMethod != null && name.startsWith("/")) { name = httpMethod + " " + name; } requestData.setName(name); telemetryItem.getTags().put(ContextTagKeys.AI_OPERATION_NAME.toString(), name); if (span.getName().equals("EventHubs.process")) { String peerAddress = removeAttributeString(attributes, "peer.address"); String destination = removeAttributeString(attributes, "message_bus.destination"); requestData.setSource(peerAddress + "/" + destination); } requestData.setId(span.getSpanId().toLowerBase16()); telemetryItem.getTags().put(ContextTagKeys.AI_OPERATION_ID.toString(), span.getTraceId().toLowerBase16()); String aiLegacyParentId = span.getTraceState().get("ai-legacy-parent-id"); if (aiLegacyParentId != null) { telemetryItem.getTags().put(ContextTagKeys.AI_OPERATION_PARENT_ID.toString(), aiLegacyParentId); String aiLegacyOperationId = span.getTraceState().get("ai-legacy-operation-id"); if (aiLegacyOperationId != null) { telemetryItem.getTags().putIfAbsent("ai_legacyRootID", aiLegacyOperationId); } } else { SpanId parentSpanId = span.getParentSpanId(); if (parentSpanId.isValid()) { telemetryItem.getTags().put(ContextTagKeys.AI_OPERATION_PARENT_ID.toString(), parentSpanId.toLowerBase16()); } } long startEpochNanos = span.getStartEpochNanos(); telemetryItem.setTime(getFormattedTime(startEpochNanos)); Duration duration = Duration.ofNanos(span.getEndEpochNanos() - startEpochNanos); requestData.setDuration(getFormattedDuration(duration)); requestData.setSuccess(span.getStatus().isOk()); String description = span.getStatus().getDescription(); if (description != null) { requestData.getProperties().put("statusDescription", description); } Double samplingPercentage = removeAiSamplingPercentage(attributes); if (stdComponent == null) { addExtraAttributes(requestData.getProperties(), attributes); } telemetryItem.setSampleRate(samplingPercentage.floatValue()); telemetryItems.add(telemetryItem); exportEvents(span, samplingPercentage, telemetryItems); }
String aiLegacyParentId = span.getTraceState().get("ai-legacy-parent-id");
private void exportRequest(String stdComponent, SpanData span, List<TelemetryItem> telemetryItems) { TelemetryItem telemetryItem = new TelemetryItem(); RequestData requestData = new RequestData(); MonitorBase monitorBase = new MonitorBase(); telemetryItem.setTags(new HashMap<>()); telemetryItem.setName(telemetryItemNamePrefix + "Request"); telemetryItem.setVersion(1); telemetryItem.setInstrumentationKey(instrumentationKey); telemetryItem.setData(monitorBase); requestData.setProperties(new HashMap<>()); requestData.setVersion(2); monitorBase.setBaseType("RequestData"); monitorBase.setBaseData(requestData); Map<String, AttributeValue> attributes = getAttributesCopy(span.getAttributes()); if ("kafka-clients".equals(stdComponent)) { requestData.setSource(span.getName()); } else if ("jms".equals(stdComponent)) { requestData.setSource(span.getName()); } addLinks(requestData.getProperties(), span.getLinks()); AttributeValue httpStatusCode = attributes.remove(SemanticAttributes.HTTP_STATUS_CODE.key()); if (isNonNullLong(httpStatusCode)) { requestData.setResponseCode(Long.toString(httpStatusCode.getLongValue())); } String httpUrl = removeAttributeString(attributes, SemanticAttributes.HTTP_URL.key()); if (httpUrl != null) { requestData.setUrl(httpUrl); } String httpMethod = removeAttributeString(attributes, SemanticAttributes.HTTP_METHOD.key()); String name = span.getName(); if (httpMethod != null && name.startsWith("/")) { name = httpMethod + " " + name; } requestData.setName(name); telemetryItem.getTags().put(ContextTagKeys.AI_OPERATION_NAME.toString(), name); if (span.getName().equals("EventHubs.process")) { String peerAddress = removeAttributeString(attributes, "peer.address"); String destination = removeAttributeString(attributes, "message_bus.destination"); requestData.setSource(peerAddress + "/" + destination); } requestData.setId(span.getSpanId().toLowerBase16()); telemetryItem.getTags().put(ContextTagKeys.AI_OPERATION_ID.toString(), span.getTraceId().toLowerBase16()); String aiLegacyParentId = span.getTraceState().get("ai-legacy-parent-id"); if (aiLegacyParentId != null) { telemetryItem.getTags().put(ContextTagKeys.AI_OPERATION_PARENT_ID.toString(), aiLegacyParentId); String aiLegacyOperationId = span.getTraceState().get("ai-legacy-operation-id"); if (aiLegacyOperationId != null) { telemetryItem.getTags().putIfAbsent("ai_legacyRootID", aiLegacyOperationId); } } else { SpanId parentSpanId = span.getParentSpanId(); if (parentSpanId.isValid()) { telemetryItem.getTags().put(ContextTagKeys.AI_OPERATION_PARENT_ID.toString(), parentSpanId.toLowerBase16()); } } long startEpochNanos = span.getStartEpochNanos(); telemetryItem.setTime(getFormattedTime(startEpochNanos)); Duration duration = Duration.ofNanos(span.getEndEpochNanos() - startEpochNanos); requestData.setDuration(getFormattedDuration(duration)); requestData.setSuccess(span.getStatus().isOk()); String description = span.getStatus().getDescription(); if (description != null) { requestData.getProperties().put("statusDescription", description); } Double samplingPercentage = removeAiSamplingPercentage(attributes); if (stdComponent == null) { addExtraAttributes(requestData.getProperties(), attributes); } telemetryItem.setSampleRate(samplingPercentage.floatValue()); telemetryItems.add(telemetryItem); exportEvents(span, samplingPercentage, telemetryItems); }
class AzureMonitorExporter implements SpanExporter { private static final Pattern COMPONENT_PATTERN = Pattern .compile("io\\.opentelemetry\\.auto\\.([^0-9]*)(-[0-9.]*)?"); private static final Set<String> SQL_DB_SYSTEMS; static { Set<String> dbSystems = new HashSet<>(); dbSystems.add("db2"); dbSystems.add("derby"); dbSystems.add("mariadb"); dbSystems.add("mssql"); dbSystems.add("mysql"); dbSystems.add("oracle"); dbSystems.add("postgresql"); dbSystems.add("sqlite"); dbSystems.add("other_sql"); dbSystems.add("hsqldb"); dbSystems.add("h2"); SQL_DB_SYSTEMS = Collections.unmodifiableSet(dbSystems); } private final MonitorExporterClient client; private final ClientLogger logger = new ClientLogger(AzureMonitorExporter.class); private final String instrumentationKey; private final String telemetryItemNamePrefix; /** * Creates an instance of exporter that is configured with given exporter client that sends telemetry events to * Application Insights resource identified by the instrumentation key. * * @param client The client used to send data to Azure Monitor. * @param instrumentationKey The instrumentation key of Application Insights resource. */ AzureMonitorExporter(MonitorExporterClient client, String instrumentationKey) { this.client = client; this.instrumentationKey = instrumentationKey; this.telemetryItemNamePrefix = "Microsoft.ApplicationInsights." + instrumentationKey + "."; } /** * {@inheritDoc} */ @Override public CompletableResultCode export(Collection<SpanData> spans) { try { List<TelemetryItem> telemetryItems = new ArrayList<>(); for (SpanData span : spans) { logger.verbose("exporting span: {}", span); export(span, telemetryItems); } client.export(telemetryItems); return CompletableResultCode.ofSuccess(); } catch (Throwable t) { logger.error(t.getMessage(), t); return CompletableResultCode.ofFailure(); } } /** * {@inheritDoc} */ @Override public CompletableResultCode flush() { return CompletableResultCode.ofSuccess(); } /** * {@inheritDoc} */ @Override public CompletableResultCode shutdown() { return CompletableResultCode.ofSuccess(); } private void export(SpanData span, List<TelemetryItem> telemetryItems) { Span.Kind kind = span.getKind(); String instrumentationName = span.getInstrumentationLibraryInfo().getName(); Matcher matcher = COMPONENT_PATTERN.matcher(instrumentationName); String stdComponent = matcher.matches() ? matcher.group(1) : null; if ("jms".equals(stdComponent) && !span.getParentSpanId().isValid() && kind == Span.Kind.CLIENT) { return; } if (kind == Span.Kind.INTERNAL) { if (span.getName().equals("log.message")) { exportLogSpan(span, telemetryItems); } else if (!span.getParentSpanId().isValid()) { exportRequest(stdComponent, span, telemetryItems); } else if (span.getName().equals("EventHubs.message")) { exportRemoteDependency(stdComponent, span, false, telemetryItems); } else { exportRemoteDependency(stdComponent, span, true, telemetryItems); } } else if (kind == Span.Kind.CLIENT || kind == Span.Kind.PRODUCER) { exportRemoteDependency(stdComponent, span, false, telemetryItems); } else if (kind == Span.Kind.SERVER || kind == Span.Kind.CONSUMER) { exportRequest(stdComponent, span, telemetryItems); } else { throw new UnsupportedOperationException(kind.name()); } } private void exportLogSpan(SpanData span, List<TelemetryItem> telemetryItems) { Map<String, AttributeValue> attributes = getAttributesCopy(span.getAttributes()); String message = removeAttributeString(attributes, "message"); String level = removeAttributeString(attributes, "level"); String loggerName = removeAttributeString(attributes, "loggerName"); String errorStack = removeAttributeString(attributes, "error.stack"); Double samplingPercentage = removeAiSamplingPercentage(attributes); if (errorStack == null) { trackTrace(message, span.getStartEpochNanos(), level, loggerName, span.getTraceId(), span.getParentSpanId(), samplingPercentage, attributes, telemetryItems); } else { trackTraceAsException(message, span.getStartEpochNanos(), level, loggerName, errorStack, span.getTraceId(), span.getParentSpanId(), samplingPercentage, attributes, telemetryItems); } } private void trackTrace(String message, long timeEpochNanos, String level, String loggerName, TraceId traceId, SpanId parentSpanId, Double samplingPercentage, Map<String, AttributeValue> attributes, List<TelemetryItem> telemetryItems) { TelemetryItem telemetryItem = new TelemetryItem(); MessageData messageData = new MessageData(); MonitorBase monitorBase = new MonitorBase(); telemetryItem.setTags(new HashMap<>()); telemetryItem.setName(telemetryItemNamePrefix + "Message"); telemetryItem.setVersion(1); telemetryItem.setInstrumentationKey(instrumentationKey); telemetryItem.setData(monitorBase); messageData.setProperties(new HashMap<>()); messageData.setVersion(2); monitorBase.setBaseType("MessageData"); monitorBase.setBaseData(messageData); messageData.setSeverityLevel(toSeverityLevel(level)); messageData.setMessage(message); if (parentSpanId.isValid()) { telemetryItem.getTags().put(ContextTagKeys.AI_OPERATION_ID.toString(), traceId.toLowerBase16()); telemetryItem.getTags().put(ContextTagKeys.AI_OPERATION_PARENT_ID.toString(), parentSpanId.toLowerBase16()); } setProperties(messageData.getProperties(), timeEpochNanos, level, loggerName, attributes); telemetryItem.setSampleRate(samplingPercentage.floatValue()); telemetryItems.add(telemetryItem); } private static void setProperties(Map<String, String> properties, long timeEpochNanos, String level, String loggerName, Map<String, AttributeValue> attributes) { if (level != null) { properties.put("SourceType", "Logger"); properties.put("LoggingLevel", level); } if (loggerName != null) { properties.put("LoggerName", loggerName); } if (attributes != null) { for (Map.Entry<String, AttributeValue> entry : attributes.entrySet()) { AttributeValue av = entry.getValue(); String stringValue = null; switch (av.getType()) { case STRING: stringValue = av.getStringValue(); break; case BOOLEAN: stringValue = String.valueOf(av.getBooleanValue()); break; case LONG: stringValue = String.valueOf(av.getLongValue()); break; case DOUBLE: stringValue = String.valueOf(av.getDoubleValue()); break; case STRING_ARRAY: stringValue = String.valueOf(av.getStringArrayValue()); break; case BOOLEAN_ARRAY: stringValue = String.valueOf(av.getBooleanArrayValue()); break; case LONG_ARRAY: stringValue = String.valueOf(av.getLongArrayValue()); break; case DOUBLE_ARRAY: stringValue = String.valueOf(av.getDoubleArrayValue()); break; } if (stringValue != null) { properties.put(entry.getKey(), stringValue); } } } } private void trackTraceAsException(String message, long timeEpochNanos, String level, String loggerName, String errorStack, TraceId traceId, SpanId parentSpanId, Double samplingPercentage, Map<String, AttributeValue> attributes, List<TelemetryItem> telemetryItems) { TelemetryItem telemetryItem = new TelemetryItem(); TelemetryExceptionData exceptionData = new TelemetryExceptionData(); MonitorBase monitorBase = new MonitorBase(); telemetryItem.setTags(new HashMap<>()); telemetryItem.setName(telemetryItemNamePrefix + "Exception"); telemetryItem.setVersion(1); telemetryItem.setInstrumentationKey(instrumentationKey); telemetryItem.setData(monitorBase); exceptionData.setProperties(new HashMap<>()); exceptionData.setVersion(2); monitorBase.setBaseType("ExceptionData"); monitorBase.setBaseData(exceptionData); if (parentSpanId.isValid()) { telemetryItem.getTags().put(ContextTagKeys.AI_OPERATION_ID.toString(), traceId.toLowerBase16()); telemetryItem.getTags().put(ContextTagKeys.AI_OPERATION_PARENT_ID.toString(), parentSpanId.toLowerBase16()); } exceptionData.setExceptions(minimalParse(errorStack)); exceptionData.setSeverityLevel(toSeverityLevel(level)); exceptionData.getProperties().put("Logger Message", message); setProperties(exceptionData.getProperties(), timeEpochNanos, level, loggerName, attributes); telemetryItem.setSampleRate(samplingPercentage.floatValue()); telemetryItems.add(telemetryItem); } private static List<TelemetryExceptionDetails> minimalParse(String errorStack) { TelemetryExceptionDetails details = new TelemetryExceptionDetails(); String line = errorStack.split("\n")[0]; int index = line.indexOf(": "); if (index != -1) { details.setTypeName(line.substring(0, index)); details.setMessage(line.substring(index + 2)); } else { details.setTypeName(line); } details.setStack(errorStack); return Arrays.asList(details); } private void exportRemoteDependency(String stdComponent, SpanData span, boolean inProc, List<TelemetryItem> telemetryItems) { TelemetryItem telemetryItem = new TelemetryItem(); RemoteDependencyData remoteDependencyData = new RemoteDependencyData(); MonitorBase monitorBase = new MonitorBase(); telemetryItem.setTags(new HashMap<>()); telemetryItem.setName(telemetryItemNamePrefix + "RemoteDependency"); telemetryItem.setVersion(1); telemetryItem.setInstrumentationKey(instrumentationKey); telemetryItem.setData(monitorBase); remoteDependencyData.setProperties(new HashMap<>()); remoteDependencyData.setVersion(2); monitorBase.setBaseType("RemoteDependencyData"); monitorBase.setBaseData(remoteDependencyData); addLinks(remoteDependencyData.getProperties(), span.getLinks()); remoteDependencyData.setName(span.getName()); span.getInstrumentationLibraryInfo().getName(); Map<String, AttributeValue> attributes = getAttributesCopy(span.getAttributes()); if (inProc) { remoteDependencyData.setType("InProc"); } else { if (attributes.containsKey("http.method")) { applyHttpRequestSpan(attributes, remoteDependencyData); } else if (attributes.containsKey(SemanticAttributes.DB_SYSTEM.key())) { applyDatabaseQuerySpan(attributes, remoteDependencyData, stdComponent); } else if (span.getName().equals("EventHubs.send")) { remoteDependencyData.setType("Microsoft.EventHub"); String peerAddress = removeAttributeString(attributes, "peer.address"); String destination = removeAttributeString(attributes, "message_bus.destination"); remoteDependencyData.setTarget(peerAddress + "/" + destination); } else if (span.getName().equals("EventHubs.message")) { String peerAddress = removeAttributeString(attributes, "peer.address"); String destination = removeAttributeString(attributes, "message_bus.destination"); if (peerAddress != null) { remoteDependencyData.setTarget(peerAddress + "/" + destination); } remoteDependencyData.setType("Microsoft.EventHub"); } else if ("kafka-clients".equals(stdComponent)) { remoteDependencyData.setType("Kafka"); remoteDependencyData.setTarget(span.getName()); } else if ("jms".equals(stdComponent)) { remoteDependencyData.setType("JMS"); remoteDependencyData.setTarget(span.getName()); } } remoteDependencyData.setId(span.getSpanId().toLowerBase16()); telemetryItem.getTags().put(ContextTagKeys.AI_OPERATION_ID.toString(), span.getTraceId().toLowerBase16()); SpanId parentSpanId = span.getParentSpanId(); if (parentSpanId.isValid()) { telemetryItem.getTags().put(ContextTagKeys.AI_OPERATION_PARENT_ID.toString(), parentSpanId.toLowerBase16()); } telemetryItem.setTime(getFormattedTime(span.getStartEpochNanos())); remoteDependencyData.setDuration(getFormattedDuration(Duration.ofNanos(span.getEndEpochNanos() - span.getStartEpochNanos()))); remoteDependencyData.setSuccess(span.getStatus().isOk()); String description = span.getStatus().getDescription(); if (description != null) { remoteDependencyData.getProperties().put("statusDescription", description); } Double samplingPercentage = removeAiSamplingPercentage(attributes); if (stdComponent == null) { addExtraAttributes(remoteDependencyData.getProperties(), attributes); } telemetryItem.setSampleRate(samplingPercentage.floatValue()); telemetryItems.add(telemetryItem); exportEvents(span, samplingPercentage, telemetryItems); } private void applyDatabaseQuerySpan(Map<String, AttributeValue> attributes, RemoteDependencyData rd, String component) { String type = removeAttributeString(attributes, SemanticAttributes.DB_SYSTEM.key()); if (SQL_DB_SYSTEMS.contains(type)) { type = "SQL"; } rd.setType(type); rd.setData(removeAttributeString(attributes, SemanticAttributes.DB_STATEMENT.key())); String dbUrl = removeAttributeString(attributes, SemanticAttributes.DB_CONNECTION_STRING.key()); if (dbUrl == null) { rd.setTarget(type); } else { String dbInstance = removeAttributeString(attributes, SemanticAttributes.DB_NAME.key()); if (dbInstance != null) { dbUrl += " | " + dbInstance; } if ("jdbc".equals(component)) { rd.setTarget("jdbc:" + dbUrl); } else { rd.setTarget(dbUrl); } } } private void applyHttpRequestSpan(Map<String, AttributeValue> attributes, RemoteDependencyData remoteDependencyData) { remoteDependencyData.setType("Http (tracked component)"); String method = removeAttributeString(attributes, SemanticAttributes.HTTP_METHOD.key()); String url = removeAttributeString(attributes, SemanticAttributes.HTTP_URL.key()); AttributeValue httpStatusCode = attributes.remove(SemanticAttributes.HTTP_STATUS_CODE.key()); if (httpStatusCode != null && httpStatusCode.getType() == AttributeValue.Type.LONG) { long statusCode = httpStatusCode.getLongValue(); remoteDependencyData.setResultCode(Long.toString(statusCode)); } if (url != null) { try { URI uriObject = new URI(url); String target = createTarget(uriObject); remoteDependencyData.setTarget(target); String path = uriObject.getPath(); if (CoreUtils.isNullOrEmpty(path)) { remoteDependencyData.setName(method + " /"); } else { remoteDependencyData.setName(method + " " + path); } } catch (URISyntaxException e) { logger.error(e.getMessage()); } } } private void exportEvents(SpanData span, Double samplingPercentage, List<TelemetryItem> telemetryItems) { boolean foundException = false; for (SpanData.Event event : span.getEvents()) { TelemetryItem telemetryItem = new TelemetryItem(); TelemetryEventData eventData = new TelemetryEventData(); MonitorBase monitorBase = new MonitorBase(); telemetryItem.setTags(new HashMap<>()); telemetryItem.setName(telemetryItemNamePrefix + "Event"); telemetryItem.setVersion(1); telemetryItem.setInstrumentationKey(instrumentationKey); telemetryItem.setData(monitorBase); eventData.setProperties(new HashMap<>()); eventData.setVersion(2); monitorBase.setBaseType("EventData"); monitorBase.setBaseData(eventData); eventData.setName(event.getName()); String operationId = span.getTraceId().toLowerBase16(); telemetryItem.getTags().put(ContextTagKeys.AI_OPERATION_ID.toString(), operationId); telemetryItem.getTags().put(ContextTagKeys.AI_OPERATION_PARENT_ID.toString(), span.getParentSpanId().toLowerBase16()); telemetryItem.setTime(getFormattedTime(event.getEpochNanos())); addExtraAttributes(eventData.getProperties(), event.getAttributes()); if (event.getAttributes().get(SemanticAttributes.EXCEPTION_TYPE.key()) != null || event.getAttributes().get(SemanticAttributes.EXCEPTION_MESSAGE.key()) != null) { if (!foundException) { AttributeValue stacktrace = event.getAttributes().get(SemanticAttributes.EXCEPTION_STACKTRACE.key()); if (stacktrace != null) { trackException(stacktrace.getStringValue(), span, operationId, span.getSpanId().toLowerBase16(), samplingPercentage, telemetryItems); } } foundException = true; } else { telemetryItem.setSampleRate(samplingPercentage.floatValue()); telemetryItems.add(telemetryItem); } } } private void trackException(String errorStack, SpanData span, String operationId, String id, Double samplingPercentage, List<TelemetryItem> telemetryItems) { TelemetryItem telemetryItem = new TelemetryItem(); TelemetryExceptionData exceptionData = new TelemetryExceptionData(); MonitorBase monitorBase = new MonitorBase(); telemetryItem.setTags(new HashMap<>()); telemetryItem.setName(telemetryItemNamePrefix + "Exception"); telemetryItem.setVersion(1); telemetryItem.setInstrumentationKey(instrumentationKey); telemetryItem.setData(monitorBase); exceptionData.setProperties(new HashMap<>()); exceptionData.setVersion(2); monitorBase.setBaseType("ExceptionData"); monitorBase.setBaseData(exceptionData); telemetryItem.getTags().put(ContextTagKeys.AI_OPERATION_ID.toString(), operationId); telemetryItem.getTags().put(ContextTagKeys.AI_OPERATION_PARENT_ID.toString(), id); telemetryItem.setTime(getFormattedTime(span.getEndEpochNanos())); telemetryItem.setSampleRate(samplingPercentage.floatValue()); exceptionData.setExceptions(minimalParse(errorStack)); telemetryItems.add(telemetryItem); } private static String getFormattedDuration(Duration duration) { return duration.toDays() + "." + duration.toHours() + ":" + duration.toMinutes() + ":" + duration.getSeconds() + "." + duration.toMillis(); } private static String getFormattedTime(long epochNanos) { return Instant.ofEpochMilli(NANOSECONDS.toMillis(epochNanos)) .atOffset(ZoneOffset.UTC) .format(DateTimeFormatter.ISO_DATE_TIME); } private boolean isNonNullLong(AttributeValue attributeValue) { return attributeValue != null && attributeValue.getType() == AttributeValue.Type.LONG; } private Map<String, AttributeValue> getAttributesCopy(ReadableAttributes attributes) { final Map<String, AttributeValue> copy = new HashMap<>(); attributes.forEach(new ReadableKeyValuePairs.KeyValueConsumer<AttributeValue>() { @Override public void consume(String key, AttributeValue value) { copy.put(key, value); } }); return copy; } private static void addLinks(Map<String, String> properties, List<SpanData.Link> links) { if (links.isEmpty()) { return; } StringBuilder sb = new StringBuilder(); sb.append("["); boolean first = true; for (SpanData.Link link : links) { if (!first) { sb.append(","); } sb.append("{\"operation_Id\":\""); sb.append(link.getContext().getTraceId().toLowerBase16()); sb.append("\",\"id\":\""); sb.append(link.getContext().getSpanId().toLowerBase16()); sb.append("\"}"); first = false; } sb.append("]"); properties.put("_MS.links", sb.toString()); } private static String removeAttributeString(Map<String, AttributeValue> attributes, String attributeName) { AttributeValue attributeValue = attributes.remove(attributeName); if (attributeValue == null) { return null; } else if (attributeValue.getType() == AttributeValue.Type.STRING) { return attributeValue.getStringValue(); } else { return null; } } private static Double removeAttributeDouble(Map<String, AttributeValue> attributes, String attributeName) { AttributeValue attributeValue = attributes.remove(attributeName); if (attributeValue == null) { return null; } else if (attributeValue.getType() == AttributeValue.Type.DOUBLE) { return attributeValue.getDoubleValue(); } else { return null; } } private static String createTarget(URI uriObject) { String target = uriObject.getHost(); if (uriObject.getPort() != 80 && uriObject.getPort() != 443 && uriObject.getPort() != -1) { target += ":" + uriObject.getPort(); } return target; } private static String getStringValue(AttributeValue value) { switch (value.getType()) { case STRING: return value.getStringValue(); case BOOLEAN: return Boolean.toString(value.getBooleanValue()); case LONG: return Long.toString(value.getLongValue()); case DOUBLE: return Double.toString(value.getDoubleValue()); case STRING_ARRAY: return join(value.getStringArrayValue()); case BOOLEAN_ARRAY: return join(value.getBooleanArrayValue()); case LONG_ARRAY: return join(value.getLongArrayValue()); case DOUBLE_ARRAY: return join(value.getDoubleArrayValue()); default: return null; } } private static <T> String join(List<T> values) { StringBuilder sb = new StringBuilder(); if (CoreUtils.isNullOrEmpty(values)) { return sb.toString(); } for (int i = 0; i < values.size() - 1; i++) { sb.append(values.get(i)); sb.append(", "); } sb.append(values.get(values.size() - 1)); return sb.toString(); } private static SeverityLevel toSeverityLevel(String level) { if (level == null) { return null; } switch (level) { case "FATAL": return SeverityLevel.CRITICAL; case "ERROR": case "SEVERE": return SeverityLevel.ERROR; case "WARN": case "WARNING": return SeverityLevel.WARNING; case "INFO": return SeverityLevel.INFORMATION; case "DEBUG": case "TRACE": case "CONFIG": case "FINE": case "FINER": case "FINEST": case "ALL": return SeverityLevel.VERBOSE; default: return SeverityLevel.VERBOSE; } } private static Double removeAiSamplingPercentage(Map<String, AttributeValue> attributes) { return removeAttributeDouble(attributes, "ai.sampling.percentage"); } private static void addExtraAttributes(Map<String, String> properties, Map<String, AttributeValue> attributes) { for (Map.Entry<String, AttributeValue> entry : attributes.entrySet()) { String value = getStringValue(entry.getValue()); if (value != null) { properties.put(entry.getKey(), value); } } } private static void addExtraAttributes(final Map<String, String> properties, Attributes attributes) { attributes.forEach(new ReadableKeyValuePairs.KeyValueConsumer<AttributeValue>() { @Override public void consume(String key, AttributeValue value) { String val = getStringValue(value); if (val != null) { properties.put(key, val); } } }); } }
class AzureMonitorExporter implements SpanExporter { private static final Pattern COMPONENT_PATTERN = Pattern .compile("io\\.opentelemetry\\.auto\\.([^0-9]*)(-[0-9.]*)?"); private static final Set<String> SQL_DB_SYSTEMS; static { Set<String> dbSystems = new HashSet<>(); dbSystems.add("db2"); dbSystems.add("derby"); dbSystems.add("mariadb"); dbSystems.add("mssql"); dbSystems.add("mysql"); dbSystems.add("oracle"); dbSystems.add("postgresql"); dbSystems.add("sqlite"); dbSystems.add("other_sql"); dbSystems.add("hsqldb"); dbSystems.add("h2"); SQL_DB_SYSTEMS = Collections.unmodifiableSet(dbSystems); } private final MonitorExporterClient client; private final ClientLogger logger = new ClientLogger(AzureMonitorExporter.class); private final String instrumentationKey; private final String telemetryItemNamePrefix; /** * Creates an instance of exporter that is configured with given exporter client that sends telemetry events to * Application Insights resource identified by the instrumentation key. * * @param client The client used to send data to Azure Monitor. * @param instrumentationKey The instrumentation key of Application Insights resource. */ AzureMonitorExporter(MonitorExporterClient client, String instrumentationKey) { this.client = client; this.instrumentationKey = instrumentationKey; String formattedInstrumentationKey = instrumentationKey.replaceAll("-", ""); this.telemetryItemNamePrefix = "Microsoft.ApplicationInsights." + formattedInstrumentationKey + "."; } /** * {@inheritDoc} */ @Override public CompletableResultCode export(Collection<SpanData> spans) { try { List<TelemetryItem> telemetryItems = new ArrayList<>(); for (SpanData span : spans) { logger.verbose("exporting span: {}", span); export(span, telemetryItems); } client.export(telemetryItems); return CompletableResultCode.ofSuccess(); } catch (Throwable t) { logger.error(t.getMessage(), t); return CompletableResultCode.ofFailure(); } } /** * {@inheritDoc} */ @Override public CompletableResultCode flush() { return CompletableResultCode.ofSuccess(); } /** * {@inheritDoc} */ @Override public CompletableResultCode shutdown() { return CompletableResultCode.ofSuccess(); } private void export(SpanData span, List<TelemetryItem> telemetryItems) { Span.Kind kind = span.getKind(); String instrumentationName = span.getInstrumentationLibraryInfo().getName(); Matcher matcher = COMPONENT_PATTERN.matcher(instrumentationName); String stdComponent = matcher.matches() ? matcher.group(1) : null; if ("jms".equals(stdComponent) && !span.getParentSpanId().isValid() && kind == Span.Kind.CLIENT) { return; } if (kind == Span.Kind.INTERNAL) { if (!span.getParentSpanId().isValid()) { exportRequest(stdComponent, span, telemetryItems); } else if (span.getName().equals("EventHubs.message")) { exportRemoteDependency(stdComponent, span, false, telemetryItems); } else { exportRemoteDependency(stdComponent, span, true, telemetryItems); } } else if (kind == Span.Kind.CLIENT || kind == Span.Kind.PRODUCER) { exportRemoteDependency(stdComponent, span, false, telemetryItems); } else if (kind == Span.Kind.SERVER || kind == Span.Kind.CONSUMER) { exportRequest(stdComponent, span, telemetryItems); } else { throw new UnsupportedOperationException(kind.name()); } } private static void setProperties(Map<String, String> properties, long timeEpochNanos, String level, String loggerName, Map<String, AttributeValue> attributes) { if (level != null) { properties.put("SourceType", "Logger"); properties.put("LoggingLevel", level); } if (loggerName != null) { properties.put("LoggerName", loggerName); } if (attributes != null) { for (Map.Entry<String, AttributeValue> entry : attributes.entrySet()) { AttributeValue av = entry.getValue(); String stringValue = null; switch (av.getType()) { case STRING: stringValue = av.getStringValue(); break; case BOOLEAN: stringValue = String.valueOf(av.getBooleanValue()); break; case LONG: stringValue = String.valueOf(av.getLongValue()); break; case DOUBLE: stringValue = String.valueOf(av.getDoubleValue()); break; case STRING_ARRAY: stringValue = String.valueOf(av.getStringArrayValue()); break; case BOOLEAN_ARRAY: stringValue = String.valueOf(av.getBooleanArrayValue()); break; case LONG_ARRAY: stringValue = String.valueOf(av.getLongArrayValue()); break; case DOUBLE_ARRAY: stringValue = String.valueOf(av.getDoubleArrayValue()); break; } if (stringValue != null) { properties.put(entry.getKey(), stringValue); } } } } private static List<TelemetryExceptionDetails> minimalParse(String errorStack) { TelemetryExceptionDetails details = new TelemetryExceptionDetails(); String line = errorStack.split("\n")[0]; int index = line.indexOf(": "); if (index != -1) { details.setTypeName(line.substring(0, index)); details.setMessage(line.substring(index + 2)); } else { details.setTypeName(line); } details.setStack(errorStack); return Arrays.asList(details); } private void exportRemoteDependency(String stdComponent, SpanData span, boolean inProc, List<TelemetryItem> telemetryItems) { TelemetryItem telemetryItem = new TelemetryItem(); RemoteDependencyData remoteDependencyData = new RemoteDependencyData(); MonitorBase monitorBase = new MonitorBase(); telemetryItem.setTags(new HashMap<>()); telemetryItem.setName(telemetryItemNamePrefix + "RemoteDependency"); telemetryItem.setVersion(1); telemetryItem.setInstrumentationKey(instrumentationKey); telemetryItem.setData(monitorBase); remoteDependencyData.setProperties(new HashMap<>()); remoteDependencyData.setVersion(2); monitorBase.setBaseType("RemoteDependencyData"); monitorBase.setBaseData(remoteDependencyData); addLinks(remoteDependencyData.getProperties(), span.getLinks()); remoteDependencyData.setName(span.getName()); span.getInstrumentationLibraryInfo().getName(); Map<String, AttributeValue> attributes = getAttributesCopy(span.getAttributes()); if (inProc) { remoteDependencyData.setType("InProc"); } else { if (attributes.containsKey("http.method")) { applyHttpRequestSpan(attributes, remoteDependencyData); } else if (attributes.containsKey(SemanticAttributes.DB_SYSTEM.key())) { applyDatabaseQuerySpan(attributes, remoteDependencyData, stdComponent); } else if (span.getName().equals("EventHubs.send")) { remoteDependencyData.setType("Microsoft.EventHub"); String peerAddress = removeAttributeString(attributes, "peer.address"); String destination = removeAttributeString(attributes, "message_bus.destination"); remoteDependencyData.setTarget(peerAddress + "/" + destination); } else if (span.getName().equals("EventHubs.message")) { String peerAddress = removeAttributeString(attributes, "peer.address"); String destination = removeAttributeString(attributes, "message_bus.destination"); if (peerAddress != null) { remoteDependencyData.setTarget(peerAddress + "/" + destination); } remoteDependencyData.setType("Microsoft.EventHub"); } else if ("kafka-clients".equals(stdComponent)) { remoteDependencyData.setType("Kafka"); remoteDependencyData.setTarget(span.getName()); } else if ("jms".equals(stdComponent)) { remoteDependencyData.setType("JMS"); remoteDependencyData.setTarget(span.getName()); } } remoteDependencyData.setId(span.getSpanId().toLowerBase16()); telemetryItem.getTags().put(ContextTagKeys.AI_OPERATION_ID.toString(), span.getTraceId().toLowerBase16()); SpanId parentSpanId = span.getParentSpanId(); if (parentSpanId.isValid()) { telemetryItem.getTags().put(ContextTagKeys.AI_OPERATION_PARENT_ID.toString(), parentSpanId.toLowerBase16()); } telemetryItem.setTime(getFormattedTime(span.getStartEpochNanos())); remoteDependencyData.setDuration(getFormattedDuration(Duration.ofNanos(span.getEndEpochNanos() - span.getStartEpochNanos()))); remoteDependencyData.setSuccess(span.getStatus().isOk()); String description = span.getStatus().getDescription(); if (description != null) { remoteDependencyData.getProperties().put("statusDescription", description); } Double samplingPercentage = removeAiSamplingPercentage(attributes); if (stdComponent == null) { addExtraAttributes(remoteDependencyData.getProperties(), attributes); } telemetryItem.setSampleRate(samplingPercentage.floatValue()); telemetryItems.add(telemetryItem); exportEvents(span, samplingPercentage, telemetryItems); } private void applyDatabaseQuerySpan(Map<String, AttributeValue> attributes, RemoteDependencyData rd, String component) { String type = removeAttributeString(attributes, SemanticAttributes.DB_SYSTEM.key()); if (SQL_DB_SYSTEMS.contains(type)) { type = "SQL"; } rd.setType(type); rd.setData(removeAttributeString(attributes, SemanticAttributes.DB_STATEMENT.key())); String dbUrl = removeAttributeString(attributes, SemanticAttributes.DB_CONNECTION_STRING.key()); if (dbUrl == null) { rd.setTarget(type); } else { String dbInstance = removeAttributeString(attributes, SemanticAttributes.DB_NAME.key()); if (dbInstance != null) { dbUrl += " | " + dbInstance; } if ("jdbc".equals(component)) { rd.setTarget("jdbc:" + dbUrl); } else { rd.setTarget(dbUrl); } } } private void applyHttpRequestSpan(Map<String, AttributeValue> attributes, RemoteDependencyData remoteDependencyData) { remoteDependencyData.setType("Http (tracked component)"); String method = removeAttributeString(attributes, SemanticAttributes.HTTP_METHOD.key()); String url = removeAttributeString(attributes, SemanticAttributes.HTTP_URL.key()); AttributeValue httpStatusCode = attributes.remove(SemanticAttributes.HTTP_STATUS_CODE.key()); if (httpStatusCode != null && httpStatusCode.getType() == AttributeValue.Type.LONG) { long statusCode = httpStatusCode.getLongValue(); remoteDependencyData.setResultCode(Long.toString(statusCode)); } if (url != null) { try { URI uriObject = new URI(url); String target = createTarget(uriObject); remoteDependencyData.setTarget(target); String path = uriObject.getPath(); if (CoreUtils.isNullOrEmpty(path)) { remoteDependencyData.setName(method + " /"); } else { remoteDependencyData.setName(method + " " + path); } } catch (URISyntaxException e) { logger.error(e.getMessage()); } } } private void exportEvents(SpanData span, Double samplingPercentage, List<TelemetryItem> telemetryItems) { boolean foundException = false; for (SpanData.Event event : span.getEvents()) { TelemetryItem telemetryItem = new TelemetryItem(); TelemetryEventData eventData = new TelemetryEventData(); MonitorBase monitorBase = new MonitorBase(); telemetryItem.setTags(new HashMap<>()); telemetryItem.setName(telemetryItemNamePrefix + "Event"); telemetryItem.setVersion(1); telemetryItem.setInstrumentationKey(instrumentationKey); telemetryItem.setData(monitorBase); eventData.setProperties(new HashMap<>()); eventData.setVersion(2); monitorBase.setBaseType("EventData"); monitorBase.setBaseData(eventData); eventData.setName(event.getName()); String operationId = span.getTraceId().toLowerBase16(); telemetryItem.getTags().put(ContextTagKeys.AI_OPERATION_ID.toString(), operationId); telemetryItem.getTags().put(ContextTagKeys.AI_OPERATION_PARENT_ID.toString(), span.getParentSpanId().toLowerBase16()); telemetryItem.setTime(getFormattedTime(event.getEpochNanos())); addExtraAttributes(eventData.getProperties(), event.getAttributes()); if (event.getAttributes().get(SemanticAttributes.EXCEPTION_TYPE.key()) != null || event.getAttributes().get(SemanticAttributes.EXCEPTION_MESSAGE.key()) != null) { if (!foundException) { AttributeValue stacktrace = event.getAttributes().get(SemanticAttributes.EXCEPTION_STACKTRACE.key()); if (stacktrace != null) { trackException(stacktrace.getStringValue(), span, operationId, span.getSpanId().toLowerBase16(), samplingPercentage, telemetryItems); } } foundException = true; } else { telemetryItem.setSampleRate(samplingPercentage.floatValue()); telemetryItems.add(telemetryItem); } } } private void trackException(String errorStack, SpanData span, String operationId, String id, Double samplingPercentage, List<TelemetryItem> telemetryItems) { TelemetryItem telemetryItem = new TelemetryItem(); TelemetryExceptionData exceptionData = new TelemetryExceptionData(); MonitorBase monitorBase = new MonitorBase(); telemetryItem.setTags(new HashMap<>()); telemetryItem.setName(telemetryItemNamePrefix + "Exception"); telemetryItem.setVersion(1); telemetryItem.setInstrumentationKey(instrumentationKey); telemetryItem.setData(monitorBase); exceptionData.setProperties(new HashMap<>()); exceptionData.setVersion(2); monitorBase.setBaseType("ExceptionData"); monitorBase.setBaseData(exceptionData); telemetryItem.getTags().put(ContextTagKeys.AI_OPERATION_ID.toString(), operationId); telemetryItem.getTags().put(ContextTagKeys.AI_OPERATION_PARENT_ID.toString(), id); telemetryItem.setTime(getFormattedTime(span.getEndEpochNanos())); telemetryItem.setSampleRate(samplingPercentage.floatValue()); exceptionData.setExceptions(minimalParse(errorStack)); telemetryItems.add(telemetryItem); } private static String getFormattedDuration(Duration duration) { return duration.toDays() + "." + duration.toHours() + ":" + duration.toMinutes() + ":" + duration.getSeconds() + "." + duration.toMillis(); } private static String getFormattedTime(long epochNanos) { return Instant.ofEpochMilli(NANOSECONDS.toMillis(epochNanos)) .atOffset(ZoneOffset.UTC) .format(DateTimeFormatter.ISO_DATE_TIME); } private boolean isNonNullLong(AttributeValue attributeValue) { return attributeValue != null && attributeValue.getType() == AttributeValue.Type.LONG; } private Map<String, AttributeValue> getAttributesCopy(ReadableAttributes attributes) { final Map<String, AttributeValue> copy = new HashMap<>(); attributes.forEach(new ReadableKeyValuePairs.KeyValueConsumer<AttributeValue>() { @Override public void consume(String key, AttributeValue value) { copy.put(key, value); } }); return copy; } private static void addLinks(Map<String, String> properties, List<SpanData.Link> links) { if (links.isEmpty()) { return; } StringBuilder sb = new StringBuilder(); sb.append("["); boolean first = true; for (SpanData.Link link : links) { if (!first) { sb.append(","); } sb.append("{\"operation_Id\":\""); sb.append(link.getContext().getTraceId().toLowerBase16()); sb.append("\",\"id\":\""); sb.append(link.getContext().getSpanId().toLowerBase16()); sb.append("\"}"); first = false; } sb.append("]"); properties.put("_MS.links", sb.toString()); } private static String removeAttributeString(Map<String, AttributeValue> attributes, String attributeName) { AttributeValue attributeValue = attributes.remove(attributeName); if (attributeValue == null) { return null; } else if (attributeValue.getType() == AttributeValue.Type.STRING) { return attributeValue.getStringValue(); } else { return null; } } private static Double removeAttributeDouble(Map<String, AttributeValue> attributes, String attributeName) { AttributeValue attributeValue = attributes.remove(attributeName); if (attributeValue == null) { return null; } else if (attributeValue.getType() == AttributeValue.Type.DOUBLE) { return attributeValue.getDoubleValue(); } else { return null; } } private static String createTarget(URI uriObject) { String target = uriObject.getHost(); if (uriObject.getPort() != 80 && uriObject.getPort() != 443 && uriObject.getPort() != -1) { target += ":" + uriObject.getPort(); } return target; } private static String getStringValue(AttributeValue value) { switch (value.getType()) { case STRING: return value.getStringValue(); case BOOLEAN: return Boolean.toString(value.getBooleanValue()); case LONG: return Long.toString(value.getLongValue()); case DOUBLE: return Double.toString(value.getDoubleValue()); case STRING_ARRAY: return join(value.getStringArrayValue()); case BOOLEAN_ARRAY: return join(value.getBooleanArrayValue()); case LONG_ARRAY: return join(value.getLongArrayValue()); case DOUBLE_ARRAY: return join(value.getDoubleArrayValue()); default: return null; } } private static <T> String join(List<T> values) { StringBuilder sb = new StringBuilder(); if (CoreUtils.isNullOrEmpty(values)) { return sb.toString(); } for (int i = 0; i < values.size() - 1; i++) { sb.append(values.get(i)); sb.append(", "); } sb.append(values.get(values.size() - 1)); return sb.toString(); } private static Double removeAiSamplingPercentage(Map<String, AttributeValue> attributes) { return removeAttributeDouble(attributes, "ai.sampling.percentage"); } private static void addExtraAttributes(Map<String, String> properties, Map<String, AttributeValue> attributes) { for (Map.Entry<String, AttributeValue> entry : attributes.entrySet()) { String value = getStringValue(entry.getValue()); if (value != null) { properties.put(entry.getKey(), value); } } } private static void addExtraAttributes(final Map<String, String> properties, Attributes attributes) { attributes.forEach(new ReadableKeyValuePairs.KeyValueConsumer<AttributeValue>() { @Override public void consume(String key, AttributeValue value) { String val = getStringValue(value); if (val != null) { properties.put(key, val); } } }); } }
I think retry attempts could be a KVP in this. we often want to understand how many attempts were tried.
public void onError(Throwable throwable) { Objects.requireNonNull(throwable, "'throwable' is required."); if (isRetryPending.get() && retryPolicy.calculateRetryDelay(throwable, retryAttempts.get()) != null) { logger.warning("Retry is already pending. Ignoring transient error.", throwable); return; } final int attemptsMade = retryAttempts.incrementAndGet(); final int attempts; final Duration retryInterval; if (((throwable instanceof AmqpException) && ((AmqpException) throwable).isTransient()) || (throwable instanceof IllegalStateException) || (throwable instanceof RejectedExecutionException)) { attempts = Math.min(attemptsMade, retryPolicy.getMaxRetries()); final Throwable throwableToUse = throwable instanceof AmqpException ? throwable : new AmqpException(true, "Non-AmqpException occurred upstream.", throwable, errorContext); retryInterval = retryPolicy.calculateRetryDelay(throwableToUse, attempts); } else { attempts = attemptsMade; retryInterval = retryPolicy.calculateRetryDelay(throwable, attempts); } if (retryInterval != null) { if (isRetryPending.getAndSet(true)) { retryAttempts.decrementAndGet(); return; } logger.info("Retry retrySubscription = Mono.delay(retryInterval).subscribe(i -> { if (isDisposed()) { logger.info("Retry } else { logger.info("Retry requestUpstream(); isRetryPending.set(false); } }); } else { logger.warning("Retry lastError = throwable; isDisposed.set(true); dispose(); synchronized (lock) { final ConcurrentLinkedDeque<ChannelSubscriber<T>> currentSubscribers = subscribers; subscribers = new ConcurrentLinkedDeque<>(); logger.info("Error in AMQP channel processor. Notifying {} subscribers.", currentSubscribers.size()); currentSubscribers.forEach(subscriber -> subscriber.onError(throwable)); } } }
logger.info("Retry
public void onError(Throwable throwable) { Objects.requireNonNull(throwable, "'throwable' is required."); if (isRetryPending.get() && retryPolicy.calculateRetryDelay(throwable, retryAttempts.get()) != null) { logger.warning("Retry is already pending. Ignoring transient error.", throwable); return; } final int attemptsMade = retryAttempts.incrementAndGet(); final int attempts; final Duration retryInterval; if (((throwable instanceof AmqpException) && ((AmqpException) throwable).isTransient()) || (throwable instanceof IllegalStateException) || (throwable instanceof RejectedExecutionException)) { attempts = Math.min(attemptsMade, retryPolicy.getMaxRetries()); final Throwable throwableToUse = throwable instanceof AmqpException ? throwable : new AmqpException(true, "Non-AmqpException occurred upstream.", throwable, errorContext); retryInterval = retryPolicy.calculateRetryDelay(throwableToUse, attempts); } else { attempts = attemptsMade; retryInterval = retryPolicy.calculateRetryDelay(throwable, attempts); } if (retryInterval != null) { if (isRetryPending.getAndSet(true)) { retryAttempts.decrementAndGet(); return; } logger.atInfo() .addKeyValue(RETRY_NUMBER_KEY, attempts) .addKeyValue(INTERVAL_KEY, retryInterval.toMillis()) .log("Transient error occurred. Retrying.", throwable); retrySubscription = Mono.delay(retryInterval).subscribe(i -> { if (isDisposed()) { logger.atInfo() .addKeyValue(RETRY_NUMBER_KEY, attempts) .log("Not requesting from upstream. Processor is disposed."); } else { logger.atInfo() .addKeyValue(RETRY_NUMBER_KEY, attempts) .log("Requesting from upstream."); requestUpstream(); isRetryPending.set(false); } }); } else { logger.atWarning() .addKeyValue(RETRY_NUMBER_KEY, attempts) .log("Retry attempts exhausted or exception was not retriable.", throwable); lastError = throwable; isDisposed.set(true); dispose(); synchronized (lock) { final ConcurrentLinkedDeque<ChannelSubscriber<T>> currentSubscribers = subscribers; subscribers = new ConcurrentLinkedDeque<>(); logger.info("Error in AMQP channel processor. Notifying {} subscribers.", currentSubscribers.size()); currentSubscribers.forEach(subscriber -> subscriber.onError(throwable)); } } }
class AmqpChannelProcessor<T> extends Mono<T> implements Processor<T, T>, CoreSubscriber<T>, Disposable { @SuppressWarnings("rawtypes") private static final AtomicReferenceFieldUpdater<AmqpChannelProcessor, Subscription> UPSTREAM = AtomicReferenceFieldUpdater.newUpdater(AmqpChannelProcessor.class, Subscription.class, "upstream"); private final ClientLogger logger; private final AtomicBoolean isDisposed = new AtomicBoolean(); private final AtomicBoolean isRequested = new AtomicBoolean(); private final AtomicBoolean isRetryPending = new AtomicBoolean(); private final AtomicInteger retryAttempts = new AtomicInteger(); private final Object lock = new Object(); private final AmqpRetryPolicy retryPolicy; private final Function<T, Flux<AmqpEndpointState>> endpointStatesFunction; private final AmqpErrorContext errorContext; private volatile Subscription upstream; private volatile ConcurrentLinkedDeque<ChannelSubscriber<T>> subscribers = new ConcurrentLinkedDeque<>(); private volatile Throwable lastError; private volatile T currentChannel; private volatile Disposable connectionSubscription; private volatile Disposable retrySubscription; public AmqpChannelProcessor(String fullyQualifiedNamespace, String entityPath, Function<T, Flux<AmqpEndpointState>> endpointStatesFunction, AmqpRetryPolicy retryPolicy, ClientLogger logger) { this.endpointStatesFunction = Objects.requireNonNull(endpointStatesFunction, "'endpointStates' cannot be null."); this.retryPolicy = Objects.requireNonNull(retryPolicy, "'retryPolicy' cannot be null."); /*Map<String, Object> loggingContext = new HashMap<>(); loggingContext.put(FULLY_QUALIFIED_NAMESPACE_KEY, Objects.requireNonNull(fullyQualifiedNamespace, "'fullyQualifiedNamespace' cannot be null.")); loggingContext.put(ENTITY_PATH_KEY, Objects.requireNonNull(entityPath, "'entityPath' cannot be null."));*/ this.logger = Objects.requireNonNull(logger, "'retryPolicy' cannot be null."); this.errorContext = new AmqpErrorContext(fullyQualifiedNamespace); } @Override public void onSubscribe(Subscription subscription) { if (Operators.setOnce(UPSTREAM, this, subscription)) { isRequested.set(true); subscription.request(1); } else { logger.warning("Processors can only be subscribed to once."); } } @Override public void onNext(T amqpChannel) { logger.info("Setting next AMQP channel."); Objects.requireNonNull(amqpChannel, "'amqpChannel' cannot be null."); final T oldChannel; final Disposable oldSubscription; synchronized (lock) { oldChannel = currentChannel; oldSubscription = connectionSubscription; currentChannel = amqpChannel; final ConcurrentLinkedDeque<ChannelSubscriber<T>> currentSubscribers = subscribers; logger.info("Next AMQP channel received, updating {} current subscribers", subscribers.size()); currentSubscribers.forEach(subscription -> subscription.onNext(amqpChannel)); connectionSubscription = endpointStatesFunction.apply(amqpChannel).subscribe( state -> { if (state == AmqpEndpointState.ACTIVE) { retryAttempts.set(0); logger.info("Channel is now active."); } }, error -> { setAndClearChannel(); onError(error); }, () -> { if (isDisposed()) { logger.info("Channel is disposed."); } else { logger.info("Channel is closed. Requesting upstream."); setAndClearChannel(); requestUpstream(); } }); } close(oldChannel); if (oldSubscription != null) { oldSubscription.dispose(); } isRequested.set(false); } /** * When downstream or upstream encounters an error, calculates whether to request another item upstream. * * @param throwable Exception to analyse. */ @Override @Override public void onComplete() { logger.info("Upstream connection publisher was completed. Terminating processor."); isDisposed.set(true); synchronized (lock) { final ConcurrentLinkedDeque<ChannelSubscriber<T>> currentSubscribers = subscribers; subscribers = new ConcurrentLinkedDeque<>(); logger.info("AMQP channel processor completed. Notifying {} subscribers.", currentSubscribers.size()); currentSubscribers.forEach(subscriber -> subscriber.onComplete()); } } @Override public void subscribe(CoreSubscriber<? super T> actual) { if (isDisposed()) { if (lastError != null) { actual.onSubscribe(Operators.emptySubscription()); actual.onError(lastError); } else { Operators.error(actual, logger.logExceptionAsError(new IllegalStateException("Cannot subscribe. Processor is already terminated."))); } return; } final ChannelSubscriber<T> subscriber = new ChannelSubscriber<T>(actual, this); actual.onSubscribe(subscriber); synchronized (lock) { if (currentChannel != null) { subscriber.complete(currentChannel); return; } } subscribers.add(subscriber); logger.atVerbose().addKeyValue("subscribers", subscribers.size()).log("Added a subscriber."); if (!isRetryPending.get()) { requestUpstream(); } } @Override public void dispose() { if (isDisposed.getAndSet(true)) { return; } if (retrySubscription != null && !retrySubscription.isDisposed()) { retrySubscription.dispose(); } onComplete(); synchronized (lock) { setAndClearChannel(); } } @Override public boolean isDisposed() { return isDisposed.get(); } private void requestUpstream() { if (currentChannel != null) { logger.verbose("Connection exists, not requesting another."); return; } else if (isDisposed()) { logger.verbose("Is already disposed."); return; } final Subscription subscription = UPSTREAM.get(this); if (subscription == null) { logger.warning("There is no upstream subscription."); return; } if (!isRequested.getAndSet(true)) { logger.info("Connection not requested, yet. Requesting one."); subscription.request(1); } } private void setAndClearChannel() { T oldChannel; synchronized (lock) { oldChannel = currentChannel; currentChannel = null; } close(oldChannel); } /** * Checks the current state of the channel for this channel and returns true if the channel is null or if this * processor is disposed. * * @return true if the current channel in the processor is null or if the processor is disposed */ public boolean isChannelClosed() { synchronized (lock) { return currentChannel == null || isDisposed(); } } private void close(T channel) { if (channel instanceof AsyncCloseable) { ((AsyncCloseable) channel).closeAsync().subscribe(); } else if (channel instanceof AutoCloseable) { try { ((AutoCloseable) channel).close(); } catch (Exception error) { logger.warning("Error occurred closing AutoCloseable channel.", error); } } else if (channel instanceof Disposable) { try { ((Disposable) channel).dispose(); } catch (Exception error) { logger.warning("Error occurred closing Disposable channel.", error); } } } /** * Represents the decorator-subscriber wrapping a downstream subscriber to AmqpChannelProcessor. * These are the subscribers waiting to receive a channel that is yet to be available in the AmqpChannelProcessor. * The AmqpChannelProcessor tracks a list of such waiting subscribers; once the processor receives * a result (channel, error or disposal) from it's upstream, each decorated-subscriber will be notified, * which removes itself from the tracking list, then propagates the notification to the wrapped subscriber. */ private static final class ChannelSubscriber<T> extends Operators.MonoSubscriber<T, T> { private final AmqpChannelProcessor<T> processor; private ChannelSubscriber(CoreSubscriber<? super T> actual, AmqpChannelProcessor<T> processor) { super(actual); this.processor = processor; } @Override public void cancel() { processor.subscribers.remove(this); super.cancel(); } @Override public void onComplete() { if (!isCancelled()) { processor.subscribers.remove(this); actual.onComplete(); } } @Override public void onNext(T channel) { if (!isCancelled()) { processor.subscribers.remove(this); super.complete(channel); } } @Override public void onError(Throwable throwable) { if (!isCancelled()) { processor.subscribers.remove(this); actual.onError(throwable); } else { Operators.onErrorDropped(throwable, currentContext()); } } } }
class AmqpChannelProcessor<T> extends Mono<T> implements Processor<T, T>, CoreSubscriber<T>, Disposable { @SuppressWarnings("rawtypes") private static final AtomicReferenceFieldUpdater<AmqpChannelProcessor, Subscription> UPSTREAM = AtomicReferenceFieldUpdater.newUpdater(AmqpChannelProcessor.class, Subscription.class, "upstream"); private static final String RETRY_NUMBER_KEY = "retry"; private final ClientLogger logger; private final AtomicBoolean isDisposed = new AtomicBoolean(); private final AtomicBoolean isRequested = new AtomicBoolean(); private final AtomicBoolean isRetryPending = new AtomicBoolean(); private final AtomicInteger retryAttempts = new AtomicInteger(); private final Object lock = new Object(); private final AmqpRetryPolicy retryPolicy; private final Function<T, Flux<AmqpEndpointState>> endpointStatesFunction; private final AmqpErrorContext errorContext; private volatile Subscription upstream; private volatile ConcurrentLinkedDeque<ChannelSubscriber<T>> subscribers = new ConcurrentLinkedDeque<>(); private volatile Throwable lastError; private volatile T currentChannel; private volatile Disposable connectionSubscription; private volatile Disposable retrySubscription; /** * @deprecated Use constructor overload that does not take {@link ClientLogger} */ @Deprecated public AmqpChannelProcessor(String fullyQualifiedNamespace, String entityPath, Function<T, Flux<AmqpEndpointState>> endpointStatesFunction, AmqpRetryPolicy retryPolicy, ClientLogger logger) { this.endpointStatesFunction = Objects.requireNonNull(endpointStatesFunction, "'endpointStates' cannot be null."); this.retryPolicy = Objects.requireNonNull(retryPolicy, "'retryPolicy' cannot be null."); this.logger = Objects.requireNonNull(logger, "'logger' cannot be null."); this.errorContext = new AmqpErrorContext(fullyQualifiedNamespace); } public AmqpChannelProcessor(String fullyQualifiedNamespace, Function<T, Flux<AmqpEndpointState>> endpointStatesFunction, AmqpRetryPolicy retryPolicy, Map<String, Object> loggingContext) { this.endpointStatesFunction = Objects.requireNonNull(endpointStatesFunction, "'endpointStates' cannot be null."); this.retryPolicy = Objects.requireNonNull(retryPolicy, "'retryPolicy' cannot be null."); this.logger = new ClientLogger(getClass(), Objects.requireNonNull(loggingContext, "'loggingContext' cannot be null.")); this.errorContext = new AmqpErrorContext(fullyQualifiedNamespace); } @Override public void onSubscribe(Subscription subscription) { if (Operators.setOnce(UPSTREAM, this, subscription)) { isRequested.set(true); subscription.request(1); } else { logger.warning("Processors can only be subscribed to once."); } } @Override public void onNext(T amqpChannel) { logger.info("Setting next AMQP channel."); Objects.requireNonNull(amqpChannel, "'amqpChannel' cannot be null."); final T oldChannel; final Disposable oldSubscription; synchronized (lock) { oldChannel = currentChannel; oldSubscription = connectionSubscription; currentChannel = amqpChannel; final ConcurrentLinkedDeque<ChannelSubscriber<T>> currentSubscribers = subscribers; logger.info("Next AMQP channel received, updating {} current subscribers", subscribers.size()); currentSubscribers.forEach(subscription -> subscription.onNext(amqpChannel)); connectionSubscription = endpointStatesFunction.apply(amqpChannel).subscribe( state -> { if (state == AmqpEndpointState.ACTIVE) { retryAttempts.set(0); logger.info("Channel is now active."); } }, error -> { setAndClearChannel(); onError(error); }, () -> { if (isDisposed()) { logger.info("Channel is disposed."); } else { logger.info("Channel is closed. Requesting upstream."); setAndClearChannel(); requestUpstream(); } }); } close(oldChannel); if (oldSubscription != null) { oldSubscription.dispose(); } isRequested.set(false); } /** * When downstream or upstream encounters an error, calculates whether to request another item upstream. * * @param throwable Exception to analyse. */ @Override @Override public void onComplete() { logger.info("Upstream connection publisher was completed. Terminating processor."); isDisposed.set(true); synchronized (lock) { final ConcurrentLinkedDeque<ChannelSubscriber<T>> currentSubscribers = subscribers; subscribers = new ConcurrentLinkedDeque<>(); logger.info("AMQP channel processor completed. Notifying {} subscribers.", currentSubscribers.size()); currentSubscribers.forEach(subscriber -> subscriber.onComplete()); } } @Override public void subscribe(CoreSubscriber<? super T> actual) { if (isDisposed()) { if (lastError != null) { actual.onSubscribe(Operators.emptySubscription()); actual.onError(lastError); } else { Operators.error(actual, logger.logExceptionAsError(new IllegalStateException("Cannot subscribe. Processor is already terminated."))); } return; } final ChannelSubscriber<T> subscriber = new ChannelSubscriber<T>(actual, this); actual.onSubscribe(subscriber); synchronized (lock) { if (currentChannel != null) { subscriber.complete(currentChannel); return; } } subscribers.add(subscriber); logger.atVerbose().addKeyValue("subscribers", subscribers.size()).log("Added a subscriber."); if (!isRetryPending.get()) { requestUpstream(); } } @Override public void dispose() { if (isDisposed.getAndSet(true)) { return; } if (retrySubscription != null && !retrySubscription.isDisposed()) { retrySubscription.dispose(); } onComplete(); synchronized (lock) { setAndClearChannel(); } } @Override public boolean isDisposed() { return isDisposed.get(); } private void requestUpstream() { if (currentChannel != null) { logger.verbose("Connection exists, not requesting another."); return; } else if (isDisposed()) { logger.verbose("Is already disposed."); return; } final Subscription subscription = UPSTREAM.get(this); if (subscription == null) { logger.warning("There is no upstream subscription."); return; } if (!isRequested.getAndSet(true)) { logger.info("Connection not requested, yet. Requesting one."); subscription.request(1); } } private void setAndClearChannel() { T oldChannel; synchronized (lock) { oldChannel = currentChannel; currentChannel = null; } close(oldChannel); } /** * Checks the current state of the channel for this channel and returns true if the channel is null or if this * processor is disposed. * * @return true if the current channel in the processor is null or if the processor is disposed */ public boolean isChannelClosed() { synchronized (lock) { return currentChannel == null || isDisposed(); } } private void close(T channel) { if (channel instanceof AsyncCloseable) { ((AsyncCloseable) channel).closeAsync().subscribe(); } else if (channel instanceof AutoCloseable) { try { ((AutoCloseable) channel).close(); } catch (Exception error) { logger.warning("Error occurred closing AutoCloseable channel.", error); } } else if (channel instanceof Disposable) { try { ((Disposable) channel).dispose(); } catch (Exception error) { logger.warning("Error occurred closing Disposable channel.", error); } } } /** * Represents the decorator-subscriber wrapping a downstream subscriber to AmqpChannelProcessor. * These are the subscribers waiting to receive a channel that is yet to be available in the AmqpChannelProcessor. * The AmqpChannelProcessor tracks a list of such waiting subscribers; once the processor receives * a result (channel, error or disposal) from it's upstream, each decorated-subscriber will be notified, * which removes itself from the tracking list, then propagates the notification to the wrapped subscriber. */ private static final class ChannelSubscriber<T> extends Operators.MonoSubscriber<T, T> { private final AmqpChannelProcessor<T> processor; private ChannelSubscriber(CoreSubscriber<? super T> actual, AmqpChannelProcessor<T> processor) { super(actual); this.processor = processor; } @Override public void cancel() { processor.subscribers.remove(this); super.cancel(); } @Override public void onComplete() { if (!isCancelled()) { processor.subscribers.remove(this); actual.onComplete(); } } @Override public void onNext(T channel) { if (!isCancelled()) { processor.subscribers.remove(this); super.complete(channel); } } @Override public void onError(Throwable throwable) { if (!isCancelled()) { processor.subscribers.remove(this); actual.onError(throwable); } else { Operators.onErrorDropped(throwable, currentContext()); } } } }
How do we configure the connection policy now?
public void setAllowTelemetry(boolean allowTelemetry) { this.allowTelemetry = allowTelemetry; }
this.allowTelemetry = allowTelemetry;
public void setAllowTelemetry(boolean allowTelemetry) { this.allowTelemetry = allowTelemetry; }
class CosmosProperties { private static final Logger LOGGER = LoggerFactory.getLogger(CosmosProperties.class); /** * Document DB URI. */ @NotEmpty private String uri; /** * Document DB key. */ @NotEmpty private String key; /** * Document DB consistency level. */ private ConsistencyLevel consistencyLevel; /** * Document DB database name. */ @NotEmpty private String database; /** * Populate Diagnostics Strings and Query metrics */ private boolean populateQueryMetrics; /** * Whether allow Microsoft to collect telemetry data. */ private boolean allowTelemetry = true; /** * The credential is used to authorize request. */ private AzureKeyCredential credential; /** * Response Diagnostics processor * Default implementation is to log the response diagnostics string */ private ResponseDiagnosticsProcessor responseDiagnosticsProcessor = responseDiagnostics -> { if (populateQueryMetrics) { LOGGER.info("Response Diagnostics {}", responseDiagnostics); } }; public String getUri() { return uri; } public void setUri(String uri) { this.uri = uri; } public String getKey() { return key; } public void setKey(String key) { this.key = key; } public String getDatabase() { return database; } public void setDatabase(String databaseName) { this.database = databaseName; } public ConsistencyLevel getConsistencyLevel() { return consistencyLevel; } public void setConsistencyLevel(ConsistencyLevel consistencyLevel) { this.consistencyLevel = consistencyLevel; } public boolean isAllowTelemetry() { return allowTelemetry; } public boolean isPopulateQueryMetrics() { return populateQueryMetrics; } public void setPopulateQueryMetrics(boolean populateQueryMetrics) { this.populateQueryMetrics = populateQueryMetrics; } public ResponseDiagnosticsProcessor getResponseDiagnosticsProcessor() { return responseDiagnosticsProcessor; } public void setResponseDiagnosticsProcessor(ResponseDiagnosticsProcessor responseDiagnosticsProcessor) { this.responseDiagnosticsProcessor = responseDiagnosticsProcessor; } public AzureKeyCredential getCredential() { return credential; } public void setCredential(AzureKeyCredential credential) { this.credential = credential; } }
class CosmosProperties { private static final Logger LOGGER = LoggerFactory.getLogger(CosmosProperties.class); /** * Document DB URI. */ @NotEmpty private String uri; /** * Document DB key. */ @NotEmpty private String key; /** * Document DB consistency level. */ private ConsistencyLevel consistencyLevel; /** * Document DB database name. */ @NotEmpty private String database; /** * Populate Diagnostics Strings and Query metrics */ private boolean populateQueryMetrics; /** * Whether allow Microsoft to collect telemetry data. */ private boolean allowTelemetry = true; /** * Represents the connection mode to be used by the client in the Azure Cosmos DB database service. */ private ConnectionMode connectionMode; /** * Response Diagnostics processor * Default implementation is to log the response diagnostics string */ private ResponseDiagnosticsProcessor responseDiagnosticsProcessor = responseDiagnostics -> { if (populateQueryMetrics) { LOGGER.info("Response Diagnostics {}", responseDiagnostics); } }; public String getUri() { return uri; } public void setUri(String uri) { this.uri = uri; } public String getKey() { return key; } public void setKey(String key) { this.key = key; } public String getDatabase() { return database; } public void setDatabase(String databaseName) { this.database = databaseName; } public ConsistencyLevel getConsistencyLevel() { return consistencyLevel; } public void setConsistencyLevel(ConsistencyLevel consistencyLevel) { this.consistencyLevel = consistencyLevel; } public boolean isAllowTelemetry() { return allowTelemetry; } public boolean isPopulateQueryMetrics() { return populateQueryMetrics; } public void setPopulateQueryMetrics(boolean populateQueryMetrics) { this.populateQueryMetrics = populateQueryMetrics; } public ResponseDiagnosticsProcessor getResponseDiagnosticsProcessor() { return responseDiagnosticsProcessor; } public void setResponseDiagnosticsProcessor(ResponseDiagnosticsProcessor responseDiagnosticsProcessor) { this.responseDiagnosticsProcessor = responseDiagnosticsProcessor; } public ConnectionMode getConnectionMode() { return connectionMode; } public void setConnectionMode(ConnectionMode connectionMode) { this.connectionMode = connectionMode; } }
randomResourceName in samples is quite a mess. Maybe not now, but need to find a better way.
public static boolean runSample(AzureResourceManager azureResourceManager, String clientId) throws IOException, KeyStoreException, CertificateException, NoSuchAlgorithmException { final String rgName = azureResourceManager.resourceGroups().manager().sdkContext().randomResourceName("rg", 24); final String serviceName = azureResourceManager.resourceGroups().manager().sdkContext().randomResourceName("service", 24); final Region region = Region.US_EAST; final String domainName = azureResourceManager.resourceGroups().manager().sdkContext().randomResourceName("jsdkdemo-", 20) + ".com"; final String certOrderName = azureResourceManager.resourceGroups().manager().sdkContext().randomResourceName("cert", 15); final String vaultName = azureResourceManager.resourceGroups().manager().sdkContext().randomResourceName("vault", 15); final String certName = azureResourceManager.resourceGroups().manager().sdkContext().randomResourceName("cert", 15); try { azureResourceManager.resourceGroups().define(rgName) .withRegion(region) .create(); System.out.printf("Creating spring cloud service %s in resource group %s ...%n", serviceName, rgName); SpringService service = azureResourceManager.springServices().define(serviceName) .withRegion(region) .withExistingResourceGroup(rgName) .create(); System.out.printf("Created spring cloud service %s%n", service.name()); Utils.print(service); File gzFile = new File("piggymetrics.tar.gz"); if (!gzFile.exists()) { HttpURLConnection connection = (HttpURLConnection) new URL(PIGGYMETRICS_TAR_GZ_URL).openConnection(); connection.connect(); try (InputStream inputStream = connection.getInputStream(); OutputStream outputStream = new FileOutputStream(gzFile)) { IOUtils.copy(inputStream, outputStream); } connection.disconnect(); } System.out.printf("Creating spring cloud app gateway in resource group %s ...%n", rgName); SpringApp gateway = service.apps().define("gateway") .defineActiveDeployment("default") .withSourceCodeTarGzFile(gzFile) .withTargetModule("gateway") .attach() .withDefaultPublicEndpoint() .withHttpsOnly() .create(); System.out.println("Created spring cloud service gateway"); Utils.print(gateway); System.out.printf("Creating spring cloud app auth-service in resource group %s ...%n", rgName); SpringApp authService = service.apps().define("auth-service") .defineActiveDeployment("default") .withSourceCodeTarGzFile(gzFile) .withTargetModule("auth-service") .attach() .create(); System.out.println("Created spring cloud service auth-service"); Utils.print(authService); System.out.printf("Creating spring cloud app account-service in resource group %s ...%n", rgName); SpringApp accountService = service.apps().define("account-service") .defineActiveDeployment("default") .withSourceCodeTarGzFile(gzFile) .withTargetModule("account-service") .attach() .create(); System.out.println("Created spring cloud service account-service"); Utils.print(accountService); System.out.println("Purchasing a domain " + domainName + "..."); AppServiceDomain domain = azureResourceManager.appServiceDomains().define(domainName) .withExistingResourceGroup(rgName) .defineRegistrantContact() .withFirstName("Jon") .withLastName("Doe") .withEmail("jondoe@contoso.com") .withAddressLine1("123 4th Ave") .withCity("Redmond") .withStateOrProvince("WA") .withCountry(CountryIsoCode.UNITED_STATES) .withPostalCode("98052") .withPhoneCountryCode(CountryPhoneCode.UNITED_STATES) .withPhoneNumber("4258828080") .attach() .withDomainPrivacyEnabled(true) .withAutoRenewEnabled(false) .create(); System.out.println("Purchased domain " + domain.name()); Utils.print(domain); DnsZone dnsZone = azureResourceManager.dnsZones().getById(domain.dnsZoneId()); gateway.refresh(); System.out.printf("Updating dns with CNAME ssl.%s to %s%n", domainName, gateway.fqdn()); dnsZone.update() .withCNameRecordSet("ssl", gateway.fqdn()) .apply(); System.out.printf("Purchasing a certificate for *.%s and save to %s in key vault named %s ...%n", domainName, certOrderName, vaultName); AppServiceCertificateOrder certificateOrder = azureResourceManager.appServiceCertificateOrders().define(certOrderName) .withExistingResourceGroup(rgName) .withHostName(String.format("*.%s", domainName)) .withWildcardSku() .withDomainVerification(domain) .withNewKeyVault(vaultName, region) .withAutoRenew(true) .create(); System.out.printf("Purchased certificate: *.%s ...%n", domain.name()); Utils.print(certificateOrder); System.out.printf("Updating key vault %s with access from %s, %s%n", vaultName, clientId, SPRING_CLOUD_SERVICE_PRINCIPAL); Vault vault = azureResourceManager.vaults().getByResourceGroup(rgName, vaultName); vault.update() .defineAccessPolicy() .forServicePrincipal(clientId) .allowSecretAllPermissions() .allowCertificateAllPermissions() .attach() .defineAccessPolicy() .forServicePrincipal(SPRING_CLOUD_SERVICE_PRINCIPAL) .allowCertificatePermissions(CertificatePermissions.GET, CertificatePermissions.LIST) .allowSecretPermissions(SecretPermissions.GET, SecretPermissions.LIST) .attach() .apply(); System.out.printf("Updated key vault %s%n", vault.name()); Utils.print(vault); Secret secret = vault.secrets().getByName(certOrderName); byte[] certificate = Base64.getDecoder().decode(secret.value()); String thumbprint = secret.tags().get("Thumbprint"); if (thumbprint == null || thumbprint.isEmpty()) { KeyStore store = KeyStore.getInstance("PKCS12"); store.load(new ByteArrayInputStream(certificate), null); String alias = Collections.list(store.aliases()).get(0); thumbprint = DatatypeConverter.printHexBinary(MessageDigest.getInstance("SHA-1").digest(store.getCertificate(alias).getEncoded())); } System.out.printf("Get certificate: %s%n", secret.value()); System.out.printf("Certificate Thumbprint: %s%n", thumbprint); CertificateClient certificateClient = new CertificateClientBuilder() .vaultUrl(vault.vaultUri()) .pipeline(service.manager().httpPipeline()) .buildClient(); System.out.printf("Uploading certificate to %s in key vault ...%n", certName); certificateClient.importCertificate( new ImportCertificateOptions(certName, certificate) .setEnabled(true) ); System.out.println("Updating Spring Cloud Service with certificate ..."); service.update() .withCertificate(certName, vault.vaultUri(), certName) .apply(); System.out.printf("Updating Spring Cloud App with domain ssl.%s ...%n", domainName); gateway.update() .withCustomDomain(String.format("ssl.%s", domainName), thumbprint) .apply(); System.out.printf("Successfully expose domain ssl.%s%n", domainName); return true; } finally { try { System.out.println("Delete Resource Group: " + rgName); azureResourceManager.resourceGroups().beginDeleteByName(rgName); } catch (NullPointerException npe) { System.out.println("Did not create any resources in Azure. No clean up is necessary"); } catch (Exception g) { g.printStackTrace(); } } }
final String rgName = azureResourceManager.resourceGroups().manager().sdkContext().randomResourceName("rg", 24);
public static boolean runSample(AzureResourceManager azureResourceManager, String clientId) throws IOException, KeyStoreException, CertificateException, NoSuchAlgorithmException { final String rgName = azureResourceManager.resourceGroups().manager().sdkContext().randomResourceName("rg", 24); final String serviceName = azureResourceManager.resourceGroups().manager().sdkContext().randomResourceName("service", 24); final Region region = Region.US_EAST; final String domainName = azureResourceManager.resourceGroups().manager().sdkContext().randomResourceName("jsdkdemo-", 20) + ".com"; final String certOrderName = azureResourceManager.resourceGroups().manager().sdkContext().randomResourceName("cert", 15); final String vaultName = azureResourceManager.resourceGroups().manager().sdkContext().randomResourceName("vault", 15); final String certName = azureResourceManager.resourceGroups().manager().sdkContext().randomResourceName("cert", 15); try { azureResourceManager.resourceGroups().define(rgName) .withRegion(region) .create(); System.out.printf("Creating spring cloud service %s in resource group %s ...%n", serviceName, rgName); SpringService service = azureResourceManager.springServices().define(serviceName) .withRegion(region) .withExistingResourceGroup(rgName) .create(); System.out.printf("Created spring cloud service %s%n", service.name()); Utils.print(service); File gzFile = new File("piggymetrics.tar.gz"); if (!gzFile.exists()) { HttpURLConnection connection = (HttpURLConnection) new URL(PIGGYMETRICS_TAR_GZ_URL).openConnection(); connection.connect(); try (InputStream inputStream = connection.getInputStream(); OutputStream outputStream = new FileOutputStream(gzFile)) { IOUtils.copy(inputStream, outputStream); } connection.disconnect(); } System.out.printf("Creating spring cloud app gateway in resource group %s ...%n", rgName); SpringApp gateway = service.apps().define("gateway") .defineActiveDeployment("default") .withSourceCodeTarGzFile(gzFile) .withTargetModule("gateway") .attach() .withDefaultPublicEndpoint() .withHttpsOnly() .create(); System.out.println("Created spring cloud service gateway"); Utils.print(gateway); System.out.printf("Creating spring cloud app auth-service in resource group %s ...%n", rgName); SpringApp authService = service.apps().define("auth-service") .defineActiveDeployment("default") .withSourceCodeTarGzFile(gzFile) .withTargetModule("auth-service") .attach() .create(); System.out.println("Created spring cloud service auth-service"); Utils.print(authService); System.out.printf("Creating spring cloud app account-service in resource group %s ...%n", rgName); SpringApp accountService = service.apps().define("account-service") .defineActiveDeployment("default") .withSourceCodeTarGzFile(gzFile) .withTargetModule("account-service") .attach() .create(); System.out.println("Created spring cloud service account-service"); Utils.print(accountService); System.out.println("Purchasing a domain " + domainName + "..."); AppServiceDomain domain = azureResourceManager.appServiceDomains().define(domainName) .withExistingResourceGroup(rgName) .defineRegistrantContact() .withFirstName("Jon") .withLastName("Doe") .withEmail("jondoe@contoso.com") .withAddressLine1("123 4th Ave") .withCity("Redmond") .withStateOrProvince("WA") .withCountry(CountryIsoCode.UNITED_STATES) .withPostalCode("98052") .withPhoneCountryCode(CountryPhoneCode.UNITED_STATES) .withPhoneNumber("4258828080") .attach() .withDomainPrivacyEnabled(true) .withAutoRenewEnabled(false) .create(); System.out.println("Purchased domain " + domain.name()); Utils.print(domain); DnsZone dnsZone = azureResourceManager.dnsZones().getById(domain.dnsZoneId()); gateway.refresh(); System.out.printf("Updating dns with CNAME ssl.%s to %s%n", domainName, gateway.fqdn()); dnsZone.update() .withCNameRecordSet("ssl", gateway.fqdn()) .apply(); System.out.printf("Purchasing a certificate for *.%s and save to %s in key vault named %s ...%n", domainName, certOrderName, vaultName); AppServiceCertificateOrder certificateOrder = azureResourceManager.appServiceCertificateOrders().define(certOrderName) .withExistingResourceGroup(rgName) .withHostName(String.format("*.%s", domainName)) .withWildcardSku() .withDomainVerification(domain) .withNewKeyVault(vaultName, region) .withAutoRenew(true) .create(); System.out.printf("Purchased certificate: *.%s ...%n", domain.name()); Utils.print(certificateOrder); System.out.printf("Updating key vault %s with access from %s, %s%n", vaultName, clientId, SPRING_CLOUD_SERVICE_PRINCIPAL); Vault vault = azureResourceManager.vaults().getByResourceGroup(rgName, vaultName); vault.update() .defineAccessPolicy() .forServicePrincipal(clientId) .allowSecretAllPermissions() .allowCertificateAllPermissions() .attach() .defineAccessPolicy() .forServicePrincipal(SPRING_CLOUD_SERVICE_PRINCIPAL) .allowCertificatePermissions(CertificatePermissions.GET, CertificatePermissions.LIST) .allowSecretPermissions(SecretPermissions.GET, SecretPermissions.LIST) .attach() .apply(); System.out.printf("Updated key vault %s%n", vault.name()); Utils.print(vault); Secret secret = vault.secrets().getByName(certOrderName); byte[] certificate = Base64.getDecoder().decode(secret.value()); String thumbprint = secret.tags().get("Thumbprint"); if (thumbprint == null || thumbprint.isEmpty()) { KeyStore store = KeyStore.getInstance("PKCS12"); store.load(new ByteArrayInputStream(certificate), null); String alias = Collections.list(store.aliases()).get(0); thumbprint = DatatypeConverter.printHexBinary(MessageDigest.getInstance("SHA-1").digest(store.getCertificate(alias).getEncoded())); } System.out.printf("Get certificate: %s%n", secret.value()); System.out.printf("Certificate Thumbprint: %s%n", thumbprint); CertificateClient certificateClient = new CertificateClientBuilder() .vaultUrl(vault.vaultUri()) .pipeline(service.manager().httpPipeline()) .buildClient(); System.out.printf("Uploading certificate to %s in key vault ...%n", certName); certificateClient.importCertificate( new ImportCertificateOptions(certName, certificate) .setEnabled(true) ); System.out.println("Updating Spring Cloud Service with certificate ..."); service.update() .withCertificate(certName, vault.vaultUri(), certName) .apply(); System.out.printf("Updating Spring Cloud App with domain ssl.%s ...%n", domainName); gateway.update() .withCustomDomain(String.format("ssl.%s", domainName), thumbprint) .apply(); System.out.printf("Successfully expose domain ssl.%s%n", domainName); return true; } finally { try { System.out.println("Delete Resource Group: " + rgName); azureResourceManager.resourceGroups().beginDeleteByName(rgName); } catch (NullPointerException npe) { System.out.println("Did not create any resources in Azure. No clean up is necessary"); } catch (Exception g) { g.printStackTrace(); } } }
class ManageSpringCloud { private static final String PIGGYMETRICS_TAR_GZ_URL = "https: private static final String SPRING_CLOUD_SERVICE_PRINCIPAL = "03b39d0f-4213-4864-a245-b1476ec03169"; /** * Main function which runs the actual sample. * @param azureResourceManager instance of the azure client * @param clientId the aad client id in azure instance * @return true if sample runs successfully * @throws IllegalStateException unexcepted state */ /** * Main entry point. * @param args the parameters */ public static void main(String[] args) { try { final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); final TokenCredential credential = new DefaultAzureCredentialBuilder() .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); AzureResourceManager azureResourceManager = AzureResourceManager .configure() .withLogLevel(HttpLogDetailLevel.BASIC) .authenticate(credential, profile) .withDefaultSubscription(); System.out.println("Selected subscription: " + azureResourceManager.subscriptionId()); runSample(azureResourceManager, Configuration.getGlobalConfiguration().get(Configuration.PROPERTY_AZURE_CLIENT_ID)); } catch (Exception e) { System.out.println(e.getMessage()); e.printStackTrace(); } } public static void extraTarGzSource(File folder, URL url) throws IOException { HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.connect(); try (TarArchiveInputStream inputStream = new TarArchiveInputStream(new GzipCompressorInputStream(connection.getInputStream()))) { TarArchiveEntry entry; while ((entry = inputStream.getNextTarEntry()) != null) { if (entry.isDirectory()) { continue; } File file = new File(folder, entry.getName()); File parent = file.getParentFile(); if (parent.exists() || parent.mkdirs()) { try (OutputStream outputStream = new FileOutputStream(file)) { IOUtils.copy(inputStream, outputStream); } } else { throw new IllegalStateException("Cannot create directory: " + parent.getAbsolutePath()); } } } finally { connection.disconnect(); } } }
class ManageSpringCloud { private static final String PIGGYMETRICS_TAR_GZ_URL = "https: private static final String SPRING_CLOUD_SERVICE_PRINCIPAL = "03b39d0f-4213-4864-a245-b1476ec03169"; /** * Main function which runs the actual sample. * @param azureResourceManager instance of the azure client * @param clientId the aad client id in azure instance * @return true if sample runs successfully * @throws IllegalStateException unexcepted state */ /** * Main entry point. * @param args the parameters */ public static void main(String[] args) { try { final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); final TokenCredential credential = new DefaultAzureCredentialBuilder() .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); AzureResourceManager azureResourceManager = AzureResourceManager .configure() .withLogLevel(HttpLogDetailLevel.BASIC) .authenticate(credential, profile) .withDefaultSubscription(); System.out.println("Selected subscription: " + azureResourceManager.subscriptionId()); runSample(azureResourceManager, Configuration.getGlobalConfiguration().get(Configuration.PROPERTY_AZURE_CLIENT_ID)); } catch (Exception e) { System.out.println(e.getMessage()); e.printStackTrace(); } } public static void extraTarGzSource(File folder, URL url) throws IOException { HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.connect(); try (TarArchiveInputStream inputStream = new TarArchiveInputStream(new GzipCompressorInputStream(connection.getInputStream()))) { TarArchiveEntry entry; while ((entry = inputStream.getNextTarEntry()) != null) { if (entry.isDirectory()) { continue; } File file = new File(folder, entry.getName()); File parent = file.getParentFile(); if (parent.exists() || parent.mkdirs()) { try (OutputStream outputStream = new FileOutputStream(file)) { IOUtils.copy(inputStream, outputStream); } } else { throw new IllegalStateException("Cannot create directory: " + parent.getAbsolutePath()); } } } finally { connection.disconnect(); } } }
the default connectionPolicy instance will be created in `CosmosClientBuilder`. ```java /** * Instantiates a new Cosmos client builder. */ public CosmosClientBuilder() { // Build default connection policy with direct default connection config this.connectionPolicy = new ConnectionPolicy(DirectConnectionConfig.getDefaultConfig()); // Some default values this.userAgentSuffix = ""; this.throttlingRetryOptions = new ThrottlingRetryOptions(); } ```
public void setAllowTelemetry(boolean allowTelemetry) { this.allowTelemetry = allowTelemetry; }
this.allowTelemetry = allowTelemetry;
public void setAllowTelemetry(boolean allowTelemetry) { this.allowTelemetry = allowTelemetry; }
class CosmosProperties { private static final Logger LOGGER = LoggerFactory.getLogger(CosmosProperties.class); /** * Document DB URI. */ @NotEmpty private String uri; /** * Document DB key. */ @NotEmpty private String key; /** * Document DB consistency level. */ private ConsistencyLevel consistencyLevel; /** * Document DB database name. */ @NotEmpty private String database; /** * Populate Diagnostics Strings and Query metrics */ private boolean populateQueryMetrics; /** * Whether allow Microsoft to collect telemetry data. */ private boolean allowTelemetry = true; /** * The credential is used to authorize request. */ private AzureKeyCredential credential; /** * Response Diagnostics processor * Default implementation is to log the response diagnostics string */ private ResponseDiagnosticsProcessor responseDiagnosticsProcessor = responseDiagnostics -> { if (populateQueryMetrics) { LOGGER.info("Response Diagnostics {}", responseDiagnostics); } }; public String getUri() { return uri; } public void setUri(String uri) { this.uri = uri; } public String getKey() { return key; } public void setKey(String key) { this.key = key; } public String getDatabase() { return database; } public void setDatabase(String databaseName) { this.database = databaseName; } public ConsistencyLevel getConsistencyLevel() { return consistencyLevel; } public void setConsistencyLevel(ConsistencyLevel consistencyLevel) { this.consistencyLevel = consistencyLevel; } public boolean isAllowTelemetry() { return allowTelemetry; } public boolean isPopulateQueryMetrics() { return populateQueryMetrics; } public void setPopulateQueryMetrics(boolean populateQueryMetrics) { this.populateQueryMetrics = populateQueryMetrics; } public ResponseDiagnosticsProcessor getResponseDiagnosticsProcessor() { return responseDiagnosticsProcessor; } public void setResponseDiagnosticsProcessor(ResponseDiagnosticsProcessor responseDiagnosticsProcessor) { this.responseDiagnosticsProcessor = responseDiagnosticsProcessor; } public AzureKeyCredential getCredential() { return credential; } public void setCredential(AzureKeyCredential credential) { this.credential = credential; } }
class CosmosProperties { private static final Logger LOGGER = LoggerFactory.getLogger(CosmosProperties.class); /** * Document DB URI. */ @NotEmpty private String uri; /** * Document DB key. */ @NotEmpty private String key; /** * Document DB consistency level. */ private ConsistencyLevel consistencyLevel; /** * Document DB database name. */ @NotEmpty private String database; /** * Populate Diagnostics Strings and Query metrics */ private boolean populateQueryMetrics; /** * Whether allow Microsoft to collect telemetry data. */ private boolean allowTelemetry = true; /** * Represents the connection mode to be used by the client in the Azure Cosmos DB database service. */ private ConnectionMode connectionMode; /** * Response Diagnostics processor * Default implementation is to log the response diagnostics string */ private ResponseDiagnosticsProcessor responseDiagnosticsProcessor = responseDiagnostics -> { if (populateQueryMetrics) { LOGGER.info("Response Diagnostics {}", responseDiagnostics); } }; public String getUri() { return uri; } public void setUri(String uri) { this.uri = uri; } public String getKey() { return key; } public void setKey(String key) { this.key = key; } public String getDatabase() { return database; } public void setDatabase(String databaseName) { this.database = databaseName; } public ConsistencyLevel getConsistencyLevel() { return consistencyLevel; } public void setConsistencyLevel(ConsistencyLevel consistencyLevel) { this.consistencyLevel = consistencyLevel; } public boolean isAllowTelemetry() { return allowTelemetry; } public boolean isPopulateQueryMetrics() { return populateQueryMetrics; } public void setPopulateQueryMetrics(boolean populateQueryMetrics) { this.populateQueryMetrics = populateQueryMetrics; } public ResponseDiagnosticsProcessor getResponseDiagnosticsProcessor() { return responseDiagnosticsProcessor; } public void setResponseDiagnosticsProcessor(ResponseDiagnosticsProcessor responseDiagnosticsProcessor) { this.responseDiagnosticsProcessor = responseDiagnosticsProcessor; } public ConnectionMode getConnectionMode() { return connectionMode; } public void setConnectionMode(ConnectionMode connectionMode) { this.connectionMode = connectionMode; } }
How does data-plane prepare their test env?
public AzureResourceManagerTest(TOptions options) throws IOException { super(options); String authFilePath = System.getenv("AZURE_AUTH_LOCATION"); if (CoreUtils.isNullOrEmpty(authFilePath)) { System.out.println("Environment variable AZURE_AUTH_LOCATION must be set."); System.exit(1); } AuthFile authFile = AuthFile.parse(new File(authFilePath)); AzureProfile profile = new AzureProfile(authFile.getTenantId(), authFile.getSubscriptionId(), AzureEnvironment.AZURE); azureResourceManager = AzureResourceManager.authenticate(authFile.getCredential(), profile).withDefaultSubscription(); }
azureResourceManager = AzureResourceManager.authenticate(authFile.getCredential(), profile).withDefaultSubscription();
public AzureResourceManagerTest(TOptions options) throws IOException { super(options); String authFilePath = System.getenv("AZURE_AUTH_LOCATION"); if (CoreUtils.isNullOrEmpty(authFilePath)) { System.out.println("Environment variable AZURE_AUTH_LOCATION must be set."); System.exit(1); } AuthFile authFile = AuthFile.parse(new File(authFilePath)); AzureProfile profile = new AzureProfile(authFile.getTenantId(), authFile.getSubscriptionId(), AzureEnvironment.AZURE); azureResourceManager = AzureResourceManager.authenticate(authFile.getCredential(), profile).withDefaultSubscription(); }
class AzureResourceManagerTest<TOptions extends PerfStressOptions> extends PerfStressTest<TOptions> { protected final AzureResourceManager azureResourceManager; }
class AzureResourceManagerTest<TOptions extends PerfStressOptions> extends PerfStressTest<TOptions> { protected final AzureResourceManager azureResourceManager; }
`String connectionString = System.getenv("STORAGE_CONNECTION_STRING");` They use the connection string.
public AzureResourceManagerTest(TOptions options) throws IOException { super(options); String authFilePath = System.getenv("AZURE_AUTH_LOCATION"); if (CoreUtils.isNullOrEmpty(authFilePath)) { System.out.println("Environment variable AZURE_AUTH_LOCATION must be set."); System.exit(1); } AuthFile authFile = AuthFile.parse(new File(authFilePath)); AzureProfile profile = new AzureProfile(authFile.getTenantId(), authFile.getSubscriptionId(), AzureEnvironment.AZURE); azureResourceManager = AzureResourceManager.authenticate(authFile.getCredential(), profile).withDefaultSubscription(); }
azureResourceManager = AzureResourceManager.authenticate(authFile.getCredential(), profile).withDefaultSubscription();
public AzureResourceManagerTest(TOptions options) throws IOException { super(options); String authFilePath = System.getenv("AZURE_AUTH_LOCATION"); if (CoreUtils.isNullOrEmpty(authFilePath)) { System.out.println("Environment variable AZURE_AUTH_LOCATION must be set."); System.exit(1); } AuthFile authFile = AuthFile.parse(new File(authFilePath)); AzureProfile profile = new AzureProfile(authFile.getTenantId(), authFile.getSubscriptionId(), AzureEnvironment.AZURE); azureResourceManager = AzureResourceManager.authenticate(authFile.getCredential(), profile).withDefaultSubscription(); }
class AzureResourceManagerTest<TOptions extends PerfStressOptions> extends PerfStressTest<TOptions> { protected final AzureResourceManager azureResourceManager; }
class AzureResourceManagerTest<TOptions extends PerfStressOptions> extends PerfStressTest<TOptions> { protected final AzureResourceManager azureResourceManager; }
Can we delete ` && Strings.isNullOrEmpty(subscriptionId)`?
private void validate() { if (autoCreateResources) { Assert.hasText(this.region, "When auto create resources is enabled, spring.cloud.azure.region must be provided"); } if (msiEnabled && Strings.isNullOrEmpty(subscriptionId)) { Assert.hasText(this.subscriptionId, "When msi is enabled, spring.cloud.azure.subscription-id must be provided"); } }
Assert.hasText(this.subscriptionId, "When msi is enabled, spring.cloud.azure.subscription-id must be provided");
private void validate() { if (autoCreateResources) { Assert.hasText(this.region, "When auto create resources is enabled, spring.cloud.azure.region must be provided"); } if (msiEnabled && Strings.isNullOrEmpty(subscriptionId)) { Assert.hasText(this.subscriptionId, "When msi is enabled, spring.cloud.azure.subscription-id must be provided"); } }
class AzureProperties implements CredentialSupplier { private String credentialFilePath; private String resourceGroup; private AzureEnvironment environment = AzureEnvironment.AZURE; private String region; private boolean autoCreateResources = false; private boolean msiEnabled = false; @NestedConfigurationProperty private AzureManagedIdentityProperties managedIdentity; private String subscriptionId; @PostConstruct @Override public String getCredentialFilePath() { return credentialFilePath; } public void setCredentialFilePath(String credentialFilePath) { this.credentialFilePath = credentialFilePath; } public String getResourceGroup() { return resourceGroup; } public void setResourceGroup(String resourceGroup) { this.resourceGroup = resourceGroup; } public AzureEnvironment getEnvironment() { return environment; } public void setEnvironment(AzureEnvironment environment) { this.environment = environment; } public String getRegion() { return region; } public void setRegion(String region) { this.region = region; } public boolean isAutoCreateResources() { return autoCreateResources; } public void setAutoCreateResources(boolean autoCreateResources) { this.autoCreateResources = autoCreateResources; } public boolean isMsiEnabled() { return msiEnabled; } public void setMsiEnabled(boolean msiEnabled) { this.msiEnabled = msiEnabled; } public String getSubscriptionId() { return subscriptionId; } public void setSubscriptionId(String subscriptionId) { this.subscriptionId = subscriptionId; } public AzureManagedIdentityProperties getManagedIdentity() { return managedIdentity; } public void setManagedIdentity(AzureManagedIdentityProperties managedIdentity) { this.managedIdentity = managedIdentity; } }
class AzureProperties implements CredentialSupplier { private String credentialFilePath; private String resourceGroup; private AzureEnvironment environment = AzureEnvironment.AZURE; private String region; private boolean autoCreateResources = false; private boolean msiEnabled = false; @NestedConfigurationProperty private AzureManagedIdentityProperties managedIdentity; private String subscriptionId; @PostConstruct @Override public String getCredentialFilePath() { return credentialFilePath; } public void setCredentialFilePath(String credentialFilePath) { this.credentialFilePath = credentialFilePath; } public String getResourceGroup() { return resourceGroup; } public void setResourceGroup(String resourceGroup) { this.resourceGroup = resourceGroup; } public AzureEnvironment getEnvironment() { return environment; } public void setEnvironment(AzureEnvironment environment) { this.environment = environment; } public String getRegion() { return region; } public void setRegion(String region) { this.region = region; } public boolean isAutoCreateResources() { return autoCreateResources; } public void setAutoCreateResources(boolean autoCreateResources) { this.autoCreateResources = autoCreateResources; } public boolean isMsiEnabled() { return msiEnabled; } public void setMsiEnabled(boolean msiEnabled) { this.msiEnabled = msiEnabled; } public String getSubscriptionId() { return subscriptionId; } public void setSubscriptionId(String subscriptionId) { this.subscriptionId = subscriptionId; } public AzureManagedIdentityProperties getManagedIdentity() { return managedIdentity; } public void setManagedIdentity(AzureManagedIdentityProperties managedIdentity) { this.managedIdentity = managedIdentity; } }
> Can we delete ` && Strings.isNullOrEmpty(subscriptionId)`? I think it's necessary, we will assert it when the subscriptionId is empty
private void validate() { if (autoCreateResources) { Assert.hasText(this.region, "When auto create resources is enabled, spring.cloud.azure.region must be provided"); } if (msiEnabled && Strings.isNullOrEmpty(subscriptionId)) { Assert.hasText(this.subscriptionId, "When msi is enabled, spring.cloud.azure.subscription-id must be provided"); } }
Assert.hasText(this.subscriptionId, "When msi is enabled, spring.cloud.azure.subscription-id must be provided");
private void validate() { if (autoCreateResources) { Assert.hasText(this.region, "When auto create resources is enabled, spring.cloud.azure.region must be provided"); } if (msiEnabled && Strings.isNullOrEmpty(subscriptionId)) { Assert.hasText(this.subscriptionId, "When msi is enabled, spring.cloud.azure.subscription-id must be provided"); } }
class AzureProperties implements CredentialSupplier { private String credentialFilePath; private String resourceGroup; private AzureEnvironment environment = AzureEnvironment.AZURE; private String region; private boolean autoCreateResources = false; private boolean msiEnabled = false; @NestedConfigurationProperty private AzureManagedIdentityProperties managedIdentity; private String subscriptionId; @PostConstruct @Override public String getCredentialFilePath() { return credentialFilePath; } public void setCredentialFilePath(String credentialFilePath) { this.credentialFilePath = credentialFilePath; } public String getResourceGroup() { return resourceGroup; } public void setResourceGroup(String resourceGroup) { this.resourceGroup = resourceGroup; } public AzureEnvironment getEnvironment() { return environment; } public void setEnvironment(AzureEnvironment environment) { this.environment = environment; } public String getRegion() { return region; } public void setRegion(String region) { this.region = region; } public boolean isAutoCreateResources() { return autoCreateResources; } public void setAutoCreateResources(boolean autoCreateResources) { this.autoCreateResources = autoCreateResources; } public boolean isMsiEnabled() { return msiEnabled; } public void setMsiEnabled(boolean msiEnabled) { this.msiEnabled = msiEnabled; } public String getSubscriptionId() { return subscriptionId; } public void setSubscriptionId(String subscriptionId) { this.subscriptionId = subscriptionId; } public AzureManagedIdentityProperties getManagedIdentity() { return managedIdentity; } public void setManagedIdentity(AzureManagedIdentityProperties managedIdentity) { this.managedIdentity = managedIdentity; } }
class AzureProperties implements CredentialSupplier { private String credentialFilePath; private String resourceGroup; private AzureEnvironment environment = AzureEnvironment.AZURE; private String region; private boolean autoCreateResources = false; private boolean msiEnabled = false; @NestedConfigurationProperty private AzureManagedIdentityProperties managedIdentity; private String subscriptionId; @PostConstruct @Override public String getCredentialFilePath() { return credentialFilePath; } public void setCredentialFilePath(String credentialFilePath) { this.credentialFilePath = credentialFilePath; } public String getResourceGroup() { return resourceGroup; } public void setResourceGroup(String resourceGroup) { this.resourceGroup = resourceGroup; } public AzureEnvironment getEnvironment() { return environment; } public void setEnvironment(AzureEnvironment environment) { this.environment = environment; } public String getRegion() { return region; } public void setRegion(String region) { this.region = region; } public boolean isAutoCreateResources() { return autoCreateResources; } public void setAutoCreateResources(boolean autoCreateResources) { this.autoCreateResources = autoCreateResources; } public boolean isMsiEnabled() { return msiEnabled; } public void setMsiEnabled(boolean msiEnabled) { this.msiEnabled = msiEnabled; } public String getSubscriptionId() { return subscriptionId; } public void setSubscriptionId(String subscriptionId) { this.subscriptionId = subscriptionId; } public AzureManagedIdentityProperties getManagedIdentity() { return managedIdentity; } public void setManagedIdentity(AzureManagedIdentityProperties managedIdentity) { this.managedIdentity = managedIdentity; } }
Here is the source code of `Assert.hasText(...)`: ``` public static void hasText(@Nullable String text, String message) { if (!StringUtils.hasText(text)) { throw new IllegalArgumentException(message); } } ``` It will check by `StringUtils.hasText(text)`. Maybe we do not need check it again by `Strings.isNullOrEmpty(subscriptionId)`?
private void validate() { if (autoCreateResources) { Assert.hasText(this.region, "When auto create resources is enabled, spring.cloud.azure.region must be provided"); } if (msiEnabled && Strings.isNullOrEmpty(subscriptionId)) { Assert.hasText(this.subscriptionId, "When msi is enabled, spring.cloud.azure.subscription-id must be provided"); } }
Assert.hasText(this.subscriptionId, "When msi is enabled, spring.cloud.azure.subscription-id must be provided");
private void validate() { if (autoCreateResources) { Assert.hasText(this.region, "When auto create resources is enabled, spring.cloud.azure.region must be provided"); } if (msiEnabled && Strings.isNullOrEmpty(subscriptionId)) { Assert.hasText(this.subscriptionId, "When msi is enabled, spring.cloud.azure.subscription-id must be provided"); } }
class AzureProperties implements CredentialSupplier { private String credentialFilePath; private String resourceGroup; private AzureEnvironment environment = AzureEnvironment.AZURE; private String region; private boolean autoCreateResources = false; private boolean msiEnabled = false; @NestedConfigurationProperty private AzureManagedIdentityProperties managedIdentity; private String subscriptionId; @PostConstruct @Override public String getCredentialFilePath() { return credentialFilePath; } public void setCredentialFilePath(String credentialFilePath) { this.credentialFilePath = credentialFilePath; } public String getResourceGroup() { return resourceGroup; } public void setResourceGroup(String resourceGroup) { this.resourceGroup = resourceGroup; } public AzureEnvironment getEnvironment() { return environment; } public void setEnvironment(AzureEnvironment environment) { this.environment = environment; } public String getRegion() { return region; } public void setRegion(String region) { this.region = region; } public boolean isAutoCreateResources() { return autoCreateResources; } public void setAutoCreateResources(boolean autoCreateResources) { this.autoCreateResources = autoCreateResources; } public boolean isMsiEnabled() { return msiEnabled; } public void setMsiEnabled(boolean msiEnabled) { this.msiEnabled = msiEnabled; } public String getSubscriptionId() { return subscriptionId; } public void setSubscriptionId(String subscriptionId) { this.subscriptionId = subscriptionId; } public AzureManagedIdentityProperties getManagedIdentity() { return managedIdentity; } public void setManagedIdentity(AzureManagedIdentityProperties managedIdentity) { this.managedIdentity = managedIdentity; } }
class AzureProperties implements CredentialSupplier { private String credentialFilePath; private String resourceGroup; private AzureEnvironment environment = AzureEnvironment.AZURE; private String region; private boolean autoCreateResources = false; private boolean msiEnabled = false; @NestedConfigurationProperty private AzureManagedIdentityProperties managedIdentity; private String subscriptionId; @PostConstruct @Override public String getCredentialFilePath() { return credentialFilePath; } public void setCredentialFilePath(String credentialFilePath) { this.credentialFilePath = credentialFilePath; } public String getResourceGroup() { return resourceGroup; } public void setResourceGroup(String resourceGroup) { this.resourceGroup = resourceGroup; } public AzureEnvironment getEnvironment() { return environment; } public void setEnvironment(AzureEnvironment environment) { this.environment = environment; } public String getRegion() { return region; } public void setRegion(String region) { this.region = region; } public boolean isAutoCreateResources() { return autoCreateResources; } public void setAutoCreateResources(boolean autoCreateResources) { this.autoCreateResources = autoCreateResources; } public boolean isMsiEnabled() { return msiEnabled; } public void setMsiEnabled(boolean msiEnabled) { this.msiEnabled = msiEnabled; } public String getSubscriptionId() { return subscriptionId; } public void setSubscriptionId(String subscriptionId) { this.subscriptionId = subscriptionId; } public AzureManagedIdentityProperties getManagedIdentity() { return managedIdentity; } public void setManagedIdentity(AzureManagedIdentityProperties managedIdentity) { this.managedIdentity = managedIdentity; } }
So this is a minor change where we will make an additional service call to get the properties of the blob before opening the stream. Are we okay with that? If so, we should add a quick document stating that we will be doing this as it is a behavioral change from the past.
public BlobInputStream openInputStream(BlobInputStreamOptions options) { options = options == null ? new BlobInputStreamOptions() : options; BlobRange range = options.getRange() == null ? new BlobRange(0) : options.getRange(); int chunkSize = options.getBlockSize() == null ? 4 * Constants.MB : options.getBlockSize(); return new BlobInputStream(client, range.getOffset(), range.getCount(), chunkSize, options.getRequestConditions(), getProperties()); }
return new BlobInputStream(client, range.getOffset(), range.getCount(), chunkSize,
public BlobInputStream openInputStream(BlobInputStreamOptions options) { options = options == null ? new BlobInputStreamOptions() : options; BlobRange range = options.getRange() == null ? new BlobRange(0) : options.getRange(); int chunkSize = options.getBlockSize() == null ? 4 * Constants.MB : options.getBlockSize(); return new BlobInputStream(client, range.getOffset(), range.getCount(), chunkSize, options.getRequestConditions(), getProperties()); }
class BlobClientBase { private final ClientLogger logger = new ClientLogger(BlobClientBase.class); private final BlobAsyncClientBase client; /** * Constructor used by {@link SpecializedBlobClientBuilder}. * * @param client the async blob client */ protected BlobClientBase(BlobAsyncClientBase client) { this.client = client; } /** * 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(client.getSnapshotClient(snapshot)); } /** * 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(client.getVersionClient(versionId)); } /** * Gets the URL of the blob represented by this client. * * @return the URL. */ public String getBlobUrl() { return client.getBlobUrl(); } /** * Get associated account name. * * @return account name associated with this storage resource. */ public String getAccountName() { return client.getAccountName(); } /** * Get the container name. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.blob.specialized.BlobClientBase.getContainerName} * * @return The name of the container. */ public final String getContainerName() { return client.getContainerName(); } /** * Decodes and gets the blob name. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.blob.specialized.BlobClientBase.getBlobName} * * @return The decoded name of the blob. */ public final String getBlobName() { return client.getBlobName(); } /** * Gets the {@link HttpPipeline} powering this client. * * @return The pipeline. */ public HttpPipeline getHttpPipeline() { return client.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 client.getCustomerProvidedKey(); } /** * Gets the {@code encryption scope} used to encrypt this blob's content on the server. * * @return the encryption scope used for encryption. */ String getEncryptionScope() { return client.getEncryptionScope(); } /** * Gets the service version the client is using. * * @return the service version the client is using. */ public BlobServiceVersion getServiceVersion() { return client.getServiceVersion(); } /** * Gets the snapshotId for a blob resource * * @return A string that represents the snapshotId of the snapshot blob */ public String getSnapshotId() { return client.getSnapshotId(); } /** * Gets the versionId for a blob resource * * @return A string that represents the versionId of the snapshot blob */ public String getVersionId() { return client.getVersionId(); } /** * Determines if a blob is a snapshot * * @return A boolean that indicates if a blob is a snapshot */ public boolean isSnapshot() { return client.isSnapshot(); } /** * Opens a blob input stream to download the blob. * <p> * * @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 final BlobInputStream openInputStream() { return openInputStream(null, null); } /** * Opens a blob input stream to download the specified range of the blob. * <p> * * @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 final 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. */ /** * Gets if the blob this client represents exists in the cloud. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.blob.specialized.BlobClientBase.exists} * * @return true if the blob exists, false if it doesn't */ 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> * * {@codesnippet 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 */ public Response<Boolean> existsWithResponse(Duration timeout, Context context) { Mono<Response<Boolean>> response = client.existsWithResponse(context); return blockWithOptionalTimeout(response, timeout); } /** * Copies the data at the source URL to a blob. * * <p><strong>Code Samples</strong></p> * * {@codesnippet 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. */ 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><strong>Code Samples</strong></p> * * {@codesnippet 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. * @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. */ 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><strong>Code Samples</strong></p> * * {@codesnippet 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. */ public SyncPoller<BlobCopyInfo, Void> beginCopy(BlobBeginCopyOptions options) { return client.beginCopy(options).getSyncPoller(); } /** * Stops a pending copy that was previously started and leaves a destination blob with 0 length and metadata. * * <p><strong>Code Samples</strong></p> * * {@codesnippet 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. */ 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> * * {@codesnippet 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. */ public Response<Void> abortCopyFromUrlWithResponse(String copyId, String leaseId, Duration timeout, Context context) { return blockWithOptionalTimeout(client.abortCopyFromUrlWithResponse(copyId, leaseId, context), timeout); } /** * Copies the data at the source URL to a blob and waits for the copy to complete before returning a response. * * <p><strong>Code Samples</strong></p> * * {@codesnippet 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}. */ 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><strong>Code Samples</strong></p> * * {@codesnippet 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. * @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}. */ 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><strong>Code Samples</strong></p> * * {@codesnippet 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}. */ public Response<String> copyFromUrlWithResponse(BlobCopyFromUrlOptions options, Duration timeout, Context context) { Mono<Response<String>> response = client .copyFromUrlWithResponse(options, context); return blockWithOptionalTimeout(response, timeout); } /** * 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> * * {@codesnippet com.azure.storage.blob.specialized.BlobClientBase.download * * <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 */ public void download(OutputStream stream) { downloadWithResponse(stream, null, null, null, false, null, Context.NONE); } /** * 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> * * {@codesnippet com.azure.storage.blob.specialized.BlobClientBase.downloadWithResponse * * <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 */ public BlobDownloadResponse downloadWithResponse(OutputStream stream, BlobRange range, DownloadRetryOptions options, BlobRequestConditions requestConditions, boolean getRangeContentMd5, Duration timeout, Context context) { StorageImplUtils.assertNotNull("stream", stream); Mono<BlobDownloadResponse> download = client .downloadWithResponse(range, options, requestConditions, getRangeContentMd5, context) .flatMap(response -> response.getValue().reduce(stream, (outputStream, buffer) -> { try { outputStream.write(FluxUtil.byteBufferToArray(buffer)); return outputStream; } catch (IOException ex) { throw logger.logExceptionAsError(Exceptions.propagate(new UncheckedIOException(ex))); } }).thenReturn(new BlobDownloadResponse(response))); 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> * * {@codesnippet 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 */ 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> * * {@codesnippet 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 or not to overwrite the file, should the file exist. * @return The blob properties and metadata. * @throws UncheckedIOException If an I/O error occurs */ 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> * * {@codesnippet 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. */ 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> * * {@codesnippet 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. */ 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) .setRangeGetContentMd5(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> * * {@codesnippet 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. */ 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. Note that deleting a blob also deletes all its snapshots. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.blob.specialized.BlobClientBase.delete} * * <p>For more information, see the * <a href="https: */ public void delete() { deleteWithResponse(null, null, null, Context.NONE); } /** * Deletes the specified blob or snapshot. Note that deleting a blob also deletes all its snapshots. * * <p><strong>Code Samples</strong></p> * * {@codesnippet 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. */ public Response<Void> deleteWithResponse(DeleteSnapshotsOptionType deleteBlobSnapshotOptions, BlobRequestConditions requestConditions, Duration timeout, Context context) { Mono<Response<Void>> response = client .deleteWithResponse(deleteBlobSnapshotOptions, requestConditions, context); return blockWithOptionalTimeout(response, timeout); } /** * Returns the blob's metadata and properties. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.blob.specialized.BlobClientBase.getProperties} * * <p>For more information, see the * <a href="https: * * @return The blob properties and metadata. */ public BlobProperties getProperties() { return getPropertiesWithResponse(null, null, Context.NONE).getValue(); } /** * Returns the blob's metadata and properties. * * <p><strong>Code Samples</strong></p> * * {@codesnippet 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. */ public Response<BlobProperties> getPropertiesWithResponse(BlobRequestConditions requestConditions, Duration timeout, Context context) { Mono<Response<BlobProperties>> response = client.getPropertiesWithResponse(requestConditions, context); return blockWithOptionalTimeout(response, timeout); } /** * 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> * * {@codesnippet com.azure.storage.blob.specialized.BlobClientBase.setHttpHeaders * * <p>For more information, see the * <a href="https: * * @param headers {@link BlobHttpHeaders} */ 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> * * {@codesnippet 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. */ public Response<Void> setHttpHeadersWithResponse(BlobHttpHeaders headers, BlobRequestConditions requestConditions, Duration timeout, Context context) { Mono<Response<Void>> response = client .setHttpHeadersWithResponse(headers, requestConditions, context); return blockWithOptionalTimeout(response, timeout); } /** * 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> * * {@codesnippet com.azure.storage.blob.specialized.BlobClientBase.setMetadata * * <p>For more information, see the * <a href="https: * * @param metadata Metadata to associate with the blob. */ 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> * * {@codesnippet com.azure.storage.blob.specialized.BlobClientBase.setMetadataWithResponse * * <p>For more information, see the * <a href="https: * * @param metadata Metadata to associate with the blob. * @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. */ public Response<Void> setMetadataWithResponse(Map<String, String> metadata, BlobRequestConditions requestConditions, Duration timeout, Context context) { Mono<Response<Void>> response = client.setMetadataWithResponse(metadata, requestConditions, context); return blockWithOptionalTimeout(response, timeout); } /** * Returns the blob's tags. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.blob.specialized.BlobClientBase.getTags} * * <p>For more information, see the * <a href="https: * * @return The blob's tags. */ 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> * * {@codesnippet 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. */ public Response<Map<String, String>> getTagsWithResponse(BlobGetTagsOptions options, Duration timeout, Context context) { Mono<Response<Map<String, String>>> response = client.getTagsWithResponse(options, context); return blockWithOptionalTimeout(response, timeout); } /** * 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> * * {@codesnippet com.azure.storage.blob.specialized.BlobClientBase.setTags * * <p>For more information, see the * <a href="https: * * @param tags Tags to associate with the blob. */ 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> * * {@codesnippet 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. */ public Response<Void> setTagsWithResponse(BlobSetTagsOptions options, Duration timeout, Context context) { Mono<Response<Void>> response = client.setTagsWithResponse(options, context); return blockWithOptionalTimeout(response, timeout); } /** * Creates a read-only snapshot of the blob. * * <p><strong>Code Samples</strong></p> * * {@codesnippet 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 */ 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> * * {@codesnippet com.azure.storage.blob.specialized.BlobClientBase.createSnapshotWithResponse * * <p>For more information, see the * <a href="https: * * @param metadata Metadata to associate with the blob snapshot. * @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 */ public Response<BlobClientBase> createSnapshotWithResponse(Map<String, String> metadata, BlobRequestConditions requestConditions, Duration timeout, Context context) { Mono<Response<BlobClientBase>> response = client .createSnapshotWithResponse(metadata, requestConditions, context) .map(rb -> new SimpleResponse<>(rb, new BlobClientBase(rb.getValue()))); return blockWithOptionalTimeout(response, timeout); } /** * 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> * * {@codesnippet com.azure.storage.blob.specialized.BlobClientBase.setAccessTier * * <p>For more information, see the * <a href="https: * * @param tier The new tier for the blob. */ 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> * * {@codesnippet 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. */ 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> * * {@codesnippet 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. */ public Response<Void> setAccessTierWithResponse(BlobSetAccessTierOptions options, Duration timeout, Context context) { return blockWithOptionalTimeout(client.setTierWithResponse(options, context), timeout); } /** * Undelete restores the content and metadata of a soft-deleted blob and/or any associated soft-deleted snapshots. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.blob.specialized.BlobClientBase.undelete} * * <p>For more information, see the * <a href="https: */ 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> * * {@codesnippet 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. */ public Response<Void> undeleteWithResponse(Duration timeout, Context context) { Mono<Response<Void>> response = client.undeleteWithResponse(context); return blockWithOptionalTimeout(response, timeout); } /** * Returns the sku name and account kind for the account. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.blob.specialized.BlobClientBase.getAccountInfo} * * <p>For more information, see the * <a href="https: * * @return The sku name and account kind. */ 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> * * {@codesnippet 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. */ public Response<StorageAccountInfo> getAccountInfoWithResponse(Duration timeout, Context context) { Mono<Response<StorageAccountInfo>> response = client.getAccountInfoWithResponse(context); return blockWithOptionalTimeout(response, timeout); } /** * 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> * * {@codesnippet com.azure.storage.blob.specialized.BlobClientBase.generateUserDelegationSas * * @param blobServiceSasSignatureValues {@link BlobServiceSasSignatureValues} * @param userDelegationKey A {@link UserDelegationKey} object used to sign the SAS values. * @see BlobServiceClient * user delegation key. * @return A {@code String} representing all SAS query parameters. */ public String generateUserDelegationSas(BlobServiceSasSignatureValues blobServiceSasSignatureValues, UserDelegationKey userDelegationKey) { return this.client.generateUserDelegationSas(blobServiceSasSignatureValues, userDelegationKey); } /** * Generates a service SAS for the blob using the specified {@link BlobServiceSasSignatureValues} * 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> * * {@codesnippet com.azure.storage.blob.specialized.BlobClientBase.generateSas * * @param blobServiceSasSignatureValues {@link BlobServiceSasSignatureValues} * * @return A {@code String} representing all SAS query parameters. */ public String generateSas(BlobServiceSasSignatureValues blobServiceSasSignatureValues) { return this.client.generateSas(blobServiceSasSignatureValues); } /** * Opens a blob input stream to query the blob. * * <p>For more information, see the * <a href="https: * * <p><strong>Code Samples</strong></p> * * {@codesnippet 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. */ 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> * * {@codesnippet 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. */ public Response<InputStream> openQueryInputStreamWithResponse(BlobQueryOptions queryOptions) { BlobQueryAsyncResponse response = client.queryWithResponse(queryOptions).block(); if (response == null) { throw logger.logExceptionAsError(new IllegalStateException("Query response cannot be null")); } return new ResponseBase<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), new FluxInputStream(response.getValue()), response.getDeserializedHeaders()); } /** * Queries an entire blob into an output stream. * * <p>For more information, see the * <a href="https: * * <p><strong>Code Samples</strong></p> * * {@codesnippet 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. */ 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> * * {@codesnippet 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. */ public BlobQueryResponse queryWithResponse(BlobQueryOptions queryOptions, Duration timeout, Context context) { StorageImplUtils.assertNotNull("options", queryOptions); StorageImplUtils.assertNotNull("outputStream", queryOptions.getOutputStream()); Mono<BlobQueryResponse> download = client .queryWithResponse(queryOptions, context) .flatMap(response -> response.getValue().reduce(queryOptions.getOutputStream(), (outputStream, buffer) -> { try { outputStream.write(FluxUtil.byteBufferToArray(buffer)); return outputStream; } catch (IOException ex) { throw logger.logExceptionAsError(Exceptions.propagate(new UncheckedIOException(ex))); } }).thenReturn(new BlobQueryResponse(response))); return blockWithOptionalTimeout(download, timeout); } }
class BlobClientBase { private final ClientLogger logger = new ClientLogger(BlobClientBase.class); private final BlobAsyncClientBase client; /** * Constructor used by {@link SpecializedBlobClientBuilder}. * * @param client the async blob client */ protected BlobClientBase(BlobAsyncClientBase client) { this.client = client; } /** * 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(client.getSnapshotClient(snapshot)); } /** * 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(client.getVersionClient(versionId)); } /** * Gets the URL of the blob represented by this client. * * @return the URL. */ public String getBlobUrl() { return client.getBlobUrl(); } /** * Get associated account name. * * @return account name associated with this storage resource. */ public String getAccountName() { return client.getAccountName(); } /** * Get the container name. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.blob.specialized.BlobClientBase.getContainerName} * * @return The name of the container. */ public final String getContainerName() { return client.getContainerName(); } /** * Decodes and gets the blob name. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.blob.specialized.BlobClientBase.getBlobName} * * @return The decoded name of the blob. */ public final String getBlobName() { return client.getBlobName(); } /** * Gets the {@link HttpPipeline} powering this client. * * @return The pipeline. */ public HttpPipeline getHttpPipeline() { return client.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 client.getCustomerProvidedKey(); } /** * Gets the {@code encryption scope} used to encrypt this blob's content on the server. * * @return the encryption scope used for encryption. */ String getEncryptionScope() { return client.getEncryptionScope(); } /** * Gets the service version the client is using. * * @return the service version the client is using. */ public BlobServiceVersion getServiceVersion() { return client.getServiceVersion(); } /** * Gets the snapshotId for a blob resource * * @return A string that represents the snapshotId of the snapshot blob */ public String getSnapshotId() { return client.getSnapshotId(); } /** * Gets the versionId for a blob resource * * @return A string that represents the versionId of the snapshot blob */ public String getVersionId() { return client.getVersionId(); } /** * Determines if a blob is a snapshot * * @return A boolean that indicates if a blob is a snapshot */ public boolean isSnapshot() { return client.isSnapshot(); } /** * Opens a blob input stream to download the blob. * <p> * * @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 final BlobInputStream openInputStream() { return openInputStream(null, null); } /** * Opens a blob input stream to download the specified range of the blob. * <p> * * @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 final 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. */ /** * Gets if the blob this client represents exists in the cloud. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.blob.specialized.BlobClientBase.exists} * * @return true if the blob exists, false if it doesn't */ 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> * * {@codesnippet 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 */ public Response<Boolean> existsWithResponse(Duration timeout, Context context) { Mono<Response<Boolean>> response = client.existsWithResponse(context); return blockWithOptionalTimeout(response, timeout); } /** * Copies the data at the source URL to a blob. * * <p><strong>Code Samples</strong></p> * * {@codesnippet 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. */ 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><strong>Code Samples</strong></p> * * {@codesnippet 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. * @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. */ 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><strong>Code Samples</strong></p> * * {@codesnippet 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. */ public SyncPoller<BlobCopyInfo, Void> beginCopy(BlobBeginCopyOptions options) { return client.beginCopy(options).getSyncPoller(); } /** * Stops a pending copy that was previously started and leaves a destination blob with 0 length and metadata. * * <p><strong>Code Samples</strong></p> * * {@codesnippet 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. */ 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> * * {@codesnippet 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. */ public Response<Void> abortCopyFromUrlWithResponse(String copyId, String leaseId, Duration timeout, Context context) { return blockWithOptionalTimeout(client.abortCopyFromUrlWithResponse(copyId, leaseId, context), timeout); } /** * Copies the data at the source URL to a blob and waits for the copy to complete before returning a response. * * <p><strong>Code Samples</strong></p> * * {@codesnippet 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}. */ 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><strong>Code Samples</strong></p> * * {@codesnippet 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. * @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}. */ 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><strong>Code Samples</strong></p> * * {@codesnippet 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}. */ public Response<String> copyFromUrlWithResponse(BlobCopyFromUrlOptions options, Duration timeout, Context context) { Mono<Response<String>> response = client .copyFromUrlWithResponse(options, context); return blockWithOptionalTimeout(response, timeout); } /** * 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> * * {@codesnippet com.azure.storage.blob.specialized.BlobClientBase.download * * <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 */ public void download(OutputStream stream) { downloadWithResponse(stream, null, null, null, false, null, Context.NONE); } /** * 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> * * {@codesnippet com.azure.storage.blob.specialized.BlobClientBase.downloadWithResponse * * <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 */ public BlobDownloadResponse downloadWithResponse(OutputStream stream, BlobRange range, DownloadRetryOptions options, BlobRequestConditions requestConditions, boolean getRangeContentMd5, Duration timeout, Context context) { StorageImplUtils.assertNotNull("stream", stream); Mono<BlobDownloadResponse> download = client .downloadWithResponse(range, options, requestConditions, getRangeContentMd5, context) .flatMap(response -> response.getValue().reduce(stream, (outputStream, buffer) -> { try { outputStream.write(FluxUtil.byteBufferToArray(buffer)); return outputStream; } catch (IOException ex) { throw logger.logExceptionAsError(Exceptions.propagate(new UncheckedIOException(ex))); } }).thenReturn(new BlobDownloadResponse(response))); 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> * * {@codesnippet 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 */ 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> * * {@codesnippet 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 or not to overwrite the file, should the file exist. * @return The blob properties and metadata. * @throws UncheckedIOException If an I/O error occurs */ 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> * * {@codesnippet 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. */ 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> * * {@codesnippet 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. */ 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) .setRangeGetContentMd5(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> * * {@codesnippet 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. */ 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. Note that deleting a blob also deletes all its snapshots. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.blob.specialized.BlobClientBase.delete} * * <p>For more information, see the * <a href="https: */ public void delete() { deleteWithResponse(null, null, null, Context.NONE); } /** * Deletes the specified blob or snapshot. Note that deleting a blob also deletes all its snapshots. * * <p><strong>Code Samples</strong></p> * * {@codesnippet 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. */ public Response<Void> deleteWithResponse(DeleteSnapshotsOptionType deleteBlobSnapshotOptions, BlobRequestConditions requestConditions, Duration timeout, Context context) { Mono<Response<Void>> response = client .deleteWithResponse(deleteBlobSnapshotOptions, requestConditions, context); return blockWithOptionalTimeout(response, timeout); } /** * Returns the blob's metadata and properties. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.blob.specialized.BlobClientBase.getProperties} * * <p>For more information, see the * <a href="https: * * @return The blob properties and metadata. */ public BlobProperties getProperties() { return getPropertiesWithResponse(null, null, Context.NONE).getValue(); } /** * Returns the blob's metadata and properties. * * <p><strong>Code Samples</strong></p> * * {@codesnippet 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. */ public Response<BlobProperties> getPropertiesWithResponse(BlobRequestConditions requestConditions, Duration timeout, Context context) { Mono<Response<BlobProperties>> response = client.getPropertiesWithResponse(requestConditions, context); return blockWithOptionalTimeout(response, timeout); } /** * 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> * * {@codesnippet com.azure.storage.blob.specialized.BlobClientBase.setHttpHeaders * * <p>For more information, see the * <a href="https: * * @param headers {@link BlobHttpHeaders} */ 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> * * {@codesnippet 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. */ public Response<Void> setHttpHeadersWithResponse(BlobHttpHeaders headers, BlobRequestConditions requestConditions, Duration timeout, Context context) { Mono<Response<Void>> response = client .setHttpHeadersWithResponse(headers, requestConditions, context); return blockWithOptionalTimeout(response, timeout); } /** * 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> * * {@codesnippet com.azure.storage.blob.specialized.BlobClientBase.setMetadata * * <p>For more information, see the * <a href="https: * * @param metadata Metadata to associate with the blob. */ 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> * * {@codesnippet com.azure.storage.blob.specialized.BlobClientBase.setMetadataWithResponse * * <p>For more information, see the * <a href="https: * * @param metadata Metadata to associate with the blob. * @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. */ public Response<Void> setMetadataWithResponse(Map<String, String> metadata, BlobRequestConditions requestConditions, Duration timeout, Context context) { Mono<Response<Void>> response = client.setMetadataWithResponse(metadata, requestConditions, context); return blockWithOptionalTimeout(response, timeout); } /** * Returns the blob's tags. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.blob.specialized.BlobClientBase.getTags} * * <p>For more information, see the * <a href="https: * * @return The blob's tags. */ 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> * * {@codesnippet 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. */ public Response<Map<String, String>> getTagsWithResponse(BlobGetTagsOptions options, Duration timeout, Context context) { Mono<Response<Map<String, String>>> response = client.getTagsWithResponse(options, context); return blockWithOptionalTimeout(response, timeout); } /** * 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> * * {@codesnippet com.azure.storage.blob.specialized.BlobClientBase.setTags * * <p>For more information, see the * <a href="https: * * @param tags Tags to associate with the blob. */ 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> * * {@codesnippet 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. */ public Response<Void> setTagsWithResponse(BlobSetTagsOptions options, Duration timeout, Context context) { Mono<Response<Void>> response = client.setTagsWithResponse(options, context); return blockWithOptionalTimeout(response, timeout); } /** * Creates a read-only snapshot of the blob. * * <p><strong>Code Samples</strong></p> * * {@codesnippet 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 */ 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> * * {@codesnippet com.azure.storage.blob.specialized.BlobClientBase.createSnapshotWithResponse * * <p>For more information, see the * <a href="https: * * @param metadata Metadata to associate with the blob snapshot. * @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 */ public Response<BlobClientBase> createSnapshotWithResponse(Map<String, String> metadata, BlobRequestConditions requestConditions, Duration timeout, Context context) { Mono<Response<BlobClientBase>> response = client .createSnapshotWithResponse(metadata, requestConditions, context) .map(rb -> new SimpleResponse<>(rb, new BlobClientBase(rb.getValue()))); return blockWithOptionalTimeout(response, timeout); } /** * 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> * * {@codesnippet com.azure.storage.blob.specialized.BlobClientBase.setAccessTier * * <p>For more information, see the * <a href="https: * * @param tier The new tier for the blob. */ 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> * * {@codesnippet 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. */ 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> * * {@codesnippet 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. */ public Response<Void> setAccessTierWithResponse(BlobSetAccessTierOptions options, Duration timeout, Context context) { return blockWithOptionalTimeout(client.setTierWithResponse(options, context), timeout); } /** * Undelete restores the content and metadata of a soft-deleted blob and/or any associated soft-deleted snapshots. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.blob.specialized.BlobClientBase.undelete} * * <p>For more information, see the * <a href="https: */ 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> * * {@codesnippet 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. */ public Response<Void> undeleteWithResponse(Duration timeout, Context context) { Mono<Response<Void>> response = client.undeleteWithResponse(context); return blockWithOptionalTimeout(response, timeout); } /** * Returns the sku name and account kind for the account. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.blob.specialized.BlobClientBase.getAccountInfo} * * <p>For more information, see the * <a href="https: * * @return The sku name and account kind. */ 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> * * {@codesnippet 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. */ public Response<StorageAccountInfo> getAccountInfoWithResponse(Duration timeout, Context context) { Mono<Response<StorageAccountInfo>> response = client.getAccountInfoWithResponse(context); return blockWithOptionalTimeout(response, timeout); } /** * 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> * * {@codesnippet com.azure.storage.blob.specialized.BlobClientBase.generateUserDelegationSas * * @param blobServiceSasSignatureValues {@link BlobServiceSasSignatureValues} * @param userDelegationKey A {@link UserDelegationKey} object used to sign the SAS values. * @see BlobServiceClient * user delegation key. * @return A {@code String} representing all SAS query parameters. */ public String generateUserDelegationSas(BlobServiceSasSignatureValues blobServiceSasSignatureValues, UserDelegationKey userDelegationKey) { return this.client.generateUserDelegationSas(blobServiceSasSignatureValues, userDelegationKey); } /** * Generates a service SAS for the blob using the specified {@link BlobServiceSasSignatureValues} * 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> * * {@codesnippet com.azure.storage.blob.specialized.BlobClientBase.generateSas * * @param blobServiceSasSignatureValues {@link BlobServiceSasSignatureValues} * * @return A {@code String} representing all SAS query parameters. */ public String generateSas(BlobServiceSasSignatureValues blobServiceSasSignatureValues) { return this.client.generateSas(blobServiceSasSignatureValues); } /** * Opens a blob input stream to query the blob. * * <p>For more information, see the * <a href="https: * * <p><strong>Code Samples</strong></p> * * {@codesnippet 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. */ 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> * * {@codesnippet 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. */ public Response<InputStream> openQueryInputStreamWithResponse(BlobQueryOptions queryOptions) { BlobQueryAsyncResponse response = client.queryWithResponse(queryOptions).block(); if (response == null) { throw logger.logExceptionAsError(new IllegalStateException("Query response cannot be null")); } return new ResponseBase<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), new FluxInputStream(response.getValue()), response.getDeserializedHeaders()); } /** * Queries an entire blob into an output stream. * * <p>For more information, see the * <a href="https: * * <p><strong>Code Samples</strong></p> * * {@codesnippet 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. */ 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> * * {@codesnippet 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. */ public BlobQueryResponse queryWithResponse(BlobQueryOptions queryOptions, Duration timeout, Context context) { StorageImplUtils.assertNotNull("options", queryOptions); StorageImplUtils.assertNotNull("outputStream", queryOptions.getOutputStream()); Mono<BlobQueryResponse> download = client .queryWithResponse(queryOptions, context) .flatMap(response -> response.getValue().reduce(queryOptions.getOutputStream(), (outputStream, buffer) -> { try { outputStream.write(FluxUtil.byteBufferToArray(buffer)); return outputStream; } catch (IOException ex) { throw logger.logExceptionAsError(Exceptions.propagate(new UncheckedIOException(ex))); } }).thenReturn(new BlobQueryResponse(response))); return blockWithOptionalTimeout(download, timeout); } }
Actually I think we already called getProperties before, I just moved it outside since we can't call it in the constructor before a call to super
public BlobInputStream openInputStream(BlobInputStreamOptions options) { options = options == null ? new BlobInputStreamOptions() : options; BlobRange range = options.getRange() == null ? new BlobRange(0) : options.getRange(); int chunkSize = options.getBlockSize() == null ? 4 * Constants.MB : options.getBlockSize(); return new BlobInputStream(client, range.getOffset(), range.getCount(), chunkSize, options.getRequestConditions(), getProperties()); }
return new BlobInputStream(client, range.getOffset(), range.getCount(), chunkSize,
public BlobInputStream openInputStream(BlobInputStreamOptions options) { options = options == null ? new BlobInputStreamOptions() : options; BlobRange range = options.getRange() == null ? new BlobRange(0) : options.getRange(); int chunkSize = options.getBlockSize() == null ? 4 * Constants.MB : options.getBlockSize(); return new BlobInputStream(client, range.getOffset(), range.getCount(), chunkSize, options.getRequestConditions(), getProperties()); }
class BlobClientBase { private final ClientLogger logger = new ClientLogger(BlobClientBase.class); private final BlobAsyncClientBase client; /** * Constructor used by {@link SpecializedBlobClientBuilder}. * * @param client the async blob client */ protected BlobClientBase(BlobAsyncClientBase client) { this.client = client; } /** * 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(client.getSnapshotClient(snapshot)); } /** * 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(client.getVersionClient(versionId)); } /** * Gets the URL of the blob represented by this client. * * @return the URL. */ public String getBlobUrl() { return client.getBlobUrl(); } /** * Get associated account name. * * @return account name associated with this storage resource. */ public String getAccountName() { return client.getAccountName(); } /** * Get the container name. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.blob.specialized.BlobClientBase.getContainerName} * * @return The name of the container. */ public final String getContainerName() { return client.getContainerName(); } /** * Decodes and gets the blob name. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.blob.specialized.BlobClientBase.getBlobName} * * @return The decoded name of the blob. */ public final String getBlobName() { return client.getBlobName(); } /** * Gets the {@link HttpPipeline} powering this client. * * @return The pipeline. */ public HttpPipeline getHttpPipeline() { return client.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 client.getCustomerProvidedKey(); } /** * Gets the {@code encryption scope} used to encrypt this blob's content on the server. * * @return the encryption scope used for encryption. */ String getEncryptionScope() { return client.getEncryptionScope(); } /** * Gets the service version the client is using. * * @return the service version the client is using. */ public BlobServiceVersion getServiceVersion() { return client.getServiceVersion(); } /** * Gets the snapshotId for a blob resource * * @return A string that represents the snapshotId of the snapshot blob */ public String getSnapshotId() { return client.getSnapshotId(); } /** * Gets the versionId for a blob resource * * @return A string that represents the versionId of the snapshot blob */ public String getVersionId() { return client.getVersionId(); } /** * Determines if a blob is a snapshot * * @return A boolean that indicates if a blob is a snapshot */ public boolean isSnapshot() { return client.isSnapshot(); } /** * Opens a blob input stream to download the blob. * <p> * * @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 final BlobInputStream openInputStream() { return openInputStream(null, null); } /** * Opens a blob input stream to download the specified range of the blob. * <p> * * @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 final 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. */ /** * Gets if the blob this client represents exists in the cloud. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.blob.specialized.BlobClientBase.exists} * * @return true if the blob exists, false if it doesn't */ 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> * * {@codesnippet 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 */ public Response<Boolean> existsWithResponse(Duration timeout, Context context) { Mono<Response<Boolean>> response = client.existsWithResponse(context); return blockWithOptionalTimeout(response, timeout); } /** * Copies the data at the source URL to a blob. * * <p><strong>Code Samples</strong></p> * * {@codesnippet 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. */ 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><strong>Code Samples</strong></p> * * {@codesnippet 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. * @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. */ 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><strong>Code Samples</strong></p> * * {@codesnippet 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. */ public SyncPoller<BlobCopyInfo, Void> beginCopy(BlobBeginCopyOptions options) { return client.beginCopy(options).getSyncPoller(); } /** * Stops a pending copy that was previously started and leaves a destination blob with 0 length and metadata. * * <p><strong>Code Samples</strong></p> * * {@codesnippet 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. */ 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> * * {@codesnippet 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. */ public Response<Void> abortCopyFromUrlWithResponse(String copyId, String leaseId, Duration timeout, Context context) { return blockWithOptionalTimeout(client.abortCopyFromUrlWithResponse(copyId, leaseId, context), timeout); } /** * Copies the data at the source URL to a blob and waits for the copy to complete before returning a response. * * <p><strong>Code Samples</strong></p> * * {@codesnippet 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}. */ 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><strong>Code Samples</strong></p> * * {@codesnippet 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. * @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}. */ 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><strong>Code Samples</strong></p> * * {@codesnippet 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}. */ public Response<String> copyFromUrlWithResponse(BlobCopyFromUrlOptions options, Duration timeout, Context context) { Mono<Response<String>> response = client .copyFromUrlWithResponse(options, context); return blockWithOptionalTimeout(response, timeout); } /** * 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> * * {@codesnippet com.azure.storage.blob.specialized.BlobClientBase.download * * <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 */ public void download(OutputStream stream) { downloadWithResponse(stream, null, null, null, false, null, Context.NONE); } /** * 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> * * {@codesnippet com.azure.storage.blob.specialized.BlobClientBase.downloadWithResponse * * <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 */ public BlobDownloadResponse downloadWithResponse(OutputStream stream, BlobRange range, DownloadRetryOptions options, BlobRequestConditions requestConditions, boolean getRangeContentMd5, Duration timeout, Context context) { StorageImplUtils.assertNotNull("stream", stream); Mono<BlobDownloadResponse> download = client .downloadWithResponse(range, options, requestConditions, getRangeContentMd5, context) .flatMap(response -> response.getValue().reduce(stream, (outputStream, buffer) -> { try { outputStream.write(FluxUtil.byteBufferToArray(buffer)); return outputStream; } catch (IOException ex) { throw logger.logExceptionAsError(Exceptions.propagate(new UncheckedIOException(ex))); } }).thenReturn(new BlobDownloadResponse(response))); 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> * * {@codesnippet 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 */ 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> * * {@codesnippet 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 or not to overwrite the file, should the file exist. * @return The blob properties and metadata. * @throws UncheckedIOException If an I/O error occurs */ 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> * * {@codesnippet 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. */ 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> * * {@codesnippet 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. */ 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) .setRangeGetContentMd5(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> * * {@codesnippet 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. */ 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. Note that deleting a blob also deletes all its snapshots. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.blob.specialized.BlobClientBase.delete} * * <p>For more information, see the * <a href="https: */ public void delete() { deleteWithResponse(null, null, null, Context.NONE); } /** * Deletes the specified blob or snapshot. Note that deleting a blob also deletes all its snapshots. * * <p><strong>Code Samples</strong></p> * * {@codesnippet 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. */ public Response<Void> deleteWithResponse(DeleteSnapshotsOptionType deleteBlobSnapshotOptions, BlobRequestConditions requestConditions, Duration timeout, Context context) { Mono<Response<Void>> response = client .deleteWithResponse(deleteBlobSnapshotOptions, requestConditions, context); return blockWithOptionalTimeout(response, timeout); } /** * Returns the blob's metadata and properties. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.blob.specialized.BlobClientBase.getProperties} * * <p>For more information, see the * <a href="https: * * @return The blob properties and metadata. */ public BlobProperties getProperties() { return getPropertiesWithResponse(null, null, Context.NONE).getValue(); } /** * Returns the blob's metadata and properties. * * <p><strong>Code Samples</strong></p> * * {@codesnippet 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. */ public Response<BlobProperties> getPropertiesWithResponse(BlobRequestConditions requestConditions, Duration timeout, Context context) { Mono<Response<BlobProperties>> response = client.getPropertiesWithResponse(requestConditions, context); return blockWithOptionalTimeout(response, timeout); } /** * 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> * * {@codesnippet com.azure.storage.blob.specialized.BlobClientBase.setHttpHeaders * * <p>For more information, see the * <a href="https: * * @param headers {@link BlobHttpHeaders} */ 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> * * {@codesnippet 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. */ public Response<Void> setHttpHeadersWithResponse(BlobHttpHeaders headers, BlobRequestConditions requestConditions, Duration timeout, Context context) { Mono<Response<Void>> response = client .setHttpHeadersWithResponse(headers, requestConditions, context); return blockWithOptionalTimeout(response, timeout); } /** * 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> * * {@codesnippet com.azure.storage.blob.specialized.BlobClientBase.setMetadata * * <p>For more information, see the * <a href="https: * * @param metadata Metadata to associate with the blob. */ 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> * * {@codesnippet com.azure.storage.blob.specialized.BlobClientBase.setMetadataWithResponse * * <p>For more information, see the * <a href="https: * * @param metadata Metadata to associate with the blob. * @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. */ public Response<Void> setMetadataWithResponse(Map<String, String> metadata, BlobRequestConditions requestConditions, Duration timeout, Context context) { Mono<Response<Void>> response = client.setMetadataWithResponse(metadata, requestConditions, context); return blockWithOptionalTimeout(response, timeout); } /** * Returns the blob's tags. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.blob.specialized.BlobClientBase.getTags} * * <p>For more information, see the * <a href="https: * * @return The blob's tags. */ 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> * * {@codesnippet 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. */ public Response<Map<String, String>> getTagsWithResponse(BlobGetTagsOptions options, Duration timeout, Context context) { Mono<Response<Map<String, String>>> response = client.getTagsWithResponse(options, context); return blockWithOptionalTimeout(response, timeout); } /** * 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> * * {@codesnippet com.azure.storage.blob.specialized.BlobClientBase.setTags * * <p>For more information, see the * <a href="https: * * @param tags Tags to associate with the blob. */ 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> * * {@codesnippet 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. */ public Response<Void> setTagsWithResponse(BlobSetTagsOptions options, Duration timeout, Context context) { Mono<Response<Void>> response = client.setTagsWithResponse(options, context); return blockWithOptionalTimeout(response, timeout); } /** * Creates a read-only snapshot of the blob. * * <p><strong>Code Samples</strong></p> * * {@codesnippet 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 */ 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> * * {@codesnippet com.azure.storage.blob.specialized.BlobClientBase.createSnapshotWithResponse * * <p>For more information, see the * <a href="https: * * @param metadata Metadata to associate with the blob snapshot. * @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 */ public Response<BlobClientBase> createSnapshotWithResponse(Map<String, String> metadata, BlobRequestConditions requestConditions, Duration timeout, Context context) { Mono<Response<BlobClientBase>> response = client .createSnapshotWithResponse(metadata, requestConditions, context) .map(rb -> new SimpleResponse<>(rb, new BlobClientBase(rb.getValue()))); return blockWithOptionalTimeout(response, timeout); } /** * 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> * * {@codesnippet com.azure.storage.blob.specialized.BlobClientBase.setAccessTier * * <p>For more information, see the * <a href="https: * * @param tier The new tier for the blob. */ 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> * * {@codesnippet 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. */ 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> * * {@codesnippet 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. */ public Response<Void> setAccessTierWithResponse(BlobSetAccessTierOptions options, Duration timeout, Context context) { return blockWithOptionalTimeout(client.setTierWithResponse(options, context), timeout); } /** * Undelete restores the content and metadata of a soft-deleted blob and/or any associated soft-deleted snapshots. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.blob.specialized.BlobClientBase.undelete} * * <p>For more information, see the * <a href="https: */ 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> * * {@codesnippet 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. */ public Response<Void> undeleteWithResponse(Duration timeout, Context context) { Mono<Response<Void>> response = client.undeleteWithResponse(context); return blockWithOptionalTimeout(response, timeout); } /** * Returns the sku name and account kind for the account. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.blob.specialized.BlobClientBase.getAccountInfo} * * <p>For more information, see the * <a href="https: * * @return The sku name and account kind. */ 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> * * {@codesnippet 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. */ public Response<StorageAccountInfo> getAccountInfoWithResponse(Duration timeout, Context context) { Mono<Response<StorageAccountInfo>> response = client.getAccountInfoWithResponse(context); return blockWithOptionalTimeout(response, timeout); } /** * 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> * * {@codesnippet com.azure.storage.blob.specialized.BlobClientBase.generateUserDelegationSas * * @param blobServiceSasSignatureValues {@link BlobServiceSasSignatureValues} * @param userDelegationKey A {@link UserDelegationKey} object used to sign the SAS values. * @see BlobServiceClient * user delegation key. * @return A {@code String} representing all SAS query parameters. */ public String generateUserDelegationSas(BlobServiceSasSignatureValues blobServiceSasSignatureValues, UserDelegationKey userDelegationKey) { return this.client.generateUserDelegationSas(blobServiceSasSignatureValues, userDelegationKey); } /** * Generates a service SAS for the blob using the specified {@link BlobServiceSasSignatureValues} * 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> * * {@codesnippet com.azure.storage.blob.specialized.BlobClientBase.generateSas * * @param blobServiceSasSignatureValues {@link BlobServiceSasSignatureValues} * * @return A {@code String} representing all SAS query parameters. */ public String generateSas(BlobServiceSasSignatureValues blobServiceSasSignatureValues) { return this.client.generateSas(blobServiceSasSignatureValues); } /** * Opens a blob input stream to query the blob. * * <p>For more information, see the * <a href="https: * * <p><strong>Code Samples</strong></p> * * {@codesnippet 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. */ 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> * * {@codesnippet 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. */ public Response<InputStream> openQueryInputStreamWithResponse(BlobQueryOptions queryOptions) { BlobQueryAsyncResponse response = client.queryWithResponse(queryOptions).block(); if (response == null) { throw logger.logExceptionAsError(new IllegalStateException("Query response cannot be null")); } return new ResponseBase<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), new FluxInputStream(response.getValue()), response.getDeserializedHeaders()); } /** * Queries an entire blob into an output stream. * * <p>For more information, see the * <a href="https: * * <p><strong>Code Samples</strong></p> * * {@codesnippet 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. */ 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> * * {@codesnippet 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. */ public BlobQueryResponse queryWithResponse(BlobQueryOptions queryOptions, Duration timeout, Context context) { StorageImplUtils.assertNotNull("options", queryOptions); StorageImplUtils.assertNotNull("outputStream", queryOptions.getOutputStream()); Mono<BlobQueryResponse> download = client .queryWithResponse(queryOptions, context) .flatMap(response -> response.getValue().reduce(queryOptions.getOutputStream(), (outputStream, buffer) -> { try { outputStream.write(FluxUtil.byteBufferToArray(buffer)); return outputStream; } catch (IOException ex) { throw logger.logExceptionAsError(Exceptions.propagate(new UncheckedIOException(ex))); } }).thenReturn(new BlobQueryResponse(response))); return blockWithOptionalTimeout(download, timeout); } }
class BlobClientBase { private final ClientLogger logger = new ClientLogger(BlobClientBase.class); private final BlobAsyncClientBase client; /** * Constructor used by {@link SpecializedBlobClientBuilder}. * * @param client the async blob client */ protected BlobClientBase(BlobAsyncClientBase client) { this.client = client; } /** * 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(client.getSnapshotClient(snapshot)); } /** * 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(client.getVersionClient(versionId)); } /** * Gets the URL of the blob represented by this client. * * @return the URL. */ public String getBlobUrl() { return client.getBlobUrl(); } /** * Get associated account name. * * @return account name associated with this storage resource. */ public String getAccountName() { return client.getAccountName(); } /** * Get the container name. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.blob.specialized.BlobClientBase.getContainerName} * * @return The name of the container. */ public final String getContainerName() { return client.getContainerName(); } /** * Decodes and gets the blob name. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.blob.specialized.BlobClientBase.getBlobName} * * @return The decoded name of the blob. */ public final String getBlobName() { return client.getBlobName(); } /** * Gets the {@link HttpPipeline} powering this client. * * @return The pipeline. */ public HttpPipeline getHttpPipeline() { return client.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 client.getCustomerProvidedKey(); } /** * Gets the {@code encryption scope} used to encrypt this blob's content on the server. * * @return the encryption scope used for encryption. */ String getEncryptionScope() { return client.getEncryptionScope(); } /** * Gets the service version the client is using. * * @return the service version the client is using. */ public BlobServiceVersion getServiceVersion() { return client.getServiceVersion(); } /** * Gets the snapshotId for a blob resource * * @return A string that represents the snapshotId of the snapshot blob */ public String getSnapshotId() { return client.getSnapshotId(); } /** * Gets the versionId for a blob resource * * @return A string that represents the versionId of the snapshot blob */ public String getVersionId() { return client.getVersionId(); } /** * Determines if a blob is a snapshot * * @return A boolean that indicates if a blob is a snapshot */ public boolean isSnapshot() { return client.isSnapshot(); } /** * Opens a blob input stream to download the blob. * <p> * * @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 final BlobInputStream openInputStream() { return openInputStream(null, null); } /** * Opens a blob input stream to download the specified range of the blob. * <p> * * @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 final 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. */ /** * Gets if the blob this client represents exists in the cloud. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.blob.specialized.BlobClientBase.exists} * * @return true if the blob exists, false if it doesn't */ 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> * * {@codesnippet 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 */ public Response<Boolean> existsWithResponse(Duration timeout, Context context) { Mono<Response<Boolean>> response = client.existsWithResponse(context); return blockWithOptionalTimeout(response, timeout); } /** * Copies the data at the source URL to a blob. * * <p><strong>Code Samples</strong></p> * * {@codesnippet 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. */ 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><strong>Code Samples</strong></p> * * {@codesnippet 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. * @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. */ 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><strong>Code Samples</strong></p> * * {@codesnippet 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. */ public SyncPoller<BlobCopyInfo, Void> beginCopy(BlobBeginCopyOptions options) { return client.beginCopy(options).getSyncPoller(); } /** * Stops a pending copy that was previously started and leaves a destination blob with 0 length and metadata. * * <p><strong>Code Samples</strong></p> * * {@codesnippet 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. */ 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> * * {@codesnippet 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. */ public Response<Void> abortCopyFromUrlWithResponse(String copyId, String leaseId, Duration timeout, Context context) { return blockWithOptionalTimeout(client.abortCopyFromUrlWithResponse(copyId, leaseId, context), timeout); } /** * Copies the data at the source URL to a blob and waits for the copy to complete before returning a response. * * <p><strong>Code Samples</strong></p> * * {@codesnippet 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}. */ 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><strong>Code Samples</strong></p> * * {@codesnippet 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. * @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}. */ 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><strong>Code Samples</strong></p> * * {@codesnippet 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}. */ public Response<String> copyFromUrlWithResponse(BlobCopyFromUrlOptions options, Duration timeout, Context context) { Mono<Response<String>> response = client .copyFromUrlWithResponse(options, context); return blockWithOptionalTimeout(response, timeout); } /** * 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> * * {@codesnippet com.azure.storage.blob.specialized.BlobClientBase.download * * <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 */ public void download(OutputStream stream) { downloadWithResponse(stream, null, null, null, false, null, Context.NONE); } /** * 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> * * {@codesnippet com.azure.storage.blob.specialized.BlobClientBase.downloadWithResponse * * <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 */ public BlobDownloadResponse downloadWithResponse(OutputStream stream, BlobRange range, DownloadRetryOptions options, BlobRequestConditions requestConditions, boolean getRangeContentMd5, Duration timeout, Context context) { StorageImplUtils.assertNotNull("stream", stream); Mono<BlobDownloadResponse> download = client .downloadWithResponse(range, options, requestConditions, getRangeContentMd5, context) .flatMap(response -> response.getValue().reduce(stream, (outputStream, buffer) -> { try { outputStream.write(FluxUtil.byteBufferToArray(buffer)); return outputStream; } catch (IOException ex) { throw logger.logExceptionAsError(Exceptions.propagate(new UncheckedIOException(ex))); } }).thenReturn(new BlobDownloadResponse(response))); 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> * * {@codesnippet 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 */ 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> * * {@codesnippet 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 or not to overwrite the file, should the file exist. * @return The blob properties and metadata. * @throws UncheckedIOException If an I/O error occurs */ 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> * * {@codesnippet 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. */ 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> * * {@codesnippet 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. */ 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) .setRangeGetContentMd5(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> * * {@codesnippet 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. */ 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. Note that deleting a blob also deletes all its snapshots. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.blob.specialized.BlobClientBase.delete} * * <p>For more information, see the * <a href="https: */ public void delete() { deleteWithResponse(null, null, null, Context.NONE); } /** * Deletes the specified blob or snapshot. Note that deleting a blob also deletes all its snapshots. * * <p><strong>Code Samples</strong></p> * * {@codesnippet 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. */ public Response<Void> deleteWithResponse(DeleteSnapshotsOptionType deleteBlobSnapshotOptions, BlobRequestConditions requestConditions, Duration timeout, Context context) { Mono<Response<Void>> response = client .deleteWithResponse(deleteBlobSnapshotOptions, requestConditions, context); return blockWithOptionalTimeout(response, timeout); } /** * Returns the blob's metadata and properties. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.blob.specialized.BlobClientBase.getProperties} * * <p>For more information, see the * <a href="https: * * @return The blob properties and metadata. */ public BlobProperties getProperties() { return getPropertiesWithResponse(null, null, Context.NONE).getValue(); } /** * Returns the blob's metadata and properties. * * <p><strong>Code Samples</strong></p> * * {@codesnippet 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. */ public Response<BlobProperties> getPropertiesWithResponse(BlobRequestConditions requestConditions, Duration timeout, Context context) { Mono<Response<BlobProperties>> response = client.getPropertiesWithResponse(requestConditions, context); return blockWithOptionalTimeout(response, timeout); } /** * 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> * * {@codesnippet com.azure.storage.blob.specialized.BlobClientBase.setHttpHeaders * * <p>For more information, see the * <a href="https: * * @param headers {@link BlobHttpHeaders} */ 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> * * {@codesnippet 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. */ public Response<Void> setHttpHeadersWithResponse(BlobHttpHeaders headers, BlobRequestConditions requestConditions, Duration timeout, Context context) { Mono<Response<Void>> response = client .setHttpHeadersWithResponse(headers, requestConditions, context); return blockWithOptionalTimeout(response, timeout); } /** * 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> * * {@codesnippet com.azure.storage.blob.specialized.BlobClientBase.setMetadata * * <p>For more information, see the * <a href="https: * * @param metadata Metadata to associate with the blob. */ 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> * * {@codesnippet com.azure.storage.blob.specialized.BlobClientBase.setMetadataWithResponse * * <p>For more information, see the * <a href="https: * * @param metadata Metadata to associate with the blob. * @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. */ public Response<Void> setMetadataWithResponse(Map<String, String> metadata, BlobRequestConditions requestConditions, Duration timeout, Context context) { Mono<Response<Void>> response = client.setMetadataWithResponse(metadata, requestConditions, context); return blockWithOptionalTimeout(response, timeout); } /** * Returns the blob's tags. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.blob.specialized.BlobClientBase.getTags} * * <p>For more information, see the * <a href="https: * * @return The blob's tags. */ 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> * * {@codesnippet 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. */ public Response<Map<String, String>> getTagsWithResponse(BlobGetTagsOptions options, Duration timeout, Context context) { Mono<Response<Map<String, String>>> response = client.getTagsWithResponse(options, context); return blockWithOptionalTimeout(response, timeout); } /** * 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> * * {@codesnippet com.azure.storage.blob.specialized.BlobClientBase.setTags * * <p>For more information, see the * <a href="https: * * @param tags Tags to associate with the blob. */ 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> * * {@codesnippet 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. */ public Response<Void> setTagsWithResponse(BlobSetTagsOptions options, Duration timeout, Context context) { Mono<Response<Void>> response = client.setTagsWithResponse(options, context); return blockWithOptionalTimeout(response, timeout); } /** * Creates a read-only snapshot of the blob. * * <p><strong>Code Samples</strong></p> * * {@codesnippet 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 */ 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> * * {@codesnippet com.azure.storage.blob.specialized.BlobClientBase.createSnapshotWithResponse * * <p>For more information, see the * <a href="https: * * @param metadata Metadata to associate with the blob snapshot. * @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 */ public Response<BlobClientBase> createSnapshotWithResponse(Map<String, String> metadata, BlobRequestConditions requestConditions, Duration timeout, Context context) { Mono<Response<BlobClientBase>> response = client .createSnapshotWithResponse(metadata, requestConditions, context) .map(rb -> new SimpleResponse<>(rb, new BlobClientBase(rb.getValue()))); return blockWithOptionalTimeout(response, timeout); } /** * 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> * * {@codesnippet com.azure.storage.blob.specialized.BlobClientBase.setAccessTier * * <p>For more information, see the * <a href="https: * * @param tier The new tier for the blob. */ 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> * * {@codesnippet 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. */ 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> * * {@codesnippet 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. */ public Response<Void> setAccessTierWithResponse(BlobSetAccessTierOptions options, Duration timeout, Context context) { return blockWithOptionalTimeout(client.setTierWithResponse(options, context), timeout); } /** * Undelete restores the content and metadata of a soft-deleted blob and/or any associated soft-deleted snapshots. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.blob.specialized.BlobClientBase.undelete} * * <p>For more information, see the * <a href="https: */ 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> * * {@codesnippet 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. */ public Response<Void> undeleteWithResponse(Duration timeout, Context context) { Mono<Response<Void>> response = client.undeleteWithResponse(context); return blockWithOptionalTimeout(response, timeout); } /** * Returns the sku name and account kind for the account. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.blob.specialized.BlobClientBase.getAccountInfo} * * <p>For more information, see the * <a href="https: * * @return The sku name and account kind. */ 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> * * {@codesnippet 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. */ public Response<StorageAccountInfo> getAccountInfoWithResponse(Duration timeout, Context context) { Mono<Response<StorageAccountInfo>> response = client.getAccountInfoWithResponse(context); return blockWithOptionalTimeout(response, timeout); } /** * 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> * * {@codesnippet com.azure.storage.blob.specialized.BlobClientBase.generateUserDelegationSas * * @param blobServiceSasSignatureValues {@link BlobServiceSasSignatureValues} * @param userDelegationKey A {@link UserDelegationKey} object used to sign the SAS values. * @see BlobServiceClient * user delegation key. * @return A {@code String} representing all SAS query parameters. */ public String generateUserDelegationSas(BlobServiceSasSignatureValues blobServiceSasSignatureValues, UserDelegationKey userDelegationKey) { return this.client.generateUserDelegationSas(blobServiceSasSignatureValues, userDelegationKey); } /** * Generates a service SAS for the blob using the specified {@link BlobServiceSasSignatureValues} * 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> * * {@codesnippet com.azure.storage.blob.specialized.BlobClientBase.generateSas * * @param blobServiceSasSignatureValues {@link BlobServiceSasSignatureValues} * * @return A {@code String} representing all SAS query parameters. */ public String generateSas(BlobServiceSasSignatureValues blobServiceSasSignatureValues) { return this.client.generateSas(blobServiceSasSignatureValues); } /** * Opens a blob input stream to query the blob. * * <p>For more information, see the * <a href="https: * * <p><strong>Code Samples</strong></p> * * {@codesnippet 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. */ 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> * * {@codesnippet 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. */ public Response<InputStream> openQueryInputStreamWithResponse(BlobQueryOptions queryOptions) { BlobQueryAsyncResponse response = client.queryWithResponse(queryOptions).block(); if (response == null) { throw logger.logExceptionAsError(new IllegalStateException("Query response cannot be null")); } return new ResponseBase<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), new FluxInputStream(response.getValue()), response.getDeserializedHeaders()); } /** * Queries an entire blob into an output stream. * * <p>For more information, see the * <a href="https: * * <p><strong>Code Samples</strong></p> * * {@codesnippet 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. */ 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> * * {@codesnippet 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. */ public BlobQueryResponse queryWithResponse(BlobQueryOptions queryOptions, Duration timeout, Context context) { StorageImplUtils.assertNotNull("options", queryOptions); StorageImplUtils.assertNotNull("outputStream", queryOptions.getOutputStream()); Mono<BlobQueryResponse> download = client .queryWithResponse(queryOptions, context) .flatMap(response -> response.getValue().reduce(queryOptions.getOutputStream(), (outputStream, buffer) -> { try { outputStream.write(FluxUtil.byteBufferToArray(buffer)); return outputStream; } catch (IOException ex) { throw logger.logExceptionAsError(Exceptions.propagate(new UncheckedIOException(ex))); } }).thenReturn(new BlobQueryResponse(response))); return blockWithOptionalTimeout(download, timeout); } }
Is this the default value for authority host? `new IdentityClientOptions().getAuthorityHost()`
public TokenCredential getCredentials(String normalizedName) { final String clientId = getPropertyValue(normalizedName, Property.CLIENT_ID); final String clientKey = getPropertyValue(normalizedName, Property.CLIENT_KEY); final String tenantId = getPropertyValue(normalizedName, Property.TENANT_ID); final String certificatePath = getPropertyValue(normalizedName, Property.CERTIFICATE_PATH); final String certificatePassword = getPropertyValue(normalizedName, Property.CERTIFICATE_PASSWORD); final String authorityHost = getPropertyValue(normalizedName, Property.AUTHORITY_HOST) == null ? new IdentityClientOptions().getAuthorityHost() : getPropertyValue(normalizedName, Property.AUTHORITY_HOST); if (clientId != null && tenantId != null && clientKey != null ) { LOGGER.debug("Will use custom credentials"); return new ClientSecretCredentialBuilder() .clientId(clientId) .clientSecret(clientKey) .tenantId(tenantId) .authorityHost(authorityHost) .build(); } if (clientId != null && tenantId != null && certificatePath != null ) { if (StringUtils.isEmpty(certificatePassword)) { return new ClientCertificateCredentialBuilder() .tenantId(tenantId) .clientId(clientId) .pemCertificate(certificatePath) .authorityHost(authorityHost) .build(); } else { return new ClientCertificateCredentialBuilder() .tenantId(tenantId) .clientId(clientId) .authorityHost(authorityHost) .pfxCertificate(certificatePath, certificatePassword) .build(); } } if (clientId != null) { LOGGER.debug("Will use MSI credentials with specified clientId"); return new ManagedIdentityCredentialBuilder().clientId(clientId).build(); } LOGGER.debug("Will use MSI credentials"); return new ManagedIdentityCredentialBuilder().build(); }
new IdentityClientOptions().getAuthorityHost() : getPropertyValue(normalizedName, Property.AUTHORITY_HOST);
public TokenCredential getCredentials(String normalizedName) { final String clientId = getPropertyValue(normalizedName, Property.CLIENT_ID); final String clientKey = getPropertyValue(normalizedName, Property.CLIENT_KEY); final String tenantId = getPropertyValue(normalizedName, Property.TENANT_ID); final String certificatePath = getPropertyValue(normalizedName, Property.CERTIFICATE_PATH); final String certificatePassword = getPropertyValue(normalizedName, Property.CERTIFICATE_PASSWORD); final String authorityHost = getPropertyValue(normalizedName, Property.AUTHORITY_HOST) == null ? new IdentityClientOptions().getAuthorityHost() : getPropertyValue(normalizedName, Property.AUTHORITY_HOST); if (clientId != null && tenantId != null && clientKey != null ) { LOGGER.debug("Will use custom credentials"); return new ClientSecretCredentialBuilder() .clientId(clientId) .clientSecret(clientKey) .tenantId(tenantId) .authorityHost(authorityHost) .build(); } if (clientId != null && tenantId != null && certificatePath != null ) { if (StringUtils.isEmpty(certificatePassword)) { return new ClientCertificateCredentialBuilder() .tenantId(tenantId) .clientId(clientId) .pemCertificate(certificatePath) .authorityHost(authorityHost) .build(); } else { return new ClientCertificateCredentialBuilder() .tenantId(tenantId) .clientId(clientId) .authorityHost(authorityHost) .pfxCertificate(certificatePath, certificatePassword) .build(); } } if (clientId != null) { LOGGER.debug("Will use MSI credentials with specified clientId"); return new ManagedIdentityCredentialBuilder().clientId(clientId).build(); } LOGGER.debug("Will use MSI credentials"); return new ManagedIdentityCredentialBuilder().build(); }
class KeyVaultEnvironmentPostProcessorHelper { private static final Logger LOGGER = LoggerFactory.getLogger(KeyVaultEnvironmentPostProcessorHelper.class); private final ConfigurableEnvironment environment; KeyVaultEnvironmentPostProcessorHelper(final ConfigurableEnvironment environment) { this.environment = environment; Assert.notNull(environment, "environment must not be null!"); sendTelemetry(); } /** * Add a key vault property source. * * <p> * The normalizedName is used to target a specific key vault (note if the name is the empty string it works as * before with only one key vault present). The normalized name is the name of the specific key vault plus a * trailing "." at the end. * </p> * * @param normalizedName the normalized name. */ public void addKeyVaultPropertySource(String normalizedName) { final String vaultUri = getPropertyValue(normalizedName, Property.URI); Assert.notNull(vaultUri, "vaultUri must not be null!"); final Long refreshInterval = Optional.ofNullable(getPropertyValue(normalizedName, Property.REFRESH_INTERVAL)) .map(Long::valueOf) .orElse(DEFAULT_REFRESH_INTERVAL_MS); final List<String> secretKeys = Binder.get(this.environment) .bind( KeyVaultProperties.getPropertyName(normalizedName, Property.SECRET_KEYS), Bindable.listOf(String.class) ) .orElse(Collections.emptyList()); final TokenCredential tokenCredential = getCredentials(normalizedName); final SecretClient secretClient = new SecretClientBuilder() .vaultUrl(vaultUri) .credential(tokenCredential) .serviceVersion(SecretServiceVersion.V7_0) .httpLogOptions(new HttpLogOptions().setApplicationId(AZURE_SPRING_KEY_VAULT)) .buildClient(); try { final MutablePropertySources sources = this.environment.getPropertySources(); final boolean caseSensitive = Boolean .parseBoolean(getPropertyValue(normalizedName, Property.CASE_SENSITIVE_KEYS)); final KeyVaultOperation keyVaultOperation = new KeyVaultOperation( secretClient, refreshInterval, secretKeys, caseSensitive); String propertySourceName = Optional.of(normalizedName) .map(String::trim) .filter(s -> !s.isEmpty()) .orElse(AZURE_KEYVAULT_PROPERTYSOURCE_NAME); KeyVaultPropertySource keyVaultPropertySource = new KeyVaultPropertySource(propertySourceName, keyVaultOperation); if (sources.contains(SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME)) { sources.addAfter( SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME, keyVaultPropertySource ); } else { sources.addFirst(keyVaultPropertySource); } } catch (final Exception ex) { throw new IllegalStateException("Failed to configure KeyVault property source", ex); } } /** * Get the token credentials. * * @return the token credentials. */ public TokenCredential getCredentials() { return getCredentials(""); } /** * Get the token credentials. * * @param normalizedName the normalized name of the key vault. * @return the token credentials. */ private String getPropertyValue(final Property property) { return Optional.of(property) .map(KeyVaultProperties::getPropertyName) .map(environment::getProperty) .orElse(null); } private String getPropertyValue( final String normalizedName, final Property property ) { return Optional.of(KeyVaultProperties.getPropertyName(normalizedName, property)) .map(environment::getProperty) .orElse(null); } private boolean allowTelemetry() { return Boolean.parseBoolean(getPropertyValue(Property.ALLOW_TELEMETRY)); } private void sendTelemetry() { if (allowTelemetry()) { final Map<String, String> events = new HashMap<>(); final TelemetrySender sender = new TelemetrySender(); events.put(SERVICE_NAME, getClassPackageSimpleName(KeyVaultEnvironmentPostProcessorHelper.class)); sender.send(ClassUtils.getUserClass(getClass()).getSimpleName(), events); } } }
class KeyVaultEnvironmentPostProcessorHelper { private static final Logger LOGGER = LoggerFactory.getLogger(KeyVaultEnvironmentPostProcessorHelper.class); private final ConfigurableEnvironment environment; KeyVaultEnvironmentPostProcessorHelper(final ConfigurableEnvironment environment) { this.environment = environment; Assert.notNull(environment, "environment must not be null!"); sendTelemetry(); } /** * Add a key vault property source. * * <p> * The normalizedName is used to target a specific key vault (note if the name is the empty string it works as * before with only one key vault present). The normalized name is the name of the specific key vault plus a * trailing "." at the end. * </p> * * @param normalizedName the normalized name. */ public void addKeyVaultPropertySource(String normalizedName) { final String vaultUri = getPropertyValue(normalizedName, Property.URI); final String version = getPropertyValue(normalizedName, Property.SECRET_SERVICE_VERSION); SecretServiceVersion secretServiceVersion = Arrays.stream(SecretServiceVersion.values()) .filter(val -> val.getVersion().equals(version)) .findFirst() .orElse(null); Assert.notNull(vaultUri, "vaultUri must not be null!"); final Long refreshInterval = Optional.ofNullable(getPropertyValue(normalizedName, Property.REFRESH_INTERVAL)) .map(Long::valueOf) .orElse(DEFAULT_REFRESH_INTERVAL_MS); final List<String> secretKeys = Binder.get(this.environment) .bind( KeyVaultProperties.getPropertyName(normalizedName, Property.SECRET_KEYS), Bindable.listOf(String.class) ) .orElse(Collections.emptyList()); final TokenCredential tokenCredential = getCredentials(normalizedName); final SecretClient secretClient = new SecretClientBuilder() .vaultUrl(vaultUri) .credential(tokenCredential) .serviceVersion(secretServiceVersion) .httpLogOptions(new HttpLogOptions().setApplicationId(AZURE_SPRING_KEY_VAULT)) .buildClient(); try { final MutablePropertySources sources = this.environment.getPropertySources(); final boolean caseSensitive = Boolean .parseBoolean(getPropertyValue(normalizedName, Property.CASE_SENSITIVE_KEYS)); final KeyVaultOperation keyVaultOperation = new KeyVaultOperation( secretClient, refreshInterval, secretKeys, caseSensitive); String propertySourceName = Optional.of(normalizedName) .map(String::trim) .filter(s -> !s.isEmpty()) .orElse(AZURE_KEYVAULT_PROPERTYSOURCE_NAME); KeyVaultPropertySource keyVaultPropertySource = new KeyVaultPropertySource(propertySourceName, keyVaultOperation); if (sources.contains(SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME)) { sources.addAfter( SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME, keyVaultPropertySource ); } else { sources.addFirst(keyVaultPropertySource); } } catch (final Exception ex) { throw new IllegalStateException("Failed to configure KeyVault property source", ex); } } /** * Get the token credentials. * * @return the token credentials. */ public TokenCredential getCredentials() { return getCredentials(""); } /** * Get the token credentials. * * @param normalizedName the normalized name of the key vault. * @return the token credentials. */ private String getPropertyValue(final Property property) { return Optional.of(property) .map(KeyVaultProperties::getPropertyName) .map(environment::getProperty) .orElse(null); } private String getPropertyValue( final String normalizedName, final Property property ) { return Optional.of(KeyVaultProperties.getPropertyName(normalizedName, property)) .map(environment::getProperty) .orElse(null); } private boolean allowTelemetry() { return Boolean.parseBoolean(getPropertyValue(Property.ALLOW_TELEMETRY)); } private void sendTelemetry() { if (allowTelemetry()) { final Map<String, String> events = new HashMap<>(); final TelemetrySender sender = new TelemetrySender(); events.put(SERVICE_NAME, getClassPackageSimpleName(KeyVaultEnvironmentPostProcessorHelper.class)); sender.send(ClassUtils.getUserClass(getClass()).getSimpleName(), events); } } }
loggger.info is too noisy for the test.
public void readAllItemsByPageWithCosmosPagedIterableHandler() throws Exception { CosmosQueryRequestOptions cosmosQueryRequestOptions = new CosmosQueryRequestOptions(); CosmosPagedIterable<InternalObjectNode> cosmosPagedIterable = cosmosContainer.readAllItems(cosmosQueryRequestOptions, InternalObjectNode.class); AtomicInteger handleCount = new AtomicInteger(); cosmosPagedIterable = cosmosPagedIterable.handle(feedResponse -> { CosmosDiagnostics cosmosDiagnostics = feedResponse.getCosmosDiagnostics(); logger.info("Cosmos Diagnostics : {}", cosmosDiagnostics); if (cosmosDiagnostics != null) { handleCount.incrementAndGet(); } }); AtomicInteger itemCount = new AtomicInteger(); AtomicInteger feedResponseCount = new AtomicInteger(); cosmosPagedIterable.iterableByPage().forEach(feedResponse -> { feedResponseCount.incrementAndGet(); int size = feedResponse.getResults().size(); itemCount.addAndGet(size); }); assertThat(handleCount.get() >= 1).isTrue(); assertThat(handleCount.get()).isEqualTo(feedResponseCount.get()); assertThat(itemCount.get()).isEqualTo(NUM_OF_ITEMS); }
logger.info("Cosmos Diagnostics : {}", cosmosDiagnostics);
public void readAllItemsByPageWithCosmosPagedIterableHandler() throws Exception { CosmosQueryRequestOptions cosmosQueryRequestOptions = new CosmosQueryRequestOptions(); CosmosPagedIterable<ObjectNode> cosmosPagedIterable = cosmosContainer.readAllItems(cosmosQueryRequestOptions, ObjectNode.class); AtomicInteger handleCount = new AtomicInteger(); cosmosPagedIterable = cosmosPagedIterable.handle(feedResponse -> { CosmosDiagnostics cosmosDiagnostics = feedResponse.getCosmosDiagnostics(); if (cosmosDiagnostics != null) { handleCount.incrementAndGet(); } }); AtomicInteger feedResponseCount = new AtomicInteger(); cosmosPagedIterable.iterableByPage().forEach(feedResponse -> { feedResponseCount.incrementAndGet(); }); assertThat(handleCount.get() >= 1).isTrue(); assertThat(handleCount.get()).isEqualTo(feedResponseCount.get()); }
class CosmosPagedIterableTest extends TestSuiteBase { private static final int NUM_OF_ITEMS = 10; private CosmosClient cosmosClient; private CosmosContainer cosmosContainer; @Factory(dataProvider = "clientBuilders") public CosmosPagedIterableTest(CosmosClientBuilder clientBuilder) { super(clientBuilder); } @BeforeClass(groups = { "simple" }, timeOut = SETUP_TIMEOUT) public void before_CosmosPagedIterableTest() { assertThat(this.cosmosClient).isNull(); this.cosmosClient = getClientBuilder().buildClient(); CosmosAsyncContainer asyncContainer = getSharedMultiPartitionCosmosContainer(this.cosmosClient.asyncClient()); cosmosContainer = cosmosClient.getDatabase(asyncContainer.getDatabase().getId()).getContainer(asyncContainer.getId()); createItems(NUM_OF_ITEMS); } @AfterClass(groups = { "simple" }, timeOut = SHUTDOWN_TIMEOUT, alwaysRun = true) public void afterClass() { assertThat(this.cosmosClient).isNotNull(); this.cosmosClient.close(); } @Test(groups = { "simple" }, timeOut = TIMEOUT) @Test(groups = { "simple" }, timeOut = TIMEOUT) public void readAllItemsBySubscribeWithCosmosPagedIterableHandler() throws Exception { CosmosQueryRequestOptions cosmosQueryRequestOptions = new CosmosQueryRequestOptions(); CosmosPagedIterable<InternalObjectNode> cosmosPagedIterable = cosmosContainer.readAllItems(cosmosQueryRequestOptions, InternalObjectNode.class); AtomicInteger handleCount = new AtomicInteger(); cosmosPagedIterable = cosmosPagedIterable.handle(feedResponse -> { CosmosDiagnostics cosmosDiagnostics = feedResponse.getCosmosDiagnostics(); logger.info("Cosmos Diagnostics : {}", cosmosDiagnostics); if (cosmosDiagnostics != null) { handleCount.incrementAndGet(); } }); AtomicInteger itemCount = new AtomicInteger(); cosmosPagedIterable.forEach(internalObjectNode -> { itemCount.incrementAndGet(); }); assertThat(handleCount.get() >= 1).isTrue(); assertThat(itemCount.get()).isEqualTo(NUM_OF_ITEMS); } private void createItems(int numOfItems) { for (int i = 0; i < numOfItems; i++) { InternalObjectNode properties = getDocumentDefinition(UUID.randomUUID().toString()); cosmosContainer.createItem(properties); } } private InternalObjectNode getDocumentDefinition(String documentId) { final String uuid = UUID.randomUUID().toString(); final InternalObjectNode properties = new InternalObjectNode(String.format("{ " + "\"id\": \"%s\", " + "\"mypk\": \"%s\", " + "\"sgmts\": [[6519456, 1471916863], [2498434, 1455671440]]" + "}" , documentId, uuid)); return properties; } }
class CosmosPagedIterableTest extends TestSuiteBase { private static final int NUM_OF_ITEMS = 10; private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper(); private CosmosClient cosmosClient; private CosmosContainer cosmosContainer; @Factory(dataProvider = "clientBuildersWithDirectSession") public CosmosPagedIterableTest(CosmosClientBuilder clientBuilder) { super(clientBuilder); } @BeforeClass(groups = { "simple" }, timeOut = SETUP_TIMEOUT) public void before_CosmosPagedIterableTest() throws JsonProcessingException { assertThat(this.cosmosClient).isNull(); this.cosmosClient = getClientBuilder().buildClient(); CosmosAsyncContainer asyncContainer = getSharedMultiPartitionCosmosContainer(this.cosmosClient.asyncClient()); cosmosContainer = cosmosClient.getDatabase(asyncContainer.getDatabase().getId()).getContainer(asyncContainer.getId()); createItems(NUM_OF_ITEMS); } @AfterClass(groups = { "simple" }, timeOut = SHUTDOWN_TIMEOUT, alwaysRun = true) public void afterClass() { assertThat(this.cosmosClient).isNotNull(); this.cosmosClient.close(); } @Test(groups = { "simple" }, timeOut = TIMEOUT) @Test(groups = { "simple" }, timeOut = TIMEOUT) public void readAllItemsBySubscribeWithCosmosPagedIterableHandler() throws Exception { CosmosQueryRequestOptions cosmosQueryRequestOptions = new CosmosQueryRequestOptions(); CosmosPagedIterable<ObjectNode> cosmosPagedIterable = cosmosContainer.readAllItems(cosmosQueryRequestOptions, ObjectNode.class); AtomicInteger handleCount = new AtomicInteger(); cosmosPagedIterable = cosmosPagedIterable.handle(feedResponse -> { CosmosDiagnostics cosmosDiagnostics = feedResponse.getCosmosDiagnostics(); if (cosmosDiagnostics != null) { handleCount.incrementAndGet(); } }); cosmosPagedIterable.forEach(objectNode -> { }); assertThat(handleCount.get() >= 1).isTrue(); } private void createItems(int numOfItems) throws JsonProcessingException { for (int i = 0; i < numOfItems; i++) { ObjectNode properties = getDocumentDefinition(UUID.randomUUID().toString(), String.valueOf(i)); cosmosContainer.createItem(properties); } } private ObjectNode getDocumentDefinition(String documentId, String pkId) throws JsonProcessingException { String json = String.format("{ " + "\"id\": \"%s\", " + "\"mypk\": \"%s\", " + "\"sgmts\": [[6519456, 1471916863], [2498434, 1455671440]]" + "}" , documentId, pkId); return OBJECT_MAPPER.readValue(json, ObjectNode.class); } }
Why do we need this value here?
public void addKeyVaultPropertySource(String normalizedName) { final String vaultUri = getPropertyValue(normalizedName, Property.URI); Assert.notNull(vaultUri, "vaultUri must not be null!"); final Long refreshInterval = Optional.ofNullable(getPropertyValue(normalizedName, Property.REFRESH_INTERVAL)) .map(Long::valueOf) .orElse(DEFAULT_REFRESH_INTERVAL_MS); final List<String> secretKeys = Binder.get(this.environment) .bind( KeyVaultProperties.getPropertyName(normalizedName, Property.SECRET_KEYS), Bindable.listOf(String.class) ) .orElse(Collections.emptyList()); final TokenCredential tokenCredential = getCredentials(normalizedName); final SecretClient secretClient = new SecretClientBuilder() .vaultUrl(vaultUri) .credential(tokenCredential) .serviceVersion(SecretServiceVersion.V7_0) .httpLogOptions(new HttpLogOptions().setApplicationId(AZURE_SPRING_KEY_VAULT)) .buildClient(); try { final MutablePropertySources sources = this.environment.getPropertySources(); final boolean caseSensitive = Boolean .parseBoolean(getPropertyValue(normalizedName, Property.CASE_SENSITIVE_KEYS)); final KeyVaultOperation keyVaultOperation = new KeyVaultOperation( secretClient, refreshInterval, secretKeys, caseSensitive); String propertySourceName = Optional.of(normalizedName) .map(String::trim) .filter(s -> !s.isEmpty()) .orElse(AZURE_KEYVAULT_PROPERTYSOURCE_NAME); KeyVaultPropertySource keyVaultPropertySource = new KeyVaultPropertySource(propertySourceName, keyVaultOperation); if (sources.contains(SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME)) { sources.addAfter( SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME, keyVaultPropertySource ); } else { sources.addFirst(keyVaultPropertySource); } } catch (final Exception ex) { throw new IllegalStateException("Failed to configure KeyVault property source", ex); } }
.serviceVersion(SecretServiceVersion.V7_0)
public void addKeyVaultPropertySource(String normalizedName) { final String vaultUri = getPropertyValue(normalizedName, Property.URI); final String version = getPropertyValue(normalizedName, Property.SECRET_SERVICE_VERSION); SecretServiceVersion secretServiceVersion = Arrays.stream(SecretServiceVersion.values()) .filter(val -> val.getVersion().equals(version)) .findFirst() .orElse(null); Assert.notNull(vaultUri, "vaultUri must not be null!"); final Long refreshInterval = Optional.ofNullable(getPropertyValue(normalizedName, Property.REFRESH_INTERVAL)) .map(Long::valueOf) .orElse(DEFAULT_REFRESH_INTERVAL_MS); final List<String> secretKeys = Binder.get(this.environment) .bind( KeyVaultProperties.getPropertyName(normalizedName, Property.SECRET_KEYS), Bindable.listOf(String.class) ) .orElse(Collections.emptyList()); final TokenCredential tokenCredential = getCredentials(normalizedName); final SecretClient secretClient = new SecretClientBuilder() .vaultUrl(vaultUri) .credential(tokenCredential) .serviceVersion(secretServiceVersion) .httpLogOptions(new HttpLogOptions().setApplicationId(AZURE_SPRING_KEY_VAULT)) .buildClient(); try { final MutablePropertySources sources = this.environment.getPropertySources(); final boolean caseSensitive = Boolean .parseBoolean(getPropertyValue(normalizedName, Property.CASE_SENSITIVE_KEYS)); final KeyVaultOperation keyVaultOperation = new KeyVaultOperation( secretClient, refreshInterval, secretKeys, caseSensitive); String propertySourceName = Optional.of(normalizedName) .map(String::trim) .filter(s -> !s.isEmpty()) .orElse(AZURE_KEYVAULT_PROPERTYSOURCE_NAME); KeyVaultPropertySource keyVaultPropertySource = new KeyVaultPropertySource(propertySourceName, keyVaultOperation); if (sources.contains(SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME)) { sources.addAfter( SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME, keyVaultPropertySource ); } else { sources.addFirst(keyVaultPropertySource); } } catch (final Exception ex) { throw new IllegalStateException("Failed to configure KeyVault property source", ex); } }
class KeyVaultEnvironmentPostProcessorHelper { private static final Logger LOGGER = LoggerFactory.getLogger(KeyVaultEnvironmentPostProcessorHelper.class); private final ConfigurableEnvironment environment; KeyVaultEnvironmentPostProcessorHelper(final ConfigurableEnvironment environment) { this.environment = environment; Assert.notNull(environment, "environment must not be null!"); sendTelemetry(); } /** * Add a key vault property source. * * <p> * The normalizedName is used to target a specific key vault (note if the name is the empty string it works as * before with only one key vault present). The normalized name is the name of the specific key vault plus a * trailing "." at the end. * </p> * * @param normalizedName the normalized name. */ /** * Get the token credentials. * * @return the token credentials. */ public TokenCredential getCredentials() { return getCredentials(""); } /** * Get the token credentials. * * @param normalizedName the normalized name of the key vault. * @return the token credentials. */ public TokenCredential getCredentials(String normalizedName) { final String clientId = getPropertyValue(normalizedName, Property.CLIENT_ID); final String clientKey = getPropertyValue(normalizedName, Property.CLIENT_KEY); final String tenantId = getPropertyValue(normalizedName, Property.TENANT_ID); final String certificatePath = getPropertyValue(normalizedName, Property.CERTIFICATE_PATH); final String certificatePassword = getPropertyValue(normalizedName, Property.CERTIFICATE_PASSWORD); final String authorityHost = getPropertyValue(normalizedName, Property.AUTHORITY_HOST) == null ? new IdentityClientOptions().getAuthorityHost() : getPropertyValue(normalizedName, Property.AUTHORITY_HOST); if (clientId != null && tenantId != null && clientKey != null ) { LOGGER.debug("Will use custom credentials"); return new ClientSecretCredentialBuilder() .clientId(clientId) .clientSecret(clientKey) .tenantId(tenantId) .authorityHost(authorityHost) .build(); } if (clientId != null && tenantId != null && certificatePath != null ) { if (StringUtils.isEmpty(certificatePassword)) { return new ClientCertificateCredentialBuilder() .tenantId(tenantId) .clientId(clientId) .pemCertificate(certificatePath) .authorityHost(authorityHost) .build(); } else { return new ClientCertificateCredentialBuilder() .tenantId(tenantId) .clientId(clientId) .authorityHost(authorityHost) .pfxCertificate(certificatePath, certificatePassword) .build(); } } if (clientId != null) { LOGGER.debug("Will use MSI credentials with specified clientId"); return new ManagedIdentityCredentialBuilder().clientId(clientId).build(); } LOGGER.debug("Will use MSI credentials"); return new ManagedIdentityCredentialBuilder().build(); } private String getPropertyValue(final Property property) { return Optional.of(property) .map(KeyVaultProperties::getPropertyName) .map(environment::getProperty) .orElse(null); } private String getPropertyValue( final String normalizedName, final Property property ) { return Optional.of(KeyVaultProperties.getPropertyName(normalizedName, property)) .map(environment::getProperty) .orElse(null); } private boolean allowTelemetry() { return Boolean.parseBoolean(getPropertyValue(Property.ALLOW_TELEMETRY)); } private void sendTelemetry() { if (allowTelemetry()) { final Map<String, String> events = new HashMap<>(); final TelemetrySender sender = new TelemetrySender(); events.put(SERVICE_NAME, getClassPackageSimpleName(KeyVaultEnvironmentPostProcessorHelper.class)); sender.send(ClassUtils.getUserClass(getClass()).getSimpleName(), events); } } }
class KeyVaultEnvironmentPostProcessorHelper { private static final Logger LOGGER = LoggerFactory.getLogger(KeyVaultEnvironmentPostProcessorHelper.class); private final ConfigurableEnvironment environment; KeyVaultEnvironmentPostProcessorHelper(final ConfigurableEnvironment environment) { this.environment = environment; Assert.notNull(environment, "environment must not be null!"); sendTelemetry(); } /** * Add a key vault property source. * * <p> * The normalizedName is used to target a specific key vault (note if the name is the empty string it works as * before with only one key vault present). The normalized name is the name of the specific key vault plus a * trailing "." at the end. * </p> * * @param normalizedName the normalized name. */ /** * Get the token credentials. * * @return the token credentials. */ public TokenCredential getCredentials() { return getCredentials(""); } /** * Get the token credentials. * * @param normalizedName the normalized name of the key vault. * @return the token credentials. */ public TokenCredential getCredentials(String normalizedName) { final String clientId = getPropertyValue(normalizedName, Property.CLIENT_ID); final String clientKey = getPropertyValue(normalizedName, Property.CLIENT_KEY); final String tenantId = getPropertyValue(normalizedName, Property.TENANT_ID); final String certificatePath = getPropertyValue(normalizedName, Property.CERTIFICATE_PATH); final String certificatePassword = getPropertyValue(normalizedName, Property.CERTIFICATE_PASSWORD); final String authorityHost = getPropertyValue(normalizedName, Property.AUTHORITY_HOST) == null ? new IdentityClientOptions().getAuthorityHost() : getPropertyValue(normalizedName, Property.AUTHORITY_HOST); if (clientId != null && tenantId != null && clientKey != null ) { LOGGER.debug("Will use custom credentials"); return new ClientSecretCredentialBuilder() .clientId(clientId) .clientSecret(clientKey) .tenantId(tenantId) .authorityHost(authorityHost) .build(); } if (clientId != null && tenantId != null && certificatePath != null ) { if (StringUtils.isEmpty(certificatePassword)) { return new ClientCertificateCredentialBuilder() .tenantId(tenantId) .clientId(clientId) .pemCertificate(certificatePath) .authorityHost(authorityHost) .build(); } else { return new ClientCertificateCredentialBuilder() .tenantId(tenantId) .clientId(clientId) .authorityHost(authorityHost) .pfxCertificate(certificatePath, certificatePassword) .build(); } } if (clientId != null) { LOGGER.debug("Will use MSI credentials with specified clientId"); return new ManagedIdentityCredentialBuilder().clientId(clientId).build(); } LOGGER.debug("Will use MSI credentials"); return new ManagedIdentityCredentialBuilder().build(); } private String getPropertyValue(final Property property) { return Optional.of(property) .map(KeyVaultProperties::getPropertyName) .map(environment::getProperty) .orElse(null); } private String getPropertyValue( final String normalizedName, final Property property ) { return Optional.of(KeyVaultProperties.getPropertyName(normalizedName, property)) .map(environment::getProperty) .orElse(null); } private boolean allowTelemetry() { return Boolean.parseBoolean(getPropertyValue(Property.ALLOW_TELEMETRY)); } private void sendTelemetry() { if (allowTelemetry()) { final Map<String, String> events = new HashMap<>(); final TelemetrySender sender = new TelemetrySender(); events.put(SERVICE_NAME, getClassPackageSimpleName(KeyVaultEnvironmentPostProcessorHelper.class)); sender.send(ClassUtils.getUserClass(getClass()).getSimpleName(), events); } } }
yes,the constructor of IdentityClientOptions will initialize authorityHost with default value
public TokenCredential getCredentials(String normalizedName) { final String clientId = getPropertyValue(normalizedName, Property.CLIENT_ID); final String clientKey = getPropertyValue(normalizedName, Property.CLIENT_KEY); final String tenantId = getPropertyValue(normalizedName, Property.TENANT_ID); final String certificatePath = getPropertyValue(normalizedName, Property.CERTIFICATE_PATH); final String certificatePassword = getPropertyValue(normalizedName, Property.CERTIFICATE_PASSWORD); final String authorityHost = getPropertyValue(normalizedName, Property.AUTHORITY_HOST) == null ? new IdentityClientOptions().getAuthorityHost() : getPropertyValue(normalizedName, Property.AUTHORITY_HOST); if (clientId != null && tenantId != null && clientKey != null ) { LOGGER.debug("Will use custom credentials"); return new ClientSecretCredentialBuilder() .clientId(clientId) .clientSecret(clientKey) .tenantId(tenantId) .authorityHost(authorityHost) .build(); } if (clientId != null && tenantId != null && certificatePath != null ) { if (StringUtils.isEmpty(certificatePassword)) { return new ClientCertificateCredentialBuilder() .tenantId(tenantId) .clientId(clientId) .pemCertificate(certificatePath) .authorityHost(authorityHost) .build(); } else { return new ClientCertificateCredentialBuilder() .tenantId(tenantId) .clientId(clientId) .authorityHost(authorityHost) .pfxCertificate(certificatePath, certificatePassword) .build(); } } if (clientId != null) { LOGGER.debug("Will use MSI credentials with specified clientId"); return new ManagedIdentityCredentialBuilder().clientId(clientId).build(); } LOGGER.debug("Will use MSI credentials"); return new ManagedIdentityCredentialBuilder().build(); }
new IdentityClientOptions().getAuthorityHost() : getPropertyValue(normalizedName, Property.AUTHORITY_HOST);
public TokenCredential getCredentials(String normalizedName) { final String clientId = getPropertyValue(normalizedName, Property.CLIENT_ID); final String clientKey = getPropertyValue(normalizedName, Property.CLIENT_KEY); final String tenantId = getPropertyValue(normalizedName, Property.TENANT_ID); final String certificatePath = getPropertyValue(normalizedName, Property.CERTIFICATE_PATH); final String certificatePassword = getPropertyValue(normalizedName, Property.CERTIFICATE_PASSWORD); final String authorityHost = getPropertyValue(normalizedName, Property.AUTHORITY_HOST) == null ? new IdentityClientOptions().getAuthorityHost() : getPropertyValue(normalizedName, Property.AUTHORITY_HOST); if (clientId != null && tenantId != null && clientKey != null ) { LOGGER.debug("Will use custom credentials"); return new ClientSecretCredentialBuilder() .clientId(clientId) .clientSecret(clientKey) .tenantId(tenantId) .authorityHost(authorityHost) .build(); } if (clientId != null && tenantId != null && certificatePath != null ) { if (StringUtils.isEmpty(certificatePassword)) { return new ClientCertificateCredentialBuilder() .tenantId(tenantId) .clientId(clientId) .pemCertificate(certificatePath) .authorityHost(authorityHost) .build(); } else { return new ClientCertificateCredentialBuilder() .tenantId(tenantId) .clientId(clientId) .authorityHost(authorityHost) .pfxCertificate(certificatePath, certificatePassword) .build(); } } if (clientId != null) { LOGGER.debug("Will use MSI credentials with specified clientId"); return new ManagedIdentityCredentialBuilder().clientId(clientId).build(); } LOGGER.debug("Will use MSI credentials"); return new ManagedIdentityCredentialBuilder().build(); }
class KeyVaultEnvironmentPostProcessorHelper { private static final Logger LOGGER = LoggerFactory.getLogger(KeyVaultEnvironmentPostProcessorHelper.class); private final ConfigurableEnvironment environment; KeyVaultEnvironmentPostProcessorHelper(final ConfigurableEnvironment environment) { this.environment = environment; Assert.notNull(environment, "environment must not be null!"); sendTelemetry(); } /** * Add a key vault property source. * * <p> * The normalizedName is used to target a specific key vault (note if the name is the empty string it works as * before with only one key vault present). The normalized name is the name of the specific key vault plus a * trailing "." at the end. * </p> * * @param normalizedName the normalized name. */ public void addKeyVaultPropertySource(String normalizedName) { final String vaultUri = getPropertyValue(normalizedName, Property.URI); Assert.notNull(vaultUri, "vaultUri must not be null!"); final Long refreshInterval = Optional.ofNullable(getPropertyValue(normalizedName, Property.REFRESH_INTERVAL)) .map(Long::valueOf) .orElse(DEFAULT_REFRESH_INTERVAL_MS); final List<String> secretKeys = Binder.get(this.environment) .bind( KeyVaultProperties.getPropertyName(normalizedName, Property.SECRET_KEYS), Bindable.listOf(String.class) ) .orElse(Collections.emptyList()); final TokenCredential tokenCredential = getCredentials(normalizedName); final SecretClient secretClient = new SecretClientBuilder() .vaultUrl(vaultUri) .credential(tokenCredential) .serviceVersion(SecretServiceVersion.V7_0) .httpLogOptions(new HttpLogOptions().setApplicationId(AZURE_SPRING_KEY_VAULT)) .buildClient(); try { final MutablePropertySources sources = this.environment.getPropertySources(); final boolean caseSensitive = Boolean .parseBoolean(getPropertyValue(normalizedName, Property.CASE_SENSITIVE_KEYS)); final KeyVaultOperation keyVaultOperation = new KeyVaultOperation( secretClient, refreshInterval, secretKeys, caseSensitive); String propertySourceName = Optional.of(normalizedName) .map(String::trim) .filter(s -> !s.isEmpty()) .orElse(AZURE_KEYVAULT_PROPERTYSOURCE_NAME); KeyVaultPropertySource keyVaultPropertySource = new KeyVaultPropertySource(propertySourceName, keyVaultOperation); if (sources.contains(SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME)) { sources.addAfter( SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME, keyVaultPropertySource ); } else { sources.addFirst(keyVaultPropertySource); } } catch (final Exception ex) { throw new IllegalStateException("Failed to configure KeyVault property source", ex); } } /** * Get the token credentials. * * @return the token credentials. */ public TokenCredential getCredentials() { return getCredentials(""); } /** * Get the token credentials. * * @param normalizedName the normalized name of the key vault. * @return the token credentials. */ private String getPropertyValue(final Property property) { return Optional.of(property) .map(KeyVaultProperties::getPropertyName) .map(environment::getProperty) .orElse(null); } private String getPropertyValue( final String normalizedName, final Property property ) { return Optional.of(KeyVaultProperties.getPropertyName(normalizedName, property)) .map(environment::getProperty) .orElse(null); } private boolean allowTelemetry() { return Boolean.parseBoolean(getPropertyValue(Property.ALLOW_TELEMETRY)); } private void sendTelemetry() { if (allowTelemetry()) { final Map<String, String> events = new HashMap<>(); final TelemetrySender sender = new TelemetrySender(); events.put(SERVICE_NAME, getClassPackageSimpleName(KeyVaultEnvironmentPostProcessorHelper.class)); sender.send(ClassUtils.getUserClass(getClass()).getSimpleName(), events); } } }
class KeyVaultEnvironmentPostProcessorHelper { private static final Logger LOGGER = LoggerFactory.getLogger(KeyVaultEnvironmentPostProcessorHelper.class); private final ConfigurableEnvironment environment; KeyVaultEnvironmentPostProcessorHelper(final ConfigurableEnvironment environment) { this.environment = environment; Assert.notNull(environment, "environment must not be null!"); sendTelemetry(); } /** * Add a key vault property source. * * <p> * The normalizedName is used to target a specific key vault (note if the name is the empty string it works as * before with only one key vault present). The normalized name is the name of the specific key vault plus a * trailing "." at the end. * </p> * * @param normalizedName the normalized name. */ public void addKeyVaultPropertySource(String normalizedName) { final String vaultUri = getPropertyValue(normalizedName, Property.URI); final String version = getPropertyValue(normalizedName, Property.SECRET_SERVICE_VERSION); SecretServiceVersion secretServiceVersion = Arrays.stream(SecretServiceVersion.values()) .filter(val -> val.getVersion().equals(version)) .findFirst() .orElse(null); Assert.notNull(vaultUri, "vaultUri must not be null!"); final Long refreshInterval = Optional.ofNullable(getPropertyValue(normalizedName, Property.REFRESH_INTERVAL)) .map(Long::valueOf) .orElse(DEFAULT_REFRESH_INTERVAL_MS); final List<String> secretKeys = Binder.get(this.environment) .bind( KeyVaultProperties.getPropertyName(normalizedName, Property.SECRET_KEYS), Bindable.listOf(String.class) ) .orElse(Collections.emptyList()); final TokenCredential tokenCredential = getCredentials(normalizedName); final SecretClient secretClient = new SecretClientBuilder() .vaultUrl(vaultUri) .credential(tokenCredential) .serviceVersion(secretServiceVersion) .httpLogOptions(new HttpLogOptions().setApplicationId(AZURE_SPRING_KEY_VAULT)) .buildClient(); try { final MutablePropertySources sources = this.environment.getPropertySources(); final boolean caseSensitive = Boolean .parseBoolean(getPropertyValue(normalizedName, Property.CASE_SENSITIVE_KEYS)); final KeyVaultOperation keyVaultOperation = new KeyVaultOperation( secretClient, refreshInterval, secretKeys, caseSensitive); String propertySourceName = Optional.of(normalizedName) .map(String::trim) .filter(s -> !s.isEmpty()) .orElse(AZURE_KEYVAULT_PROPERTYSOURCE_NAME); KeyVaultPropertySource keyVaultPropertySource = new KeyVaultPropertySource(propertySourceName, keyVaultOperation); if (sources.contains(SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME)) { sources.addAfter( SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME, keyVaultPropertySource ); } else { sources.addFirst(keyVaultPropertySource); } } catch (final Exception ex) { throw new IllegalStateException("Failed to configure KeyVault property source", ex); } } /** * Get the token credentials. * * @return the token credentials. */ public TokenCredential getCredentials() { return getCredentials(""); } /** * Get the token credentials. * * @param normalizedName the normalized name of the key vault. * @return the token credentials. */ private String getPropertyValue(final Property property) { return Optional.of(property) .map(KeyVaultProperties::getPropertyName) .map(environment::getProperty) .orElse(null); } private String getPropertyValue( final String normalizedName, final Property property ) { return Optional.of(KeyVaultProperties.getPropertyName(normalizedName, property)) .map(environment::getProperty) .orElse(null); } private boolean allowTelemetry() { return Boolean.parseBoolean(getPropertyValue(Property.ALLOW_TELEMETRY)); } private void sendTelemetry() { if (allowTelemetry()) { final Map<String, String> events = new HashMap<>(); final TelemetrySender sender = new TelemetrySender(); events.put(SERVICE_NAME, getClassPackageSimpleName(KeyVaultEnvironmentPostProcessorHelper.class)); sender.send(ClassUtils.getUserClass(getClass()).getSimpleName(), events); } } }
by default, serviceVersion value is V7_1, but the starter run failed with errors below ``` {"error":{"code":"BadParameter","message":"The specified version (7.1) is not recognized. Consider using the latest supported version (2016-10-01)."}} ```
public void addKeyVaultPropertySource(String normalizedName) { final String vaultUri = getPropertyValue(normalizedName, Property.URI); Assert.notNull(vaultUri, "vaultUri must not be null!"); final Long refreshInterval = Optional.ofNullable(getPropertyValue(normalizedName, Property.REFRESH_INTERVAL)) .map(Long::valueOf) .orElse(DEFAULT_REFRESH_INTERVAL_MS); final List<String> secretKeys = Binder.get(this.environment) .bind( KeyVaultProperties.getPropertyName(normalizedName, Property.SECRET_KEYS), Bindable.listOf(String.class) ) .orElse(Collections.emptyList()); final TokenCredential tokenCredential = getCredentials(normalizedName); final SecretClient secretClient = new SecretClientBuilder() .vaultUrl(vaultUri) .credential(tokenCredential) .serviceVersion(SecretServiceVersion.V7_0) .httpLogOptions(new HttpLogOptions().setApplicationId(AZURE_SPRING_KEY_VAULT)) .buildClient(); try { final MutablePropertySources sources = this.environment.getPropertySources(); final boolean caseSensitive = Boolean .parseBoolean(getPropertyValue(normalizedName, Property.CASE_SENSITIVE_KEYS)); final KeyVaultOperation keyVaultOperation = new KeyVaultOperation( secretClient, refreshInterval, secretKeys, caseSensitive); String propertySourceName = Optional.of(normalizedName) .map(String::trim) .filter(s -> !s.isEmpty()) .orElse(AZURE_KEYVAULT_PROPERTYSOURCE_NAME); KeyVaultPropertySource keyVaultPropertySource = new KeyVaultPropertySource(propertySourceName, keyVaultOperation); if (sources.contains(SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME)) { sources.addAfter( SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME, keyVaultPropertySource ); } else { sources.addFirst(keyVaultPropertySource); } } catch (final Exception ex) { throw new IllegalStateException("Failed to configure KeyVault property source", ex); } }
.serviceVersion(SecretServiceVersion.V7_0)
public void addKeyVaultPropertySource(String normalizedName) { final String vaultUri = getPropertyValue(normalizedName, Property.URI); final String version = getPropertyValue(normalizedName, Property.SECRET_SERVICE_VERSION); SecretServiceVersion secretServiceVersion = Arrays.stream(SecretServiceVersion.values()) .filter(val -> val.getVersion().equals(version)) .findFirst() .orElse(null); Assert.notNull(vaultUri, "vaultUri must not be null!"); final Long refreshInterval = Optional.ofNullable(getPropertyValue(normalizedName, Property.REFRESH_INTERVAL)) .map(Long::valueOf) .orElse(DEFAULT_REFRESH_INTERVAL_MS); final List<String> secretKeys = Binder.get(this.environment) .bind( KeyVaultProperties.getPropertyName(normalizedName, Property.SECRET_KEYS), Bindable.listOf(String.class) ) .orElse(Collections.emptyList()); final TokenCredential tokenCredential = getCredentials(normalizedName); final SecretClient secretClient = new SecretClientBuilder() .vaultUrl(vaultUri) .credential(tokenCredential) .serviceVersion(secretServiceVersion) .httpLogOptions(new HttpLogOptions().setApplicationId(AZURE_SPRING_KEY_VAULT)) .buildClient(); try { final MutablePropertySources sources = this.environment.getPropertySources(); final boolean caseSensitive = Boolean .parseBoolean(getPropertyValue(normalizedName, Property.CASE_SENSITIVE_KEYS)); final KeyVaultOperation keyVaultOperation = new KeyVaultOperation( secretClient, refreshInterval, secretKeys, caseSensitive); String propertySourceName = Optional.of(normalizedName) .map(String::trim) .filter(s -> !s.isEmpty()) .orElse(AZURE_KEYVAULT_PROPERTYSOURCE_NAME); KeyVaultPropertySource keyVaultPropertySource = new KeyVaultPropertySource(propertySourceName, keyVaultOperation); if (sources.contains(SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME)) { sources.addAfter( SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME, keyVaultPropertySource ); } else { sources.addFirst(keyVaultPropertySource); } } catch (final Exception ex) { throw new IllegalStateException("Failed to configure KeyVault property source", ex); } }
class KeyVaultEnvironmentPostProcessorHelper { private static final Logger LOGGER = LoggerFactory.getLogger(KeyVaultEnvironmentPostProcessorHelper.class); private final ConfigurableEnvironment environment; KeyVaultEnvironmentPostProcessorHelper(final ConfigurableEnvironment environment) { this.environment = environment; Assert.notNull(environment, "environment must not be null!"); sendTelemetry(); } /** * Add a key vault property source. * * <p> * The normalizedName is used to target a specific key vault (note if the name is the empty string it works as * before with only one key vault present). The normalized name is the name of the specific key vault plus a * trailing "." at the end. * </p> * * @param normalizedName the normalized name. */ /** * Get the token credentials. * * @return the token credentials. */ public TokenCredential getCredentials() { return getCredentials(""); } /** * Get the token credentials. * * @param normalizedName the normalized name of the key vault. * @return the token credentials. */ public TokenCredential getCredentials(String normalizedName) { final String clientId = getPropertyValue(normalizedName, Property.CLIENT_ID); final String clientKey = getPropertyValue(normalizedName, Property.CLIENT_KEY); final String tenantId = getPropertyValue(normalizedName, Property.TENANT_ID); final String certificatePath = getPropertyValue(normalizedName, Property.CERTIFICATE_PATH); final String certificatePassword = getPropertyValue(normalizedName, Property.CERTIFICATE_PASSWORD); final String authorityHost = getPropertyValue(normalizedName, Property.AUTHORITY_HOST) == null ? new IdentityClientOptions().getAuthorityHost() : getPropertyValue(normalizedName, Property.AUTHORITY_HOST); if (clientId != null && tenantId != null && clientKey != null ) { LOGGER.debug("Will use custom credentials"); return new ClientSecretCredentialBuilder() .clientId(clientId) .clientSecret(clientKey) .tenantId(tenantId) .authorityHost(authorityHost) .build(); } if (clientId != null && tenantId != null && certificatePath != null ) { if (StringUtils.isEmpty(certificatePassword)) { return new ClientCertificateCredentialBuilder() .tenantId(tenantId) .clientId(clientId) .pemCertificate(certificatePath) .authorityHost(authorityHost) .build(); } else { return new ClientCertificateCredentialBuilder() .tenantId(tenantId) .clientId(clientId) .authorityHost(authorityHost) .pfxCertificate(certificatePath, certificatePassword) .build(); } } if (clientId != null) { LOGGER.debug("Will use MSI credentials with specified clientId"); return new ManagedIdentityCredentialBuilder().clientId(clientId).build(); } LOGGER.debug("Will use MSI credentials"); return new ManagedIdentityCredentialBuilder().build(); } private String getPropertyValue(final Property property) { return Optional.of(property) .map(KeyVaultProperties::getPropertyName) .map(environment::getProperty) .orElse(null); } private String getPropertyValue( final String normalizedName, final Property property ) { return Optional.of(KeyVaultProperties.getPropertyName(normalizedName, property)) .map(environment::getProperty) .orElse(null); } private boolean allowTelemetry() { return Boolean.parseBoolean(getPropertyValue(Property.ALLOW_TELEMETRY)); } private void sendTelemetry() { if (allowTelemetry()) { final Map<String, String> events = new HashMap<>(); final TelemetrySender sender = new TelemetrySender(); events.put(SERVICE_NAME, getClassPackageSimpleName(KeyVaultEnvironmentPostProcessorHelper.class)); sender.send(ClassUtils.getUserClass(getClass()).getSimpleName(), events); } } }
class KeyVaultEnvironmentPostProcessorHelper { private static final Logger LOGGER = LoggerFactory.getLogger(KeyVaultEnvironmentPostProcessorHelper.class); private final ConfigurableEnvironment environment; KeyVaultEnvironmentPostProcessorHelper(final ConfigurableEnvironment environment) { this.environment = environment; Assert.notNull(environment, "environment must not be null!"); sendTelemetry(); } /** * Add a key vault property source. * * <p> * The normalizedName is used to target a specific key vault (note if the name is the empty string it works as * before with only one key vault present). The normalized name is the name of the specific key vault plus a * trailing "." at the end. * </p> * * @param normalizedName the normalized name. */ /** * Get the token credentials. * * @return the token credentials. */ public TokenCredential getCredentials() { return getCredentials(""); } /** * Get the token credentials. * * @param normalizedName the normalized name of the key vault. * @return the token credentials. */ public TokenCredential getCredentials(String normalizedName) { final String clientId = getPropertyValue(normalizedName, Property.CLIENT_ID); final String clientKey = getPropertyValue(normalizedName, Property.CLIENT_KEY); final String tenantId = getPropertyValue(normalizedName, Property.TENANT_ID); final String certificatePath = getPropertyValue(normalizedName, Property.CERTIFICATE_PATH); final String certificatePassword = getPropertyValue(normalizedName, Property.CERTIFICATE_PASSWORD); final String authorityHost = getPropertyValue(normalizedName, Property.AUTHORITY_HOST) == null ? new IdentityClientOptions().getAuthorityHost() : getPropertyValue(normalizedName, Property.AUTHORITY_HOST); if (clientId != null && tenantId != null && clientKey != null ) { LOGGER.debug("Will use custom credentials"); return new ClientSecretCredentialBuilder() .clientId(clientId) .clientSecret(clientKey) .tenantId(tenantId) .authorityHost(authorityHost) .build(); } if (clientId != null && tenantId != null && certificatePath != null ) { if (StringUtils.isEmpty(certificatePassword)) { return new ClientCertificateCredentialBuilder() .tenantId(tenantId) .clientId(clientId) .pemCertificate(certificatePath) .authorityHost(authorityHost) .build(); } else { return new ClientCertificateCredentialBuilder() .tenantId(tenantId) .clientId(clientId) .authorityHost(authorityHost) .pfxCertificate(certificatePath, certificatePassword) .build(); } } if (clientId != null) { LOGGER.debug("Will use MSI credentials with specified clientId"); return new ManagedIdentityCredentialBuilder().clientId(clientId).build(); } LOGGER.debug("Will use MSI credentials"); return new ManagedIdentityCredentialBuilder().build(); } private String getPropertyValue(final Property property) { return Optional.of(property) .map(KeyVaultProperties::getPropertyName) .map(environment::getProperty) .orElse(null); } private String getPropertyValue( final String normalizedName, final Property property ) { return Optional.of(KeyVaultProperties.getPropertyName(normalizedName, property)) .map(environment::getProperty) .orElse(null); } private boolean allowTelemetry() { return Boolean.parseBoolean(getPropertyValue(Property.ALLOW_TELEMETRY)); } private void sendTelemetry() { if (allowTelemetry()) { final Map<String, String> events = new HashMap<>(); final TelemetrySender sender = new TelemetrySender(); events.put(SERVICE_NAME, getClassPackageSimpleName(KeyVaultEnvironmentPostProcessorHelper.class)); sender.send(ClassUtils.getUserClass(getClass()).getSimpleName(), events); } } }
Pattern compilation is expensive. So, maybe it's good to just make this pattern into a static final constant.
public static List<X509Certificate> publicKeyFromPem(byte[] pem) { Pattern pattern = Pattern.compile("(?s)-----BEGIN CERTIFICATE-----.*?-----END CERTIFICATE-----"); Matcher matcher = pattern.matcher(new String(pem, StandardCharsets.UTF_8)); List<X509Certificate> x509CertificateList = new ArrayList<>(); while (matcher.find()) { try { CertificateFactory factory = CertificateFactory.getInstance("X.509"); InputStream stream = new ByteArrayInputStream(matcher.group().getBytes(StandardCharsets.UTF_8)); x509CertificateList.add((X509Certificate) factory.generateCertificate(stream)); } catch (CertificateException e) { throw LOGGER.logExceptionAsError(new IllegalStateException(e)); } } if (x509CertificateList.size() == 0) { throw LOGGER.logExceptionAsError(new IllegalArgumentException( "PEM certificate provided does not contain -----BEGIN CERTIFICATE-----END CERTIFICATE----- block")); } return x509CertificateList; }
Pattern pattern = Pattern.compile("(?s)-----BEGIN CERTIFICATE-----.*?-----END CERTIFICATE-----");
public static List<X509Certificate> publicKeyFromPem(byte[] pem) { Pattern pattern = Pattern.compile("(?s)-----BEGIN CERTIFICATE-----.*?-----END CERTIFICATE-----"); Matcher matcher = pattern.matcher(new String(pem, StandardCharsets.UTF_8)); List<X509Certificate> x509CertificateList = new ArrayList<>(); while (matcher.find()) { try { CertificateFactory factory = CertificateFactory.getInstance("X.509"); InputStream stream = new ByteArrayInputStream(matcher.group().getBytes(StandardCharsets.UTF_8)); x509CertificateList.add((X509Certificate) factory.generateCertificate(stream)); } catch (CertificateException e) { throw LOGGER.logExceptionAsError(new IllegalStateException(e)); } } if (x509CertificateList.size() == 0) { throw LOGGER.logExceptionAsError(new IllegalArgumentException( "PEM certificate provided does not contain -----BEGIN CERTIFICATE-----END CERTIFICATE----- block")); } return x509CertificateList; }
class CertificateUtil { private static final ClientLogger LOGGER = new ClientLogger(CertificateUtil.class); /** * Extracts the PrivateKey from a PEM certificate. * @param pem the contents of a PEM certificate. * @return the PrivateKey */ public static PrivateKey privateKeyFromPem(byte[] pem) { Pattern pattern = Pattern.compile("(?s)-----BEGIN PRIVATE KEY-----.*-----END PRIVATE KEY-----"); Matcher matcher = pattern.matcher(new String(pem, StandardCharsets.UTF_8)); if (!matcher.find()) { throw LOGGER.logExceptionAsError(new IllegalArgumentException( "Certificate file provided is not a valid PEM file.")); } String base64 = matcher.group() .replace("-----BEGIN PRIVATE KEY-----", "") .replace("-----END PRIVATE KEY-----", "") .replace("\n", "") .replace("\r", ""); byte[] key = Base64Util.decode(base64.getBytes(StandardCharsets.UTF_8)); PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(key); try { KeyFactory kf = KeyFactory.getInstance("RSA"); return kf.generatePrivate(spec); } catch (NoSuchAlgorithmException | InvalidKeySpecException e) { throw LOGGER.logExceptionAsError(new IllegalStateException(e)); } } /** * Extracts the X509Certificate certificate/certificate-chain from a PEM certificate. * @param pem the contents of a PEM certificate. * @return the {@link List} of X509Certificate certificate */ private CertificateUtil() { } }
class CertificateUtil { private static final ClientLogger LOGGER = new ClientLogger(CertificateUtil.class); /** * Extracts the PrivateKey from a PEM certificate. * @param pem the contents of a PEM certificate. * @return the PrivateKey */ public static PrivateKey privateKeyFromPem(byte[] pem) { Pattern pattern = Pattern.compile("(?s)-----BEGIN PRIVATE KEY-----.*-----END PRIVATE KEY-----"); Matcher matcher = pattern.matcher(new String(pem, StandardCharsets.UTF_8)); if (!matcher.find()) { throw LOGGER.logExceptionAsError(new IllegalArgumentException( "Certificate file provided is not a valid PEM file.")); } String base64 = matcher.group() .replace("-----BEGIN PRIVATE KEY-----", "") .replace("-----END PRIVATE KEY-----", "") .replace("\n", "") .replace("\r", ""); byte[] key = Base64Util.decode(base64.getBytes(StandardCharsets.UTF_8)); PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(key); try { KeyFactory kf = KeyFactory.getInstance("RSA"); return kf.generatePrivate(spec); } catch (NoSuchAlgorithmException | InvalidKeySpecException e) { throw LOGGER.logExceptionAsError(new IllegalStateException(e)); } } /** * Extracts the X509Certificate certificate/certificate-chain from a PEM certificate. * @param pem the contents of a PEM certificate. * @return the {@link List} of X509Certificate certificate */ private CertificateUtil() { } }
In this case, it is only called once during client construction and not in any API call. So, having it localized will help to get it garbage collected, after use.
public static List<X509Certificate> publicKeyFromPem(byte[] pem) { Pattern pattern = Pattern.compile("(?s)-----BEGIN CERTIFICATE-----.*?-----END CERTIFICATE-----"); Matcher matcher = pattern.matcher(new String(pem, StandardCharsets.UTF_8)); List<X509Certificate> x509CertificateList = new ArrayList<>(); while (matcher.find()) { try { CertificateFactory factory = CertificateFactory.getInstance("X.509"); InputStream stream = new ByteArrayInputStream(matcher.group().getBytes(StandardCharsets.UTF_8)); x509CertificateList.add((X509Certificate) factory.generateCertificate(stream)); } catch (CertificateException e) { throw LOGGER.logExceptionAsError(new IllegalStateException(e)); } } if (x509CertificateList.size() == 0) { throw LOGGER.logExceptionAsError(new IllegalArgumentException( "PEM certificate provided does not contain -----BEGIN CERTIFICATE-----END CERTIFICATE----- block")); } return x509CertificateList; }
Pattern pattern = Pattern.compile("(?s)-----BEGIN CERTIFICATE-----.*?-----END CERTIFICATE-----");
public static List<X509Certificate> publicKeyFromPem(byte[] pem) { Pattern pattern = Pattern.compile("(?s)-----BEGIN CERTIFICATE-----.*?-----END CERTIFICATE-----"); Matcher matcher = pattern.matcher(new String(pem, StandardCharsets.UTF_8)); List<X509Certificate> x509CertificateList = new ArrayList<>(); while (matcher.find()) { try { CertificateFactory factory = CertificateFactory.getInstance("X.509"); InputStream stream = new ByteArrayInputStream(matcher.group().getBytes(StandardCharsets.UTF_8)); x509CertificateList.add((X509Certificate) factory.generateCertificate(stream)); } catch (CertificateException e) { throw LOGGER.logExceptionAsError(new IllegalStateException(e)); } } if (x509CertificateList.size() == 0) { throw LOGGER.logExceptionAsError(new IllegalArgumentException( "PEM certificate provided does not contain -----BEGIN CERTIFICATE-----END CERTIFICATE----- block")); } return x509CertificateList; }
class CertificateUtil { private static final ClientLogger LOGGER = new ClientLogger(CertificateUtil.class); /** * Extracts the PrivateKey from a PEM certificate. * @param pem the contents of a PEM certificate. * @return the PrivateKey */ public static PrivateKey privateKeyFromPem(byte[] pem) { Pattern pattern = Pattern.compile("(?s)-----BEGIN PRIVATE KEY-----.*-----END PRIVATE KEY-----"); Matcher matcher = pattern.matcher(new String(pem, StandardCharsets.UTF_8)); if (!matcher.find()) { throw LOGGER.logExceptionAsError(new IllegalArgumentException( "Certificate file provided is not a valid PEM file.")); } String base64 = matcher.group() .replace("-----BEGIN PRIVATE KEY-----", "") .replace("-----END PRIVATE KEY-----", "") .replace("\n", "") .replace("\r", ""); byte[] key = Base64Util.decode(base64.getBytes(StandardCharsets.UTF_8)); PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(key); try { KeyFactory kf = KeyFactory.getInstance("RSA"); return kf.generatePrivate(spec); } catch (NoSuchAlgorithmException | InvalidKeySpecException e) { throw LOGGER.logExceptionAsError(new IllegalStateException(e)); } } /** * Extracts the X509Certificate certificate/certificate-chain from a PEM certificate. * @param pem the contents of a PEM certificate. * @return the {@link List} of X509Certificate certificate */ private CertificateUtil() { } }
class CertificateUtil { private static final ClientLogger LOGGER = new ClientLogger(CertificateUtil.class); /** * Extracts the PrivateKey from a PEM certificate. * @param pem the contents of a PEM certificate. * @return the PrivateKey */ public static PrivateKey privateKeyFromPem(byte[] pem) { Pattern pattern = Pattern.compile("(?s)-----BEGIN PRIVATE KEY-----.*-----END PRIVATE KEY-----"); Matcher matcher = pattern.matcher(new String(pem, StandardCharsets.UTF_8)); if (!matcher.find()) { throw LOGGER.logExceptionAsError(new IllegalArgumentException( "Certificate file provided is not a valid PEM file.")); } String base64 = matcher.group() .replace("-----BEGIN PRIVATE KEY-----", "") .replace("-----END PRIVATE KEY-----", "") .replace("\n", "") .replace("\r", ""); byte[] key = Base64Util.decode(base64.getBytes(StandardCharsets.UTF_8)); PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(key); try { KeyFactory kf = KeyFactory.getInstance("RSA"); return kf.generatePrivate(spec); } catch (NoSuchAlgorithmException | InvalidKeySpecException e) { throw LOGGER.logExceptionAsError(new IllegalStateException(e)); } } /** * Extracts the X509Certificate certificate/certificate-chain from a PEM certificate. * @param pem the contents of a PEM certificate. * @return the {@link List} of X509Certificate certificate */ private CertificateUtil() { } }
Do we want to state `No value initialized`?
public T getValue() { if (!this.isInitialized) { throw new NoSuchElementException("No value present"); } return this.value; }
throw new NoSuchElementException("No value present");
public T getValue() { if (!this.isInitialized) { throw new NoSuchElementException("No value initialized"); } return this.value; }
class Option<T> { private static final Option<?> UNINITIALIZED = new Option<>(); private static final Option<?> EMPTY = new Option<>(null); private final boolean isInitialized; private final T value; /** * Returns an {@link Option} with the specified null-value or non-null-value. * * @param <T> The value type. * @param value the value. * @return an {@link Option} with the value present. */ public static <T> Option<T> of(T value) { return value == null ? empty() : new Option<>(value); } /** * Returns an {@link Option} with null-value. * <p> * {@code Option.empty()} is a syntactic sugar for {@code Option.of(null)}. * </p> * @param <T> The value type. * @return an {@link Option} with a null-value. */ public static <T> Option<T> empty() { @SuppressWarnings("unchecked") Option<T> empty = (Option<T>) EMPTY; return empty; } /** * Returns an {@link Option} instance with no-value. * * @param <T> Type of the non-existent value. * @return An Option type with no-value. */ public static <T> Option<T> uninitialized() { @SuppressWarnings("unchecked") Option<T> uninitialized = (Option<T>) UNINITIALIZED; return uninitialized; } /** * Return {@code true} if this instance is initialized with a null-value or non-null-value, * otherwise {@code false}. * * @return {@code true} if there is a value present, otherwise {@code false} */ public boolean isInitialized() { return this.isInitialized; } /** * Gets the value in the {@link Option}. * * @return The value. * @throws NoSuchElementException thrown if the {@link Option} has no value. */ private Option() { this.isInitialized = false; this.value = null; } private Option(T value) { this.isInitialized = true; this.value = value; } }
class Option<T> { private static final Option<?> UNINITIALIZED = new Option<>(); private static final Option<?> EMPTY = new Option<>(null); private final boolean isInitialized; private final T value; /** * Returns an {@link Option} with the specified null-value or non-null-value. * * @param <T> The value type. * @param value the value. * @return an {@link Option} with the value present. */ public static <T> Option<T> of(T value) { return value == null ? empty() : new Option<>(value); } /** * Returns an {@link Option} with null-value. * <p> * {@code Option.empty()} is a syntactic sugar for {@code Option.of(null)}. * </p> * @param <T> The value type. * @return an {@link Option} with a null-value. */ public static <T> Option<T> empty() { @SuppressWarnings("unchecked") Option<T> empty = (Option<T>) EMPTY; return empty; } /** * Returns an {@link Option} instance with no-value. * * @param <T> Type of the non-existent value. * @return An Option type with no-value. */ public static <T> Option<T> uninitialized() { @SuppressWarnings("unchecked") Option<T> uninitialized = (Option<T>) UNINITIALIZED; return uninitialized; } /** * Return {@code true} if this instance is initialized with a null-value or non-null-value, * otherwise {@code false}. * * @return {@code true} if a value has been initialized, otherwise {@code false} */ public boolean isInitialized() { return this.isInitialized; } /** * Gets the value in the {@link Option}. * * @return The {@code null} (null-value) or non-null-value that the {@link Option} * is initialized with. * @throws NoSuchElementException thrown if the {@link Option} is in no-value state. */ private Option() { this.isInitialized = false; this.value = null; } private Option(T value) { this.isInitialized = true; this.value = value; } }
agree, the proposed text better aligns the purpose of type, will update.
public T getValue() { if (!this.isInitialized) { throw new NoSuchElementException("No value present"); } return this.value; }
throw new NoSuchElementException("No value present");
public T getValue() { if (!this.isInitialized) { throw new NoSuchElementException("No value initialized"); } return this.value; }
class Option<T> { private static final Option<?> UNINITIALIZED = new Option<>(); private static final Option<?> EMPTY = new Option<>(null); private final boolean isInitialized; private final T value; /** * Returns an {@link Option} with the specified null-value or non-null-value. * * @param <T> The value type. * @param value the value. * @return an {@link Option} with the value present. */ public static <T> Option<T> of(T value) { return value == null ? empty() : new Option<>(value); } /** * Returns an {@link Option} with null-value. * <p> * {@code Option.empty()} is a syntactic sugar for {@code Option.of(null)}. * </p> * @param <T> The value type. * @return an {@link Option} with a null-value. */ public static <T> Option<T> empty() { @SuppressWarnings("unchecked") Option<T> empty = (Option<T>) EMPTY; return empty; } /** * Returns an {@link Option} instance with no-value. * * @param <T> Type of the non-existent value. * @return An Option type with no-value. */ public static <T> Option<T> uninitialized() { @SuppressWarnings("unchecked") Option<T> uninitialized = (Option<T>) UNINITIALIZED; return uninitialized; } /** * Return {@code true} if this instance is initialized with a null-value or non-null-value, * otherwise {@code false}. * * @return {@code true} if there is a value present, otherwise {@code false} */ public boolean isInitialized() { return this.isInitialized; } /** * Gets the value in the {@link Option}. * * @return The value. * @throws NoSuchElementException thrown if the {@link Option} has no value. */ private Option() { this.isInitialized = false; this.value = null; } private Option(T value) { this.isInitialized = true; this.value = value; } }
class Option<T> { private static final Option<?> UNINITIALIZED = new Option<>(); private static final Option<?> EMPTY = new Option<>(null); private final boolean isInitialized; private final T value; /** * Returns an {@link Option} with the specified null-value or non-null-value. * * @param <T> The value type. * @param value the value. * @return an {@link Option} with the value present. */ public static <T> Option<T> of(T value) { return value == null ? empty() : new Option<>(value); } /** * Returns an {@link Option} with null-value. * <p> * {@code Option.empty()} is a syntactic sugar for {@code Option.of(null)}. * </p> * @param <T> The value type. * @return an {@link Option} with a null-value. */ public static <T> Option<T> empty() { @SuppressWarnings("unchecked") Option<T> empty = (Option<T>) EMPTY; return empty; } /** * Returns an {@link Option} instance with no-value. * * @param <T> Type of the non-existent value. * @return An Option type with no-value. */ public static <T> Option<T> uninitialized() { @SuppressWarnings("unchecked") Option<T> uninitialized = (Option<T>) UNINITIALIZED; return uninitialized; } /** * Return {@code true} if this instance is initialized with a null-value or non-null-value, * otherwise {@code false}. * * @return {@code true} if a value has been initialized, otherwise {@code false} */ public boolean isInitialized() { return this.isInitialized; } /** * Gets the value in the {@link Option}. * * @return The {@code null} (null-value) or non-null-value that the {@link Option} * is initialized with. * @throws NoSuchElementException thrown if the {@link Option} is in no-value state. */ private Option() { this.isInitialized = false; this.value = null; } private Option(T value) { this.isInitialized = true; this.value = value; } }
This should log and throw.
public T getValue() { if (!this.isInitialized) { throw new NoSuchElementException("No value present"); } return this.value; }
throw new NoSuchElementException("No value present");
public T getValue() { if (!this.isInitialized) { throw new NoSuchElementException("No value initialized"); } return this.value; }
class Option<T> { private static final Option<?> UNINITIALIZED = new Option<>(); private static final Option<?> EMPTY = new Option<>(null); private final boolean isInitialized; private final T value; /** * Returns an {@link Option} with the specified null-value or non-null-value. * * @param <T> The value type. * @param value the value. * @return an {@link Option} with the value present. */ public static <T> Option<T> of(T value) { return value == null ? empty() : new Option<>(value); } /** * Returns an {@link Option} with null-value. * <p> * {@code Option.empty()} is a syntactic sugar for {@code Option.of(null)}. * </p> * @param <T> The value type. * @return an {@link Option} with a null-value. */ public static <T> Option<T> empty() { @SuppressWarnings("unchecked") Option<T> empty = (Option<T>) EMPTY; return empty; } /** * Returns an {@link Option} instance with no-value. * * @param <T> Type of the non-existent value. * @return An Option type with no-value. */ public static <T> Option<T> uninitialized() { @SuppressWarnings("unchecked") Option<T> uninitialized = (Option<T>) UNINITIALIZED; return uninitialized; } /** * Return {@code true} if this instance is initialized with a null-value or non-null-value, * otherwise {@code false}. * * @return {@code true} if there is a value present, otherwise {@code false} */ public boolean isInitialized() { return this.isInitialized; } /** * Gets the value in the {@link Option}. * * @return The value. * @throws NoSuchElementException thrown if the {@link Option} has no value. */ private Option() { this.isInitialized = false; this.value = null; } private Option(T value) { this.isInitialized = true; this.value = value; } }
class Option<T> { private static final Option<?> UNINITIALIZED = new Option<>(); private static final Option<?> EMPTY = new Option<>(null); private final boolean isInitialized; private final T value; /** * Returns an {@link Option} with the specified null-value or non-null-value. * * @param <T> The value type. * @param value the value. * @return an {@link Option} with the value present. */ public static <T> Option<T> of(T value) { return value == null ? empty() : new Option<>(value); } /** * Returns an {@link Option} with null-value. * <p> * {@code Option.empty()} is a syntactic sugar for {@code Option.of(null)}. * </p> * @param <T> The value type. * @return an {@link Option} with a null-value. */ public static <T> Option<T> empty() { @SuppressWarnings("unchecked") Option<T> empty = (Option<T>) EMPTY; return empty; } /** * Returns an {@link Option} instance with no-value. * * @param <T> Type of the non-existent value. * @return An Option type with no-value. */ public static <T> Option<T> uninitialized() { @SuppressWarnings("unchecked") Option<T> uninitialized = (Option<T>) UNINITIALIZED; return uninitialized; } /** * Return {@code true} if this instance is initialized with a null-value or non-null-value, * otherwise {@code false}. * * @return {@code true} if a value has been initialized, otherwise {@code false} */ public boolean isInitialized() { return this.isInitialized; } /** * Gets the value in the {@link Option}. * * @return The {@code null} (null-value) or non-null-value that the {@link Option} * is initialized with. * @throws NoSuchElementException thrown if the {@link Option} is in no-value state. */ private Option() { this.isInitialized = false; this.value = null; } private Option(T value) { this.isInitialized = true; this.value = value; } }
@srnagar I have a question - Is it a hard rule that any exception has to be wrapped in logger? The reason for asking is - this method we will be called from serializer and will have a `isInitialized` check before accessing it. We will not have an output model with Option property where the user have to call `getValue()`. My question is, for a type used in input only model with internal guarded access, do we need a logger?. Think of it as the `Optional ::value()` method in an input only model. If we still require a logger - do we need ONE logger instance per Option instance given there can be many patch Option properties OR should we prefer a static logger?
public T getValue() { if (!this.isInitialized) { throw new NoSuchElementException("No value present"); } return this.value; }
throw new NoSuchElementException("No value present");
public T getValue() { if (!this.isInitialized) { throw new NoSuchElementException("No value initialized"); } return this.value; }
class Option<T> { private static final Option<?> UNINITIALIZED = new Option<>(); private static final Option<?> EMPTY = new Option<>(null); private final boolean isInitialized; private final T value; /** * Returns an {@link Option} with the specified null-value or non-null-value. * * @param <T> The value type. * @param value the value. * @return an {@link Option} with the value present. */ public static <T> Option<T> of(T value) { return value == null ? empty() : new Option<>(value); } /** * Returns an {@link Option} with null-value. * <p> * {@code Option.empty()} is a syntactic sugar for {@code Option.of(null)}. * </p> * @param <T> The value type. * @return an {@link Option} with a null-value. */ public static <T> Option<T> empty() { @SuppressWarnings("unchecked") Option<T> empty = (Option<T>) EMPTY; return empty; } /** * Returns an {@link Option} instance with no-value. * * @param <T> Type of the non-existent value. * @return An Option type with no-value. */ public static <T> Option<T> uninitialized() { @SuppressWarnings("unchecked") Option<T> uninitialized = (Option<T>) UNINITIALIZED; return uninitialized; } /** * Return {@code true} if this instance is initialized with a null-value or non-null-value, * otherwise {@code false}. * * @return {@code true} if there is a value present, otherwise {@code false} */ public boolean isInitialized() { return this.isInitialized; } /** * Gets the value in the {@link Option}. * * @return The value. * @throws NoSuchElementException thrown if the {@link Option} has no value. */ private Option() { this.isInitialized = false; this.value = null; } private Option(T value) { this.isInitialized = true; this.value = value; } }
class Option<T> { private static final Option<?> UNINITIALIZED = new Option<>(); private static final Option<?> EMPTY = new Option<>(null); private final boolean isInitialized; private final T value; /** * Returns an {@link Option} with the specified null-value or non-null-value. * * @param <T> The value type. * @param value the value. * @return an {@link Option} with the value present. */ public static <T> Option<T> of(T value) { return value == null ? empty() : new Option<>(value); } /** * Returns an {@link Option} with null-value. * <p> * {@code Option.empty()} is a syntactic sugar for {@code Option.of(null)}. * </p> * @param <T> The value type. * @return an {@link Option} with a null-value. */ public static <T> Option<T> empty() { @SuppressWarnings("unchecked") Option<T> empty = (Option<T>) EMPTY; return empty; } /** * Returns an {@link Option} instance with no-value. * * @param <T> Type of the non-existent value. * @return An Option type with no-value. */ public static <T> Option<T> uninitialized() { @SuppressWarnings("unchecked") Option<T> uninitialized = (Option<T>) UNINITIALIZED; return uninitialized; } /** * Return {@code true} if this instance is initialized with a null-value or non-null-value, * otherwise {@code false}. * * @return {@code true} if a value has been initialized, otherwise {@code false} */ public boolean isInitialized() { return this.isInitialized; } /** * Gets the value in the {@link Option}. * * @return The {@code null} (null-value) or non-null-value that the {@link Option} * is initialized with. * @throws NoSuchElementException thrown if the {@link Option} is in no-value state. */ private Option() { this.isInitialized = false; this.value = null; } private Option(T value) { this.isInitialized = true; this.value = value; } }
@anuchandy - logging the exception before throwing is just a general guideline to help us investigate issues when customers contact us. In this case, it's debatable whether it adds too much value, so, I am fine with not logging if this doesn't help much in troubleshooting any issues. If we do want to log, then instead of creating a lot of logger instances, we can simply use a static logger.
public T getValue() { if (!this.isInitialized) { throw new NoSuchElementException("No value present"); } return this.value; }
throw new NoSuchElementException("No value present");
public T getValue() { if (!this.isInitialized) { throw new NoSuchElementException("No value initialized"); } return this.value; }
class Option<T> { private static final Option<?> UNINITIALIZED = new Option<>(); private static final Option<?> EMPTY = new Option<>(null); private final boolean isInitialized; private final T value; /** * Returns an {@link Option} with the specified null-value or non-null-value. * * @param <T> The value type. * @param value the value. * @return an {@link Option} with the value present. */ public static <T> Option<T> of(T value) { return value == null ? empty() : new Option<>(value); } /** * Returns an {@link Option} with null-value. * <p> * {@code Option.empty()} is a syntactic sugar for {@code Option.of(null)}. * </p> * @param <T> The value type. * @return an {@link Option} with a null-value. */ public static <T> Option<T> empty() { @SuppressWarnings("unchecked") Option<T> empty = (Option<T>) EMPTY; return empty; } /** * Returns an {@link Option} instance with no-value. * * @param <T> Type of the non-existent value. * @return An Option type with no-value. */ public static <T> Option<T> uninitialized() { @SuppressWarnings("unchecked") Option<T> uninitialized = (Option<T>) UNINITIALIZED; return uninitialized; } /** * Return {@code true} if this instance is initialized with a null-value or non-null-value, * otherwise {@code false}. * * @return {@code true} if there is a value present, otherwise {@code false} */ public boolean isInitialized() { return this.isInitialized; } /** * Gets the value in the {@link Option}. * * @return The value. * @throws NoSuchElementException thrown if the {@link Option} has no value. */ private Option() { this.isInitialized = false; this.value = null; } private Option(T value) { this.isInitialized = true; this.value = value; } }
class Option<T> { private static final Option<?> UNINITIALIZED = new Option<>(); private static final Option<?> EMPTY = new Option<>(null); private final boolean isInitialized; private final T value; /** * Returns an {@link Option} with the specified null-value or non-null-value. * * @param <T> The value type. * @param value the value. * @return an {@link Option} with the value present. */ public static <T> Option<T> of(T value) { return value == null ? empty() : new Option<>(value); } /** * Returns an {@link Option} with null-value. * <p> * {@code Option.empty()} is a syntactic sugar for {@code Option.of(null)}. * </p> * @param <T> The value type. * @return an {@link Option} with a null-value. */ public static <T> Option<T> empty() { @SuppressWarnings("unchecked") Option<T> empty = (Option<T>) EMPTY; return empty; } /** * Returns an {@link Option} instance with no-value. * * @param <T> Type of the non-existent value. * @return An Option type with no-value. */ public static <T> Option<T> uninitialized() { @SuppressWarnings("unchecked") Option<T> uninitialized = (Option<T>) UNINITIALIZED; return uninitialized; } /** * Return {@code true} if this instance is initialized with a null-value or non-null-value, * otherwise {@code false}. * * @return {@code true} if a value has been initialized, otherwise {@code false} */ public boolean isInitialized() { return this.isInitialized; } /** * Gets the value in the {@link Option}. * * @return The {@code null} (null-value) or non-null-value that the {@link Option} * is initialized with. * @throws NoSuchElementException thrown if the {@link Option} is in no-value state. */ private Option() { this.isInitialized = false; this.value = null; } private Option(T value) { this.isInitialized = true; this.value = value; } }
thanks for the response, yep it's a bit hard to pick here - general guideline vs value addition for the specific case. Let's go without logger and add it if we ever use it in the output model.
public T getValue() { if (!this.isInitialized) { throw new NoSuchElementException("No value present"); } return this.value; }
throw new NoSuchElementException("No value present");
public T getValue() { if (!this.isInitialized) { throw new NoSuchElementException("No value initialized"); } return this.value; }
class Option<T> { private static final Option<?> UNINITIALIZED = new Option<>(); private static final Option<?> EMPTY = new Option<>(null); private final boolean isInitialized; private final T value; /** * Returns an {@link Option} with the specified null-value or non-null-value. * * @param <T> The value type. * @param value the value. * @return an {@link Option} with the value present. */ public static <T> Option<T> of(T value) { return value == null ? empty() : new Option<>(value); } /** * Returns an {@link Option} with null-value. * <p> * {@code Option.empty()} is a syntactic sugar for {@code Option.of(null)}. * </p> * @param <T> The value type. * @return an {@link Option} with a null-value. */ public static <T> Option<T> empty() { @SuppressWarnings("unchecked") Option<T> empty = (Option<T>) EMPTY; return empty; } /** * Returns an {@link Option} instance with no-value. * * @param <T> Type of the non-existent value. * @return An Option type with no-value. */ public static <T> Option<T> uninitialized() { @SuppressWarnings("unchecked") Option<T> uninitialized = (Option<T>) UNINITIALIZED; return uninitialized; } /** * Return {@code true} if this instance is initialized with a null-value or non-null-value, * otherwise {@code false}. * * @return {@code true} if there is a value present, otherwise {@code false} */ public boolean isInitialized() { return this.isInitialized; } /** * Gets the value in the {@link Option}. * * @return The value. * @throws NoSuchElementException thrown if the {@link Option} has no value. */ private Option() { this.isInitialized = false; this.value = null; } private Option(T value) { this.isInitialized = true; this.value = value; } }
class Option<T> { private static final Option<?> UNINITIALIZED = new Option<>(); private static final Option<?> EMPTY = new Option<>(null); private final boolean isInitialized; private final T value; /** * Returns an {@link Option} with the specified null-value or non-null-value. * * @param <T> The value type. * @param value the value. * @return an {@link Option} with the value present. */ public static <T> Option<T> of(T value) { return value == null ? empty() : new Option<>(value); } /** * Returns an {@link Option} with null-value. * <p> * {@code Option.empty()} is a syntactic sugar for {@code Option.of(null)}. * </p> * @param <T> The value type. * @return an {@link Option} with a null-value. */ public static <T> Option<T> empty() { @SuppressWarnings("unchecked") Option<T> empty = (Option<T>) EMPTY; return empty; } /** * Returns an {@link Option} instance with no-value. * * @param <T> Type of the non-existent value. * @return An Option type with no-value. */ public static <T> Option<T> uninitialized() { @SuppressWarnings("unchecked") Option<T> uninitialized = (Option<T>) UNINITIALIZED; return uninitialized; } /** * Return {@code true} if this instance is initialized with a null-value or non-null-value, * otherwise {@code false}. * * @return {@code true} if a value has been initialized, otherwise {@code false} */ public boolean isInitialized() { return this.isInitialized; } /** * Gets the value in the {@link Option}. * * @return The {@code null} (null-value) or non-null-value that the {@link Option} * is initialized with. * @throws NoSuchElementException thrown if the {@link Option} is in no-value state. */ private Option() { this.isInitialized = false; this.value = null; } private Option(T value) { this.isInitialized = true; this.value = value; } }
Same here, Chat takes a token, not the access key. (Look out for CommunicationUserCredential which always wraps a token)
public ChatClient createChatClient() { String endpoint = "https: NettyAsyncHttpClientBuilder httpClientBuilder = new NettyAsyncHttpClientBuilder(); HttpClient httpClient = httpClientBuilder.build(); String accessKey = "SECRET"; CommunicationUserCredential credential = new CommunicationUserCredential(accessKey); final ChatClientBuilder builder = new ChatClientBuilder(); builder.endpoint(endpoint) .credential(credential) .httpClient(httpClient); ChatClient chatClient = builder.buildClient(); return chatClient; }
CommunicationUserCredential credential = new CommunicationUserCredential(accessKey);
public ChatClient createChatClient() { String endpoint = "https: NettyAsyncHttpClientBuilder httpClientBuilder = new NettyAsyncHttpClientBuilder(); HttpClient httpClient = httpClientBuilder.build(); String token = "SECRET"; CommunicationUserCredential credential = new CommunicationUserCredential(token); final ChatClientBuilder builder = new ChatClientBuilder(); builder.endpoint(endpoint) .credential(credential) .httpClient(httpClient); ChatClient chatClient = builder.buildClient(); return chatClient; }
class ReadmeSamples { /** * Sample code for creating a sync chat client. * * @return the chat client. */ /** * Sample code for creating a chat thread using the sync chat client. */ public void createChatThread() { ChatClient chatClient = createChatClient(); CommunicationUser user1 = new CommunicationUser("Id 1"); CommunicationUser user2 = new CommunicationUser("Id 2"); List<ChatThreadMember> members = new ArrayList<ChatThreadMember>(); ChatThreadMember firstThreadMember = new ChatThreadMember() .setUser(user1) .setDisplayName("Member Display Name 1"); ChatThreadMember secondThreadMember = new ChatThreadMember() .setUser(user2) .setDisplayName("Member Display Name 2"); members.add(firstThreadMember); members.add(secondThreadMember); CreateChatThreadOptions createChatThreadOptions = new CreateChatThreadOptions() .setTopic("Topic") .setMembers(members); ChatThreadClient chatThreadClient = chatClient.createChatThread(createChatThreadOptions); String chatThreadId = chatThreadClient.getChatThreadId(); } /** * Sample code for getting a chat thread using the sync chat client. */ public void getChatThread() { ChatClient chatClient = createChatClient(); String chatThreadId = "Id"; ChatThread chatThread = chatClient.getChatThread(chatThreadId); } /** * Sample code for deleting a chat thread using the sync chat client. */ public void deleteChatThread() { ChatClient chatClient = createChatClient(); String chatThreadId = "Id"; chatClient.deleteChatThread(chatThreadId); } /** * Sample code for getting a sync chat thread client using the sync chat client. * * @return the chat thread client. */ public ChatThreadClient getChatThreadClient() { ChatClient chatClient = createChatClient(); String chatThreadId = "Id"; ChatThreadClient chatThreadClient = chatClient.getChatThreadClient(chatThreadId); return chatThreadClient; } /** * Sample code for updating a chat thread using the sync chat thread client. */ public void updateChatThread() { ChatThreadClient chatThreadClient = getChatThreadClient(); UpdateChatThreadOptions updateChatThreadOptions = new UpdateChatThreadOptions() .setTopic("New Topic"); chatThreadClient.updateChatThread(updateChatThreadOptions); } /** * Sample code for sending a chat message using the sync chat thread client. */ public void sendChatMessage() { ChatThreadClient chatThreadClient = getChatThreadClient(); SendChatMessageOptions sendChatMessageOptions = new SendChatMessageOptions() .setContent("Message content") .setPriority(ChatMessagePriority.NORMAL) .setSenderDisplayName("Sender Display Name"); SendChatMessageResult sendChatMessageResult = chatThreadClient.sendMessage(sendChatMessageOptions); String chatMessageId = sendChatMessageResult.getId(); } /** * Sample code for getting a chat message using the sync chat thread client. */ public void getChatMessage() { ChatThreadClient chatThreadClient = getChatThreadClient(); String chatMessageId = "Id"; ChatMessage chatMessage = chatThreadClient.getMessage(chatMessageId); } /** * Sample code getting the thread messages using the sync chat thread client. */ public void getChatMessages() { ChatThreadClient chatThreadClient = getChatThreadClient(); PagedIterable<ChatMessage> chatMessagesResponse = chatThreadClient.listMessages(); chatMessagesResponse.iterableByPage().forEach(resp -> { System.out.printf("Response headers are %s. Url %s and status code %d %n", resp.getHeaders(), resp.getRequest().getUrl(), resp.getStatusCode()); resp.getItems().forEach(message -> { System.out.printf("Message id is %s.", message.getId()); }); }); } /** * Sample code updating a thread message using the sync chat thread client. */ public void updateChatMessage() { ChatThreadClient chatThreadClient = getChatThreadClient(); String chatMessageId = "Id"; UpdateChatMessageOptions updateChatMessageOptions = new UpdateChatMessageOptions() .setContent("Updated message content"); chatThreadClient.updateMessage(chatMessageId, updateChatMessageOptions); } /** * Sample code deleting a thread message using the sync chat thread client. */ public void deleteChatMessage() { ChatThreadClient chatThreadClient = getChatThreadClient(); String chatMessageId = "Id"; chatThreadClient.deleteMessage(chatMessageId); } /** * Sample code listing chat thread members using the sync chat thread client. */ public void listChatThreadMember() { ChatThreadClient chatThreadClient = getChatThreadClient(); PagedIterable<ChatThreadMember> chatThreadMembersResponse = chatThreadClient.listMembers(); chatThreadMembersResponse.iterableByPage().forEach(resp -> { System.out.printf("Response headers are %s. Url %s and status code %d %n", resp.getHeaders(), resp.getRequest().getUrl(), resp.getStatusCode()); resp.getItems().forEach(chatMember -> { System.out.printf("Member id is %s.", chatMember.getUser().getId()); }); }); } /** * Sample code adding chat thread members using the sync chat thread client. */ public void addChatThreadMembers() { ChatThreadClient chatThreadClient = getChatThreadClient(); CommunicationUser user1 = new CommunicationUser("Id 1"); CommunicationUser user2 = new CommunicationUser("Id 2"); List<ChatThreadMember> members = new ArrayList<ChatThreadMember>(); ChatThreadMember firstThreadMember = new ChatThreadMember() .setUser(user1) .setDisplayName("Display Name 1"); ChatThreadMember secondThreadMember = new ChatThreadMember() .setUser(user2) .setDisplayName("Display Name 2"); members.add(firstThreadMember); members.add(secondThreadMember); AddChatThreadMembersOptions addChatThreadMembersOptions = new AddChatThreadMembersOptions() .setMembers(members); chatThreadClient.addMembers(addChatThreadMembersOptions); } /** * Sample code removing a chat thread member using the sync chat thread client. */ public void removeChatThreadMember() { ChatThreadClient chatThreadClient = getChatThreadClient(); CommunicationUser user = new CommunicationUser("Id"); chatThreadClient.removeMember(user); } /** * Sample code sending a read receipt using the sync chat thread client. */ public void sendReadReceipt() { ChatThreadClient chatThreadClient = getChatThreadClient(); String chatMessageId = "Id"; chatThreadClient.sendReadReceipt(chatMessageId); } /** * Sample code listing read receipts using the sync chat thread client. */ public void listReadReceipts() { ChatThreadClient chatThreadClient = getChatThreadClient(); PagedIterable<ReadReceipt> readReceiptsResponse = chatThreadClient.listReadReceipts(); readReceiptsResponse.iterableByPage().forEach(resp -> { System.out.printf("Response headers are %s. Url %s and status code %d %n", resp.getHeaders(), resp.getRequest().getUrl(), resp.getStatusCode()); resp.getItems().forEach(readReceipt -> { System.out.printf("Read message id is %s.", readReceipt.getChatMessageId()); }); }); } /** * Sample code sending a read receipt using the sync chat thread client. */ public void sendTypingNotification() { ChatThreadClient chatThreadClient = getChatThreadClient(); chatThreadClient.sendTypingNotification(); } }
class ReadmeSamples { /** * Sample code for creating a sync chat client. * * @return the chat client. */ /** * Sample code for creating a chat thread using the sync chat client. */ public void createChatThread() { ChatClient chatClient = createChatClient(); CommunicationUser user1 = new CommunicationUser("Id 1"); CommunicationUser user2 = new CommunicationUser("Id 2"); List<ChatThreadMember> members = new ArrayList<ChatThreadMember>(); ChatThreadMember firstThreadMember = new ChatThreadMember() .setUser(user1) .setDisplayName("Member Display Name 1"); ChatThreadMember secondThreadMember = new ChatThreadMember() .setUser(user2) .setDisplayName("Member Display Name 2"); members.add(firstThreadMember); members.add(secondThreadMember); CreateChatThreadOptions createChatThreadOptions = new CreateChatThreadOptions() .setTopic("Topic") .setMembers(members); ChatThreadClient chatThreadClient = chatClient.createChatThread(createChatThreadOptions); String chatThreadId = chatThreadClient.getChatThreadId(); } /** * Sample code for getting a chat thread using the sync chat client. */ public void getChatThread() { ChatClient chatClient = createChatClient(); String chatThreadId = "Id"; ChatThread chatThread = chatClient.getChatThread(chatThreadId); } /** * Sample code for deleting a chat thread using the sync chat client. */ public void deleteChatThread() { ChatClient chatClient = createChatClient(); String chatThreadId = "Id"; chatClient.deleteChatThread(chatThreadId); } /** * Sample code for getting a sync chat thread client using the sync chat client. * * @return the chat thread client. */ public ChatThreadClient getChatThreadClient() { ChatClient chatClient = createChatClient(); String chatThreadId = "Id"; ChatThreadClient chatThreadClient = chatClient.getChatThreadClient(chatThreadId); return chatThreadClient; } /** * Sample code for updating a chat thread using the sync chat thread client. */ public void updateChatThread() { ChatThreadClient chatThreadClient = getChatThreadClient(); UpdateChatThreadOptions updateChatThreadOptions = new UpdateChatThreadOptions() .setTopic("New Topic"); chatThreadClient.updateChatThread(updateChatThreadOptions); } /** * Sample code for sending a chat message using the sync chat thread client. */ public void sendChatMessage() { ChatThreadClient chatThreadClient = getChatThreadClient(); SendChatMessageOptions sendChatMessageOptions = new SendChatMessageOptions() .setContent("Message content") .setPriority(ChatMessagePriority.NORMAL) .setSenderDisplayName("Sender Display Name"); SendChatMessageResult sendChatMessageResult = chatThreadClient.sendMessage(sendChatMessageOptions); String chatMessageId = sendChatMessageResult.getId(); } /** * Sample code for getting a chat message using the sync chat thread client. */ public void getChatMessage() { ChatThreadClient chatThreadClient = getChatThreadClient(); String chatMessageId = "Id"; ChatMessage chatMessage = chatThreadClient.getMessage(chatMessageId); } /** * Sample code getting the thread messages using the sync chat thread client. */ public void getChatMessages() { ChatThreadClient chatThreadClient = getChatThreadClient(); PagedIterable<ChatMessage> chatMessagesResponse = chatThreadClient.listMessages(); chatMessagesResponse.iterableByPage().forEach(resp -> { System.out.printf("Response headers are %s. Url %s and status code %d %n", resp.getHeaders(), resp.getRequest().getUrl(), resp.getStatusCode()); resp.getItems().forEach(message -> { System.out.printf("Message id is %s.", message.getId()); }); }); } /** * Sample code updating a thread message using the sync chat thread client. */ public void updateChatMessage() { ChatThreadClient chatThreadClient = getChatThreadClient(); String chatMessageId = "Id"; UpdateChatMessageOptions updateChatMessageOptions = new UpdateChatMessageOptions() .setContent("Updated message content"); chatThreadClient.updateMessage(chatMessageId, updateChatMessageOptions); } /** * Sample code deleting a thread message using the sync chat thread client. */ public void deleteChatMessage() { ChatThreadClient chatThreadClient = getChatThreadClient(); String chatMessageId = "Id"; chatThreadClient.deleteMessage(chatMessageId); } /** * Sample code listing chat thread members using the sync chat thread client. */ public void listChatThreadMember() { ChatThreadClient chatThreadClient = getChatThreadClient(); PagedIterable<ChatThreadMember> chatThreadMembersResponse = chatThreadClient.listMembers(); chatThreadMembersResponse.iterableByPage().forEach(resp -> { System.out.printf("Response headers are %s. Url %s and status code %d %n", resp.getHeaders(), resp.getRequest().getUrl(), resp.getStatusCode()); resp.getItems().forEach(chatMember -> { System.out.printf("Member id is %s.", chatMember.getUser().getId()); }); }); } /** * Sample code adding chat thread members using the sync chat thread client. */ public void addChatThreadMembers() { ChatThreadClient chatThreadClient = getChatThreadClient(); CommunicationUser user1 = new CommunicationUser("Id 1"); CommunicationUser user2 = new CommunicationUser("Id 2"); List<ChatThreadMember> members = new ArrayList<ChatThreadMember>(); ChatThreadMember firstThreadMember = new ChatThreadMember() .setUser(user1) .setDisplayName("Display Name 1"); ChatThreadMember secondThreadMember = new ChatThreadMember() .setUser(user2) .setDisplayName("Display Name 2"); members.add(firstThreadMember); members.add(secondThreadMember); AddChatThreadMembersOptions addChatThreadMembersOptions = new AddChatThreadMembersOptions() .setMembers(members); chatThreadClient.addMembers(addChatThreadMembersOptions); } /** * Sample code removing a chat thread member using the sync chat thread client. */ public void removeChatThreadMember() { ChatThreadClient chatThreadClient = getChatThreadClient(); CommunicationUser user = new CommunicationUser("Id"); chatThreadClient.removeMember(user); } /** * Sample code sending a read receipt using the sync chat thread client. */ public void sendReadReceipt() { ChatThreadClient chatThreadClient = getChatThreadClient(); String chatMessageId = "Id"; chatThreadClient.sendReadReceipt(chatMessageId); } /** * Sample code listing read receipts using the sync chat thread client. */ public void listReadReceipts() { ChatThreadClient chatThreadClient = getChatThreadClient(); PagedIterable<ReadReceipt> readReceiptsResponse = chatThreadClient.listReadReceipts(); readReceiptsResponse.iterableByPage().forEach(resp -> { System.out.printf("Response headers are %s. Url %s and status code %d %n", resp.getHeaders(), resp.getRequest().getUrl(), resp.getStatusCode()); resp.getItems().forEach(readReceipt -> { System.out.printf("Read message id is %s.", readReceipt.getChatMessageId()); }); }); } /** * Sample code sending a read receipt using the sync chat thread client. */ public void sendTypingNotification() { ChatThreadClient chatThreadClient = getChatThreadClient(); chatThreadClient.sendTypingNotification(); } }
should we add a test for using `pagedIterable.stream().parallel()` and iteration on output of parallel? just double confirming our iterable impl is stream safe.
public void streamFindFirstOnlyRetrievesOnePage() throws InterruptedException { OnlyOnePageRetriever pageRetriever = new OnlyOnePageRetriever(); OnlyOnePagedIterable pagedIterable = new OnlyOnePagedIterable(new OnlyOnePagedFlux(() -> pageRetriever)); pagedIterable.stream().count(); int fullPageCount = pageRetriever.getGetCount(); assertTrue(fullPageCount > 1); Integer next = pagedIterable.stream().findFirst().get(); Thread.sleep(2000); /* * Given that each page contains more than one element we are able to only retrieve a single page. */ assertEquals(1, pageRetriever.getGetCount() - fullPageCount); }
}
public void streamFindFirstOnlyRetrievesOnePage() throws InterruptedException { OnlyOnePageRetriever pageRetriever = new OnlyOnePageRetriever(DEFAULT_PAGE_COUNT); OnlyOnePagedIterable pagedIterable = new OnlyOnePagedIterable(new OnlyOnePagedFlux(() -> pageRetriever)); pagedIterable.stream().count(); assertEquals(DEFAULT_PAGE_COUNT, pageRetriever.getGetCount()); Integer next = pagedIterable.stream().findFirst().get(); Thread.sleep(2000); /* * Given that each page contains more than one element we are able to only retrieve a single page. */ assertEquals(1, pageRetriever.getGetCount() - DEFAULT_PAGE_COUNT); }
class TestPagedFlux<T> extends PagedFlux<T> { private int nextPageRetrievals = 0; TestPagedFlux(Supplier<Mono<PagedResponse<T>>> firstPageRetriever, Function<String, Mono<PagedResponse<T>>> nextPageRetriever) { super(firstPageRetriever, nextPageRetriever); } @Override public Flux<PagedResponse<T>> byPage(String continuationToken) { nextPageRetrievals++; return super.byPage(continuationToken); } /* * Returns the number of times another page has been retrieved. */ int getNextPageRetrievals() { return nextPageRetrievals; } }
class TestPagedFlux<T> extends PagedFlux<T> { private int nextPageRetrievals = 0; TestPagedFlux(Supplier<Mono<PagedResponse<T>>> firstPageRetriever, Function<String, Mono<PagedResponse<T>>> nextPageRetriever) { super(firstPageRetriever, nextPageRetriever); } @Override public Flux<PagedResponse<T>> byPage(String continuationToken) { nextPageRetrievals++; return super.byPage(continuationToken); } /* * Returns the number of times another page has been retrieved. */ int getNextPageRetrievals() { return nextPageRetrievals; } }
Will add tests for these
public void streamFindFirstOnlyRetrievesOnePage() throws InterruptedException { OnlyOnePageRetriever pageRetriever = new OnlyOnePageRetriever(); OnlyOnePagedIterable pagedIterable = new OnlyOnePagedIterable(new OnlyOnePagedFlux(() -> pageRetriever)); pagedIterable.stream().count(); int fullPageCount = pageRetriever.getGetCount(); assertTrue(fullPageCount > 1); Integer next = pagedIterable.stream().findFirst().get(); Thread.sleep(2000); /* * Given that each page contains more than one element we are able to only retrieve a single page. */ assertEquals(1, pageRetriever.getGetCount() - fullPageCount); }
}
public void streamFindFirstOnlyRetrievesOnePage() throws InterruptedException { OnlyOnePageRetriever pageRetriever = new OnlyOnePageRetriever(DEFAULT_PAGE_COUNT); OnlyOnePagedIterable pagedIterable = new OnlyOnePagedIterable(new OnlyOnePagedFlux(() -> pageRetriever)); pagedIterable.stream().count(); assertEquals(DEFAULT_PAGE_COUNT, pageRetriever.getGetCount()); Integer next = pagedIterable.stream().findFirst().get(); Thread.sleep(2000); /* * Given that each page contains more than one element we are able to only retrieve a single page. */ assertEquals(1, pageRetriever.getGetCount() - DEFAULT_PAGE_COUNT); }
class TestPagedFlux<T> extends PagedFlux<T> { private int nextPageRetrievals = 0; TestPagedFlux(Supplier<Mono<PagedResponse<T>>> firstPageRetriever, Function<String, Mono<PagedResponse<T>>> nextPageRetriever) { super(firstPageRetriever, nextPageRetriever); } @Override public Flux<PagedResponse<T>> byPage(String continuationToken) { nextPageRetrievals++; return super.byPage(continuationToken); } /* * Returns the number of times another page has been retrieved. */ int getNextPageRetrievals() { return nextPageRetrievals; } }
class TestPagedFlux<T> extends PagedFlux<T> { private int nextPageRetrievals = 0; TestPagedFlux(Supplier<Mono<PagedResponse<T>>> firstPageRetriever, Function<String, Mono<PagedResponse<T>>> nextPageRetriever) { super(firstPageRetriever, nextPageRetriever); } @Override public Flux<PagedResponse<T>> byPage(String continuationToken) { nextPageRetrievals++; return super.byPage(continuationToken); } /* * Returns the number of times another page has been retrieved. */ int getNextPageRetrievals() { return nextPageRetrievals; } }
nice! thanks.
public Mono<StoreResponse> invokeStoreAsync(final Uri addressUri, final RxDocumentServiceRequest request) { checkNotNull(addressUri, "expected non-null address"); checkNotNull(request, "expected non-null request"); this.throwIfClosed(); final URI address = addressUri.getURI(); final RntbdRequestArgs requestArgs = new RntbdRequestArgs(request, address); final RntbdEndpoint endpoint = this.endpointProvider.get(address); final RntbdRequestRecord record = endpoint.request(requestArgs); final Context reactorContext = Context.of(KEY_ON_ERROR_DROPPED, onErrorDropHookWithReduceLogLevel); final Mono<StoreResponse> result = Mono.fromFuture(record.whenComplete((response, throwable) -> { record.stage(RntbdRequestRecord.Stage.COMPLETED); if (request.requestContext.cosmosDiagnostics == null) { request.requestContext.cosmosDiagnostics = BridgeInternal.createCosmosDiagnostics(); } if (response != null) { RequestTimeline timeline = record.takeTimelineSnapshot(); response.setRequestTimeline(timeline); response.setEndpointStatistics(record.serviceEndpointStatistics()); response.setRntbdResponseLength(record.responseLength()); response.setRntbdRequestLength(record.requestLength()); response.setRequestPayloadLength(request.getContentLength()); response.setRntbdChannelTaskQueueSize(record.channelTaskQueueLength()); response.setRntbdPendingRequestSize(record.pendingRequestQueueSize()); } })).onErrorMap(throwable -> { Throwable error = throwable instanceof CompletionException ? throwable.getCause() : throwable; if (!(error instanceof CosmosException)) { String unexpectedError = RntbdObjectMapper.toJson(error); reportIssue(logger, endpoint, "request completed with an unexpected {}: \\{\"record\":{},\"error\":{}}", error.getClass(), record, unexpectedError); error = new GoneException( lenientFormat("an unexpected %s occurred: %s", unexpectedError), address.toString()); } assert error instanceof CosmosException; CosmosException cosmosException = (CosmosException) error; BridgeInternal.setServiceEndpointStatistics(cosmosException, record.serviceEndpointStatistics()); BridgeInternal.setRntbdRequestLength(cosmosException, record.requestLength()); BridgeInternal.setRntbdResponseLength(cosmosException, record.responseLength()); BridgeInternal.setRequestBodyLength(cosmosException, request.getContentLength()); BridgeInternal.setRequestTimeline(cosmosException, record.takeTimelineSnapshot()); BridgeInternal.setRntbdPendingRequestQueueSize(cosmosException, record.pendingRequestQueueSize()); BridgeInternal.setChannelTaskQueueSize(cosmosException, record.channelTaskQueueLength()); BridgeInternal.setSendingRequestStarted(cosmosException, record.hasSendingRequestStarted()); return cosmosException; }); return result.doFinally(signalType -> { if (signalType != SignalType.CANCEL) { return; } result.subscribe( response -> { if (logger.isDebugEnabled()) { logger.debug( "received response to cancelled request: {\"request\":{},\"response\":{\"type\":{}," + "\"value\":{}}}}", RntbdObjectMapper.toJson(record), response.getClass().getSimpleName(), RntbdObjectMapper.toJson(response)); } }, throwable -> { if (logger.isDebugEnabled()) { logger.debug( "received response to cancelled request: {\"request\":{},\"response\":{\"type\":{}," + "\"value\":{}}}", RntbdObjectMapper.toJson(record), throwable.getClass().getSimpleName(), RntbdObjectMapper.toJson(throwable)); } }); }).subscriberContext(reactorContext);
BridgeInternal.setSendingRequestStarted(cosmosException, record.hasSendingRequestStarted());
public Mono<StoreResponse> invokeStoreAsync(final Uri addressUri, final RxDocumentServiceRequest request) { checkNotNull(addressUri, "expected non-null address"); checkNotNull(request, "expected non-null request"); this.throwIfClosed(); final URI address = addressUri.getURI(); final RntbdRequestArgs requestArgs = new RntbdRequestArgs(request, address); final RntbdEndpoint endpoint = this.endpointProvider.get(address); final RntbdRequestRecord record = endpoint.request(requestArgs); final Context reactorContext = Context.of(KEY_ON_ERROR_DROPPED, onErrorDropHookWithReduceLogLevel); final Mono<StoreResponse> result = Mono.fromFuture(record.whenComplete((response, throwable) -> { record.stage(RntbdRequestRecord.Stage.COMPLETED); if (request.requestContext.cosmosDiagnostics == null) { request.requestContext.cosmosDiagnostics = request.createCosmosDiagnostics(); } if (response != null) { RequestTimeline timeline = record.takeTimelineSnapshot(); response.setRequestTimeline(timeline); response.setEndpointStatistics(record.serviceEndpointStatistics()); response.setRntbdResponseLength(record.responseLength()); response.setRntbdRequestLength(record.requestLength()); response.setRequestPayloadLength(request.getContentLength()); response.setRntbdChannelTaskQueueSize(record.channelTaskQueueLength()); response.setRntbdPendingRequestSize(record.pendingRequestQueueSize()); } })).onErrorMap(throwable -> { Throwable error = throwable instanceof CompletionException ? throwable.getCause() : throwable; if (!(error instanceof CosmosException)) { String unexpectedError = RntbdObjectMapper.toJson(error); reportIssue(logger, endpoint, "request completed with an unexpected {}: \\{\"record\":{},\"error\":{}}", error.getClass(), record, unexpectedError); error = new GoneException( lenientFormat("an unexpected %s occurred: %s", unexpectedError), address.toString()); } assert error instanceof CosmosException; CosmosException cosmosException = (CosmosException) error; BridgeInternal.setServiceEndpointStatistics(cosmosException, record.serviceEndpointStatistics()); BridgeInternal.setRntbdRequestLength(cosmosException, record.requestLength()); BridgeInternal.setRntbdResponseLength(cosmosException, record.responseLength()); BridgeInternal.setRequestBodyLength(cosmosException, request.getContentLength()); BridgeInternal.setRequestTimeline(cosmosException, record.takeTimelineSnapshot()); BridgeInternal.setRntbdPendingRequestQueueSize(cosmosException, record.pendingRequestQueueSize()); BridgeInternal.setChannelTaskQueueSize(cosmosException, record.channelTaskQueueLength()); BridgeInternal.setSendingRequestStarted(cosmosException, record.hasSendingRequestStarted()); return cosmosException; }); return result.doFinally(signalType -> { if (signalType != SignalType.CANCEL) { return; } result.subscribe( response -> { if (logger.isDebugEnabled()) { logger.debug( "received response to cancelled request: {\"request\":{},\"response\":{\"type\":{}," + "\"value\":{}}}}", RntbdObjectMapper.toJson(record), response.getClass().getSimpleName(), RntbdObjectMapper.toJson(response)); } }, throwable -> { if (logger.isDebugEnabled()) { logger.debug( "received response to cancelled request: {\"request\":{},\"response\":{\"type\":{}," + "\"value\":{}}}", RntbdObjectMapper.toJson(record), throwable.getClass().getSimpleName(), RntbdObjectMapper.toJson(throwable)); } }); }
class RntbdTransportClient extends TransportClient { private static final String TAG_NAME = RntbdTransportClient.class.getSimpleName(); private static final AtomicLong instanceCount = new AtomicLong(); private static final Logger logger = LoggerFactory.getLogger(RntbdTransportClient.class); /** * NOTE: This context key name has been copied from {link Hooks * not exposed as public Api but package internal only * * A key that can be used to store a sequence-specific {@link Hooks * hook in a {@link Context}, as a {@link Consumer Consumer&lt;Throwable&gt;}. */ private static final String KEY_ON_ERROR_DROPPED = "reactor.onErrorDropped.local"; /** * This lambda gets injected into the local Reactor Context to react tot he onErrorDropped event and * log the throwable with DEBUG level instead of the ERROR level used in the default hook. * This is safe here because we guarantee resource clean-up with the doFinally-lambda */ private static final Consumer<? super Throwable> onErrorDropHookWithReduceLogLevel = throwable -> { if (logger.isDebugEnabled()) { logger.debug( "Extra error - on error dropped - operator called :", throwable); } }; private final AtomicBoolean closed = new AtomicBoolean(); private final RntbdEndpoint.Provider endpointProvider; private final long id; private final Tag tag; RntbdTransportClient(final RntbdEndpoint.Provider endpointProvider) { this.endpointProvider = endpointProvider; this.id = instanceCount.incrementAndGet(); this.tag = RntbdTransportClient.tag(this.id); } RntbdTransportClient(final Options options, final SslContext sslContext) { this.endpointProvider = new RntbdServiceEndpoint.Provider(this, options, sslContext); this.id = instanceCount.incrementAndGet(); this.tag = RntbdTransportClient.tag(this.id); } RntbdTransportClient(final Configs configs, final ConnectionPolicy connectionPolicy, final UserAgentContainer userAgent) { this(new Options.Builder(connectionPolicy).userAgent(userAgent).build(), configs.getSslContext()); } public boolean isClosed() { return this.closed.get(); } @Override public void close() { if (this.closed.compareAndSet(false, true)) { logger.debug("close {}", this); this.endpointProvider.close(); return; } logger.debug("already closed {}", this); } public int endpointCount() { return this.endpointProvider.count(); } public int endpointEvictionCount() { return this.endpointProvider.evictions(); } public long id() { return this.id; } @Override ).subscriberContext(reactorContext); }
class RntbdTransportClient extends TransportClient { private static final String TAG_NAME = RntbdTransportClient.class.getSimpleName(); private static final AtomicLong instanceCount = new AtomicLong(); private static final Logger logger = LoggerFactory.getLogger(RntbdTransportClient.class); /** * NOTE: This context key name has been copied from {link Hooks * not exposed as public Api but package internal only * * A key that can be used to store a sequence-specific {@link Hooks * hook in a {@link Context}, as a {@link Consumer Consumer&lt;Throwable&gt;}. */ private static final String KEY_ON_ERROR_DROPPED = "reactor.onErrorDropped.local"; /** * This lambda gets injected into the local Reactor Context to react tot he onErrorDropped event and * log the throwable with DEBUG level instead of the ERROR level used in the default hook. * This is safe here because we guarantee resource clean-up with the doFinally-lambda */ private static final Consumer<? super Throwable> onErrorDropHookWithReduceLogLevel = throwable -> { if (logger.isDebugEnabled()) { logger.debug( "Extra error - on error dropped - operator called :", throwable); } }; private final AtomicBoolean closed = new AtomicBoolean(); private final RntbdEndpoint.Provider endpointProvider; private final long id; private final Tag tag; RntbdTransportClient(final RntbdEndpoint.Provider endpointProvider) { this.endpointProvider = endpointProvider; this.id = instanceCount.incrementAndGet(); this.tag = RntbdTransportClient.tag(this.id); } RntbdTransportClient(final Options options, final SslContext sslContext) { this.endpointProvider = new RntbdServiceEndpoint.Provider(this, options, sslContext); this.id = instanceCount.incrementAndGet(); this.tag = RntbdTransportClient.tag(this.id); } public boolean isClosed() { return this.closed.get(); } @Override public void close() { if (this.closed.compareAndSet(false, true)) { logger.debug("close {}", this); this.endpointProvider.close(); return; } logger.debug("already closed {}", this); } public int endpointCount() { return this.endpointProvider.count(); } public int endpointEvictionCount() { return this.endpointProvider.evictions(); } public long id() { return this.id; } @Override ).subscriberContext(reactorContext); }
I wonder if we should incorporate that into the RntbdRequestRecord stages as SEND_STARTED stage, and this as an event to the request timeline. e.g.: QUEUED, PIPELINED, SEND_STARTED, SENT, RECEIVED, COMPLETED
void setSendingRequestHasStarted() { this.sendingRequestHasStarted = true; }
this.sendingRequestHasStarted = true;
void setSendingRequestHasStarted() { this.sendingRequestHasStarted = true; }
class RntbdRequestRecord extends CompletableFuture<StoreResponse> { private static final Logger logger = LoggerFactory.getLogger(RntbdRequestRecord.class); private static final AtomicIntegerFieldUpdater<RntbdRequestRecord> REQUEST_LENGTH = AtomicIntegerFieldUpdater.newUpdater(RntbdRequestRecord.class, "requestLength"); private static final AtomicIntegerFieldUpdater<RntbdRequestRecord> RESPONSE_LENGTH = AtomicIntegerFieldUpdater.newUpdater(RntbdRequestRecord.class, "responseLength"); private static final AtomicReferenceFieldUpdater<RntbdRequestRecord, Stage> STAGE = AtomicReferenceFieldUpdater.newUpdater( RntbdRequestRecord.class, Stage.class, "stage"); private final RntbdRequestArgs args; private volatile int channelTaskQueueLength; private volatile int pendingRequestsQueueSize; private volatile RntbdEndpointStatistics serviceEndpointStatistics; private volatile int requestLength; private volatile int responseLength; private volatile Stage stage; private volatile Instant timeCompleted; private volatile Instant timePipelined; private final Instant timeQueued; private volatile Instant timeSent; private volatile Instant timeReceived; private volatile boolean sendingRequestHasStarted; protected RntbdRequestRecord(final RntbdRequestArgs args) { checkNotNull(args, "expected non-null args"); this.timeQueued = Instant.now(); this.requestLength = -1; this.responseLength = -1; this.stage = Stage.QUEUED; this.args = args; } public UUID activityId() { return this.args.activityId(); } public RntbdRequestArgs args() { return this.args; } public Duration lifetime() { return this.args.lifetime(); } public int requestLength() { return this.requestLength; } RntbdRequestRecord requestLength(int value) { REQUEST_LENGTH.set(this, value); return this; } public int responseLength() { return this.responseLength; } RntbdRequestRecord responseLength(int value) { RESPONSE_LENGTH.set(this, value); return this; } public Stage stage() { return this.stage; } public RntbdRequestRecord stage(final Stage value) { final Instant time = Instant.now(); STAGE.updateAndGet(this, current -> { switch (value) { case PIPELINED: if (current != Stage.QUEUED) { logger.debug("Expected transition from QUEUED to PIPELINED, not {} to PIPELINED", current); break; } this.timePipelined = time; break; case SENT: if (current != Stage.PIPELINED) { logger.debug("Expected transition from PIPELINED to SENT, not {} to SENT", current); break; } this.timeSent = time; break; case RECEIVED: if (current != Stage.SENT) { logger.debug("Expected transition from SENT to RECEIVED, not {} to RECEIVED", current); break; } this.timeReceived = time; break; case COMPLETED: if (current == Stage.COMPLETED) { logger.debug("Request already COMPLETED"); break; } this.timeCompleted = time; break; default: throw new IllegalStateException(lenientFormat("there is no transition from %s to %s", current, value)); } return value; }); return this; } public Instant timeCompleted() { return this.timeCompleted; } public Instant timeCreated() { return this.args.timeCreated(); } public Instant timePipelined() { return this.timePipelined; } public Instant timeQueued() { return this.timeQueued; } public Instant timeReceived() { return this.timeReceived; } public Instant timeSent() { return this.timeSent; } public void serviceEndpointStatistics(RntbdEndpointStatistics endpointMetrics) { this.serviceEndpointStatistics = endpointMetrics; } public int pendingRequestQueueSize() { return this.pendingRequestsQueueSize; } public void pendingRequestQueueSize(int pendingRequestsQueueSize) { this.pendingRequestsQueueSize = pendingRequestsQueueSize; } public int channelTaskQueueLength() { return channelTaskQueueLength; } void channelTaskQueueLength(int value) { this.channelTaskQueueLength = value; } public RntbdEndpointStatistics serviceEndpointStatistics() { return this.serviceEndpointStatistics; } public long transportRequestId() { return this.args.transportRequestId(); } public boolean expire() { final GoneException error = new GoneException(this.toString(), null, this.args.physicalAddress()); BridgeInternal.setRequestHeaders(error, this.args.serviceRequest().getHeaders()); return this.completeExceptionally(error); } public abstract Timeout newTimeout(final TimerTask task); /** * Provides information whether the request could have been sent to the service * @return fals if it is possible to guarantee that the request never arrived at the service - true otherwise */ public boolean hasSendingRequestStarted() { return this.sendingRequestHasStarted; } public RequestTimeline takeTimelineSnapshot() { Instant now = Instant.now(); Instant timeCreated = this.timeCreated(); Instant timeQueued = this.timeQueued(); Instant timePipelined = this.timePipelined(); Instant timeSent = this.timeSent(); Instant timeReceived = this.timeReceived(); Instant timeCompleted = this.timeCompleted(); Instant timeCompletedOrNow = timeCompleted == null ? now : timeCompleted; return RequestTimeline.of( new RequestTimeline.Event("created", timeCreated, timeQueued == null ? timeCompletedOrNow : timeQueued), new RequestTimeline.Event("queued", timeQueued, timePipelined == null ? timeCompletedOrNow : timePipelined), new RequestTimeline.Event("pipelined", timePipelined, timeSent == null ? timeCompletedOrNow : timeSent), new RequestTimeline.Event("transitTime", timeSent, timeReceived == null ? timeCompletedOrNow : timeReceived), new RequestTimeline.Event("received", timeReceived, timeCompletedOrNow), new RequestTimeline.Event("completed", timeCompleted, now)); } public long stop(Timer requests, Timer responses) { return this.args.stop(requests, responses); } @Override public String toString() { return RntbdObjectMapper.toString(this); } public enum Stage { QUEUED, PIPELINED, SENT, RECEIVED, COMPLETED } static final class JsonSerializer extends StdSerializer<RntbdRequestRecord> { private static final long serialVersionUID = -6869331366500298083L; JsonSerializer() { super(RntbdRequestRecord.class); } @Override public void serialize( final RntbdRequestRecord value, final JsonGenerator generator, final SerializerProvider provider) throws IOException { generator.writeStartObject(); generator.writeObjectField("args", value.args()); generator.writeNumberField("requestLength", value.requestLength()); generator.writeNumberField("responseLength", value.responseLength()); generator.writeObjectFieldStart("status"); generator.writeBooleanField("done", value.isDone()); generator.writeBooleanField("cancelled", value.isCancelled()); generator.writeBooleanField("completedExceptionally", value.isCompletedExceptionally()); if (value.isCompletedExceptionally()) { try { value.get(); } catch (final ExecutionException executionException) { final Throwable error = executionException.getCause(); generator.writeObjectFieldStart("error"); generator.writeStringField("type", error.getClass().getName()); generator.writeObjectField("value", error); generator.writeEndObject(); } catch (CancellationException | InterruptedException exception) { generator.writeObjectFieldStart("error"); generator.writeStringField("type", exception.getClass().getName()); generator.writeObjectField("value", exception); generator.writeEndObject(); } } generator.writeEndObject(); generator.writeObjectField("timeline", value.takeTimelineSnapshot()); generator.writeEndObject(); } } }
class RntbdRequestRecord extends CompletableFuture<StoreResponse> { private static final Logger logger = LoggerFactory.getLogger(RntbdRequestRecord.class); private static final AtomicIntegerFieldUpdater<RntbdRequestRecord> REQUEST_LENGTH = AtomicIntegerFieldUpdater.newUpdater(RntbdRequestRecord.class, "requestLength"); private static final AtomicIntegerFieldUpdater<RntbdRequestRecord> RESPONSE_LENGTH = AtomicIntegerFieldUpdater.newUpdater(RntbdRequestRecord.class, "responseLength"); private static final AtomicReferenceFieldUpdater<RntbdRequestRecord, Stage> STAGE = AtomicReferenceFieldUpdater.newUpdater( RntbdRequestRecord.class, Stage.class, "stage"); private final RntbdRequestArgs args; private volatile int channelTaskQueueLength; private volatile int pendingRequestsQueueSize; private volatile RntbdEndpointStatistics serviceEndpointStatistics; private volatile int requestLength; private volatile int responseLength; private volatile Stage stage; private volatile Instant timeCompleted; private volatile Instant timePipelined; private final Instant timeQueued; private volatile Instant timeSent; private volatile Instant timeReceived; private volatile boolean sendingRequestHasStarted; protected RntbdRequestRecord(final RntbdRequestArgs args) { checkNotNull(args, "expected non-null args"); this.timeQueued = Instant.now(); this.requestLength = -1; this.responseLength = -1; this.stage = Stage.QUEUED; this.args = args; } public UUID activityId() { return this.args.activityId(); } public RntbdRequestArgs args() { return this.args; } public Duration lifetime() { return this.args.lifetime(); } public int requestLength() { return this.requestLength; } RntbdRequestRecord requestLength(int value) { REQUEST_LENGTH.set(this, value); return this; } public int responseLength() { return this.responseLength; } RntbdRequestRecord responseLength(int value) { RESPONSE_LENGTH.set(this, value); return this; } public Stage stage() { return this.stage; } public RntbdRequestRecord stage(final Stage value) { final Instant time = Instant.now(); STAGE.updateAndGet(this, current -> { switch (value) { case PIPELINED: if (current != Stage.QUEUED) { logger.debug("Expected transition from QUEUED to PIPELINED, not {} to PIPELINED", current); break; } this.timePipelined = time; break; case SENT: if (current != Stage.PIPELINED) { logger.debug("Expected transition from PIPELINED to SENT, not {} to SENT", current); break; } this.timeSent = time; break; case RECEIVED: if (current != Stage.SENT) { logger.debug("Expected transition from SENT to RECEIVED, not {} to RECEIVED", current); break; } this.timeReceived = time; break; case COMPLETED: if (current == Stage.COMPLETED) { logger.debug("Request already COMPLETED"); break; } this.timeCompleted = time; break; default: throw new IllegalStateException(lenientFormat("there is no transition from %s to %s", current, value)); } return value; }); return this; } public Instant timeCompleted() { return this.timeCompleted; } public Instant timeCreated() { return this.args.timeCreated(); } public Instant timePipelined() { return this.timePipelined; } public Instant timeQueued() { return this.timeQueued; } public Instant timeReceived() { return this.timeReceived; } public Instant timeSent() { return this.timeSent; } public void serviceEndpointStatistics(RntbdEndpointStatistics endpointMetrics) { this.serviceEndpointStatistics = endpointMetrics; } public int pendingRequestQueueSize() { return this.pendingRequestsQueueSize; } public void pendingRequestQueueSize(int pendingRequestsQueueSize) { this.pendingRequestsQueueSize = pendingRequestsQueueSize; } public int channelTaskQueueLength() { return channelTaskQueueLength; } void channelTaskQueueLength(int value) { this.channelTaskQueueLength = value; } public RntbdEndpointStatistics serviceEndpointStatistics() { return this.serviceEndpointStatistics; } public long transportRequestId() { return this.args.transportRequestId(); } public boolean expire() { final GoneException error = new GoneException(this.toString(), null, this.args.physicalAddress()); BridgeInternal.setRequestHeaders(error, this.args.serviceRequest().getHeaders()); return this.completeExceptionally(error); } public abstract Timeout newTimeout(final TimerTask task); /** * Provides information whether the request could have been sent to the service * @return false if it is possible to guarantee that the request never arrived at the service - true otherwise */ public boolean hasSendingRequestStarted() { return this.sendingRequestHasStarted; } public RequestTimeline takeTimelineSnapshot() { Instant now = Instant.now(); Instant timeCreated = this.timeCreated(); Instant timeQueued = this.timeQueued(); Instant timePipelined = this.timePipelined(); Instant timeSent = this.timeSent(); Instant timeReceived = this.timeReceived(); Instant timeCompleted = this.timeCompleted(); Instant timeCompletedOrNow = timeCompleted == null ? now : timeCompleted; return RequestTimeline.of( new RequestTimeline.Event("created", timeCreated, timeQueued == null ? timeCompletedOrNow : timeQueued), new RequestTimeline.Event("queued", timeQueued, timePipelined == null ? timeCompletedOrNow : timePipelined), new RequestTimeline.Event("pipelined", timePipelined, timeSent == null ? timeCompletedOrNow : timeSent), new RequestTimeline.Event("transitTime", timeSent, timeReceived == null ? timeCompletedOrNow : timeReceived), new RequestTimeline.Event("received", timeReceived, timeCompletedOrNow), new RequestTimeline.Event("completed", timeCompleted, now)); } public long stop(Timer requests, Timer responses) { return this.args.stop(requests, responses); } @Override public String toString() { return RntbdObjectMapper.toString(this); } public enum Stage { QUEUED, PIPELINED, SENT, RECEIVED, COMPLETED } static final class JsonSerializer extends StdSerializer<RntbdRequestRecord> { private static final long serialVersionUID = -6869331366500298083L; JsonSerializer() { super(RntbdRequestRecord.class); } @Override public void serialize( final RntbdRequestRecord value, final JsonGenerator generator, final SerializerProvider provider) throws IOException { generator.writeStartObject(); generator.writeObjectField("args", value.args()); generator.writeNumberField("requestLength", value.requestLength()); generator.writeNumberField("responseLength", value.responseLength()); generator.writeObjectFieldStart("status"); generator.writeBooleanField("done", value.isDone()); generator.writeBooleanField("cancelled", value.isCancelled()); generator.writeBooleanField("completedExceptionally", value.isCompletedExceptionally()); if (value.isCompletedExceptionally()) { try { value.get(); } catch (final ExecutionException executionException) { final Throwable error = executionException.getCause(); generator.writeObjectFieldStart("error"); generator.writeStringField("type", error.getClass().getName()); generator.writeObjectField("value", error); generator.writeEndObject(); } catch (CancellationException | InterruptedException exception) { generator.writeObjectFieldStart("error"); generator.writeStringField("type", exception.getClass().getName()); generator.writeObjectField("value", exception); generator.writeEndObject(); } } generator.writeEndObject(); generator.writeObjectField("timeline", value.takeTimelineSnapshot()); generator.writeEndObject(); } } }
I thought about it - decided against it because I haven't found a place where I could interrupt really when starting to send on the wire. Right now I set the flag at the last point where I can guarantee that sending hasn't started yet - which is good enough for the exception handling. But when pushing it into a first-class STAGE i think we should do it really when starting to send data to the wire. So my preference would to leave this as is - are you ok with it or still disagree?
void setSendingRequestHasStarted() { this.sendingRequestHasStarted = true; }
this.sendingRequestHasStarted = true;
void setSendingRequestHasStarted() { this.sendingRequestHasStarted = true; }
class RntbdRequestRecord extends CompletableFuture<StoreResponse> { private static final Logger logger = LoggerFactory.getLogger(RntbdRequestRecord.class); private static final AtomicIntegerFieldUpdater<RntbdRequestRecord> REQUEST_LENGTH = AtomicIntegerFieldUpdater.newUpdater(RntbdRequestRecord.class, "requestLength"); private static final AtomicIntegerFieldUpdater<RntbdRequestRecord> RESPONSE_LENGTH = AtomicIntegerFieldUpdater.newUpdater(RntbdRequestRecord.class, "responseLength"); private static final AtomicReferenceFieldUpdater<RntbdRequestRecord, Stage> STAGE = AtomicReferenceFieldUpdater.newUpdater( RntbdRequestRecord.class, Stage.class, "stage"); private final RntbdRequestArgs args; private volatile int channelTaskQueueLength; private volatile int pendingRequestsQueueSize; private volatile RntbdEndpointStatistics serviceEndpointStatistics; private volatile int requestLength; private volatile int responseLength; private volatile Stage stage; private volatile Instant timeCompleted; private volatile Instant timePipelined; private final Instant timeQueued; private volatile Instant timeSent; private volatile Instant timeReceived; private volatile boolean sendingRequestHasStarted; protected RntbdRequestRecord(final RntbdRequestArgs args) { checkNotNull(args, "expected non-null args"); this.timeQueued = Instant.now(); this.requestLength = -1; this.responseLength = -1; this.stage = Stage.QUEUED; this.args = args; } public UUID activityId() { return this.args.activityId(); } public RntbdRequestArgs args() { return this.args; } public Duration lifetime() { return this.args.lifetime(); } public int requestLength() { return this.requestLength; } RntbdRequestRecord requestLength(int value) { REQUEST_LENGTH.set(this, value); return this; } public int responseLength() { return this.responseLength; } RntbdRequestRecord responseLength(int value) { RESPONSE_LENGTH.set(this, value); return this; } public Stage stage() { return this.stage; } public RntbdRequestRecord stage(final Stage value) { final Instant time = Instant.now(); STAGE.updateAndGet(this, current -> { switch (value) { case PIPELINED: if (current != Stage.QUEUED) { logger.debug("Expected transition from QUEUED to PIPELINED, not {} to PIPELINED", current); break; } this.timePipelined = time; break; case SENT: if (current != Stage.PIPELINED) { logger.debug("Expected transition from PIPELINED to SENT, not {} to SENT", current); break; } this.timeSent = time; break; case RECEIVED: if (current != Stage.SENT) { logger.debug("Expected transition from SENT to RECEIVED, not {} to RECEIVED", current); break; } this.timeReceived = time; break; case COMPLETED: if (current == Stage.COMPLETED) { logger.debug("Request already COMPLETED"); break; } this.timeCompleted = time; break; default: throw new IllegalStateException(lenientFormat("there is no transition from %s to %s", current, value)); } return value; }); return this; } public Instant timeCompleted() { return this.timeCompleted; } public Instant timeCreated() { return this.args.timeCreated(); } public Instant timePipelined() { return this.timePipelined; } public Instant timeQueued() { return this.timeQueued; } public Instant timeReceived() { return this.timeReceived; } public Instant timeSent() { return this.timeSent; } public void serviceEndpointStatistics(RntbdEndpointStatistics endpointMetrics) { this.serviceEndpointStatistics = endpointMetrics; } public int pendingRequestQueueSize() { return this.pendingRequestsQueueSize; } public void pendingRequestQueueSize(int pendingRequestsQueueSize) { this.pendingRequestsQueueSize = pendingRequestsQueueSize; } public int channelTaskQueueLength() { return channelTaskQueueLength; } void channelTaskQueueLength(int value) { this.channelTaskQueueLength = value; } public RntbdEndpointStatistics serviceEndpointStatistics() { return this.serviceEndpointStatistics; } public long transportRequestId() { return this.args.transportRequestId(); } public boolean expire() { final GoneException error = new GoneException(this.toString(), null, this.args.physicalAddress()); BridgeInternal.setRequestHeaders(error, this.args.serviceRequest().getHeaders()); return this.completeExceptionally(error); } public abstract Timeout newTimeout(final TimerTask task); /** * Provides information whether the request could have been sent to the service * @return fals if it is possible to guarantee that the request never arrived at the service - true otherwise */ public boolean hasSendingRequestStarted() { return this.sendingRequestHasStarted; } public RequestTimeline takeTimelineSnapshot() { Instant now = Instant.now(); Instant timeCreated = this.timeCreated(); Instant timeQueued = this.timeQueued(); Instant timePipelined = this.timePipelined(); Instant timeSent = this.timeSent(); Instant timeReceived = this.timeReceived(); Instant timeCompleted = this.timeCompleted(); Instant timeCompletedOrNow = timeCompleted == null ? now : timeCompleted; return RequestTimeline.of( new RequestTimeline.Event("created", timeCreated, timeQueued == null ? timeCompletedOrNow : timeQueued), new RequestTimeline.Event("queued", timeQueued, timePipelined == null ? timeCompletedOrNow : timePipelined), new RequestTimeline.Event("pipelined", timePipelined, timeSent == null ? timeCompletedOrNow : timeSent), new RequestTimeline.Event("transitTime", timeSent, timeReceived == null ? timeCompletedOrNow : timeReceived), new RequestTimeline.Event("received", timeReceived, timeCompletedOrNow), new RequestTimeline.Event("completed", timeCompleted, now)); } public long stop(Timer requests, Timer responses) { return this.args.stop(requests, responses); } @Override public String toString() { return RntbdObjectMapper.toString(this); } public enum Stage { QUEUED, PIPELINED, SENT, RECEIVED, COMPLETED } static final class JsonSerializer extends StdSerializer<RntbdRequestRecord> { private static final long serialVersionUID = -6869331366500298083L; JsonSerializer() { super(RntbdRequestRecord.class); } @Override public void serialize( final RntbdRequestRecord value, final JsonGenerator generator, final SerializerProvider provider) throws IOException { generator.writeStartObject(); generator.writeObjectField("args", value.args()); generator.writeNumberField("requestLength", value.requestLength()); generator.writeNumberField("responseLength", value.responseLength()); generator.writeObjectFieldStart("status"); generator.writeBooleanField("done", value.isDone()); generator.writeBooleanField("cancelled", value.isCancelled()); generator.writeBooleanField("completedExceptionally", value.isCompletedExceptionally()); if (value.isCompletedExceptionally()) { try { value.get(); } catch (final ExecutionException executionException) { final Throwable error = executionException.getCause(); generator.writeObjectFieldStart("error"); generator.writeStringField("type", error.getClass().getName()); generator.writeObjectField("value", error); generator.writeEndObject(); } catch (CancellationException | InterruptedException exception) { generator.writeObjectFieldStart("error"); generator.writeStringField("type", exception.getClass().getName()); generator.writeObjectField("value", exception); generator.writeEndObject(); } } generator.writeEndObject(); generator.writeObjectField("timeline", value.takeTimelineSnapshot()); generator.writeEndObject(); } } }
class RntbdRequestRecord extends CompletableFuture<StoreResponse> { private static final Logger logger = LoggerFactory.getLogger(RntbdRequestRecord.class); private static final AtomicIntegerFieldUpdater<RntbdRequestRecord> REQUEST_LENGTH = AtomicIntegerFieldUpdater.newUpdater(RntbdRequestRecord.class, "requestLength"); private static final AtomicIntegerFieldUpdater<RntbdRequestRecord> RESPONSE_LENGTH = AtomicIntegerFieldUpdater.newUpdater(RntbdRequestRecord.class, "responseLength"); private static final AtomicReferenceFieldUpdater<RntbdRequestRecord, Stage> STAGE = AtomicReferenceFieldUpdater.newUpdater( RntbdRequestRecord.class, Stage.class, "stage"); private final RntbdRequestArgs args; private volatile int channelTaskQueueLength; private volatile int pendingRequestsQueueSize; private volatile RntbdEndpointStatistics serviceEndpointStatistics; private volatile int requestLength; private volatile int responseLength; private volatile Stage stage; private volatile Instant timeCompleted; private volatile Instant timePipelined; private final Instant timeQueued; private volatile Instant timeSent; private volatile Instant timeReceived; private volatile boolean sendingRequestHasStarted; protected RntbdRequestRecord(final RntbdRequestArgs args) { checkNotNull(args, "expected non-null args"); this.timeQueued = Instant.now(); this.requestLength = -1; this.responseLength = -1; this.stage = Stage.QUEUED; this.args = args; } public UUID activityId() { return this.args.activityId(); } public RntbdRequestArgs args() { return this.args; } public Duration lifetime() { return this.args.lifetime(); } public int requestLength() { return this.requestLength; } RntbdRequestRecord requestLength(int value) { REQUEST_LENGTH.set(this, value); return this; } public int responseLength() { return this.responseLength; } RntbdRequestRecord responseLength(int value) { RESPONSE_LENGTH.set(this, value); return this; } public Stage stage() { return this.stage; } public RntbdRequestRecord stage(final Stage value) { final Instant time = Instant.now(); STAGE.updateAndGet(this, current -> { switch (value) { case PIPELINED: if (current != Stage.QUEUED) { logger.debug("Expected transition from QUEUED to PIPELINED, not {} to PIPELINED", current); break; } this.timePipelined = time; break; case SENT: if (current != Stage.PIPELINED) { logger.debug("Expected transition from PIPELINED to SENT, not {} to SENT", current); break; } this.timeSent = time; break; case RECEIVED: if (current != Stage.SENT) { logger.debug("Expected transition from SENT to RECEIVED, not {} to RECEIVED", current); break; } this.timeReceived = time; break; case COMPLETED: if (current == Stage.COMPLETED) { logger.debug("Request already COMPLETED"); break; } this.timeCompleted = time; break; default: throw new IllegalStateException(lenientFormat("there is no transition from %s to %s", current, value)); } return value; }); return this; } public Instant timeCompleted() { return this.timeCompleted; } public Instant timeCreated() { return this.args.timeCreated(); } public Instant timePipelined() { return this.timePipelined; } public Instant timeQueued() { return this.timeQueued; } public Instant timeReceived() { return this.timeReceived; } public Instant timeSent() { return this.timeSent; } public void serviceEndpointStatistics(RntbdEndpointStatistics endpointMetrics) { this.serviceEndpointStatistics = endpointMetrics; } public int pendingRequestQueueSize() { return this.pendingRequestsQueueSize; } public void pendingRequestQueueSize(int pendingRequestsQueueSize) { this.pendingRequestsQueueSize = pendingRequestsQueueSize; } public int channelTaskQueueLength() { return channelTaskQueueLength; } void channelTaskQueueLength(int value) { this.channelTaskQueueLength = value; } public RntbdEndpointStatistics serviceEndpointStatistics() { return this.serviceEndpointStatistics; } public long transportRequestId() { return this.args.transportRequestId(); } public boolean expire() { final GoneException error = new GoneException(this.toString(), null, this.args.physicalAddress()); BridgeInternal.setRequestHeaders(error, this.args.serviceRequest().getHeaders()); return this.completeExceptionally(error); } public abstract Timeout newTimeout(final TimerTask task); /** * Provides information whether the request could have been sent to the service * @return false if it is possible to guarantee that the request never arrived at the service - true otherwise */ public boolean hasSendingRequestStarted() { return this.sendingRequestHasStarted; } public RequestTimeline takeTimelineSnapshot() { Instant now = Instant.now(); Instant timeCreated = this.timeCreated(); Instant timeQueued = this.timeQueued(); Instant timePipelined = this.timePipelined(); Instant timeSent = this.timeSent(); Instant timeReceived = this.timeReceived(); Instant timeCompleted = this.timeCompleted(); Instant timeCompletedOrNow = timeCompleted == null ? now : timeCompleted; return RequestTimeline.of( new RequestTimeline.Event("created", timeCreated, timeQueued == null ? timeCompletedOrNow : timeQueued), new RequestTimeline.Event("queued", timeQueued, timePipelined == null ? timeCompletedOrNow : timePipelined), new RequestTimeline.Event("pipelined", timePipelined, timeSent == null ? timeCompletedOrNow : timeSent), new RequestTimeline.Event("transitTime", timeSent, timeReceived == null ? timeCompletedOrNow : timeReceived), new RequestTimeline.Event("received", timeReceived, timeCompletedOrNow), new RequestTimeline.Event("completed", timeCompleted, now)); } public long stop(Timer requests, Timer responses) { return this.args.stop(requests, responses); } @Override public String toString() { return RntbdObjectMapper.toString(this); } public enum Stage { QUEUED, PIPELINED, SENT, RECEIVED, COMPLETED } static final class JsonSerializer extends StdSerializer<RntbdRequestRecord> { private static final long serialVersionUID = -6869331366500298083L; JsonSerializer() { super(RntbdRequestRecord.class); } @Override public void serialize( final RntbdRequestRecord value, final JsonGenerator generator, final SerializerProvider provider) throws IOException { generator.writeStartObject(); generator.writeObjectField("args", value.args()); generator.writeNumberField("requestLength", value.requestLength()); generator.writeNumberField("responseLength", value.responseLength()); generator.writeObjectFieldStart("status"); generator.writeBooleanField("done", value.isDone()); generator.writeBooleanField("cancelled", value.isCancelled()); generator.writeBooleanField("completedExceptionally", value.isCompletedExceptionally()); if (value.isCompletedExceptionally()) { try { value.get(); } catch (final ExecutionException executionException) { final Throwable error = executionException.getCause(); generator.writeObjectFieldStart("error"); generator.writeStringField("type", error.getClass().getName()); generator.writeObjectField("value", error); generator.writeEndObject(); } catch (CancellationException | InterruptedException exception) { generator.writeObjectFieldStart("error"); generator.writeStringField("type", exception.getClass().getName()); generator.writeObjectField("value", exception); generator.writeEndObject(); } } generator.writeEndObject(); generator.writeObjectField("timeline", value.takeTimelineSnapshot()); generator.writeEndObject(); } } }
Other similar tracers are at warn below. Warn seems makes sense.
public Mono<ShouldRetryResult> shouldRetry(Exception exception) { CosmosException exceptionToThrow = null; Duration backoffTime = Duration.ofSeconds(0); Duration timeout = Duration.ofSeconds(0); boolean forceRefreshAddressCache = false; if (!(exception instanceof GoneException) && !(exception instanceof RetryWithException) && !(exception instanceof PartitionIsMigratingException) && !(exception instanceof InvalidPartitionException && (this.request.getPartitionKeyRangeIdentity() == null || this.request.getPartitionKeyRangeIdentity().getCollectionRid() == null)) && !(exception instanceof PartitionKeyRangeIsSplittingException)) { logger.debug("Operation will NOT be retried. Current attempt {}, Exception: ", this.attemptCount, exception); stopStopWatch(this.durationTimer); return Mono.just(ShouldRetryResult.noRetry()); } else if (exception instanceof GoneException && !request.isReadOnly() && BridgeInternal.hasSendingRequestStarted((CosmosException)exception)) { logger.debug( "Operation will NOT be retried. Write operations can not be retried safely when sending the request " + "to the service because they aren't idempotent. Current attempt {}, Exception: ", this.attemptCount, exception); stopStopWatch(this.durationTimer); return Mono.just(ShouldRetryResult.noRetry( Quadruple.with(true, true, Duration.ofMillis(0), this.attemptCount))); } else if (exception instanceof RetryWithException) { this.lastRetryWithException = (RetryWithException) exception; } long remainingSeconds = this.waitTimeInSeconds - this.durationTimer.getTime() / 1000; int currentRetryAttemptCount = this.attemptCount; if (this.attemptCount++ > 1) { if (remainingSeconds <= 0) { if (exception instanceof GoneException) { if (this.lastRetryWithException != null) { logger.warn( "Received gone exception after backoff/retry including at least one RetryWithException. " + "Will fail the request with RetryWithException. GoneException: {}. RetryWithException: {}", exception, this.lastRetryWithException); exceptionToThrow = this.lastRetryWithException; } else { logger.warn("Received gone exception after backoff/retry. Will fail the request. {}", exception.toString()); exceptionToThrow = BridgeInternal.createServiceUnavailableException(exception); } } else if (exception instanceof PartitionKeyRangeGoneException) { if (this.lastRetryWithException != null) { logger.warn( "Received partition key range gone exception after backoff/retry including at least one RetryWithException." + "Will fail the request with RetryWithException. GoneException: {}. RetryWithException: {}", exception, this.lastRetryWithException); exceptionToThrow = this.lastRetryWithException; } else { logger.warn( "Received partition key range gone exception after backoff/retry. Will fail the request. {}", exception.toString()); exceptionToThrow = BridgeInternal.createServiceUnavailableException(exception); } } else if (exception instanceof InvalidPartitionException) { if (this.lastRetryWithException != null) { logger.warn( "Received InvalidPartitionException after backoff/retry including at least one RetryWithException. " + "Will fail the request with RetryWithException. InvalidPartitionException: {}. RetryWithException: {}", exception, this.lastRetryWithException); } else { logger.warn( "Received invalid collection partition exception after backoff/retry. Will fail the request. {}", exception.toString()); exceptionToThrow = BridgeInternal.createServiceUnavailableException(exception); } } else { logger.warn("Received retrywith exception after backoff/retry. Will fail the request. {}", exception.toString()); } stopStopWatch(this.durationTimer); return Mono.just(ShouldRetryResult.error(exceptionToThrow)); } backoffTime = Duration.ofSeconds(Math.min(Math.min(this.currentBackoffSeconds, remainingSeconds), GoneAndRetryWithRetryPolicy.MAXIMUM_BACKOFF_TIME_IN_SECONDS)); this.currentBackoffSeconds *= GoneAndRetryWithRetryPolicy.BACK_OFF_MULTIPLIER; logger.debug("BackoffTime: {} seconds.", backoffTime.getSeconds()); } long timeoutInMillSec = remainingSeconds*1000 - backoffTime.toMillis(); timeout = timeoutInMillSec > 0 ? Duration.ofMillis(timeoutInMillSec) : Duration.ofSeconds(GoneAndRetryWithRetryPolicy.MAXIMUM_BACKOFF_TIME_IN_SECONDS); if (exception instanceof GoneException) { logger.debug("Received gone exception, will retry, {}", exception.toString()); forceRefreshAddressCache = true; } else if (exception instanceof PartitionIsMigratingException) { logger.warn("Received PartitionIsMigratingException, will retry, {}", exception.toString()); this.request.forceCollectionRoutingMapRefresh = true; forceRefreshAddressCache = true; } else if (exception instanceof InvalidPartitionException) { this.request.requestContext.quorumSelectedLSN = -1; this.request.requestContext.resolvedPartitionKeyRange = null; this.request.requestContext.quorumSelectedStoreResponse = null; this.request.requestContext.globalCommittedSelectedLSN = -1; if (this.attemptCountInvalidPartition++ > 2) { logger.warn("Received second InvalidPartitionException after backoff/retry. Will fail the request. {}", exception.toString()); return Mono.just(ShouldRetryResult .error(BridgeInternal.createServiceUnavailableException(exception))); } if (this.request != null) { logger.warn("Received invalid collection exception, will retry, {}", exception.toString()); this.request.forceNameCacheRefresh = true; } else { logger.error("Received unexpected invalid collection exception, request should be non-null.", exception); return Mono.just(ShouldRetryResult .error(BridgeInternal.createCosmosException(HttpConstants.StatusCodes.INTERNAL_SERVER_ERROR, exception))); } forceRefreshAddressCache = false; } else if (exception instanceof PartitionKeyRangeIsSplittingException) { this.request.requestContext.resolvedPartitionKeyRange = null; this.request.requestContext.quorumSelectedLSN = -1; this.request.requestContext.quorumSelectedStoreResponse = null; logger.info("Received partition key range splitting exception, will retry, {}", exception.toString()); this.request.forcePartitionKeyRangeRefresh = true; forceRefreshAddressCache = false; } else { logger.warn("Received retrywith exception, will retry, {}", exception); forceRefreshAddressCache = false; } return Mono.just(ShouldRetryResult.retryAfter(backoffTime, Quadruple.with(forceRefreshAddressCache, true, timeout, currentRetryAttemptCount))); }
logger.debug(
public Mono<ShouldRetryResult> shouldRetry(Exception exception) { CosmosException exceptionToThrow = null; Duration backoffTime = Duration.ofSeconds(0); Duration timeout = Duration.ofSeconds(0); boolean forceRefreshAddressCache = false; if (!(exception instanceof GoneException) && !(exception instanceof RetryWithException) && !(exception instanceof PartitionIsMigratingException) && !(exception instanceof InvalidPartitionException && (this.request.getPartitionKeyRangeIdentity() == null || this.request.getPartitionKeyRangeIdentity().getCollectionRid() == null)) && !(exception instanceof PartitionKeyRangeIsSplittingException)) { logger.warn("Operation will NOT be retried. Current attempt {}, Exception: ", this.attemptCount, exception); stopStopWatch(this.durationTimer); return Mono.just(ShouldRetryResult.noRetry()); } else if (exception instanceof GoneException && !request.isReadOnly() && BridgeInternal.hasSendingRequestStarted((CosmosException)exception)) { logger.warn( "Operation will NOT be retried. Write operations can not be retried safely when sending the request " + "to the service because they aren't idempotent. Current attempt {}, Exception: ", this.attemptCount, exception); stopStopWatch(this.durationTimer); return Mono.just(ShouldRetryResult.noRetry( Quadruple.with(true, true, Duration.ofMillis(0), this.attemptCount))); } else if (exception instanceof RetryWithException) { this.lastRetryWithException = (RetryWithException) exception; } long remainingSeconds = this.waitTimeInSeconds - this.durationTimer.getTime() / 1000; int currentRetryAttemptCount = this.attemptCount; if (this.attemptCount++ > 1) { if (remainingSeconds <= 0) { if (exception instanceof GoneException) { if (this.lastRetryWithException != null) { logger.warn( "Received gone exception after backoff/retry including at least one RetryWithException. " + "Will fail the request with RetryWithException. GoneException: {}. RetryWithException: {}", exception, this.lastRetryWithException); exceptionToThrow = this.lastRetryWithException; } else { logger.warn("Received gone exception after backoff/retry. Will fail the request. {}", exception.toString()); exceptionToThrow = BridgeInternal.createServiceUnavailableException(exception); } } else if (exception instanceof PartitionKeyRangeGoneException) { if (this.lastRetryWithException != null) { logger.warn( "Received partition key range gone exception after backoff/retry including at least one RetryWithException." + "Will fail the request with RetryWithException. GoneException: {}. RetryWithException: {}", exception, this.lastRetryWithException); exceptionToThrow = this.lastRetryWithException; } else { logger.warn( "Received partition key range gone exception after backoff/retry. Will fail the request. {}", exception.toString()); exceptionToThrow = BridgeInternal.createServiceUnavailableException(exception); } } else if (exception instanceof InvalidPartitionException) { if (this.lastRetryWithException != null) { logger.warn( "Received InvalidPartitionException after backoff/retry including at least one RetryWithException. " + "Will fail the request with RetryWithException. InvalidPartitionException: {}. RetryWithException: {}", exception, this.lastRetryWithException); } else { logger.warn( "Received invalid collection partition exception after backoff/retry. Will fail the request. {}", exception.toString()); exceptionToThrow = BridgeInternal.createServiceUnavailableException(exception); } } else { logger.warn("Received retrywith exception after backoff/retry. Will fail the request. {}", exception.toString()); } stopStopWatch(this.durationTimer); return Mono.just(ShouldRetryResult.error(exceptionToThrow)); } backoffTime = Duration.ofSeconds(Math.min(Math.min(this.currentBackoffSeconds, remainingSeconds), GoneAndRetryWithRetryPolicy.MAXIMUM_BACKOFF_TIME_IN_SECONDS)); this.currentBackoffSeconds *= GoneAndRetryWithRetryPolicy.BACK_OFF_MULTIPLIER; logger.debug("BackoffTime: {} seconds.", backoffTime.getSeconds()); } long timeoutInMillSec = remainingSeconds*1000 - backoffTime.toMillis(); timeout = timeoutInMillSec > 0 ? Duration.ofMillis(timeoutInMillSec) : Duration.ofSeconds(GoneAndRetryWithRetryPolicy.MAXIMUM_BACKOFF_TIME_IN_SECONDS); if (exception instanceof GoneException) { logger.debug("Received gone exception, will retry, {}", exception.toString()); forceRefreshAddressCache = true; } else if (exception instanceof PartitionIsMigratingException) { logger.warn("Received PartitionIsMigratingException, will retry, {}", exception.toString()); this.request.forceCollectionRoutingMapRefresh = true; forceRefreshAddressCache = true; } else if (exception instanceof InvalidPartitionException) { this.request.requestContext.quorumSelectedLSN = -1; this.request.requestContext.resolvedPartitionKeyRange = null; this.request.requestContext.quorumSelectedStoreResponse = null; this.request.requestContext.globalCommittedSelectedLSN = -1; if (this.attemptCountInvalidPartition++ > 2) { logger.warn("Received second InvalidPartitionException after backoff/retry. Will fail the request. {}", exception.toString()); return Mono.just(ShouldRetryResult .error(BridgeInternal.createServiceUnavailableException(exception))); } if (this.request != null) { logger.warn("Received invalid collection exception, will retry, {}", exception.toString()); this.request.forceNameCacheRefresh = true; } else { logger.error("Received unexpected invalid collection exception, request should be non-null.", exception); return Mono.just(ShouldRetryResult .error(BridgeInternal.createCosmosException(HttpConstants.StatusCodes.INTERNAL_SERVER_ERROR, exception))); } forceRefreshAddressCache = false; } else if (exception instanceof PartitionKeyRangeIsSplittingException) { this.request.requestContext.resolvedPartitionKeyRange = null; this.request.requestContext.quorumSelectedLSN = -1; this.request.requestContext.quorumSelectedStoreResponse = null; logger.info("Received partition key range splitting exception, will retry, {}", exception.toString()); this.request.forcePartitionKeyRangeRefresh = true; forceRefreshAddressCache = false; } else { logger.warn("Received retrywith exception, will retry, {}", exception); forceRefreshAddressCache = false; } return Mono.just(ShouldRetryResult.retryAfter(backoffTime, Quadruple.with(forceRefreshAddressCache, true, timeout, currentRetryAttemptCount))); }
class GoneAndRetryWithRetryPolicy extends RetryPolicyWithDiagnostics { private final static Logger logger = LoggerFactory.getLogger(GoneAndRetryWithRetryPolicy.class); private final static int DEFAULT_WAIT_TIME_IN_SECONDS = 30; private final static int MAXIMUM_BACKOFF_TIME_IN_SECONDS = 15; private final static int INITIAL_BACKOFF_TIME = 1; private final static int BACK_OFF_MULTIPLIER = 2; private final RxDocumentServiceRequest request; private volatile int attemptCount = 1; private volatile int attemptCountInvalidPartition = 1; private volatile int currentBackoffSeconds = GoneAndRetryWithRetryPolicy.INITIAL_BACKOFF_TIME; private volatile RetryWithException lastRetryWithException; private final StopWatch durationTimer = new StopWatch(); private final int waitTimeInSeconds; public final static Quadruple<Boolean, Boolean, Duration, Integer> INITIAL_ARGUMENT_VALUE_POLICY_ARG = Quadruple.with(false, false, Duration.ofSeconds(60), 0); public GoneAndRetryWithRetryPolicy(RxDocumentServiceRequest request, Integer waitTimeInSeconds) { this.request = request; startStopWatch(this.durationTimer); if (waitTimeInSeconds != null) { this.waitTimeInSeconds = waitTimeInSeconds; } else { this.waitTimeInSeconds = DEFAULT_WAIT_TIME_IN_SECONDS; } } @Override private void stopStopWatch(StopWatch stopwatch) { synchronized (stopwatch) { stopwatch.stop(); } } private void startStopWatch(StopWatch stopwatch) { synchronized (stopwatch) { stopwatch.start(); } } }
class GoneAndRetryWithRetryPolicy extends RetryPolicyWithDiagnostics { private final static Logger logger = LoggerFactory.getLogger(GoneAndRetryWithRetryPolicy.class); private final static int DEFAULT_WAIT_TIME_IN_SECONDS = 30; private final static int MAXIMUM_BACKOFF_TIME_IN_SECONDS = 15; private final static int INITIAL_BACKOFF_TIME = 1; private final static int BACK_OFF_MULTIPLIER = 2; private final RxDocumentServiceRequest request; private volatile int attemptCount = 1; private volatile int attemptCountInvalidPartition = 1; private volatile int currentBackoffSeconds = GoneAndRetryWithRetryPolicy.INITIAL_BACKOFF_TIME; private volatile RetryWithException lastRetryWithException; private final StopWatch durationTimer = new StopWatch(); private final int waitTimeInSeconds; public final static Quadruple<Boolean, Boolean, Duration, Integer> INITIAL_ARGUMENT_VALUE_POLICY_ARG = Quadruple.with(false, false, Duration.ofSeconds(60), 0); public GoneAndRetryWithRetryPolicy(RxDocumentServiceRequest request, Integer waitTimeInSeconds) { this.request = request; startStopWatch(this.durationTimer); if (waitTimeInSeconds != null) { this.waitTimeInSeconds = waitTimeInSeconds; } else { this.waitTimeInSeconds = DEFAULT_WAIT_TIME_IN_SECONDS; } } @Override private void stopStopWatch(StopWatch stopwatch) { synchronized (stopwatch) { stopwatch.stop(); } } private void startStopWatch(StopWatch stopwatch) { synchronized (stopwatch) { stopwatch.start(); } } }
I agree with you. Thanks.
void setSendingRequestHasStarted() { this.sendingRequestHasStarted = true; }
this.sendingRequestHasStarted = true;
void setSendingRequestHasStarted() { this.sendingRequestHasStarted = true; }
class RntbdRequestRecord extends CompletableFuture<StoreResponse> { private static final Logger logger = LoggerFactory.getLogger(RntbdRequestRecord.class); private static final AtomicIntegerFieldUpdater<RntbdRequestRecord> REQUEST_LENGTH = AtomicIntegerFieldUpdater.newUpdater(RntbdRequestRecord.class, "requestLength"); private static final AtomicIntegerFieldUpdater<RntbdRequestRecord> RESPONSE_LENGTH = AtomicIntegerFieldUpdater.newUpdater(RntbdRequestRecord.class, "responseLength"); private static final AtomicReferenceFieldUpdater<RntbdRequestRecord, Stage> STAGE = AtomicReferenceFieldUpdater.newUpdater( RntbdRequestRecord.class, Stage.class, "stage"); private final RntbdRequestArgs args; private volatile int channelTaskQueueLength; private volatile int pendingRequestsQueueSize; private volatile RntbdEndpointStatistics serviceEndpointStatistics; private volatile int requestLength; private volatile int responseLength; private volatile Stage stage; private volatile Instant timeCompleted; private volatile Instant timePipelined; private final Instant timeQueued; private volatile Instant timeSent; private volatile Instant timeReceived; private volatile boolean sendingRequestHasStarted; protected RntbdRequestRecord(final RntbdRequestArgs args) { checkNotNull(args, "expected non-null args"); this.timeQueued = Instant.now(); this.requestLength = -1; this.responseLength = -1; this.stage = Stage.QUEUED; this.args = args; } public UUID activityId() { return this.args.activityId(); } public RntbdRequestArgs args() { return this.args; } public Duration lifetime() { return this.args.lifetime(); } public int requestLength() { return this.requestLength; } RntbdRequestRecord requestLength(int value) { REQUEST_LENGTH.set(this, value); return this; } public int responseLength() { return this.responseLength; } RntbdRequestRecord responseLength(int value) { RESPONSE_LENGTH.set(this, value); return this; } public Stage stage() { return this.stage; } public RntbdRequestRecord stage(final Stage value) { final Instant time = Instant.now(); STAGE.updateAndGet(this, current -> { switch (value) { case PIPELINED: if (current != Stage.QUEUED) { logger.debug("Expected transition from QUEUED to PIPELINED, not {} to PIPELINED", current); break; } this.timePipelined = time; break; case SENT: if (current != Stage.PIPELINED) { logger.debug("Expected transition from PIPELINED to SENT, not {} to SENT", current); break; } this.timeSent = time; break; case RECEIVED: if (current != Stage.SENT) { logger.debug("Expected transition from SENT to RECEIVED, not {} to RECEIVED", current); break; } this.timeReceived = time; break; case COMPLETED: if (current == Stage.COMPLETED) { logger.debug("Request already COMPLETED"); break; } this.timeCompleted = time; break; default: throw new IllegalStateException(lenientFormat("there is no transition from %s to %s", current, value)); } return value; }); return this; } public Instant timeCompleted() { return this.timeCompleted; } public Instant timeCreated() { return this.args.timeCreated(); } public Instant timePipelined() { return this.timePipelined; } public Instant timeQueued() { return this.timeQueued; } public Instant timeReceived() { return this.timeReceived; } public Instant timeSent() { return this.timeSent; } public void serviceEndpointStatistics(RntbdEndpointStatistics endpointMetrics) { this.serviceEndpointStatistics = endpointMetrics; } public int pendingRequestQueueSize() { return this.pendingRequestsQueueSize; } public void pendingRequestQueueSize(int pendingRequestsQueueSize) { this.pendingRequestsQueueSize = pendingRequestsQueueSize; } public int channelTaskQueueLength() { return channelTaskQueueLength; } void channelTaskQueueLength(int value) { this.channelTaskQueueLength = value; } public RntbdEndpointStatistics serviceEndpointStatistics() { return this.serviceEndpointStatistics; } public long transportRequestId() { return this.args.transportRequestId(); } public boolean expire() { final GoneException error = new GoneException(this.toString(), null, this.args.physicalAddress()); BridgeInternal.setRequestHeaders(error, this.args.serviceRequest().getHeaders()); return this.completeExceptionally(error); } public abstract Timeout newTimeout(final TimerTask task); /** * Provides information whether the request could have been sent to the service * @return fals if it is possible to guarantee that the request never arrived at the service - true otherwise */ public boolean hasSendingRequestStarted() { return this.sendingRequestHasStarted; } public RequestTimeline takeTimelineSnapshot() { Instant now = Instant.now(); Instant timeCreated = this.timeCreated(); Instant timeQueued = this.timeQueued(); Instant timePipelined = this.timePipelined(); Instant timeSent = this.timeSent(); Instant timeReceived = this.timeReceived(); Instant timeCompleted = this.timeCompleted(); Instant timeCompletedOrNow = timeCompleted == null ? now : timeCompleted; return RequestTimeline.of( new RequestTimeline.Event("created", timeCreated, timeQueued == null ? timeCompletedOrNow : timeQueued), new RequestTimeline.Event("queued", timeQueued, timePipelined == null ? timeCompletedOrNow : timePipelined), new RequestTimeline.Event("pipelined", timePipelined, timeSent == null ? timeCompletedOrNow : timeSent), new RequestTimeline.Event("transitTime", timeSent, timeReceived == null ? timeCompletedOrNow : timeReceived), new RequestTimeline.Event("received", timeReceived, timeCompletedOrNow), new RequestTimeline.Event("completed", timeCompleted, now)); } public long stop(Timer requests, Timer responses) { return this.args.stop(requests, responses); } @Override public String toString() { return RntbdObjectMapper.toString(this); } public enum Stage { QUEUED, PIPELINED, SENT, RECEIVED, COMPLETED } static final class JsonSerializer extends StdSerializer<RntbdRequestRecord> { private static final long serialVersionUID = -6869331366500298083L; JsonSerializer() { super(RntbdRequestRecord.class); } @Override public void serialize( final RntbdRequestRecord value, final JsonGenerator generator, final SerializerProvider provider) throws IOException { generator.writeStartObject(); generator.writeObjectField("args", value.args()); generator.writeNumberField("requestLength", value.requestLength()); generator.writeNumberField("responseLength", value.responseLength()); generator.writeObjectFieldStart("status"); generator.writeBooleanField("done", value.isDone()); generator.writeBooleanField("cancelled", value.isCancelled()); generator.writeBooleanField("completedExceptionally", value.isCompletedExceptionally()); if (value.isCompletedExceptionally()) { try { value.get(); } catch (final ExecutionException executionException) { final Throwable error = executionException.getCause(); generator.writeObjectFieldStart("error"); generator.writeStringField("type", error.getClass().getName()); generator.writeObjectField("value", error); generator.writeEndObject(); } catch (CancellationException | InterruptedException exception) { generator.writeObjectFieldStart("error"); generator.writeStringField("type", exception.getClass().getName()); generator.writeObjectField("value", exception); generator.writeEndObject(); } } generator.writeEndObject(); generator.writeObjectField("timeline", value.takeTimelineSnapshot()); generator.writeEndObject(); } } }
class RntbdRequestRecord extends CompletableFuture<StoreResponse> { private static final Logger logger = LoggerFactory.getLogger(RntbdRequestRecord.class); private static final AtomicIntegerFieldUpdater<RntbdRequestRecord> REQUEST_LENGTH = AtomicIntegerFieldUpdater.newUpdater(RntbdRequestRecord.class, "requestLength"); private static final AtomicIntegerFieldUpdater<RntbdRequestRecord> RESPONSE_LENGTH = AtomicIntegerFieldUpdater.newUpdater(RntbdRequestRecord.class, "responseLength"); private static final AtomicReferenceFieldUpdater<RntbdRequestRecord, Stage> STAGE = AtomicReferenceFieldUpdater.newUpdater( RntbdRequestRecord.class, Stage.class, "stage"); private final RntbdRequestArgs args; private volatile int channelTaskQueueLength; private volatile int pendingRequestsQueueSize; private volatile RntbdEndpointStatistics serviceEndpointStatistics; private volatile int requestLength; private volatile int responseLength; private volatile Stage stage; private volatile Instant timeCompleted; private volatile Instant timePipelined; private final Instant timeQueued; private volatile Instant timeSent; private volatile Instant timeReceived; private volatile boolean sendingRequestHasStarted; protected RntbdRequestRecord(final RntbdRequestArgs args) { checkNotNull(args, "expected non-null args"); this.timeQueued = Instant.now(); this.requestLength = -1; this.responseLength = -1; this.stage = Stage.QUEUED; this.args = args; } public UUID activityId() { return this.args.activityId(); } public RntbdRequestArgs args() { return this.args; } public Duration lifetime() { return this.args.lifetime(); } public int requestLength() { return this.requestLength; } RntbdRequestRecord requestLength(int value) { REQUEST_LENGTH.set(this, value); return this; } public int responseLength() { return this.responseLength; } RntbdRequestRecord responseLength(int value) { RESPONSE_LENGTH.set(this, value); return this; } public Stage stage() { return this.stage; } public RntbdRequestRecord stage(final Stage value) { final Instant time = Instant.now(); STAGE.updateAndGet(this, current -> { switch (value) { case PIPELINED: if (current != Stage.QUEUED) { logger.debug("Expected transition from QUEUED to PIPELINED, not {} to PIPELINED", current); break; } this.timePipelined = time; break; case SENT: if (current != Stage.PIPELINED) { logger.debug("Expected transition from PIPELINED to SENT, not {} to SENT", current); break; } this.timeSent = time; break; case RECEIVED: if (current != Stage.SENT) { logger.debug("Expected transition from SENT to RECEIVED, not {} to RECEIVED", current); break; } this.timeReceived = time; break; case COMPLETED: if (current == Stage.COMPLETED) { logger.debug("Request already COMPLETED"); break; } this.timeCompleted = time; break; default: throw new IllegalStateException(lenientFormat("there is no transition from %s to %s", current, value)); } return value; }); return this; } public Instant timeCompleted() { return this.timeCompleted; } public Instant timeCreated() { return this.args.timeCreated(); } public Instant timePipelined() { return this.timePipelined; } public Instant timeQueued() { return this.timeQueued; } public Instant timeReceived() { return this.timeReceived; } public Instant timeSent() { return this.timeSent; } public void serviceEndpointStatistics(RntbdEndpointStatistics endpointMetrics) { this.serviceEndpointStatistics = endpointMetrics; } public int pendingRequestQueueSize() { return this.pendingRequestsQueueSize; } public void pendingRequestQueueSize(int pendingRequestsQueueSize) { this.pendingRequestsQueueSize = pendingRequestsQueueSize; } public int channelTaskQueueLength() { return channelTaskQueueLength; } void channelTaskQueueLength(int value) { this.channelTaskQueueLength = value; } public RntbdEndpointStatistics serviceEndpointStatistics() { return this.serviceEndpointStatistics; } public long transportRequestId() { return this.args.transportRequestId(); } public boolean expire() { final GoneException error = new GoneException(this.toString(), null, this.args.physicalAddress()); BridgeInternal.setRequestHeaders(error, this.args.serviceRequest().getHeaders()); return this.completeExceptionally(error); } public abstract Timeout newTimeout(final TimerTask task); /** * Provides information whether the request could have been sent to the service * @return false if it is possible to guarantee that the request never arrived at the service - true otherwise */ public boolean hasSendingRequestStarted() { return this.sendingRequestHasStarted; } public RequestTimeline takeTimelineSnapshot() { Instant now = Instant.now(); Instant timeCreated = this.timeCreated(); Instant timeQueued = this.timeQueued(); Instant timePipelined = this.timePipelined(); Instant timeSent = this.timeSent(); Instant timeReceived = this.timeReceived(); Instant timeCompleted = this.timeCompleted(); Instant timeCompletedOrNow = timeCompleted == null ? now : timeCompleted; return RequestTimeline.of( new RequestTimeline.Event("created", timeCreated, timeQueued == null ? timeCompletedOrNow : timeQueued), new RequestTimeline.Event("queued", timeQueued, timePipelined == null ? timeCompletedOrNow : timePipelined), new RequestTimeline.Event("pipelined", timePipelined, timeSent == null ? timeCompletedOrNow : timeSent), new RequestTimeline.Event("transitTime", timeSent, timeReceived == null ? timeCompletedOrNow : timeReceived), new RequestTimeline.Event("received", timeReceived, timeCompletedOrNow), new RequestTimeline.Event("completed", timeCompleted, now)); } public long stop(Timer requests, Timer responses) { return this.args.stop(requests, responses); } @Override public String toString() { return RntbdObjectMapper.toString(this); } public enum Stage { QUEUED, PIPELINED, SENT, RECEIVED, COMPLETED } static final class JsonSerializer extends StdSerializer<RntbdRequestRecord> { private static final long serialVersionUID = -6869331366500298083L; JsonSerializer() { super(RntbdRequestRecord.class); } @Override public void serialize( final RntbdRequestRecord value, final JsonGenerator generator, final SerializerProvider provider) throws IOException { generator.writeStartObject(); generator.writeObjectField("args", value.args()); generator.writeNumberField("requestLength", value.requestLength()); generator.writeNumberField("responseLength", value.responseLength()); generator.writeObjectFieldStart("status"); generator.writeBooleanField("done", value.isDone()); generator.writeBooleanField("cancelled", value.isCancelled()); generator.writeBooleanField("completedExceptionally", value.isCompletedExceptionally()); if (value.isCompletedExceptionally()) { try { value.get(); } catch (final ExecutionException executionException) { final Throwable error = executionException.getCause(); generator.writeObjectFieldStart("error"); generator.writeStringField("type", error.getClass().getName()); generator.writeObjectField("value", error); generator.writeEndObject(); } catch (CancellationException | InterruptedException exception) { generator.writeObjectFieldStart("error"); generator.writeStringField("type", exception.getClass().getName()); generator.writeObjectField("value", exception); generator.writeEndObject(); } } generator.writeEndObject(); generator.writeObjectField("timeline", value.takeTimelineSnapshot()); generator.writeEndObject(); } } }
for the new test please don't use `InternalObjectNode` this will be used by the end user. Please rely on ObjectNode or a simple POJO.
public void readAllItemsByPageWithCosmosPagedFluxHandler() throws Exception { CosmosQueryRequestOptions cosmosQueryRequestOptions = new CosmosQueryRequestOptions(); CosmosPagedFlux<InternalObjectNode> cosmosPagedFlux = cosmosAsyncContainer.readAllItems(cosmosQueryRequestOptions, InternalObjectNode.class); AtomicInteger handleCount = new AtomicInteger(); cosmosPagedFlux = cosmosPagedFlux.handle(feedResponse -> { CosmosDiagnostics cosmosDiagnostics = feedResponse.getCosmosDiagnostics(); if (cosmosDiagnostics != null) { handleCount.incrementAndGet(); } }); AtomicInteger itemCount = new AtomicInteger(); AtomicInteger feedResponseCount = new AtomicInteger(); cosmosPagedFlux.byPage().toIterable().forEach(feedResponse -> { feedResponseCount.incrementAndGet(); int size = feedResponse.getResults().size(); itemCount.addAndGet(size); }); assertThat(handleCount.get() >= 1).isTrue(); assertThat(handleCount.get()).isEqualTo(feedResponseCount.get()); assertThat(itemCount.get()).isEqualTo(NUM_OF_ITEMS); }
CosmosPagedFlux<InternalObjectNode> cosmosPagedFlux =
public void readAllItemsByPageWithCosmosPagedFluxHandler() throws Exception { CosmosQueryRequestOptions cosmosQueryRequestOptions = new CosmosQueryRequestOptions(); CosmosPagedFlux<ObjectNode> cosmosPagedFlux = cosmosAsyncContainer.readAllItems(cosmosQueryRequestOptions, ObjectNode.class); AtomicInteger handleCount = new AtomicInteger(); cosmosPagedFlux = cosmosPagedFlux.handle(feedResponse -> { CosmosDiagnostics cosmosDiagnostics = feedResponse.getCosmosDiagnostics(); if (cosmosDiagnostics != null) { handleCount.incrementAndGet(); } }); AtomicInteger feedResponseCount = new AtomicInteger(); cosmosPagedFlux.byPage().toIterable().forEach(feedResponse -> { feedResponseCount.incrementAndGet(); }); assertThat(handleCount.get() >= 1).isTrue(); assertThat(handleCount.get()).isEqualTo(feedResponseCount.get()); }
class CosmosPagedFluxTest extends TestSuiteBase { private static final int NUM_OF_ITEMS = 10; private CosmosAsyncClient cosmosAsyncClient; private CosmosAsyncContainer cosmosAsyncContainer; @Factory(dataProvider = "clientBuilders") public CosmosPagedFluxTest(CosmosClientBuilder clientBuilder) { super(clientBuilder); } @BeforeClass(groups = { "simple" }, timeOut = SETUP_TIMEOUT) public void before_CosmosPagedFluxTest() { assertThat(this.cosmosAsyncClient).isNull(); this.cosmosAsyncClient = getClientBuilder().buildAsyncClient(); CosmosAsyncContainer asyncContainer = getSharedMultiPartitionCosmosContainer(this.cosmosAsyncClient); cosmosAsyncContainer = cosmosAsyncClient.getDatabase(asyncContainer.getDatabase().getId()).getContainer(asyncContainer.getId()); createItems(NUM_OF_ITEMS); } @AfterClass(groups = { "simple" }, timeOut = SHUTDOWN_TIMEOUT, alwaysRun = true) public void afterClass() { assertThat(this.cosmosAsyncClient).isNotNull(); this.cosmosAsyncClient.close(); } @Test(groups = { "simple" }, timeOut = TIMEOUT) @Test(groups = { "simple" }, timeOut = TIMEOUT) public void readAllItemsBySubscribeWithCosmosPagedFluxHandler() throws Exception { CosmosQueryRequestOptions cosmosQueryRequestOptions = new CosmosQueryRequestOptions(); CosmosPagedFlux<InternalObjectNode> cosmosPagedFlux = cosmosAsyncContainer.readAllItems(cosmosQueryRequestOptions, InternalObjectNode.class); AtomicInteger handleCount = new AtomicInteger(); cosmosPagedFlux = cosmosPagedFlux.handle(feedResponse -> { CosmosDiagnostics cosmosDiagnostics = feedResponse.getCosmosDiagnostics(); if (cosmosDiagnostics != null) { handleCount.incrementAndGet(); } }); AtomicInteger itemCount = new AtomicInteger(); cosmosPagedFlux.toIterable().forEach(internalObjectNode -> { itemCount.incrementAndGet(); }); assertThat(handleCount.get() >= 1).isTrue(); assertThat(itemCount.get()).isEqualTo(NUM_OF_ITEMS); } private void createItems(int numOfItems) { for (int i = 0; i < numOfItems; i++) { InternalObjectNode properties = getDocumentDefinition(UUID.randomUUID().toString()); cosmosAsyncContainer.createItem(properties).block(); } } private InternalObjectNode getDocumentDefinition(String documentId) { final String uuid = UUID.randomUUID().toString(); final InternalObjectNode properties = new InternalObjectNode(String.format("{ " + "\"id\": \"%s\", " + "\"mypk\": \"%s\", " + "\"sgmts\": [[6519456, 1471916863], [2498434, 1455671440]]" + "}" , documentId, uuid)); return properties; } }
class CosmosPagedFluxTest extends TestSuiteBase { private static final int NUM_OF_ITEMS = 10; private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper(); private CosmosAsyncClient cosmosAsyncClient; private CosmosAsyncContainer cosmosAsyncContainer; @Factory(dataProvider = "clientBuildersWithDirectSession") public CosmosPagedFluxTest(CosmosClientBuilder clientBuilder) { super(clientBuilder); } @BeforeClass(groups = { "simple" }, timeOut = SETUP_TIMEOUT) public void before_CosmosPagedFluxTest() throws JsonProcessingException { assertThat(this.cosmosAsyncClient).isNull(); this.cosmosAsyncClient = getClientBuilder().buildAsyncClient(); CosmosAsyncContainer asyncContainer = getSharedMultiPartitionCosmosContainer(this.cosmosAsyncClient); cosmosAsyncContainer = cosmosAsyncClient.getDatabase(asyncContainer.getDatabase().getId()).getContainer(asyncContainer.getId()); createItems(NUM_OF_ITEMS); } @AfterClass(groups = { "simple" }, timeOut = SHUTDOWN_TIMEOUT, alwaysRun = true) public void afterClass() { assertThat(this.cosmosAsyncClient).isNotNull(); this.cosmosAsyncClient.close(); } @Test(groups = { "simple" }, timeOut = TIMEOUT) @Test(groups = { "simple" }, timeOut = TIMEOUT) public void readAllItemsBySubscribeWithCosmosPagedFluxHandler() throws Exception { CosmosQueryRequestOptions cosmosQueryRequestOptions = new CosmosQueryRequestOptions(); CosmosPagedFlux<ObjectNode> cosmosPagedFlux = cosmosAsyncContainer.readAllItems(cosmosQueryRequestOptions, ObjectNode.class); AtomicInteger handleCount = new AtomicInteger(); cosmosPagedFlux = cosmosPagedFlux.handle(feedResponse -> { CosmosDiagnostics cosmosDiagnostics = feedResponse.getCosmosDiagnostics(); if (cosmosDiagnostics != null) { handleCount.incrementAndGet(); } }); cosmosPagedFlux.toIterable().forEach(objectNode -> {}); assertThat(handleCount.get() >= 1).isTrue(); } private void createItems(int numOfItems) throws JsonProcessingException { for (int i = 0; i < numOfItems; i++) { ObjectNode properties = getDocumentDefinition(UUID.randomUUID().toString(), String.valueOf(i)); cosmosAsyncContainer.createItem(properties).block(); } } private ObjectNode getDocumentDefinition(String documentId, String pkId) throws JsonProcessingException { String json = String.format("{ " + "\"id\": \"%s\", " + "\"mypk\": \"%s\", " + "\"sgmts\": [[6519456, 1471916863], [2498434, 1455671440]]" + "}" , documentId, pkId); return OBJECT_MAPPER.readValue(json, ObjectNode.class); } }
ditto. for the new test please don't use `InternalObjectNode` this will be used by the end user. Please rely on ObjectNode or a simple POJO.
public void readAllItemsByPageWithCosmosPagedIterableHandler() throws Exception { CosmosQueryRequestOptions cosmosQueryRequestOptions = new CosmosQueryRequestOptions(); CosmosPagedIterable<InternalObjectNode> cosmosPagedIterable = cosmosContainer.readAllItems(cosmosQueryRequestOptions, InternalObjectNode.class); AtomicInteger handleCount = new AtomicInteger(); cosmosPagedIterable = cosmosPagedIterable.handle(feedResponse -> { CosmosDiagnostics cosmosDiagnostics = feedResponse.getCosmosDiagnostics(); logger.info("Cosmos Diagnostics : {}", cosmosDiagnostics); if (cosmosDiagnostics != null) { handleCount.incrementAndGet(); } }); AtomicInteger itemCount = new AtomicInteger(); AtomicInteger feedResponseCount = new AtomicInteger(); cosmosPagedIterable.iterableByPage().forEach(feedResponse -> { feedResponseCount.incrementAndGet(); int size = feedResponse.getResults().size(); itemCount.addAndGet(size); }); assertThat(handleCount.get() >= 1).isTrue(); assertThat(handleCount.get()).isEqualTo(feedResponseCount.get()); assertThat(itemCount.get()).isEqualTo(NUM_OF_ITEMS); }
CosmosPagedIterable<InternalObjectNode> cosmosPagedIterable =
public void readAllItemsByPageWithCosmosPagedIterableHandler() throws Exception { CosmosQueryRequestOptions cosmosQueryRequestOptions = new CosmosQueryRequestOptions(); CosmosPagedIterable<ObjectNode> cosmosPagedIterable = cosmosContainer.readAllItems(cosmosQueryRequestOptions, ObjectNode.class); AtomicInteger handleCount = new AtomicInteger(); cosmosPagedIterable = cosmosPagedIterable.handle(feedResponse -> { CosmosDiagnostics cosmosDiagnostics = feedResponse.getCosmosDiagnostics(); if (cosmosDiagnostics != null) { handleCount.incrementAndGet(); } }); AtomicInteger feedResponseCount = new AtomicInteger(); cosmosPagedIterable.iterableByPage().forEach(feedResponse -> { feedResponseCount.incrementAndGet(); }); assertThat(handleCount.get() >= 1).isTrue(); assertThat(handleCount.get()).isEqualTo(feedResponseCount.get()); }
class CosmosPagedIterableTest extends TestSuiteBase { private static final int NUM_OF_ITEMS = 10; private CosmosClient cosmosClient; private CosmosContainer cosmosContainer; @Factory(dataProvider = "clientBuilders") public CosmosPagedIterableTest(CosmosClientBuilder clientBuilder) { super(clientBuilder); } @BeforeClass(groups = { "simple" }, timeOut = SETUP_TIMEOUT) public void before_CosmosPagedIterableTest() { assertThat(this.cosmosClient).isNull(); this.cosmosClient = getClientBuilder().buildClient(); CosmosAsyncContainer asyncContainer = getSharedMultiPartitionCosmosContainer(this.cosmosClient.asyncClient()); cosmosContainer = cosmosClient.getDatabase(asyncContainer.getDatabase().getId()).getContainer(asyncContainer.getId()); createItems(NUM_OF_ITEMS); } @AfterClass(groups = { "simple" }, timeOut = SHUTDOWN_TIMEOUT, alwaysRun = true) public void afterClass() { assertThat(this.cosmosClient).isNotNull(); this.cosmosClient.close(); } @Test(groups = { "simple" }, timeOut = TIMEOUT) @Test(groups = { "simple" }, timeOut = TIMEOUT) public void readAllItemsBySubscribeWithCosmosPagedIterableHandler() throws Exception { CosmosQueryRequestOptions cosmosQueryRequestOptions = new CosmosQueryRequestOptions(); CosmosPagedIterable<InternalObjectNode> cosmosPagedIterable = cosmosContainer.readAllItems(cosmosQueryRequestOptions, InternalObjectNode.class); AtomicInteger handleCount = new AtomicInteger(); cosmosPagedIterable = cosmosPagedIterable.handle(feedResponse -> { CosmosDiagnostics cosmosDiagnostics = feedResponse.getCosmosDiagnostics(); logger.info("Cosmos Diagnostics : {}", cosmosDiagnostics); if (cosmosDiagnostics != null) { handleCount.incrementAndGet(); } }); AtomicInteger itemCount = new AtomicInteger(); cosmosPagedIterable.forEach(internalObjectNode -> { itemCount.incrementAndGet(); }); assertThat(handleCount.get() >= 1).isTrue(); assertThat(itemCount.get()).isEqualTo(NUM_OF_ITEMS); } private void createItems(int numOfItems) { for (int i = 0; i < numOfItems; i++) { InternalObjectNode properties = getDocumentDefinition(UUID.randomUUID().toString()); cosmosContainer.createItem(properties); } } private InternalObjectNode getDocumentDefinition(String documentId) { final String uuid = UUID.randomUUID().toString(); final InternalObjectNode properties = new InternalObjectNode(String.format("{ " + "\"id\": \"%s\", " + "\"mypk\": \"%s\", " + "\"sgmts\": [[6519456, 1471916863], [2498434, 1455671440]]" + "}" , documentId, uuid)); return properties; } }
class CosmosPagedIterableTest extends TestSuiteBase { private static final int NUM_OF_ITEMS = 10; private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper(); private CosmosClient cosmosClient; private CosmosContainer cosmosContainer; @Factory(dataProvider = "clientBuildersWithDirectSession") public CosmosPagedIterableTest(CosmosClientBuilder clientBuilder) { super(clientBuilder); } @BeforeClass(groups = { "simple" }, timeOut = SETUP_TIMEOUT) public void before_CosmosPagedIterableTest() throws JsonProcessingException { assertThat(this.cosmosClient).isNull(); this.cosmosClient = getClientBuilder().buildClient(); CosmosAsyncContainer asyncContainer = getSharedMultiPartitionCosmosContainer(this.cosmosClient.asyncClient()); cosmosContainer = cosmosClient.getDatabase(asyncContainer.getDatabase().getId()).getContainer(asyncContainer.getId()); createItems(NUM_OF_ITEMS); } @AfterClass(groups = { "simple" }, timeOut = SHUTDOWN_TIMEOUT, alwaysRun = true) public void afterClass() { assertThat(this.cosmosClient).isNotNull(); this.cosmosClient.close(); } @Test(groups = { "simple" }, timeOut = TIMEOUT) @Test(groups = { "simple" }, timeOut = TIMEOUT) public void readAllItemsBySubscribeWithCosmosPagedIterableHandler() throws Exception { CosmosQueryRequestOptions cosmosQueryRequestOptions = new CosmosQueryRequestOptions(); CosmosPagedIterable<ObjectNode> cosmosPagedIterable = cosmosContainer.readAllItems(cosmosQueryRequestOptions, ObjectNode.class); AtomicInteger handleCount = new AtomicInteger(); cosmosPagedIterable = cosmosPagedIterable.handle(feedResponse -> { CosmosDiagnostics cosmosDiagnostics = feedResponse.getCosmosDiagnostics(); if (cosmosDiagnostics != null) { handleCount.incrementAndGet(); } }); cosmosPagedIterable.forEach(objectNode -> { }); assertThat(handleCount.get() >= 1).isTrue(); } private void createItems(int numOfItems) throws JsonProcessingException { for (int i = 0; i < numOfItems; i++) { ObjectNode properties = getDocumentDefinition(UUID.randomUUID().toString(), String.valueOf(i)); cosmosContainer.createItem(properties); } } private ObjectNode getDocumentDefinition(String documentId, String pkId) throws JsonProcessingException { String json = String.format("{ " + "\"id\": \"%s\", " + "\"mypk\": \"%s\", " + "\"sgmts\": [[6519456, 1471916863], [2498434, 1455671440]]" + "}" , documentId, pkId); return OBJECT_MAPPER.readValue(json, ObjectNode.class); } }
NIT: similar as above - have a helper function IsNonIOBoundOperation or similar that returns true for now if addres refresh or query plan retrieval but can be extended easily
public Mono<ShouldRetryResult> shouldRetry(Exception e) { logger.debug("retry count {}, isReadRequest {}, canUseMultipleWriteLocations {}, due to failure:", cnt.incrementAndGet(), isReadRequest, canUseMultipleWriteLocations, e); if (this.locationEndpoint == null) { logger.error("locationEndpoint is null because ClientRetryPolicy::onBeforeRequest(.) is not invoked, " + "probably request creation failed due to invalid options, serialization setting, etc."); return Mono.just(ShouldRetryResult.error(e)); } this.retryContext = null; CosmosException clientException = Utils.as(e, CosmosException.class); if (clientException != null && clientException.getDiagnostics() != null) { this.cosmosDiagnostics = clientException.getDiagnostics(); } if (clientException != null && Exceptions.isStatusCode(clientException, HttpConstants.StatusCodes.FORBIDDEN) && Exceptions.isSubStatusCode(clientException, HttpConstants.SubStatusCodes.FORBIDDEN_WRITEFORBIDDEN)) { logger.warn("Endpoint not writable. Will refresh cache and retry ", e); return this.shouldRetryOnEndpointFailureAsync(false, true); } if (clientException != null && Exceptions.isStatusCode(clientException, HttpConstants.StatusCodes.FORBIDDEN) && Exceptions.isSubStatusCode(clientException, HttpConstants.SubStatusCodes.DATABASE_ACCOUNT_NOTFOUND) && this.isReadRequest) { logger.warn("Endpoint not available for reads. Will refresh cache and retry. ", e); return this.shouldRetryOnEndpointFailureAsync(true, false); } if (WebExceptionUtility.isNetworkFailure(e)) { if (clientException != null && Exceptions.isSubStatusCode(clientException, HttpConstants.SubStatusCodes.GATEWAY_ENDPOINT_UNAVAILABLE)) { if (this.isReadRequest || WebExceptionUtility.isWebExceptionRetriable(e)) { logger.warn("Gateway endpoint not reachable. Will refresh cache and retry. ", e); return this.shouldRetryOnEndpointFailureAsync(this.isReadRequest, false); } else { return this.shouldNotRetryOnEndpointFailureAsync(this.isReadRequest, false); } } else if (clientException != null && clientException.getCause() instanceof ReadTimeoutException) { if (this.operationType == OperationType.QueryPlan || this.operationType == OperationType.AddressRefresh) { return shouldRetryQueryPlanAndAddress(); } } else { logger.warn("Backend endpoint not reachable. ", e); return this.shouldRetryOnBackendServiceUnavailableAsync(this.isReadRequest, WebExceptionUtility .isWebExceptionRetriable(e)); } } if (clientException != null && Exceptions.isStatusCode(clientException, HttpConstants.StatusCodes.NOTFOUND) && Exceptions.isSubStatusCode(clientException, HttpConstants.SubStatusCodes.READ_SESSION_NOT_AVAILABLE)) { return Mono.just(this.shouldRetryOnSessionNotAvailable()); } return this.throttlingRetry.shouldRetry(e); }
} else if (clientException != null && clientException.getCause() instanceof ReadTimeoutException) {
public Mono<ShouldRetryResult> shouldRetry(Exception e) { logger.debug("retry count {}, isReadRequest {}, canUseMultipleWriteLocations {}, due to failure:", cnt.incrementAndGet(), isReadRequest, canUseMultipleWriteLocations, e); if (this.locationEndpoint == null) { logger.error("locationEndpoint is null because ClientRetryPolicy::onBeforeRequest(.) is not invoked, " + "probably request creation failed due to invalid options, serialization setting, etc."); return Mono.just(ShouldRetryResult.error(e)); } this.retryContext = null; CosmosException clientException = Utils.as(e, CosmosException.class); if (clientException != null && clientException.getDiagnostics() != null) { this.cosmosDiagnostics = clientException.getDiagnostics(); } if (clientException != null && Exceptions.isStatusCode(clientException, HttpConstants.StatusCodes.FORBIDDEN) && Exceptions.isSubStatusCode(clientException, HttpConstants.SubStatusCodes.FORBIDDEN_WRITEFORBIDDEN)) { logger.warn("Endpoint not writable. Will refresh cache and retry ", e); return this.shouldRetryOnEndpointFailureAsync(false, true); } if (clientException != null && Exceptions.isStatusCode(clientException, HttpConstants.StatusCodes.FORBIDDEN) && Exceptions.isSubStatusCode(clientException, HttpConstants.SubStatusCodes.DATABASE_ACCOUNT_NOTFOUND) && this.isReadRequest) { logger.warn("Endpoint not available for reads. Will refresh cache and retry. ", e); return this.shouldRetryOnEndpointFailureAsync(true, false); } if (WebExceptionUtility.isNetworkFailure(e)) { if (clientException != null && Exceptions.isSubStatusCode(clientException, HttpConstants.SubStatusCodes.GATEWAY_ENDPOINT_UNAVAILABLE)) { if (this.isReadRequest || WebExceptionUtility.isWebExceptionRetriable(e)) { logger.warn("Gateway endpoint not reachable. Will refresh cache and retry. ", e); return this.shouldRetryOnEndpointFailureAsync(this.isReadRequest, false); } else { return this.shouldNotRetryOnEndpointFailureAsync(this.isReadRequest, false); } } else if (clientException != null && WebExceptionUtility.isReadTimeoutException(clientException) && Exceptions.isSubStatusCode(clientException, HttpConstants.SubStatusCodes.GATEWAY_ENDPOINT_READ_TIMEOUT)) { if (this.request.getOperationType() == OperationType.QueryPlan || this.request.isAddressRefresh()) { return shouldRetryQueryPlanAndAddress(); } } else { logger.warn("Backend endpoint not reachable. ", e); return this.shouldRetryOnBackendServiceUnavailableAsync(this.isReadRequest, WebExceptionUtility .isWebExceptionRetriable(e)); } } if (clientException != null && Exceptions.isStatusCode(clientException, HttpConstants.StatusCodes.NOTFOUND) && Exceptions.isSubStatusCode(clientException, HttpConstants.SubStatusCodes.READ_SESSION_NOT_AVAILABLE)) { return Mono.just(this.shouldRetryOnSessionNotAvailable()); } return this.throttlingRetry.shouldRetry(e); }
class ClientRetryPolicy extends DocumentClientRetryPolicy { private final static Logger logger = LoggerFactory.getLogger(ClientRetryPolicy.class); final static int RetryIntervalInMS = 1000; final static int MaxRetryCount = 120; private final static int MaxServiceUnavailableRetryCount = 1; private final static int MAX_QUERYPLAN_ADDRESS_RETRY_COUNT = 2; private final DocumentClientRetryPolicy throttlingRetry; private final GlobalEndpointManager globalEndpointManager; private final boolean enableEndpointDiscovery; private int failoverRetryCount; private int sessionTokenRetryCount; private boolean isReadRequest; private boolean canUseMultipleWriteLocations; private URI locationEndpoint; private RetryContext retryContext; private CosmosDiagnostics cosmosDiagnostics; private AtomicInteger cnt = new AtomicInteger(0); private int serviceUnavailableRetryCount; private int queryplanAddressRefreshCount; private OperationType operationType; public ClientRetryPolicy(GlobalEndpointManager globalEndpointManager, boolean enableEndpointDiscovery, ThrottlingRetryOptions throttlingRetryOptions) { this.throttlingRetry = new ResourceThrottleRetryPolicy( throttlingRetryOptions.getMaxRetryAttemptsOnThrottledRequests(), throttlingRetryOptions.getMaxRetryWaitTime()); this.globalEndpointManager = globalEndpointManager; this.failoverRetryCount = 0; this.enableEndpointDiscovery = enableEndpointDiscovery; this.sessionTokenRetryCount = 0; this.canUseMultipleWriteLocations = false; this.cosmosDiagnostics = BridgeInternal.createCosmosDiagnostics(); } @Override private Mono<ShouldRetryResult> shouldRetryQueryPlanAndAddress() { if (this.queryplanAddressRefreshCount++ > MAX_QUERYPLAN_ADDRESS_RETRY_COUNT) { logger .warn("shouldRetryQueryPlanAndAddress() Not retrying. Retry count = {}", this.serviceUnavailableRetryCount); return Mono.just(ShouldRetryResult.noRetry()); } Duration retryDelay = Duration.ZERO; return Mono.just(ShouldRetryResult.retryAfter(retryDelay)); } private ShouldRetryResult shouldRetryOnSessionNotAvailable() { this.sessionTokenRetryCount++; if (!this.enableEndpointDiscovery) { return ShouldRetryResult.noRetry(); } else { if (this.canUseMultipleWriteLocations) { UnmodifiableList<URI> endpoints = this.isReadRequest ? this.globalEndpointManager.getReadEndpoints() : this.globalEndpointManager.getWriteEndpoints(); if (this.sessionTokenRetryCount > endpoints.size()) { return ShouldRetryResult.noRetry(); } else { this.retryContext = new RetryContext(this.sessionTokenRetryCount - 1, this.sessionTokenRetryCount > 1); return ShouldRetryResult.retryAfter(Duration.ZERO); } } else { if (this.sessionTokenRetryCount > 1) { return ShouldRetryResult.noRetry(); } else { this.retryContext = new RetryContext(this.sessionTokenRetryCount - 1, false); return ShouldRetryResult.retryAfter(Duration.ZERO); } } } } private Mono<ShouldRetryResult> shouldRetryOnEndpointFailureAsync(boolean isReadRequest , boolean forceRefresh) { if (!this.enableEndpointDiscovery || this.failoverRetryCount > MaxRetryCount) { logger.warn("ShouldRetryOnEndpointFailureAsync() Not retrying. Retry count = {}", this.failoverRetryCount); return Mono.just(ShouldRetryResult.noRetry()); } Mono<Void> refreshLocationCompletable = this.refreshLocation(isReadRequest, forceRefresh); Duration retryDelay = Duration.ZERO; if (!isReadRequest) { logger.debug("Failover happening. retryCount {}", this.failoverRetryCount); if (this.failoverRetryCount > 1) { retryDelay = Duration.ofMillis(ClientRetryPolicy.RetryIntervalInMS); } } else { retryDelay = Duration.ofMillis(ClientRetryPolicy.RetryIntervalInMS); } return refreshLocationCompletable.then(Mono.just(ShouldRetryResult.retryAfter(retryDelay))); } private Mono<ShouldRetryResult> shouldNotRetryOnEndpointFailureAsync(boolean isReadRequest , boolean forceRefresh) { if (!this.enableEndpointDiscovery || this.failoverRetryCount > MaxRetryCount) { logger.warn("ShouldRetryOnEndpointFailureAsync() Not retrying. Retry count = {}", this.failoverRetryCount); return Mono.just(ShouldRetryResult.noRetry()); } Mono<Void> refreshLocationCompletable = this.refreshLocation(isReadRequest, forceRefresh); return refreshLocationCompletable.then(Mono.just(ShouldRetryResult.noRetry())); } private Mono<Void> refreshLocation(boolean isReadRequest, boolean forceRefresh) { this.failoverRetryCount++; if (isReadRequest) { logger.warn("marking the endpoint {} as unavailable for read",this.locationEndpoint); this.globalEndpointManager.markEndpointUnavailableForRead(this.locationEndpoint); } else { logger.warn("marking the endpoint {} as unavailable for write",this.locationEndpoint); this.globalEndpointManager.markEndpointUnavailableForWrite(this.locationEndpoint); } this.retryContext = new RetryContext(this.failoverRetryCount, false); return this.globalEndpointManager.refreshLocationAsync(null, forceRefresh); } private Mono<ShouldRetryResult> shouldRetryOnBackendServiceUnavailableAsync(boolean isReadRequest, boolean isWebExceptionRetriable) { if (!isReadRequest && !isWebExceptionRetriable) { logger.warn("shouldRetryOnBackendServiceUnavailableAsync() Not retrying on write with non retriable exception. Retry count = {}", this.serviceUnavailableRetryCount); return Mono.just(ShouldRetryResult.noRetry()); } if (this.serviceUnavailableRetryCount++ > MaxServiceUnavailableRetryCount) { logger.warn("shouldRetryOnBackendServiceUnavailableAsync() Not retrying. Retry count = {}", this.serviceUnavailableRetryCount); return Mono.just(ShouldRetryResult.noRetry()); } if (!this.canUseMultipleWriteLocations && !isReadRequest) { return Mono.just(ShouldRetryResult.noRetry()); } int availablePreferredLocations = this.globalEndpointManager.getPreferredLocationCount(); if (availablePreferredLocations <= 1) { logger.warn("shouldRetryOnServiceUnavailable() Not retrying. No other regions available for the request. AvailablePreferredLocations = {}", availablePreferredLocations); return Mono.just(ShouldRetryResult.noRetry()); } logger.warn("shouldRetryOnServiceUnavailable() Retrying. Received on endpoint {}, IsReadRequest = {}", this.locationEndpoint, isReadRequest); this.retryContext = new RetryContext(this.serviceUnavailableRetryCount, true); return Mono.just(ShouldRetryResult.retryAfter(Duration.ZERO)); } @Override public void onBeforeSendRequest(RxDocumentServiceRequest request) { this.operationType = request.getOperationType(); this.isReadRequest = request.isReadOnlyRequest(); this.canUseMultipleWriteLocations = this.globalEndpointManager.canUseMultipleWriteLocations(request); if (request.requestContext != null) { request.requestContext.cosmosDiagnostics = this.cosmosDiagnostics; } if (request.requestContext != null) { request.requestContext.clearRouteToLocation(); } if (this.retryContext != null) { request.requestContext.routeToLocation(this.retryContext.retryCount, this.retryContext.retryRequestOnPreferredLocations); } this.locationEndpoint = this.globalEndpointManager.resolveServiceEndpoint(request); if (request.requestContext != null) { request.requestContext.routeToLocation(this.locationEndpoint); } } private static class RetryContext { public int retryCount; public boolean retryRequestOnPreferredLocations; public RetryContext(int retryCount, boolean retryRequestOnPreferredLocations) { this.retryCount = retryCount; this.retryRequestOnPreferredLocations = retryRequestOnPreferredLocations; } } }
class ClientRetryPolicy extends DocumentClientRetryPolicy { private final static Logger logger = LoggerFactory.getLogger(ClientRetryPolicy.class); final static int RetryIntervalInMS = 1000; final static int MaxRetryCount = 120; private final static int MaxServiceUnavailableRetryCount = 1; private final static int MAX_QUERY_PLAN_AND_ADDRESS_RETRY_COUNT = 2; private final DocumentClientRetryPolicy throttlingRetry; private final GlobalEndpointManager globalEndpointManager; private final boolean enableEndpointDiscovery; private int failoverRetryCount; private int sessionTokenRetryCount; private boolean isReadRequest; private boolean canUseMultipleWriteLocations; private URI locationEndpoint; private RetryContext retryContext; private CosmosDiagnostics cosmosDiagnostics; private AtomicInteger cnt = new AtomicInteger(0); private int serviceUnavailableRetryCount; private int queryPlanAddressRefreshCount; private RxDocumentServiceRequest request; public ClientRetryPolicy(GlobalEndpointManager globalEndpointManager, boolean enableEndpointDiscovery, ThrottlingRetryOptions throttlingRetryOptions) { this.throttlingRetry = new ResourceThrottleRetryPolicy( throttlingRetryOptions.getMaxRetryAttemptsOnThrottledRequests(), throttlingRetryOptions.getMaxRetryWaitTime()); this.globalEndpointManager = globalEndpointManager; this.failoverRetryCount = 0; this.enableEndpointDiscovery = enableEndpointDiscovery; this.sessionTokenRetryCount = 0; this.canUseMultipleWriteLocations = false; this.cosmosDiagnostics = BridgeInternal.createCosmosDiagnostics(); } @Override private Mono<ShouldRetryResult> shouldRetryQueryPlanAndAddress() { if (this.queryPlanAddressRefreshCount++ > MAX_QUERY_PLAN_AND_ADDRESS_RETRY_COUNT) { logger .warn( "shouldRetryQueryPlanAndAddress() No more retrying on endpoint {}, operationType = {}, count = {}, " + "isAddressRefresh = {}", this.locationEndpoint, this.request.getOperationType(), this.queryPlanAddressRefreshCount, this.request.isAddressRefresh()); return Mono.just(ShouldRetryResult.noRetry()); } logger .warn("shouldRetryQueryPlanAndAddress() Retrying on endpoint {}, operationType = {}, count = {}, " + "isAddressRefresh = {}", this.locationEndpoint, this.request.getOperationType(), this.queryPlanAddressRefreshCount, this.request.isAddressRefresh()); Duration retryDelay = Duration.ZERO; return Mono.just(ShouldRetryResult.retryAfter(retryDelay)); } private ShouldRetryResult shouldRetryOnSessionNotAvailable() { this.sessionTokenRetryCount++; if (!this.enableEndpointDiscovery) { return ShouldRetryResult.noRetry(); } else { if (this.canUseMultipleWriteLocations) { UnmodifiableList<URI> endpoints = this.isReadRequest ? this.globalEndpointManager.getReadEndpoints() : this.globalEndpointManager.getWriteEndpoints(); if (this.sessionTokenRetryCount > endpoints.size()) { return ShouldRetryResult.noRetry(); } else { this.retryContext = new RetryContext(this.sessionTokenRetryCount - 1, this.sessionTokenRetryCount > 1); return ShouldRetryResult.retryAfter(Duration.ZERO); } } else { if (this.sessionTokenRetryCount > 1) { return ShouldRetryResult.noRetry(); } else { this.retryContext = new RetryContext(this.sessionTokenRetryCount - 1, false); return ShouldRetryResult.retryAfter(Duration.ZERO); } } } } private Mono<ShouldRetryResult> shouldRetryOnEndpointFailureAsync(boolean isReadRequest , boolean forceRefresh) { if (!this.enableEndpointDiscovery || this.failoverRetryCount > MaxRetryCount) { logger.warn("ShouldRetryOnEndpointFailureAsync() Not retrying. Retry count = {}", this.failoverRetryCount); return Mono.just(ShouldRetryResult.noRetry()); } Mono<Void> refreshLocationCompletable = this.refreshLocation(isReadRequest, forceRefresh); Duration retryDelay = Duration.ZERO; if (!isReadRequest) { logger.debug("Failover happening. retryCount {}", this.failoverRetryCount); if (this.failoverRetryCount > 1) { retryDelay = Duration.ofMillis(ClientRetryPolicy.RetryIntervalInMS); } } else { retryDelay = Duration.ofMillis(ClientRetryPolicy.RetryIntervalInMS); } return refreshLocationCompletable.then(Mono.just(ShouldRetryResult.retryAfter(retryDelay))); } private Mono<ShouldRetryResult> shouldNotRetryOnEndpointFailureAsync(boolean isReadRequest , boolean forceRefresh) { if (!this.enableEndpointDiscovery || this.failoverRetryCount > MaxRetryCount) { logger.warn("ShouldRetryOnEndpointFailureAsync() Not retrying. Retry count = {}", this.failoverRetryCount); return Mono.just(ShouldRetryResult.noRetry()); } Mono<Void> refreshLocationCompletable = this.refreshLocation(isReadRequest, forceRefresh); return refreshLocationCompletable.then(Mono.just(ShouldRetryResult.noRetry())); } private Mono<Void> refreshLocation(boolean isReadRequest, boolean forceRefresh) { this.failoverRetryCount++; if (isReadRequest) { logger.warn("marking the endpoint {} as unavailable for read",this.locationEndpoint); this.globalEndpointManager.markEndpointUnavailableForRead(this.locationEndpoint); } else { logger.warn("marking the endpoint {} as unavailable for write",this.locationEndpoint); this.globalEndpointManager.markEndpointUnavailableForWrite(this.locationEndpoint); } this.retryContext = new RetryContext(this.failoverRetryCount, false); return this.globalEndpointManager.refreshLocationAsync(null, forceRefresh); } private Mono<ShouldRetryResult> shouldRetryOnBackendServiceUnavailableAsync(boolean isReadRequest, boolean isWebExceptionRetriable) { if (!isReadRequest && !isWebExceptionRetriable) { logger.warn("shouldRetryOnBackendServiceUnavailableAsync() Not retrying on write with non retriable exception. Retry count = {}", this.serviceUnavailableRetryCount); return Mono.just(ShouldRetryResult.noRetry()); } if (this.serviceUnavailableRetryCount++ > MaxServiceUnavailableRetryCount) { logger.warn("shouldRetryOnBackendServiceUnavailableAsync() Not retrying. Retry count = {}", this.serviceUnavailableRetryCount); return Mono.just(ShouldRetryResult.noRetry()); } if (!this.canUseMultipleWriteLocations && !isReadRequest) { return Mono.just(ShouldRetryResult.noRetry()); } int availablePreferredLocations = this.globalEndpointManager.getPreferredLocationCount(); if (availablePreferredLocations <= 1) { logger.warn("shouldRetryOnServiceUnavailable() Not retrying. No other regions available for the request. AvailablePreferredLocations = {}", availablePreferredLocations); return Mono.just(ShouldRetryResult.noRetry()); } logger.warn("shouldRetryOnServiceUnavailable() Retrying. Received on endpoint {}, IsReadRequest = {}", this.locationEndpoint, isReadRequest); this.retryContext = new RetryContext(this.serviceUnavailableRetryCount, true); return Mono.just(ShouldRetryResult.retryAfter(Duration.ZERO)); } @Override public void onBeforeSendRequest(RxDocumentServiceRequest request) { this.request = request; this.isReadRequest = request.isReadOnlyRequest(); this.canUseMultipleWriteLocations = this.globalEndpointManager.canUseMultipleWriteLocations(request); if (request.requestContext != null) { request.requestContext.cosmosDiagnostics = this.cosmosDiagnostics; } if (request.requestContext != null) { request.requestContext.clearRouteToLocation(); } if (this.retryContext != null) { request.requestContext.routeToLocation(this.retryContext.retryCount, this.retryContext.retryRequestOnPreferredLocations); } this.locationEndpoint = this.globalEndpointManager.resolveServiceEndpoint(request); if (request.requestContext != null) { request.requestContext.routeToLocation(this.locationEndpoint); } } private static class RetryContext { public int retryCount; public boolean retryRequestOnPreferredLocations; public RetryContext(int retryCount, boolean retryRequestOnPreferredLocations) { this.retryCount = retryCount; this.retryRequestOnPreferredLocations = retryRequestOnPreferredLocations; } } }
We already have a utility class/methods for similar functionality. This should go to the same class as `WebExceptionUtility.isNetworkFailure()`.
public Mono<ShouldRetryResult> shouldRetry(Exception e) { logger.debug("retry count {}, isReadRequest {}, canUseMultipleWriteLocations {}, due to failure:", cnt.incrementAndGet(), isReadRequest, canUseMultipleWriteLocations, e); if (this.locationEndpoint == null) { logger.error("locationEndpoint is null because ClientRetryPolicy::onBeforeRequest(.) is not invoked, " + "probably request creation failed due to invalid options, serialization setting, etc."); return Mono.just(ShouldRetryResult.error(e)); } this.retryContext = null; CosmosException clientException = Utils.as(e, CosmosException.class); if (clientException != null && clientException.getDiagnostics() != null) { this.cosmosDiagnostics = clientException.getDiagnostics(); } if (clientException != null && Exceptions.isStatusCode(clientException, HttpConstants.StatusCodes.FORBIDDEN) && Exceptions.isSubStatusCode(clientException, HttpConstants.SubStatusCodes.FORBIDDEN_WRITEFORBIDDEN)) { logger.warn("Endpoint not writable. Will refresh cache and retry ", e); return this.shouldRetryOnEndpointFailureAsync(false, true); } if (clientException != null && Exceptions.isStatusCode(clientException, HttpConstants.StatusCodes.FORBIDDEN) && Exceptions.isSubStatusCode(clientException, HttpConstants.SubStatusCodes.DATABASE_ACCOUNT_NOTFOUND) && this.isReadRequest) { logger.warn("Endpoint not available for reads. Will refresh cache and retry. ", e); return this.shouldRetryOnEndpointFailureAsync(true, false); } if (WebExceptionUtility.isNetworkFailure(e)) { if (clientException != null && Exceptions.isSubStatusCode(clientException, HttpConstants.SubStatusCodes.GATEWAY_ENDPOINT_UNAVAILABLE)) { if (this.isReadRequest || WebExceptionUtility.isWebExceptionRetriable(e)) { logger.warn("Gateway endpoint not reachable. Will refresh cache and retry. ", e); return this.shouldRetryOnEndpointFailureAsync(this.isReadRequest, false); } else { return this.shouldNotRetryOnEndpointFailureAsync(this.isReadRequest, false); } } else if (clientException != null && clientException.getCause() instanceof ReadTimeoutException) { if (this.operationType == OperationType.QueryPlan || this.operationType == OperationType.AddressRefresh) { return shouldRetryQueryPlanAndAddress(); } } else { logger.warn("Backend endpoint not reachable. ", e); return this.shouldRetryOnBackendServiceUnavailableAsync(this.isReadRequest, WebExceptionUtility .isWebExceptionRetriable(e)); } } if (clientException != null && Exceptions.isStatusCode(clientException, HttpConstants.StatusCodes.NOTFOUND) && Exceptions.isSubStatusCode(clientException, HttpConstants.SubStatusCodes.READ_SESSION_NOT_AVAILABLE)) { return Mono.just(this.shouldRetryOnSessionNotAvailable()); } return this.throttlingRetry.shouldRetry(e); }
} else if (clientException != null && clientException.getCause() instanceof ReadTimeoutException) {
public Mono<ShouldRetryResult> shouldRetry(Exception e) { logger.debug("retry count {}, isReadRequest {}, canUseMultipleWriteLocations {}, due to failure:", cnt.incrementAndGet(), isReadRequest, canUseMultipleWriteLocations, e); if (this.locationEndpoint == null) { logger.error("locationEndpoint is null because ClientRetryPolicy::onBeforeRequest(.) is not invoked, " + "probably request creation failed due to invalid options, serialization setting, etc."); return Mono.just(ShouldRetryResult.error(e)); } this.retryContext = null; CosmosException clientException = Utils.as(e, CosmosException.class); if (clientException != null && clientException.getDiagnostics() != null) { this.cosmosDiagnostics = clientException.getDiagnostics(); } if (clientException != null && Exceptions.isStatusCode(clientException, HttpConstants.StatusCodes.FORBIDDEN) && Exceptions.isSubStatusCode(clientException, HttpConstants.SubStatusCodes.FORBIDDEN_WRITEFORBIDDEN)) { logger.warn("Endpoint not writable. Will refresh cache and retry ", e); return this.shouldRetryOnEndpointFailureAsync(false, true); } if (clientException != null && Exceptions.isStatusCode(clientException, HttpConstants.StatusCodes.FORBIDDEN) && Exceptions.isSubStatusCode(clientException, HttpConstants.SubStatusCodes.DATABASE_ACCOUNT_NOTFOUND) && this.isReadRequest) { logger.warn("Endpoint not available for reads. Will refresh cache and retry. ", e); return this.shouldRetryOnEndpointFailureAsync(true, false); } if (WebExceptionUtility.isNetworkFailure(e)) { if (clientException != null && Exceptions.isSubStatusCode(clientException, HttpConstants.SubStatusCodes.GATEWAY_ENDPOINT_UNAVAILABLE)) { if (this.isReadRequest || WebExceptionUtility.isWebExceptionRetriable(e)) { logger.warn("Gateway endpoint not reachable. Will refresh cache and retry. ", e); return this.shouldRetryOnEndpointFailureAsync(this.isReadRequest, false); } else { return this.shouldNotRetryOnEndpointFailureAsync(this.isReadRequest, false); } } else if (clientException != null && WebExceptionUtility.isReadTimeoutException(clientException) && Exceptions.isSubStatusCode(clientException, HttpConstants.SubStatusCodes.GATEWAY_ENDPOINT_READ_TIMEOUT)) { if (this.request.getOperationType() == OperationType.QueryPlan || this.request.isAddressRefresh()) { return shouldRetryQueryPlanAndAddress(); } } else { logger.warn("Backend endpoint not reachable. ", e); return this.shouldRetryOnBackendServiceUnavailableAsync(this.isReadRequest, WebExceptionUtility .isWebExceptionRetriable(e)); } } if (clientException != null && Exceptions.isStatusCode(clientException, HttpConstants.StatusCodes.NOTFOUND) && Exceptions.isSubStatusCode(clientException, HttpConstants.SubStatusCodes.READ_SESSION_NOT_AVAILABLE)) { return Mono.just(this.shouldRetryOnSessionNotAvailable()); } return this.throttlingRetry.shouldRetry(e); }
class ClientRetryPolicy extends DocumentClientRetryPolicy { private final static Logger logger = LoggerFactory.getLogger(ClientRetryPolicy.class); final static int RetryIntervalInMS = 1000; final static int MaxRetryCount = 120; private final static int MaxServiceUnavailableRetryCount = 1; private final static int MAX_QUERYPLAN_ADDRESS_RETRY_COUNT = 2; private final DocumentClientRetryPolicy throttlingRetry; private final GlobalEndpointManager globalEndpointManager; private final boolean enableEndpointDiscovery; private int failoverRetryCount; private int sessionTokenRetryCount; private boolean isReadRequest; private boolean canUseMultipleWriteLocations; private URI locationEndpoint; private RetryContext retryContext; private CosmosDiagnostics cosmosDiagnostics; private AtomicInteger cnt = new AtomicInteger(0); private int serviceUnavailableRetryCount; private int queryplanAddressRefreshCount; private OperationType operationType; public ClientRetryPolicy(GlobalEndpointManager globalEndpointManager, boolean enableEndpointDiscovery, ThrottlingRetryOptions throttlingRetryOptions) { this.throttlingRetry = new ResourceThrottleRetryPolicy( throttlingRetryOptions.getMaxRetryAttemptsOnThrottledRequests(), throttlingRetryOptions.getMaxRetryWaitTime()); this.globalEndpointManager = globalEndpointManager; this.failoverRetryCount = 0; this.enableEndpointDiscovery = enableEndpointDiscovery; this.sessionTokenRetryCount = 0; this.canUseMultipleWriteLocations = false; this.cosmosDiagnostics = BridgeInternal.createCosmosDiagnostics(); } @Override private Mono<ShouldRetryResult> shouldRetryQueryPlanAndAddress() { if (this.queryplanAddressRefreshCount++ > MAX_QUERYPLAN_ADDRESS_RETRY_COUNT) { logger .warn("shouldRetryQueryPlanAndAddress() Not retrying. Retry count = {}", this.serviceUnavailableRetryCount); return Mono.just(ShouldRetryResult.noRetry()); } Duration retryDelay = Duration.ZERO; return Mono.just(ShouldRetryResult.retryAfter(retryDelay)); } private ShouldRetryResult shouldRetryOnSessionNotAvailable() { this.sessionTokenRetryCount++; if (!this.enableEndpointDiscovery) { return ShouldRetryResult.noRetry(); } else { if (this.canUseMultipleWriteLocations) { UnmodifiableList<URI> endpoints = this.isReadRequest ? this.globalEndpointManager.getReadEndpoints() : this.globalEndpointManager.getWriteEndpoints(); if (this.sessionTokenRetryCount > endpoints.size()) { return ShouldRetryResult.noRetry(); } else { this.retryContext = new RetryContext(this.sessionTokenRetryCount - 1, this.sessionTokenRetryCount > 1); return ShouldRetryResult.retryAfter(Duration.ZERO); } } else { if (this.sessionTokenRetryCount > 1) { return ShouldRetryResult.noRetry(); } else { this.retryContext = new RetryContext(this.sessionTokenRetryCount - 1, false); return ShouldRetryResult.retryAfter(Duration.ZERO); } } } } private Mono<ShouldRetryResult> shouldRetryOnEndpointFailureAsync(boolean isReadRequest , boolean forceRefresh) { if (!this.enableEndpointDiscovery || this.failoverRetryCount > MaxRetryCount) { logger.warn("ShouldRetryOnEndpointFailureAsync() Not retrying. Retry count = {}", this.failoverRetryCount); return Mono.just(ShouldRetryResult.noRetry()); } Mono<Void> refreshLocationCompletable = this.refreshLocation(isReadRequest, forceRefresh); Duration retryDelay = Duration.ZERO; if (!isReadRequest) { logger.debug("Failover happening. retryCount {}", this.failoverRetryCount); if (this.failoverRetryCount > 1) { retryDelay = Duration.ofMillis(ClientRetryPolicy.RetryIntervalInMS); } } else { retryDelay = Duration.ofMillis(ClientRetryPolicy.RetryIntervalInMS); } return refreshLocationCompletable.then(Mono.just(ShouldRetryResult.retryAfter(retryDelay))); } private Mono<ShouldRetryResult> shouldNotRetryOnEndpointFailureAsync(boolean isReadRequest , boolean forceRefresh) { if (!this.enableEndpointDiscovery || this.failoverRetryCount > MaxRetryCount) { logger.warn("ShouldRetryOnEndpointFailureAsync() Not retrying. Retry count = {}", this.failoverRetryCount); return Mono.just(ShouldRetryResult.noRetry()); } Mono<Void> refreshLocationCompletable = this.refreshLocation(isReadRequest, forceRefresh); return refreshLocationCompletable.then(Mono.just(ShouldRetryResult.noRetry())); } private Mono<Void> refreshLocation(boolean isReadRequest, boolean forceRefresh) { this.failoverRetryCount++; if (isReadRequest) { logger.warn("marking the endpoint {} as unavailable for read",this.locationEndpoint); this.globalEndpointManager.markEndpointUnavailableForRead(this.locationEndpoint); } else { logger.warn("marking the endpoint {} as unavailable for write",this.locationEndpoint); this.globalEndpointManager.markEndpointUnavailableForWrite(this.locationEndpoint); } this.retryContext = new RetryContext(this.failoverRetryCount, false); return this.globalEndpointManager.refreshLocationAsync(null, forceRefresh); } private Mono<ShouldRetryResult> shouldRetryOnBackendServiceUnavailableAsync(boolean isReadRequest, boolean isWebExceptionRetriable) { if (!isReadRequest && !isWebExceptionRetriable) { logger.warn("shouldRetryOnBackendServiceUnavailableAsync() Not retrying on write with non retriable exception. Retry count = {}", this.serviceUnavailableRetryCount); return Mono.just(ShouldRetryResult.noRetry()); } if (this.serviceUnavailableRetryCount++ > MaxServiceUnavailableRetryCount) { logger.warn("shouldRetryOnBackendServiceUnavailableAsync() Not retrying. Retry count = {}", this.serviceUnavailableRetryCount); return Mono.just(ShouldRetryResult.noRetry()); } if (!this.canUseMultipleWriteLocations && !isReadRequest) { return Mono.just(ShouldRetryResult.noRetry()); } int availablePreferredLocations = this.globalEndpointManager.getPreferredLocationCount(); if (availablePreferredLocations <= 1) { logger.warn("shouldRetryOnServiceUnavailable() Not retrying. No other regions available for the request. AvailablePreferredLocations = {}", availablePreferredLocations); return Mono.just(ShouldRetryResult.noRetry()); } logger.warn("shouldRetryOnServiceUnavailable() Retrying. Received on endpoint {}, IsReadRequest = {}", this.locationEndpoint, isReadRequest); this.retryContext = new RetryContext(this.serviceUnavailableRetryCount, true); return Mono.just(ShouldRetryResult.retryAfter(Duration.ZERO)); } @Override public void onBeforeSendRequest(RxDocumentServiceRequest request) { this.operationType = request.getOperationType(); this.isReadRequest = request.isReadOnlyRequest(); this.canUseMultipleWriteLocations = this.globalEndpointManager.canUseMultipleWriteLocations(request); if (request.requestContext != null) { request.requestContext.cosmosDiagnostics = this.cosmosDiagnostics; } if (request.requestContext != null) { request.requestContext.clearRouteToLocation(); } if (this.retryContext != null) { request.requestContext.routeToLocation(this.retryContext.retryCount, this.retryContext.retryRequestOnPreferredLocations); } this.locationEndpoint = this.globalEndpointManager.resolveServiceEndpoint(request); if (request.requestContext != null) { request.requestContext.routeToLocation(this.locationEndpoint); } } private static class RetryContext { public int retryCount; public boolean retryRequestOnPreferredLocations; public RetryContext(int retryCount, boolean retryRequestOnPreferredLocations) { this.retryCount = retryCount; this.retryRequestOnPreferredLocations = retryRequestOnPreferredLocations; } } }
class ClientRetryPolicy extends DocumentClientRetryPolicy { private final static Logger logger = LoggerFactory.getLogger(ClientRetryPolicy.class); final static int RetryIntervalInMS = 1000; final static int MaxRetryCount = 120; private final static int MaxServiceUnavailableRetryCount = 1; private final static int MAX_QUERY_PLAN_AND_ADDRESS_RETRY_COUNT = 2; private final DocumentClientRetryPolicy throttlingRetry; private final GlobalEndpointManager globalEndpointManager; private final boolean enableEndpointDiscovery; private int failoverRetryCount; private int sessionTokenRetryCount; private boolean isReadRequest; private boolean canUseMultipleWriteLocations; private URI locationEndpoint; private RetryContext retryContext; private CosmosDiagnostics cosmosDiagnostics; private AtomicInteger cnt = new AtomicInteger(0); private int serviceUnavailableRetryCount; private int queryPlanAddressRefreshCount; private RxDocumentServiceRequest request; public ClientRetryPolicy(GlobalEndpointManager globalEndpointManager, boolean enableEndpointDiscovery, ThrottlingRetryOptions throttlingRetryOptions) { this.throttlingRetry = new ResourceThrottleRetryPolicy( throttlingRetryOptions.getMaxRetryAttemptsOnThrottledRequests(), throttlingRetryOptions.getMaxRetryWaitTime()); this.globalEndpointManager = globalEndpointManager; this.failoverRetryCount = 0; this.enableEndpointDiscovery = enableEndpointDiscovery; this.sessionTokenRetryCount = 0; this.canUseMultipleWriteLocations = false; this.cosmosDiagnostics = BridgeInternal.createCosmosDiagnostics(); } @Override private Mono<ShouldRetryResult> shouldRetryQueryPlanAndAddress() { if (this.queryPlanAddressRefreshCount++ > MAX_QUERY_PLAN_AND_ADDRESS_RETRY_COUNT) { logger .warn( "shouldRetryQueryPlanAndAddress() No more retrying on endpoint {}, operationType = {}, count = {}, " + "isAddressRefresh = {}", this.locationEndpoint, this.request.getOperationType(), this.queryPlanAddressRefreshCount, this.request.isAddressRefresh()); return Mono.just(ShouldRetryResult.noRetry()); } logger .warn("shouldRetryQueryPlanAndAddress() Retrying on endpoint {}, operationType = {}, count = {}, " + "isAddressRefresh = {}", this.locationEndpoint, this.request.getOperationType(), this.queryPlanAddressRefreshCount, this.request.isAddressRefresh()); Duration retryDelay = Duration.ZERO; return Mono.just(ShouldRetryResult.retryAfter(retryDelay)); } private ShouldRetryResult shouldRetryOnSessionNotAvailable() { this.sessionTokenRetryCount++; if (!this.enableEndpointDiscovery) { return ShouldRetryResult.noRetry(); } else { if (this.canUseMultipleWriteLocations) { UnmodifiableList<URI> endpoints = this.isReadRequest ? this.globalEndpointManager.getReadEndpoints() : this.globalEndpointManager.getWriteEndpoints(); if (this.sessionTokenRetryCount > endpoints.size()) { return ShouldRetryResult.noRetry(); } else { this.retryContext = new RetryContext(this.sessionTokenRetryCount - 1, this.sessionTokenRetryCount > 1); return ShouldRetryResult.retryAfter(Duration.ZERO); } } else { if (this.sessionTokenRetryCount > 1) { return ShouldRetryResult.noRetry(); } else { this.retryContext = new RetryContext(this.sessionTokenRetryCount - 1, false); return ShouldRetryResult.retryAfter(Duration.ZERO); } } } } private Mono<ShouldRetryResult> shouldRetryOnEndpointFailureAsync(boolean isReadRequest , boolean forceRefresh) { if (!this.enableEndpointDiscovery || this.failoverRetryCount > MaxRetryCount) { logger.warn("ShouldRetryOnEndpointFailureAsync() Not retrying. Retry count = {}", this.failoverRetryCount); return Mono.just(ShouldRetryResult.noRetry()); } Mono<Void> refreshLocationCompletable = this.refreshLocation(isReadRequest, forceRefresh); Duration retryDelay = Duration.ZERO; if (!isReadRequest) { logger.debug("Failover happening. retryCount {}", this.failoverRetryCount); if (this.failoverRetryCount > 1) { retryDelay = Duration.ofMillis(ClientRetryPolicy.RetryIntervalInMS); } } else { retryDelay = Duration.ofMillis(ClientRetryPolicy.RetryIntervalInMS); } return refreshLocationCompletable.then(Mono.just(ShouldRetryResult.retryAfter(retryDelay))); } private Mono<ShouldRetryResult> shouldNotRetryOnEndpointFailureAsync(boolean isReadRequest , boolean forceRefresh) { if (!this.enableEndpointDiscovery || this.failoverRetryCount > MaxRetryCount) { logger.warn("ShouldRetryOnEndpointFailureAsync() Not retrying. Retry count = {}", this.failoverRetryCount); return Mono.just(ShouldRetryResult.noRetry()); } Mono<Void> refreshLocationCompletable = this.refreshLocation(isReadRequest, forceRefresh); return refreshLocationCompletable.then(Mono.just(ShouldRetryResult.noRetry())); } private Mono<Void> refreshLocation(boolean isReadRequest, boolean forceRefresh) { this.failoverRetryCount++; if (isReadRequest) { logger.warn("marking the endpoint {} as unavailable for read",this.locationEndpoint); this.globalEndpointManager.markEndpointUnavailableForRead(this.locationEndpoint); } else { logger.warn("marking the endpoint {} as unavailable for write",this.locationEndpoint); this.globalEndpointManager.markEndpointUnavailableForWrite(this.locationEndpoint); } this.retryContext = new RetryContext(this.failoverRetryCount, false); return this.globalEndpointManager.refreshLocationAsync(null, forceRefresh); } private Mono<ShouldRetryResult> shouldRetryOnBackendServiceUnavailableAsync(boolean isReadRequest, boolean isWebExceptionRetriable) { if (!isReadRequest && !isWebExceptionRetriable) { logger.warn("shouldRetryOnBackendServiceUnavailableAsync() Not retrying on write with non retriable exception. Retry count = {}", this.serviceUnavailableRetryCount); return Mono.just(ShouldRetryResult.noRetry()); } if (this.serviceUnavailableRetryCount++ > MaxServiceUnavailableRetryCount) { logger.warn("shouldRetryOnBackendServiceUnavailableAsync() Not retrying. Retry count = {}", this.serviceUnavailableRetryCount); return Mono.just(ShouldRetryResult.noRetry()); } if (!this.canUseMultipleWriteLocations && !isReadRequest) { return Mono.just(ShouldRetryResult.noRetry()); } int availablePreferredLocations = this.globalEndpointManager.getPreferredLocationCount(); if (availablePreferredLocations <= 1) { logger.warn("shouldRetryOnServiceUnavailable() Not retrying. No other regions available for the request. AvailablePreferredLocations = {}", availablePreferredLocations); return Mono.just(ShouldRetryResult.noRetry()); } logger.warn("shouldRetryOnServiceUnavailable() Retrying. Received on endpoint {}, IsReadRequest = {}", this.locationEndpoint, isReadRequest); this.retryContext = new RetryContext(this.serviceUnavailableRetryCount, true); return Mono.just(ShouldRetryResult.retryAfter(Duration.ZERO)); } @Override public void onBeforeSendRequest(RxDocumentServiceRequest request) { this.request = request; this.isReadRequest = request.isReadOnlyRequest(); this.canUseMultipleWriteLocations = this.globalEndpointManager.canUseMultipleWriteLocations(request); if (request.requestContext != null) { request.requestContext.cosmosDiagnostics = this.cosmosDiagnostics; } if (request.requestContext != null) { request.requestContext.clearRouteToLocation(); } if (this.retryContext != null) { request.requestContext.routeToLocation(this.retryContext.retryCount, this.retryContext.retryRequestOnPreferredLocations); } this.locationEndpoint = this.globalEndpointManager.resolveServiceEndpoint(request); if (request.requestContext != null) { request.requestContext.routeToLocation(this.locationEndpoint); } } private static class RetryContext { public int retryCount; public boolean retryRequestOnPreferredLocations; public RetryContext(int retryCount, boolean retryRequestOnPreferredLocations) { this.retryCount = retryCount; this.retryRequestOnPreferredLocations = retryRequestOnPreferredLocations; } } }
Rename it to `sendPostRequest`.
public static String getSecondaryServicePrincipalClientID(String envSecondaryServicePrincipal) throws IOException { String content = new String(Files.readAllBytes(new File(envSecondaryServicePrincipal).toPath()), StandardCharsets.UTF_8).trim(); HashMap<String, String> auth = new HashMap<>(); if (content.startsWith("{")) { auth = new JacksonAdapter().deserialize(content, auth.getClass(), SerializerEncoding.JSON); return auth.get("clientId"); } else { Properties authSettings = new Properties(); try (FileInputStream credentialsFileStream = new FileInputStream(new File(envSecondaryServicePrincipal))) { authSettings.load(credentialsFileStream); } return authSettings.getProperty("client"); } } /** * Retrieve the secondary service principal secret. * * @param envSecondaryServicePrincipal an Azure Container Registry * @return a service principal secret * @throws Exception exception */ public static String getSecondaryServicePrincipalSecret(String envSecondaryServicePrincipal) throws IOException { String content = new String(Files.readAllBytes(new File(envSecondaryServicePrincipal).toPath()), StandardCharsets.UTF_8).trim(); HashMap<String, String> auth = new HashMap<>(); if (content.startsWith("{")) { auth = new JacksonAdapter().deserialize(content, auth.getClass(), SerializerEncoding.JSON); return auth.get("clientSecret"); } else { Properties authSettings = new Properties(); try (FileInputStream credentialsFileStream = new FileInputStream(new File(envSecondaryServicePrincipal))) { authSettings.load(credentialsFileStream); } return authSettings.getProperty("key"); } } /** * This method creates a certificate for given password. * * @param certPath location of certificate file * @param pfxPath location of pfx file * @param alias User alias * @param password alias password * @param cnName domain name * @throws Exception exceptions from the creation * @throws IOException IO Exception */ public static void createCertificate(String certPath, String pfxPath, String alias, String password, String cnName) throws IOException { if (new File(pfxPath).exists()) { return; } String validityInDays = "3650"; String keyAlg = "RSA"; String sigAlg = "SHA1withRSA"; String keySize = "2048"; String storeType = "pkcs12"; String command = "keytool"; String jdkPath = System.getProperty("java.home"); if (jdkPath != null && !jdkPath.isEmpty()) { jdkPath = jdkPath.concat("\\bin"); if (new File(jdkPath).isDirectory()) { command = String.format("%s%s%s", jdkPath, File.separator, command); } } else { return; } String[] commandArgs = {command, "-genkey", "-alias", alias, "-keystore", pfxPath, "-storepass", password, "-validity", validityInDays, "-keyalg", keyAlg, "-sigalg", sigAlg, "-keysize", keySize, "-storetype", storeType, "-dname", "CN=" + cnName, "-ext", "EKU=1.3.6.1.5.5.7.3.1"}; Utils.cmdInvocation(commandArgs, true); File pfxFile = new File(pfxPath); if (pfxFile.exists()) { String[] certCommandArgs = {command, "-export", "-alias", alias, "-storetype", storeType, "-keystore", pfxPath, "-storepass", password, "-rfc", "-file", certPath}; Utils.cmdInvocation(certCommandArgs, true); File cerFile = new File(pfxPath); if (!cerFile.exists()) { throw new IOException( "Error occurred while creating certificate" + String.join(" ", certCommandArgs)); } } else { throw new IOException("Error occurred while creating certificates" + String.join(" ", commandArgs)); } } /** * This method is used for invoking native commands. * * @param command :- command to invoke. * @param ignoreErrorStream : Boolean which controls whether to throw exception or not * based on error stream. * @return result :- depending on the method invocation. * @throws Exception exceptions thrown from the execution */ public static String cmdInvocation(String[] command, boolean ignoreErrorStream) throws IOException { String result = ""; String error = ""; Process process = new ProcessBuilder(command).start(); try ( InputStream inputStream = process.getInputStream(); InputStream errorStream = process.getErrorStream(); BufferedReader br = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8)); BufferedReader ebr = new BufferedReader(new InputStreamReader(errorStream, StandardCharsets.UTF_8)); ) { result = br.readLine(); process.waitFor(); error = ebr.readLine(); if (error != null && (!error.equals(""))) { if (!ignoreErrorStream) { throw new IOException(error, null); } } } catch (Exception e) { throw new RuntimeException("Exception occurred while invoking command", e); } return result; } /** * Prints information for passed SQL Server. * * @param sqlServer sqlServer to be printed */ public static void print(SqlServer sqlServer) { StringBuilder builder = new StringBuilder().append("Sql Server: ").append(sqlServer.id()) .append("Name: ").append(sqlServer.name()) .append("\n\tResource group: ").append(sqlServer.resourceGroupName()) .append("\n\tRegion: ").append(sqlServer.region()) .append("\n\tSqlServer version: ").append(sqlServer.version()) .append("\n\tFully qualified name for Sql Server: ").append(sqlServer.fullyQualifiedDomainName()); System.out.println(builder.toString()); } /** * Prints information for the passed SQL Database. * * @param database database to be printed */ public static void print(SqlDatabase database) { StringBuilder builder = new StringBuilder().append("Sql Database: ").append(database.id()) .append("Name: ").append(database.name()) .append("\n\tResource group: ").append(database.resourceGroupName()) .append("\n\tRegion: ").append(database.region()) .append("\n\tSqlServer Name: ").append(database.sqlServerName()) .append("\n\tEdition of SQL database: ").append(database.edition()) .append("\n\tCollation of SQL database: ").append(database.collation()) .append("\n\tCreation date of SQL database: ").append(database.creationDate()) .append("\n\tIs data warehouse: ").append(database.isDataWarehouse()) .append("\n\tRequested service objective of SQL database: ").append(database.requestedServiceObjectiveName()) .append("\n\tName of current service objective of SQL database: ").append(database.currentServiceObjectiveName()) .append("\n\tMax size bytes of SQL database: ").append(database.maxSizeBytes()) .append("\n\tDefault secondary location of SQL database: ").append(database.defaultSecondaryLocation()); System.out.println(builder.toString()); } /** * Prints information for the passed firewall rule. * * @param firewallRule firewall rule to be printed. */ public static void print(SqlFirewallRule firewallRule) { StringBuilder builder = new StringBuilder().append("Sql firewall rule: ").append(firewallRule.id()) .append("Name: ").append(firewallRule.name()) .append("\n\tResource group: ").append(firewallRule.resourceGroupName()) .append("\n\tRegion: ").append(firewallRule.region()) .append("\n\tSqlServer Name: ").append(firewallRule.sqlServerName()) .append("\n\tStart IP Address of the firewall rule: ").append(firewallRule.startIpAddress()) .append("\n\tEnd IP Address of the firewall rule: ").append(firewallRule.endIpAddress()); System.out.println(builder.toString()); } /** * Prints information for the passed virtual network rule. * * @param virtualNetworkRule virtual network rule to be printed. */ public static void print(SqlVirtualNetworkRule virtualNetworkRule) { StringBuilder builder = new StringBuilder().append("SQL virtual network rule: ").append(virtualNetworkRule.id()) .append("Name: ").append(virtualNetworkRule.name()) .append("\n\tResource group: ").append(virtualNetworkRule.resourceGroupName()) .append("\n\tSqlServer Name: ").append(virtualNetworkRule.sqlServerName()) .append("\n\tSubnet ID: ").append(virtualNetworkRule.subnetId()) .append("\n\tState: ").append(virtualNetworkRule.state()); System.out.println(builder.toString()); } /** * Prints information for the passed SQL subscription usage metric. * * @param subscriptionUsageMetric metric to be printed. */ public static void print(SqlSubscriptionUsageMetric subscriptionUsageMetric) { StringBuilder builder = new StringBuilder().append("SQL Subscription Usage Metric: ").append(subscriptionUsageMetric.id()) .append("Name: ").append(subscriptionUsageMetric.name()) .append("\n\tDisplay Name: ").append(subscriptionUsageMetric.displayName()) .append("\n\tCurrent Value: ").append(subscriptionUsageMetric.currentValue()) .append("\n\tLimit: ").append(subscriptionUsageMetric.limit()) .append("\n\tUnit: ").append(subscriptionUsageMetric.unit()) .append("\n\tType: ").append(subscriptionUsageMetric.type()); System.out.println(builder.toString()); } /** * Prints information for the passed SQL database usage metric. * * @param dbUsageMetric metric to be printed. */ public static void print(SqlDatabaseUsageMetric dbUsageMetric) { StringBuilder builder = new StringBuilder().append("SQL Database Usage Metric") .append("Name: ").append(dbUsageMetric.name()) .append("\n\tResource Name: ").append(dbUsageMetric.resourceName()) .append("\n\tDisplay Name: ").append(dbUsageMetric.displayName()) .append("\n\tCurrent Value: ").append(dbUsageMetric.currentValue()) .append("\n\tLimit: ").append(dbUsageMetric.limit()) .append("\n\tUnit: ").append(dbUsageMetric.unit()) .append("\n\tNext Reset Time: ").append(dbUsageMetric.nextResetTime()); System.out.println(builder.toString()); } /** * Prints information for the passed SQL database metric. * * @param dbMetric metric to be printed. */ public static void print(SqlDatabaseMetric dbMetric) { StringBuilder builder = new StringBuilder().append("SQL Database Metric") .append("Name: ").append(dbMetric.name()) .append("\n\tStart Time: ").append(dbMetric.startTime()) .append("\n\tEnd Time: ").append(dbMetric.endTime()) .append("\n\tTime Grain: ").append(dbMetric.timeGrain()) .append("\n\tUnit: ").append(dbMetric.unit()); for (SqlDatabaseMetricValue metricValue : dbMetric.metricValues()) { builder .append("\n\tMetric Value: ") .append("\n\t\tCount: ").append(metricValue.count()) .append("\n\t\tAverage: ").append(metricValue.average()) .append("\n\t\tMaximum: ").append(metricValue.maximum()) .append("\n\t\tMinimum: ").append(metricValue.minimum()) .append("\n\t\tTimestamp: ").append(metricValue.timestamp()) .append("\n\t\tTotal: ").append(metricValue.total()); } System.out.println(builder.toString()); } /** * Prints information for the passed Failover Group. * * @param failoverGroup the SQL Failover Group to be printed. */ public static void print(SqlFailoverGroup failoverGroup) { StringBuilder builder = new StringBuilder().append("SQL Failover Group: ").append(failoverGroup.id()) .append("Name: ").append(failoverGroup.name()) .append("\n\tResource group: ").append(failoverGroup.resourceGroupName()) .append("\n\tSqlServer Name: ").append(failoverGroup.sqlServerName()) .append("\n\tRead-write endpoint policy: ").append(failoverGroup.readWriteEndpointPolicy()) .append("\n\tData loss grace period: ").append(failoverGroup.readWriteEndpointDataLossGracePeriodMinutes()) .append("\n\tRead-only endpoint policy: ").append(failoverGroup.readOnlyEndpointPolicy()) .append("\n\tReplication state: ").append(failoverGroup.replicationState()) .append("\n\tReplication role: ").append(failoverGroup.replicationRole()); builder.append("\n\tPartner Servers: "); for (PartnerInfo item : failoverGroup.partnerServers()) { builder .append("\n\t\tId: ").append(item.id()) .append("\n\t\tLocation: ").append(item.location()) .append("\n\t\tReplication role: ").append(item.replicationRole()); } builder.append("\n\tDatabases: "); for (String databaseId : failoverGroup.databases()) { builder.append("\n\t\tID: ").append(databaseId); } System.out.println(builder.toString()); } /** * Prints information for the passed SQL server key. * * @param serverKey virtual network rule to be printed. */ public static void print(SqlServerKey serverKey) { StringBuilder builder = new StringBuilder().append("SQL server key: ").append(serverKey.id()) .append("Name: ").append(serverKey.name()) .append("\n\tResource group: ").append(serverKey.resourceGroupName()) .append("\n\tSqlServer Name: ").append(serverKey.sqlServerName()) .append("\n\tRegion: ").append(serverKey.region() != null ? serverKey.region().name() : "") .append("\n\tServer Key Type: ").append(serverKey.serverKeyType()) .append("\n\tServer Key URI: ").append(serverKey.uri()) .append("\n\tServer Key Thumbprint: ").append(serverKey.thumbprint()) .append("\n\tServer Key Creation Date: ").append(serverKey.creationDate() != null ? serverKey.creationDate().toString() : ""); System.out.println(builder.toString()); } /** * Prints information of the elastic pool passed in. * * @param elasticPool elastic pool to be printed */ public static void print(SqlElasticPool elasticPool) { StringBuilder builder = new StringBuilder().append("Sql elastic pool: ").append(elasticPool.id()) .append("Name: ").append(elasticPool.name()) .append("\n\tResource group: ").append(elasticPool.resourceGroupName()) .append("\n\tRegion: ").append(elasticPool.region()) .append("\n\tSqlServer Name: ").append(elasticPool.sqlServerName()) .append("\n\tEdition of elastic pool: ").append(elasticPool.edition()) .append("\n\tTotal number of DTUs in the elastic pool: ").append(elasticPool.dtu()) .append("\n\tMaximum DTUs a database can get in elastic pool: ").append(elasticPool.databaseDtuMax()) .append("\n\tMinimum DTUs a database is guaranteed in elastic pool: ").append(elasticPool.databaseDtuMin()) .append("\n\tCreation date for the elastic pool: ").append(elasticPool.creationDate()) .append("\n\tState of the elastic pool: ").append(elasticPool.state()) .append("\n\tStorage capacity in MBs for the elastic pool: ").append(elasticPool.storageCapacity()); System.out.println(builder.toString()); } /** * Prints information of the elastic pool activity. * * @param elasticPoolActivity elastic pool activity to be printed */ public static void print(ElasticPoolActivity elasticPoolActivity) { StringBuilder builder = new StringBuilder().append("Sql elastic pool activity: ").append(elasticPoolActivity.id()) .append("Name: ").append(elasticPoolActivity.name()) .append("\n\tResource group: ").append(elasticPoolActivity.resourceGroupName()) .append("\n\tState: ").append(elasticPoolActivity.state()) .append("\n\tElastic pool name: ").append(elasticPoolActivity.elasticPoolName()) .append("\n\tStart time of activity: ").append(elasticPoolActivity.startTime()) .append("\n\tEnd time of activity: ").append(elasticPoolActivity.endTime()) .append("\n\tError code of activity: ").append(elasticPoolActivity.errorCode()) .append("\n\tError message of activity: ").append(elasticPoolActivity.errorMessage()) .append("\n\tError severity of activity: ").append(elasticPoolActivity.errorSeverity()) .append("\n\tOperation: ").append(elasticPoolActivity.operation()) .append("\n\tCompleted percentage of activity: ").append(elasticPoolActivity.percentComplete()) .append("\n\tRequested DTU max limit in activity: ").append(elasticPoolActivity.requestedDatabaseDtuMax()) .append("\n\tRequested DTU min limit in activity: ").append(elasticPoolActivity.requestedDatabaseDtuMin()) .append("\n\tRequested DTU limit in activity: ").append(elasticPoolActivity.requestedDtu()); System.out.println(builder.toString()); } /** * Prints information of the database activity. * * @param databaseActivity database activity to be printed */ public static void print(ElasticPoolDatabaseActivity databaseActivity) { StringBuilder builder = new StringBuilder().append("Sql elastic pool database activity: ").append(databaseActivity.id()) .append("Name: ").append(databaseActivity.name()) .append("\n\tResource group: ").append(databaseActivity.resourceGroupName()) .append("\n\tSQL Server Name: ").append(databaseActivity.serverName()) .append("\n\tDatabase name name: ").append(databaseActivity.databaseName()) .append("\n\tCurrent elastic pool name of the database: ").append(databaseActivity.currentElasticPoolName()) .append("\n\tState: ").append(databaseActivity.state()) .append("\n\tStart time of activity: ").append(databaseActivity.startTime()) .append("\n\tEnd time of activity: ").append(databaseActivity.endTime()) .append("\n\tCompleted percentage: ").append(databaseActivity.percentComplete()) .append("\n\tError code of activity: ").append(databaseActivity.errorCode()) .append("\n\tError message of activity: ").append(databaseActivity.errorMessage()) .append("\n\tError severity of activity: ").append(databaseActivity.errorSeverity()); System.out.println(builder.toString()); } /** * Print an application gateway. * * @param resource an application gateway */ public static void print(ApplicationGateway resource) { StringBuilder info = new StringBuilder(); info.append("Application gateway: ").append(resource.id()) .append("Name: ").append(resource.name()) .append("\n\tResource group: ").append(resource.resourceGroupName()) .append("\n\tRegion: ").append(resource.region()) .append("\n\tTags: ").append(resource.tags()) .append("\n\tSKU: ").append(resource.sku().toString()) .append("\n\tOperational state: ").append(resource.operationalState()) .append("\n\tInternet-facing? ").append(resource.isPublic()) .append("\n\tInternal? ").append(resource.isPrivate()) .append("\n\tDefault private IP address: ").append(resource.privateIpAddress()) .append("\n\tPrivate IP address allocation method: ").append(resource.privateIpAllocationMethod()) .append("\n\tDisabled SSL protocols: ").append(resource.disabledSslProtocols().toString()); Map<String, ApplicationGatewayIpConfiguration> ipConfigs = resource.ipConfigurations(); info.append("\n\tIP configurations: ").append(ipConfigs.size()); for (ApplicationGatewayIpConfiguration ipConfig : ipConfigs.values()) { info.append("\n\t\tName: ").append(ipConfig.name()) .append("\n\t\t\tNetwork id: ").append(ipConfig.networkId()) .append("\n\t\t\tSubnet name: ").append(ipConfig.subnetName()); } Map<String, ApplicationGatewayFrontend> frontends = resource.frontends(); info.append("\n\tFrontends: ").append(frontends.size()); for (ApplicationGatewayFrontend frontend : frontends.values()) { info.append("\n\t\tName: ").append(frontend.name()) .append("\n\t\t\tPublic? ").append(frontend.isPublic()); if (frontend.isPublic()) { info.append("\n\t\t\tPublic IP address ID: ").append(frontend.publicIpAddressId()); } if (frontend.isPrivate()) { info.append("\n\t\t\tPrivate IP address: ").append(frontend.privateIpAddress()) .append("\n\t\t\tPrivate IP allocation method: ").append(frontend.privateIpAllocationMethod()) .append("\n\t\t\tSubnet name: ").append(frontend.subnetName()) .append("\n\t\t\tVirtual network ID: ").append(frontend.networkId()); } } Map<String, ApplicationGatewayBackend> backends = resource.backends(); info.append("\n\tBackends: ").append(backends.size()); for (ApplicationGatewayBackend backend : backends.values()) { info.append("\n\t\tName: ").append(backend.name()) .append("\n\t\t\tAssociated NIC IP configuration IDs: ").append(backend.backendNicIPConfigurationNames().keySet()); Collection<ApplicationGatewayBackendAddress> addresses = backend.addresses(); info.append("\n\t\t\tAddresses: ").append(addresses.size()); for (ApplicationGatewayBackendAddress address : addresses) { info.append("\n\t\t\t\tFQDN: ").append(address.fqdn()) .append("\n\t\t\t\tIP: ").append(address.ipAddress()); } } Map<String, ApplicationGatewayBackendHttpConfiguration> httpConfigs = resource.backendHttpConfigurations(); info.append("\n\tHTTP Configurations: ").append(httpConfigs.size()); for (ApplicationGatewayBackendHttpConfiguration httpConfig : httpConfigs.values()) { info.append("\n\t\tName: ").append(httpConfig.name()) .append("\n\t\t\tCookie based affinity: ").append(httpConfig.cookieBasedAffinity()) .append("\n\t\t\tPort: ").append(httpConfig.port()) .append("\n\t\t\tRequest timeout in seconds: ").append(httpConfig.requestTimeout()) .append("\n\t\t\tProtocol: ").append(httpConfig.protocol()) .append("\n\t\tHost header: ").append(httpConfig.hostHeader()) .append("\n\t\tHost header comes from backend? ").append(httpConfig.isHostHeaderFromBackend()) .append("\n\t\tConnection draining timeout in seconds: ").append(httpConfig.connectionDrainingTimeoutInSeconds()) .append("\n\t\tAffinity cookie name: ").append(httpConfig.affinityCookieName()) .append("\n\t\tPath: ").append(httpConfig.path()); ApplicationGatewayProbe probe = httpConfig.probe(); if (probe != null) { info.append("\n\t\tProbe: " + probe.name()); } info.append("\n\t\tIs probe enabled? ").append(httpConfig.isProbeEnabled()); } Map<String, ApplicationGatewaySslCertificate> sslCerts = resource.sslCertificates(); info.append("\n\tSSL certificates: ").append(sslCerts.size()); for (ApplicationGatewaySslCertificate cert : sslCerts.values()) { info.append("\n\t\tName: ").append(cert.name()) .append("\n\t\t\tCert data: ").append(cert.publicData()); } Map<String, ApplicationGatewayRedirectConfiguration> redirects = resource.redirectConfigurations(); info.append("\n\tRedirect configurations: ").append(redirects.size()); for (ApplicationGatewayRedirectConfiguration redirect : redirects.values()) { info.append("\n\t\tName: ").append(redirect.name()) .append("\n\t\tTarget URL: ").append(redirect.type()) .append("\n\t\tTarget URL: ").append(redirect.targetUrl()) .append("\n\t\tTarget listener: ").append(redirect.targetListener() != null ? redirect.targetListener().name() : null) .append("\n\t\tIs path included? ").append(redirect.isPathIncluded()) .append("\n\t\tIs query string included? ").append(redirect.isQueryStringIncluded()) .append("\n\t\tReferencing request routing rules: ").append(redirect.requestRoutingRules().values()); } Map<String, ApplicationGatewayListener> listeners = resource.listeners(); info.append("\n\tHTTP listeners: ").append(listeners.size()); for (ApplicationGatewayListener listener : listeners.values()) { info.append("\n\t\tName: ").append(listener.name()) .append("\n\t\t\tHost name: ").append(listener.hostname()) .append("\n\t\t\tServer name indication required? ").append(listener.requiresServerNameIndication()) .append("\n\t\t\tAssociated frontend name: ").append(listener.frontend().name()) .append("\n\t\t\tFrontend port name: ").append(listener.frontendPortName()) .append("\n\t\t\tFrontend port number: ").append(listener.frontendPortNumber()) .append("\n\t\t\tProtocol: ").append(listener.protocol().toString()); if (listener.sslCertificate() != null) { info.append("\n\t\t\tAssociated SSL certificate: ").append(listener.sslCertificate().name()); } } Map<String, ApplicationGatewayProbe> probes = resource.probes(); info.append("\n\tProbes: ").append(probes.size()); for (ApplicationGatewayProbe probe : probes.values()) { info.append("\n\t\tName: ").append(probe.name()) .append("\n\t\tProtocol:").append(probe.protocol().toString()) .append("\n\t\tInterval in seconds: ").append(probe.timeBetweenProbesInSeconds()) .append("\n\t\tRetries: ").append(probe.retriesBeforeUnhealthy()) .append("\n\t\tTimeout: ").append(probe.timeoutInSeconds()) .append("\n\t\tHost: ").append(probe.host()) .append("\n\t\tHealthy HTTP response status code ranges: ").append(probe.healthyHttpResponseStatusCodeRanges()) .append("\n\t\tHealthy HTTP response body contents: ").append(probe.healthyHttpResponseBodyContents()); } Map<String, ApplicationGatewayRequestRoutingRule> rules = resource.requestRoutingRules(); info.append("\n\tRequest routing rules: ").append(rules.size()); for (ApplicationGatewayRequestRoutingRule rule : rules.values()) { info.append("\n\t\tName: ").append(rule.name()) .append("\n\t\tType: ").append(rule.ruleType()) .append("\n\t\tPublic IP address ID: ").append(rule.publicIpAddressId()) .append("\n\t\tHost name: ").append(rule.hostname()) .append("\n\t\tServer name indication required? ").append(rule.requiresServerNameIndication()) .append("\n\t\tFrontend port: ").append(rule.frontendPort()) .append("\n\t\tFrontend protocol: ").append(rule.frontendProtocol().toString()) .append("\n\t\tBackend port: ").append(rule.backendPort()) .append("\n\t\tCookie based affinity enabled? ").append(rule.cookieBasedAffinity()) .append("\n\t\tRedirect configuration: ").append(rule.redirectConfiguration() != null ? rule.redirectConfiguration().name() : "(none)"); Collection<ApplicationGatewayBackendAddress> addresses = rule.backendAddresses(); info.append("\n\t\t\tBackend addresses: ").append(addresses.size()); for (ApplicationGatewayBackendAddress address : addresses) { info.append("\n\t\t\t\t") .append(address.fqdn()) .append(" [").append(address.ipAddress()).append("]"); } info.append("\n\t\t\tSSL certificate name: "); ApplicationGatewaySslCertificate cert = rule.sslCertificate(); if (cert == null) { info.append("(None)"); } else { info.append(cert.name()); } info.append("\n\t\t\tAssociated backend address pool: "); ApplicationGatewayBackend backend = rule.backend(); if (backend == null) { info.append("(None)"); } else { info.append(backend.name()); } info.append("\n\t\t\tAssociated backend HTTP settings configuration: "); ApplicationGatewayBackendHttpConfiguration config = rule.backendHttpConfiguration(); if (config == null) { info.append("(None)"); } else { info.append(config.name()); } info.append("\n\t\t\tAssociated frontend listener: "); ApplicationGatewayListener listener = rule.listener(); if (listener == null) { info.append("(None)"); } else { info.append(config.name()); } } System.out.println(info.toString()); } /** * Prints information of a virtual machine custom image. * * @param image the image */ public static void print(VirtualMachineCustomImage image) { StringBuilder builder = new StringBuilder().append("Virtual machine custom image: ").append(image.id()) .append("Name: ").append(image.name()) .append("\n\tResource group: ").append(image.resourceGroupName()) .append("\n\tCreated from virtual machine: ").append(image.sourceVirtualMachineId()); builder.append("\n\tOS disk image: ") .append("\n\t\tOperating system: ").append(image.osDiskImage().osType()) .append("\n\t\tOperating system state: ").append(image.osDiskImage().osState()) .append("\n\t\tCaching: ").append(image.osDiskImage().caching()) .append("\n\t\tSize (GB): ").append(image.osDiskImage().diskSizeGB()); if (image.isCreatedFromVirtualMachine()) { builder.append("\n\t\tSource virtual machine: ").append(image.sourceVirtualMachineId()); } if (image.osDiskImage().managedDisk() != null) { builder.append("\n\t\tSource managed disk: ").append(image.osDiskImage().managedDisk().id()); } if (image.osDiskImage().snapshot() != null) { builder.append("\n\t\tSource snapshot: ").append(image.osDiskImage().snapshot().id()); } if (image.osDiskImage().blobUri() != null) { builder.append("\n\t\tSource un-managed vhd: ").append(image.osDiskImage().blobUri()); } if (image.dataDiskImages() != null) { for (ImageDataDisk diskImage : image.dataDiskImages().values()) { builder.append("\n\tDisk Image (Lun) .append("\n\t\tCaching: ").append(diskImage.caching()) .append("\n\t\tSize (GB): ").append(diskImage.diskSizeGB()); if (image.isCreatedFromVirtualMachine()) { builder.append("\n\t\tSource virtual machine: ").append(image.sourceVirtualMachineId()); } if (diskImage.managedDisk() != null) { builder.append("\n\t\tSource managed disk: ").append(diskImage.managedDisk().id()); } if (diskImage.snapshot() != null) { builder.append("\n\t\tSource snapshot: ").append(diskImage.snapshot().id()); } if (diskImage.blobUri() != null) { builder.append("\n\t\tSource un-managed vhd: ").append(diskImage.blobUri()); } } } System.out.println(builder.toString()); } /** * Uploads a file to an Azure app service. * * @param profile the publishing profile for the app service. * @param fileName the name of the file on server * @param file the local file */ public static void uploadFileViaFtp(PublishingProfile profile, String fileName, InputStream file) { FTPClient ftpClient = new FTPClient(); String[] ftpUrlSegments = profile.ftpUrl().split("/", 2); String server = ftpUrlSegments[0]; String path = "./site/wwwroot/webapps"; if (fileName.contains("/")) { int lastslash = fileName.lastIndexOf('/'); path = path + "/" + fileName.substring(0, lastslash); fileName = fileName.substring(lastslash + 1); } try { ftpClient.connect(server); ftpClient.enterLocalPassiveMode(); ftpClient.login(profile.ftpUsername(), profile.ftpPassword()); ftpClient.setFileType(FTP.BINARY_FILE_TYPE); for (String segment : path.split("/")) { if (!ftpClient.changeWorkingDirectory(segment)) { ftpClient.makeDirectory(segment); ftpClient.changeWorkingDirectory(segment); } } ftpClient.storeFile(fileName, file); ftpClient.disconnect(); } catch (IOException e) { e.printStackTrace(); } } private Utils() { } /** * Print service bus namespace info. * * @param serviceBusNamespace a service bus namespace */ public static void print(ServiceBusNamespace serviceBusNamespace) { StringBuilder builder = new StringBuilder() .append("Service bus Namespace: ").append(serviceBusNamespace.id()) .append("\n\tName: ").append(serviceBusNamespace.name()) .append("\n\tRegion: ").append(serviceBusNamespace.regionName()) .append("\n\tResourceGroupName: ").append(serviceBusNamespace.resourceGroupName()) .append("\n\tCreatedAt: ").append(serviceBusNamespace.createdAt()) .append("\n\tUpdatedAt: ").append(serviceBusNamespace.updatedAt()) .append("\n\tDnsLabel: ").append(serviceBusNamespace.dnsLabel()) .append("\n\tFQDN: ").append(serviceBusNamespace.fqdn()) .append("\n\tSku: ") .append("\n\t\tCapacity: ").append(serviceBusNamespace.sku().capacity()) .append("\n\t\tSkuName: ").append(serviceBusNamespace.sku().name()) .append("\n\t\tTier: ").append(serviceBusNamespace.sku().tier()); System.out.println(builder.toString()); } /** * Print service bus queue info. * * @param queue a service bus queue */ public static void print(Queue queue) { StringBuilder builder = new StringBuilder() .append("Service bus Queue: ").append(queue.id()) .append("\n\tName: ").append(queue.name()) .append("\n\tResourceGroupName: ").append(queue.resourceGroupName()) .append("\n\tCreatedAt: ").append(queue.createdAt()) .append("\n\tUpdatedAt: ").append(queue.updatedAt()) .append("\n\tAccessedAt: ").append(queue.accessedAt()) .append("\n\tActiveMessageCount: ").append(queue.activeMessageCount()) .append("\n\tCurrentSizeInBytes: ").append(queue.currentSizeInBytes()) .append("\n\tDeadLetterMessageCount: ").append(queue.deadLetterMessageCount()) .append("\n\tDefaultMessageTtlDuration: ").append(queue.defaultMessageTtlDuration()) .append("\n\tDuplicateMessageDetectionHistoryDuration: ").append(queue.duplicateMessageDetectionHistoryDuration()) .append("\n\tIsBatchedOperationsEnabled: ").append(queue.isBatchedOperationsEnabled()) .append("\n\tIsDeadLetteringEnabledForExpiredMessages: ").append(queue.isDeadLetteringEnabledForExpiredMessages()) .append("\n\tIsDuplicateDetectionEnabled: ").append(queue.isDuplicateDetectionEnabled()) .append("\n\tIsExpressEnabled: ").append(queue.isExpressEnabled()) .append("\n\tIsPartitioningEnabled: ").append(queue.isPartitioningEnabled()) .append("\n\tIsSessionEnabled: ").append(queue.isSessionEnabled()) .append("\n\tDeleteOnIdleDurationInMinutes: ").append(queue.deleteOnIdleDurationInMinutes()) .append("\n\tMaxDeliveryCountBeforeDeadLetteringMessage: ").append(queue.maxDeliveryCountBeforeDeadLetteringMessage()) .append("\n\tMaxSizeInMB: ").append(queue.maxSizeInMB()) .append("\n\tMessageCount: ").append(queue.messageCount()) .append("\n\tScheduledMessageCount: ").append(queue.scheduledMessageCount()) .append("\n\tStatus: ").append(queue.status()) .append("\n\tTransferMessageCount: ").append(queue.transferMessageCount()) .append("\n\tLockDurationInSeconds: ").append(queue.lockDurationInSeconds()) .append("\n\tTransferDeadLetterMessageCount: ").append(queue.transferDeadLetterMessageCount()); System.out.println(builder.toString()); } /** * Print service bus queue authorization keys info. * * @param queueAuthorizationRule a service bus queue authorization keys */ public static void print(QueueAuthorizationRule queueAuthorizationRule) { StringBuilder builder = new StringBuilder() .append("Service bus queue authorization rule: ").append(queueAuthorizationRule.id()) .append("\n\tName: ").append(queueAuthorizationRule.name()) .append("\n\tResourceGroupName: ").append(queueAuthorizationRule.resourceGroupName()) .append("\n\tNamespace Name: ").append(queueAuthorizationRule.namespaceName()) .append("\n\tQueue Name: ").append(queueAuthorizationRule.queueName()); List<com.azure.resourcemanager.servicebus.models.AccessRights> rights = queueAuthorizationRule.rights(); builder.append("\n\tNumber of access rights in queue: ").append(rights.size()); for (com.azure.resourcemanager.servicebus.models.AccessRights right : rights) { builder.append("\n\t\tAccessRight: ") .append("\n\t\t\tName :").append(right.name()); } System.out.println(builder.toString()); } /** * Print service bus namespace authorization keys info. * * @param keys a service bus namespace authorization keys */ public static void print(AuthorizationKeys keys) { StringBuilder builder = new StringBuilder() .append("Authorization keys: ") .append("\n\tPrimaryKey: ").append(keys.primaryKey()) .append("\n\tPrimaryConnectionString: ").append(keys.primaryConnectionString()) .append("\n\tSecondaryKey: ").append(keys.secondaryKey()) .append("\n\tSecondaryConnectionString: ").append(keys.secondaryConnectionString()); System.out.println(builder.toString()); } /** * Print service bus namespace authorization rule info. * * @param namespaceAuthorizationRule a service bus namespace authorization rule */ public static void print(NamespaceAuthorizationRule namespaceAuthorizationRule) { StringBuilder builder = new StringBuilder() .append("Service bus queue authorization rule: ").append(namespaceAuthorizationRule.id()) .append("\n\tName: ").append(namespaceAuthorizationRule.name()) .append("\n\tResourceGroupName: ").append(namespaceAuthorizationRule.resourceGroupName()) .append("\n\tNamespace Name: ").append(namespaceAuthorizationRule.namespaceName()); List<com.azure.resourcemanager.servicebus.models.AccessRights> rights = namespaceAuthorizationRule.rights(); builder.append("\n\tNumber of access rights in queue: ").append(rights.size()); for (com.azure.resourcemanager.servicebus.models.AccessRights right : rights) { builder.append("\n\t\tAccessRight: ") .append("\n\t\t\tName :").append(right.name()); } System.out.println(builder.toString()); } /** * Print service bus topic info. * * @param topic a service bus topic */ public static void print(Topic topic) { StringBuilder builder = new StringBuilder() .append("Service bus topic: ").append(topic.id()) .append("\n\tName: ").append(topic.name()) .append("\n\tResourceGroupName: ").append(topic.resourceGroupName()) .append("\n\tCreatedAt: ").append(topic.createdAt()) .append("\n\tUpdatedAt: ").append(topic.updatedAt()) .append("\n\tAccessedAt: ").append(topic.accessedAt()) .append("\n\tActiveMessageCount: ").append(topic.activeMessageCount()) .append("\n\tCurrentSizeInBytes: ").append(topic.currentSizeInBytes()) .append("\n\tDeadLetterMessageCount: ").append(topic.deadLetterMessageCount()) .append("\n\tDefaultMessageTtlDuration: ").append(topic.defaultMessageTtlDuration()) .append("\n\tDuplicateMessageDetectionHistoryDuration: ").append(topic.duplicateMessageDetectionHistoryDuration()) .append("\n\tIsBatchedOperationsEnabled: ").append(topic.isBatchedOperationsEnabled()) .append("\n\tIsDuplicateDetectionEnabled: ").append(topic.isDuplicateDetectionEnabled()) .append("\n\tIsExpressEnabled: ").append(topic.isExpressEnabled()) .append("\n\tIsPartitioningEnabled: ").append(topic.isPartitioningEnabled()) .append("\n\tDeleteOnIdleDurationInMinutes: ").append(topic.deleteOnIdleDurationInMinutes()) .append("\n\tMaxSizeInMB: ").append(topic.maxSizeInMB()) .append("\n\tScheduledMessageCount: ").append(topic.scheduledMessageCount()) .append("\n\tStatus: ").append(topic.status()) .append("\n\tTransferMessageCount: ").append(topic.transferMessageCount()) .append("\n\tSubscriptionCount: ").append(topic.subscriptionCount()) .append("\n\tTransferDeadLetterMessageCount: ").append(topic.transferDeadLetterMessageCount()); System.out.println(builder.toString()); } /** * Print service bus subscription info. * * @param serviceBusSubscription a service bus subscription */ public static void print(ServiceBusSubscription serviceBusSubscription) { StringBuilder builder = new StringBuilder() .append("Service bus subscription: ").append(serviceBusSubscription.id()) .append("\n\tName: ").append(serviceBusSubscription.name()) .append("\n\tResourceGroupName: ").append(serviceBusSubscription.resourceGroupName()) .append("\n\tCreatedAt: ").append(serviceBusSubscription.createdAt()) .append("\n\tUpdatedAt: ").append(serviceBusSubscription.updatedAt()) .append("\n\tAccessedAt: ").append(serviceBusSubscription.accessedAt()) .append("\n\tActiveMessageCount: ").append(serviceBusSubscription.activeMessageCount()) .append("\n\tDeadLetterMessageCount: ").append(serviceBusSubscription.deadLetterMessageCount()) .append("\n\tDefaultMessageTtlDuration: ").append(serviceBusSubscription.defaultMessageTtlDuration()) .append("\n\tIsBatchedOperationsEnabled: ").append(serviceBusSubscription.isBatchedOperationsEnabled()) .append("\n\tDeleteOnIdleDurationInMinutes: ").append(serviceBusSubscription.deleteOnIdleDurationInMinutes()) .append("\n\tScheduledMessageCount: ").append(serviceBusSubscription.scheduledMessageCount()) .append("\n\tStatus: ").append(serviceBusSubscription.status()) .append("\n\tTransferMessageCount: ").append(serviceBusSubscription.transferMessageCount()) .append("\n\tIsDeadLetteringEnabledForExpiredMessages: ").append(serviceBusSubscription.isDeadLetteringEnabledForExpiredMessages()) .append("\n\tIsSessionEnabled: ").append(serviceBusSubscription.isSessionEnabled()) .append("\n\tLockDurationInSeconds: ").append(serviceBusSubscription.lockDurationInSeconds()) .append("\n\tMaxDeliveryCountBeforeDeadLetteringMessage: ").append(serviceBusSubscription.maxDeliveryCountBeforeDeadLetteringMessage()) .append("\n\tIsDeadLetteringEnabledForFilterEvaluationFailedMessages: ").append(serviceBusSubscription.isDeadLetteringEnabledForFilterEvaluationFailedMessages()) .append("\n\tTransferMessageCount: ").append(serviceBusSubscription.transferMessageCount()) .append("\n\tTransferDeadLetterMessageCount: ").append(serviceBusSubscription.transferDeadLetterMessageCount()); System.out.println(builder.toString()); } /** * Print topic Authorization Rule info. * * @param topicAuthorizationRule a topic Authorization Rule */ public static void print(TopicAuthorizationRule topicAuthorizationRule) { StringBuilder builder = new StringBuilder() .append("Service bus topic authorization rule: ").append(topicAuthorizationRule.id()) .append("\n\tName: ").append(topicAuthorizationRule.name()) .append("\n\tResourceGroupName: ").append(topicAuthorizationRule.resourceGroupName()) .append("\n\tNamespace Name: ").append(topicAuthorizationRule.namespaceName()) .append("\n\tTopic Name: ").append(topicAuthorizationRule.topicName()); List<com.azure.resourcemanager.servicebus.models.AccessRights> rights = topicAuthorizationRule.rights(); builder.append("\n\tNumber of access rights in queue: ").append(rights.size()); for (com.azure.resourcemanager.servicebus.models.AccessRights right : rights) { builder.append("\n\t\tAccessRight: ") .append("\n\t\t\tName :").append(right.name()); } System.out.println(builder.toString()); } /** * Print CosmosDB info. * * @param cosmosDBAccount a CosmosDB */ public static void print(CosmosDBAccount cosmosDBAccount) { StringBuilder builder = new StringBuilder() .append("CosmosDB: ").append(cosmosDBAccount.id()) .append("\n\tName: ").append(cosmosDBAccount.name()) .append("\n\tResourceGroupName: ").append(cosmosDBAccount.resourceGroupName()) .append("\n\tKind: ").append(cosmosDBAccount.kind().toString()) .append("\n\tDefault consistency level: ").append(cosmosDBAccount.consistencyPolicy().defaultConsistencyLevel()) .append("\n\tIP range filter: ").append(cosmosDBAccount.ipRangeFilter()); DatabaseAccountListKeysResult keys = cosmosDBAccount.listKeys(); DatabaseAccountListReadOnlyKeysResult readOnlyKeys = cosmosDBAccount.listReadOnlyKeys(); builder .append("\n\tPrimary Master Key: ").append(keys.primaryMasterKey()) .append("\n\tSecondary Master Key: ").append(keys.secondaryMasterKey()) .append("\n\tPrimary Read-Only Key: ").append(readOnlyKeys.primaryReadonlyMasterKey()) .append("\n\tSecondary Read-Only Key: ").append(readOnlyKeys.secondaryReadonlyMasterKey()); for (Location writeReplica : cosmosDBAccount.writableReplications()) { builder.append("\n\t\tWrite replication: ") .append("\n\t\t\tName :").append(writeReplica.locationName()); } builder.append("\n\tNumber of read replications: ").append(cosmosDBAccount.readableReplications().size()); for (Location readReplica : cosmosDBAccount.readableReplications()) { builder.append("\n\t\tRead replication: ") .append("\n\t\t\tName :").append(readReplica.locationName()); } } /** * Print Active Directory User info. * * @param user active directory user */ public static void print(ActiveDirectoryUser user) { StringBuilder builder = new StringBuilder() .append("Active Directory User: ").append(user.id()) .append("\n\tName: ").append(user.name()) .append("\n\tMail: ").append(user.mail()) .append("\n\tMail Nickname: ").append(user.mailNickname()) .append("\n\tSign In Name: ").append(user.signInName()) .append("\n\tUser Principal Name: ").append(user.userPrincipalName()); System.out.println(builder.toString()); } /** * Print Active Directory User info. * * @param role role definition */ public static void print(RoleDefinition role) { StringBuilder builder = new StringBuilder() .append("Role Definition: ").append(role.id()) .append("\n\tName: ").append(role.name()) .append("\n\tRole Name: ").append(role.roleName()) .append("\n\tType: ").append(role.type()) .append("\n\tDescription: ").append(role.description()) .append("\n\tType: ").append(role.type()); Set<Permission> permissions = role.permissions(); builder.append("\n\tPermissions: ").append(permissions.size()); for (Permission permission : permissions) { builder.append("\n\t\tPermission Actions: " + permission.actions().size()); for (String action : permission.actions()) { builder.append("\n\t\t\tName :").append(action); } builder.append("\n\t\tPermission Not Actions: " + permission.notActions().size()); for (String notAction : permission.notActions()) { builder.append("\n\t\t\tName :").append(notAction); } } Set<String> assignableScopes = role.assignableScopes(); builder.append("\n\tAssignable scopes: ").append(assignableScopes.size()); for (String scope : assignableScopes) { builder.append("\n\t\tAssignable Scope: ") .append("\n\t\t\tName :").append(scope); } System.out.println(builder.toString()); } /** * Print Role Assignment info. * * @param roleAssignment role assignment */ public static void print(RoleAssignment roleAssignment) { StringBuilder builder = new StringBuilder() .append("Role Assignment: ") .append("\n\tScope: ").append(roleAssignment.scope()) .append("\n\tPrincipal Id: ").append(roleAssignment.principalId()) .append("\n\tRole Definition Id: ").append(roleAssignment.roleDefinitionId()); System.out.println(builder.toString()); } /** * Print Active Directory Group info. * * @param group active directory group */ public static void print(ActiveDirectoryGroup group) { StringBuilder builder = new StringBuilder() .append("Active Directory Group: ").append(group.id()) .append("\n\tName: ").append(group.name()) .append("\n\tMail: ").append(group.mail()) .append("\n\tSecurity Enabled: ").append(group.securityEnabled()) .append("\n\tGroup members:"); for (ActiveDirectoryObject object : group.listMembers()) { builder.append("\n\t\tType: ").append(object.getClass().getSimpleName()) .append("\tName: ").append(object.name()); } System.out.println(builder.toString()); } /** * Print Active Directory Application info. * * @param application active directory application */ public static void print(ActiveDirectoryApplication application) { StringBuilder builder = new StringBuilder() .append("Active Directory Application: ").append(application.id()) .append("\n\tName: ").append(application.name()) .append("\n\tSign on URL: ").append(application.signOnUrl()) .append("\n\tReply URLs:"); for (String replyUrl : application.replyUrls()) { builder.append("\n\t\t").append(replyUrl); } System.out.println(builder.toString()); } /** * Print Service Principal info. * * @param servicePrincipal service principal */ public static void print(ServicePrincipal servicePrincipal) { StringBuilder builder = new StringBuilder() .append("Service Principal: ").append(servicePrincipal.id()) .append("\n\tName: ").append(servicePrincipal.name()) .append("\n\tApplication Id: ").append(servicePrincipal.applicationId()); List<String> names = servicePrincipal.servicePrincipalNames(); builder.append("\n\tNames: ").append(names.size()); for (String name : names) { builder.append("\n\t\tName: ").append(name); } System.out.println(builder.toString()); } /** * Print Network Watcher info. * * @param nw network watcher */ public static void print(NetworkWatcher nw) { StringBuilder builder = new StringBuilder() .append("Network Watcher: ").append(nw.id()) .append("\n\tName: ").append(nw.name()) .append("\n\tResource group name: ").append(nw.resourceGroupName()) .append("\n\tRegion name: ").append(nw.regionName()); System.out.println(builder.toString()); } /** * Print packet capture info. * * @param resource packet capture */ public static void print(PacketCapture resource) { StringBuilder sb = new StringBuilder().append("Packet Capture: ").append(resource.id()) .append("\n\tName: ").append(resource.name()) .append("\n\tTarget id: ").append(resource.targetId()) .append("\n\tTime limit in seconds: ").append(resource.timeLimitInSeconds()) .append("\n\tBytes to capture per packet: ").append(resource.bytesToCapturePerPacket()) .append("\n\tProvisioning state: ").append(resource.provisioningState()) .append("\n\tStorage location:") .append("\n\tStorage account id: ").append(resource.storageLocation().storageId()) .append("\n\tStorage account path: ").append(resource.storageLocation().storagePath()) .append("\n\tFile path: ").append(resource.storageLocation().filePath()) .append("\n\t Packet capture filters: ").append(resource.filters().size()); for (PacketCaptureFilter filter : resource.filters()) { sb.append("\n\t\tProtocol: ").append(filter.protocol()); sb.append("\n\t\tLocal IP address: ").append(filter.localIpAddress()); sb.append("\n\t\tRemote IP address: ").append(filter.remoteIpAddress()); sb.append("\n\t\tLocal port: ").append(filter.localPort()); sb.append("\n\t\tRemote port: ").append(filter.remotePort()); } System.out.println(sb.toString()); } /** * Print verification IP flow info. * * @param resource IP flow verification info */ public static void print(VerificationIPFlow resource) { System.out.println(new StringBuilder("IP flow verification: ") .append("\n\tAccess: ").append(resource.access()) .append("\n\tRule name: ").append(resource.ruleName()) .toString()); } /** * Print topology info. * * @param resource topology */ public static void print(Topology resource) { StringBuilder sb = new StringBuilder().append("Topology: ").append(resource.id()) .append("\n\tTopology parameters: ") .append("\n\t\tResource group: ").append(resource.topologyParameters().targetResourceGroupName()) .append("\n\t\tVirtual network: ").append(resource.topologyParameters().targetVirtualNetwork() == null ? "" : resource.topologyParameters().targetVirtualNetwork().id()) .append("\n\t\tSubnet id: ").append(resource.topologyParameters().targetSubnet() == null ? "" : resource.topologyParameters().targetSubnet().id()) .append("\n\tCreated time: ").append(resource.createdTime()) .append("\n\tLast modified time: ").append(resource.lastModifiedTime()); for (TopologyResource tr : resource.resources().values()) { sb.append("\n\tTopology resource: ").append(tr.id()) .append("\n\t\tName: ").append(tr.name()) .append("\n\t\tLocation: ").append(tr.location()) .append("\n\t\tAssociations:"); for (TopologyAssociation association : tr.associations()) { sb.append("\n\t\t\tName:").append(association.name()) .append("\n\t\t\tResource id:").append(association.resourceId()) .append("\n\t\t\tAssociation type:").append(association.associationType()); } } System.out.println(sb.toString()); } /** * Print flow log settings info. * * @param resource flow log settings */ public static void print(FlowLogSettings resource) { System.out.println(new StringBuilder().append("Flow log settings: ") .append("Target resource id: ").append(resource.targetResourceId()) .append("\n\tFlow log enabled: ").append(resource.enabled()) .append("\n\tStorage account id: ").append(resource.storageId()) .append("\n\tRetention policy enabled: ").append(resource.isRetentionEnabled()) .append("\n\tRetention policy days: ").append(resource.retentionDays()) .toString()); } /** * Print availability set info. * * @param resource an availability set */ public static void print(SecurityGroupView resource) { StringBuilder sb = new StringBuilder().append("Security group view: ") .append("\n\tVirtual machine id: ").append(resource.vmId()); for (SecurityGroupNetworkInterface sgni : resource.networkInterfaces().values()) { sb.append("\n\tSecurity group network interface:").append(sgni.id()) .append("\n\t\tSecurity group network interface:") .append("\n\t\tEffective security rules:"); for (EffectiveNetworkSecurityRule rule : sgni.securityRuleAssociations().effectiveSecurityRules()) { sb.append("\n\t\t\tName: ").append(rule.name()) .append("\n\t\t\tDirection: ").append(rule.direction()) .append("\n\t\t\tAccess: ").append(rule.access()) .append("\n\t\t\tPriority: ").append(rule.priority()) .append("\n\t\t\tSource address prefix: ").append(rule.sourceAddressPrefix()) .append("\n\t\t\tSource port range: ").append(rule.sourcePortRange()) .append("\n\t\t\tDestination address prefix: ").append(rule.destinationAddressPrefix()) .append("\n\t\t\tDestination port range: ").append(rule.destinationPortRange()) .append("\n\t\t\tProtocol: ").append(rule.protocol()); } sb.append("\n\t\tSubnet:").append(sgni.securityRuleAssociations().subnetAssociation().id()); printSecurityRule(sb, sgni.securityRuleAssociations().subnetAssociation().securityRules()); if (sgni.securityRuleAssociations().networkInterfaceAssociation() != null) { sb.append("\n\t\tNetwork interface:").append(sgni.securityRuleAssociations().networkInterfaceAssociation().id()); printSecurityRule(sb, sgni.securityRuleAssociations().networkInterfaceAssociation().securityRules()); } sb.append("\n\t\tDefault security rules:"); printSecurityRule(sb, sgni.securityRuleAssociations().defaultSecurityRules()); } System.out.println(sb.toString()); } private static void printSecurityRule(StringBuilder sb, List<SecurityRuleInner> rules) { for (SecurityRuleInner rule : rules) { sb.append("\n\t\t\tName: ").append(rule.name()) .append("\n\t\t\tDirection: ").append(rule.direction()) .append("\n\t\t\tAccess: ").append(rule.access()) .append("\n\t\t\tPriority: ").append(rule.priority()) .append("\n\t\t\tSource address prefix: ").append(rule.sourceAddressPrefix()) .append("\n\t\t\tSource port range: ").append(rule.sourcePortRange()) .append("\n\t\t\tDestination address prefix: ").append(rule.destinationAddressPrefix()) .append("\n\t\t\tDestination port range: ").append(rule.destinationPortRange()) .append("\n\t\t\tProtocol: ").append(rule.protocol()) .append("\n\t\t\tDescription: ").append(rule.description()) .append("\n\t\t\tProvisioning state: ").append(rule.provisioningState()); } } /** * Print next hop info. * * @param resource an availability set */ public static void print(NextHop resource) { System.out.println(new StringBuilder("Next hop: ") .append("Next hop type: ").append(resource.nextHopType()) .append("\n\tNext hop ip address: ").append(resource.nextHopIpAddress()) .append("\n\tRoute table id: ").append(resource.routeTableId()) .toString()); } /** * Print container group info. * * @param resource a container group */ public static void print(ContainerGroup resource) { StringBuilder info = new StringBuilder().append("Container Group: ").append(resource.id()) .append("Name: ").append(resource.name()) .append("\n\tResource group: ").append(resource.resourceGroupName()) .append("\n\tRegion: ").append(resource.region()) .append("\n\tTags: ").append(resource.tags()) .append("\n\tOS type: ").append(resource.osType()); if (resource.ipAddress() != null) { info.append("\n\tPublic IP address: ").append(resource.ipAddress()); } if (resource.externalTcpPorts() != null) { info.append("\n\tExternal TCP ports:"); for (int port : resource.externalTcpPorts()) { info.append(" ").append(port); } } if (resource.externalUdpPorts() != null) { info.append("\n\tExternal UDP ports:"); for (int port : resource.externalUdpPorts()) { info.append(" ").append(port); } } if (resource.imageRegistryServers() != null) { info.append("\n\tPrivate Docker image registries:"); for (String server : resource.imageRegistryServers()) { info.append(" ").append(server); } } if (resource.volumes() != null) { info.append("\n\tVolume mapping: "); for (Map.Entry<String, Volume> entry : resource.volumes().entrySet()) { info.append("\n\t\tName: ").append(entry.getKey()).append(" -> ") .append(entry.getValue().azureFile() != null ? entry.getValue().azureFile().shareName() : "empty direcory volume"); } } if (resource.containers() != null) { info.append("\n\tContainer instances: "); for (Map.Entry<String, Container> entry : resource.containers().entrySet()) { Container container = entry.getValue(); info.append("\n\t\tName: ").append(entry.getKey()).append(" -> ").append(container.image()); info.append("\n\t\t\tResources: "); info.append(container.resources().requests().cpu()).append("CPUs "); info.append(container.resources().requests().memoryInGB()).append("GB"); info.append("\n\t\t\tPorts:"); for (ContainerPort port : container.ports()) { info.append(" ").append(port.port()); } if (container.volumeMounts() != null) { info.append("\n\t\t\tVolume mounts:"); for (VolumeMount volumeMount : container.volumeMounts()) { info.append(" ").append(volumeMount.name()).append("->").append(volumeMount.mountPath()); } } if (container.command() != null) { info.append("\n\t\t\tStart commands:"); for (String command : container.command()) { info.append("\n\t\t\t\t").append(command); } } if (container.environmentVariables() != null) { info.append("\n\t\t\tENV vars:"); for (EnvironmentVariable envVar : container.environmentVariables()) { info.append("\n\t\t\t\t").append(envVar.name()).append("=").append(envVar.value()); } } } } System.out.println(info.toString()); } /** * Print event hub namespace. * * @param resource a virtual machine */ public static void print(EventHubNamespace resource) { StringBuilder info = new StringBuilder(); info.append("Eventhub Namespace: ").append(resource.id()) .append("\n\tName: ").append(resource.name()) .append("\n\tRegion: ").append(resource.region()) .append("\n\tTags: ").append(resource.tags()) .append("\n\tAzureInsightMetricId: ").append(resource.azureInsightMetricId()) .append("\n\tIsAutoScale enabled: ").append(resource.isAutoScaleEnabled()) .append("\n\tServiceBus endpoint: ").append(resource.serviceBusEndpoint()) .append("\n\tThroughPut upper limit: ").append(resource.throughputUnitsUpperLimit()) .append("\n\tCurrent ThroughPut: ").append(resource.currentThroughputUnits()) .append("\n\tCreated time: ").append(resource.createdAt()) .append("\n\tUpdated time: ").append(resource.updatedAt()); System.out.println(info.toString()); } /** * Print event hub. * * @param resource event hub */ public static void print(EventHub resource) { StringBuilder info = new StringBuilder(); info.append("Eventhub: ").append(resource.id()) .append("\n\tName: ").append(resource.name()) .append("\n\tNamespace resource group: ").append(resource.namespaceResourceGroupName()) .append("\n\tNamespace: ").append(resource.namespaceName()) .append("\n\tIs data capture enabled: ").append(resource.isDataCaptureEnabled()) .append("\n\tPartition ids: ").append(resource.partitionIds()); if (resource.isDataCaptureEnabled()) { info.append("\n\t\t\tData capture window size in MB: ").append(resource.dataCaptureWindowSizeInMB()); info.append("\n\t\t\tData capture window size in seconds: ").append(resource.dataCaptureWindowSizeInSeconds()); if (resource.captureDestination() != null) { info.append("\n\t\t\tData capture storage account: ").append(resource.captureDestination().storageAccountResourceId()); info.append("\n\t\t\tData capture storage container: ").append(resource.captureDestination().blobContainer()); } } System.out.println(info.toString()); } /** * Print event hub namespace recovery pairing. * * @param resource event hub namespace disaster recovery pairing */ public static void print(EventHubDisasterRecoveryPairing resource) { StringBuilder info = new StringBuilder(); info.append("DisasterRecoveryPairing: ").append(resource.id()) .append("\n\tName: ").append(resource.name()) .append("\n\tPrimary namespace resource group name: ").append(resource.primaryNamespaceResourceGroupName()) .append("\n\tPrimary namespace name: ").append(resource.primaryNamespaceName()) .append("\n\tSecondary namespace: ").append(resource.secondaryNamespaceId()) .append("\n\tNamespace role: ").append(resource.namespaceRole()); System.out.println(info.toString()); } /** * Print event hub namespace recovery pairing auth rules. * * @param resource event hub namespace disaster recovery pairing auth rule */ public static void print(DisasterRecoveryPairingAuthorizationRule resource) { StringBuilder info = new StringBuilder(); info.append("DisasterRecoveryPairing auth rule: ").append(resource.name()); List<String> rightsStr = new ArrayList<>(); for (AccessRights rights : resource.rights()) { rightsStr.add(rights.toString()); } info.append("\n\tRights: ").append(rightsStr); System.out.println(info.toString()); } /** * Print event hub namespace recovery pairing auth rule key. * * @param resource event hub namespace disaster recovery pairing auth rule key */ public static void print(DisasterRecoveryPairingAuthorizationKey resource) { StringBuilder info = new StringBuilder(); info.append("DisasterRecoveryPairing auth key: ") .append("\n\t Alias primary connection string: ").append(resource.aliasPrimaryConnectionString()) .append("\n\t Alias secondary connection string: ").append(resource.aliasSecondaryConnectionString()) .append("\n\t Primary key: ").append(resource.primaryKey()) .append("\n\t Secondary key: ").append(resource.secondaryKey()) .append("\n\t Primary connection string: ").append(resource.primaryConnectionString()) .append("\n\t Secondary connection string: ").append(resource.secondaryConnectionString()); System.out.println(info.toString()); } /** * Print event hub consumer group. * * @param resource event hub consumer group */ public static void print(EventHubConsumerGroup resource) { StringBuilder info = new StringBuilder(); info.append("Event hub consumer group: ").append(resource.id()) .append("\n\tName: ").append(resource.name()) .append("\n\tNamespace resource group: ").append(resource.namespaceResourceGroupName()) .append("\n\tNamespace: ").append(resource.namespaceName()) .append("\n\tEvent hub name: ").append(resource.eventHubName()) .append("\n\tUser metadata: ").append(resource.userMetadata()); System.out.println(info.toString()); } /** * Print Diagnostic Setting. * * @param resource Diagnostic Setting instance */ public static void print(DiagnosticSetting resource) { StringBuilder info = new StringBuilder("Diagnostic Setting: ") .append("\n\tId: ").append(resource.id()) .append("\n\tAssociated resource Id: ").append(resource.resourceId()) .append("\n\tName: ").append(resource.name()) .append("\n\tStorage Account Id: ").append(resource.storageAccountId()) .append("\n\tEventHub Namespace Autorization Rule Id: ").append(resource.eventHubAuthorizationRuleId()) .append("\n\tEventHub name: ").append(resource.eventHubName()) .append("\n\tLog Analytics workspace Id: ").append(resource.workspaceId()); if (resource.logs() != null && !resource.logs().isEmpty()) { info.append("\n\tLog Settings: "); for (LogSettings ls : resource.logs()) { info.append("\n\t\tCategory: ").append(ls.category()); info.append("\n\t\tRetention policy: "); if (ls.retentionPolicy() != null) { info.append(ls.retentionPolicy().days() + " days"); } else { info.append("NONE"); } } } if (resource.metrics() != null && !resource.metrics().isEmpty()) { info.append("\n\tMetric Settings: "); for (MetricSettings ls : resource.metrics()) { info.append("\n\t\tCategory: ").append(ls.category()); info.append("\n\t\tTimegrain: ").append(ls.timeGrain()); info.append("\n\t\tRetention policy: "); if (ls.retentionPolicy() != null) { info.append(ls.retentionPolicy().days() + " days"); } else { info.append("NONE"); } } } System.out.println(info.toString()); } /** * Print Action group settings. * * @param actionGroup action group instance */ public static void print(ActionGroup actionGroup) { StringBuilder info = new StringBuilder("Action Group: ") .append("\n\tId: ").append(actionGroup.id()) .append("\n\tName: ").append(actionGroup.name()) .append("\n\tShort Name: ").append(actionGroup.shortName()); if (actionGroup.emailReceivers() != null && !actionGroup.emailReceivers().isEmpty()) { info.append("\n\tEmail receivers: "); for (EmailReceiver er : actionGroup.emailReceivers()) { info.append("\n\t\tName: ").append(er.name()); info.append("\n\t\tEMail: ").append(er.emailAddress()); info.append("\n\t\tStatus: ").append(er.status()); info.append("\n\t\t==="); } } if (actionGroup.smsReceivers() != null && !actionGroup.smsReceivers().isEmpty()) { info.append("\n\tSMS text message receivers: "); for (SmsReceiver er : actionGroup.smsReceivers()) { info.append("\n\t\tName: ").append(er.name()); info.append("\n\t\tPhone: ").append(er.countryCode() + er.phoneNumber()); info.append("\n\t\tStatus: ").append(er.status()); info.append("\n\t\t==="); } } if (actionGroup.webhookReceivers() != null && !actionGroup.webhookReceivers().isEmpty()) { info.append("\n\tWebhook receivers: "); for (WebhookReceiver er : actionGroup.webhookReceivers()) { info.append("\n\t\tName: ").append(er.name()); info.append("\n\t\tURI: ").append(er.serviceUri()); info.append("\n\t\t==="); } } if (actionGroup.pushNotificationReceivers() != null && !actionGroup.pushNotificationReceivers().isEmpty()) { info.append("\n\tApp Push Notification receivers: "); for (AzureAppPushReceiver er : actionGroup.pushNotificationReceivers()) { info.append("\n\t\tName: ").append(er.name()); info.append("\n\t\tEmail: ").append(er.emailAddress()); info.append("\n\t\t==="); } } if (actionGroup.voiceReceivers() != null && !actionGroup.voiceReceivers().isEmpty()) { info.append("\n\tVoice Message receivers: "); for (VoiceReceiver er : actionGroup.voiceReceivers()) { info.append("\n\t\tName: ").append(er.name()); info.append("\n\t\tPhone: ").append(er.countryCode() + er.phoneNumber()); info.append("\n\t\t==="); } } if (actionGroup.automationRunbookReceivers() != null && !actionGroup.automationRunbookReceivers().isEmpty()) { info.append("\n\tAutomation Runbook receivers: "); for (AutomationRunbookReceiver er : actionGroup.automationRunbookReceivers()) { info.append("\n\t\tName: ").append(er.name()); info.append("\n\t\tRunbook Name: ").append(er.runbookName()); info.append("\n\t\tAccount Id: ").append(er.automationAccountId()); info.append("\n\t\tIs Global: ").append(er.isGlobalRunbook()); info.append("\n\t\tService URI: ").append(er.serviceUri()); info.append("\n\t\tWebhook resource Id: ").append(er.webhookResourceId()); info.append("\n\t\t==="); } } if (actionGroup.azureFunctionReceivers() != null && !actionGroup.azureFunctionReceivers().isEmpty()) { info.append("\n\tAzure Functions receivers: "); for (AzureFunctionReceiver er : actionGroup.azureFunctionReceivers()) { info.append("\n\t\tName: ").append(er.name()); info.append("\n\t\tFunction Name: ").append(er.functionName()); info.append("\n\t\tFunction App Resource Id: ").append(er.functionAppResourceId()); info.append("\n\t\tFunction Trigger URI: ").append(er.httpTriggerUrl()); info.append("\n\t\t==="); } } if (actionGroup.logicAppReceivers() != null && !actionGroup.logicAppReceivers().isEmpty()) { info.append("\n\tLogic App receivers: "); for (LogicAppReceiver er : actionGroup.logicAppReceivers()) { info.append("\n\t\tName: ").append(er.name()); info.append("\n\t\tResource Id: ").append(er.resourceId()); info.append("\n\t\tCallback URL: ").append(er.callbackUrl()); info.append("\n\t\t==="); } } if (actionGroup.itsmReceivers() != null && !actionGroup.itsmReceivers().isEmpty()) { info.append("\n\tITSM receivers: "); for (ItsmReceiver er : actionGroup.itsmReceivers()) { info.append("\n\t\tName: ").append(er.name()); info.append("\n\t\tWorkspace Id: ").append(er.workspaceId()); info.append("\n\t\tConnection Id: ").append(er.connectionId()); info.append("\n\t\tRegion: ").append(er.region()); info.append("\n\t\tTicket Configuration: ").append(er.ticketConfiguration()); info.append("\n\t\t==="); } } System.out.println(info.toString()); } /** * Print activity log alert settings. * * @param activityLogAlert activity log instance */ public static void print(ActivityLogAlert activityLogAlert) { StringBuilder info = new StringBuilder("Activity Log Alert: ") .append("\n\tId: ").append(activityLogAlert.id()) .append("\n\tName: ").append(activityLogAlert.name()) .append("\n\tDescription: ").append(activityLogAlert.description()) .append("\n\tIs Enabled: ").append(activityLogAlert.enabled()); if (activityLogAlert.scopes() != null && !activityLogAlert.scopes().isEmpty()) { info.append("\n\tScopes: "); for (String er : activityLogAlert.scopes()) { info.append("\n\t\tId: ").append(er); } } if (activityLogAlert.actionGroupIds() != null && !activityLogAlert.actionGroupIds().isEmpty()) { info.append("\n\tAction Groups: "); for (String er : activityLogAlert.actionGroupIds()) { info.append("\n\t\tAction Group Id: ").append(er); } } if (activityLogAlert.equalsConditions() != null && !activityLogAlert.equalsConditions().isEmpty()) { info.append("\n\tAlert conditions (when all of is true): "); for (Map.Entry<String, String> er : activityLogAlert.equalsConditions().entrySet()) { info.append("\n\t\t'").append(er.getKey()).append("' equals '").append(er.getValue()).append("'"); } } System.out.println(info.toString()); } /** * Print metric alert settings. * * @param metricAlert metric alert instance */ public static void print(MetricAlert metricAlert) { StringBuilder info = new StringBuilder("Metric Alert: ") .append("\n\tId: ").append(metricAlert.id()) .append("\n\tName: ").append(metricAlert.name()) .append("\n\tDescription: ").append(metricAlert.description()) .append("\n\tIs Enabled: ").append(metricAlert.enabled()) .append("\n\tIs Auto Mitigated: ").append(metricAlert.autoMitigate()) .append("\n\tSeverity: ").append(metricAlert.severity()) .append("\n\tWindow Size: ").append(metricAlert.windowSize()) .append("\n\tEvaluation Frequency: ").append(metricAlert.evaluationFrequency()); if (metricAlert.scopes() != null && !metricAlert.scopes().isEmpty()) { info.append("\n\tScopes: "); for (String er : metricAlert.scopes()) { info.append("\n\t\tId: ").append(er); } } if (metricAlert.actionGroupIds() != null && !metricAlert.actionGroupIds().isEmpty()) { info.append("\n\tAction Groups: "); for (String er : metricAlert.actionGroupIds()) { info.append("\n\t\tAction Group Id: ").append(er); } } if (metricAlert.alertCriterias() != null && !metricAlert.alertCriterias().isEmpty()) { info.append("\n\tAlert conditions (when all of is true): "); for (Map.Entry<String, MetricAlertCondition> er : metricAlert.alertCriterias().entrySet()) { MetricAlertCondition alertCondition = er.getValue(); info.append("\n\t\tCondition name: ").append(er.getKey()) .append("\n\t\tSignal name: ").append(alertCondition.metricName()) .append("\n\t\tMetric Namespace: ").append(alertCondition.metricNamespace()) .append("\n\t\tOperator: ").append(alertCondition.condition()) .append("\n\t\tThreshold: ").append(alertCondition.threshold()) .append("\n\t\tTime Aggregation: ").append(alertCondition.timeAggregation()); if (alertCondition.dimensions() != null && !alertCondition.dimensions().isEmpty()) { for (MetricDimension dimon : alertCondition.dimensions()) { info.append("\n\t\tDimension Filter: ").append("Name [").append(dimon.name()).append("] operator [Include] values["); for (String vals : dimon.values()) { info.append(vals).append(", "); } info.append("]"); } } } } System.out.println(info.toString()); } /** * Print spring service settings. * * @param springService spring service instance */ public static void print(SpringService springService) { StringBuilder info = new StringBuilder("Spring Service: ") .append("\n\tId: ").append(springService.id()) .append("\n\tName: ").append(springService.name()) .append("\n\tResource Group: ").append(springService.resourceGroupName()) .append("\n\tRegion: ").append(springService.region()) .append("\n\tTags: ").append(springService.tags()); ConfigServerProperties serverProperties = springService.getServerProperties(); if (serverProperties != null && serverProperties.provisioningState() != null && serverProperties.provisioningState().equals(ConfigServerState.SUCCEEDED) && serverProperties.configServer() != null) { info.append("\n\tProperties: "); if (serverProperties.configServer().gitProperty() != null) { info.append("\n\t\tGit: ").append(serverProperties.configServer().gitProperty().uri()); } } if (springService.sku() != null) { info.append("\n\tSku: ") .append("\n\t\tName: ").append(springService.sku().name()) .append("\n\t\tTier: ").append(springService.sku().tier()) .append("\n\t\tCapacity: ").append(springService.sku().capacity()); } MonitoringSettingProperties monitoringSettingProperties = springService.getMonitoringSetting(); if (monitoringSettingProperties != null && monitoringSettingProperties.provisioningState() != null && monitoringSettingProperties.provisioningState().equals(MonitoringSettingState.SUCCEEDED)) { info.append("\n\tTrace: ") .append("\n\t\tEnabled: ").append(monitoringSettingProperties.traceEnabled()) .append("\n\t\tApp Insight Instrumentation Key: ").append(monitoringSettingProperties.appInsightsInstrumentationKey()); } System.out.println(info.toString()); } /** * Print spring app settings. * * @param springApp spring app instance */ public static void print(SpringApp springApp) { StringBuilder info = new StringBuilder("Spring Service: ") .append("\n\tId: ").append(springApp.id()) .append("\n\tName: ").append(springApp.name()) .append("\n\tCreated Time: ").append(springApp.createdTime()) .append("\n\tPublic Endpoint: ").append(springApp.isPublic()) .append("\n\tUrl: ").append(springApp.url()) .append("\n\tHttps Only: ").append(springApp.isHttpsOnly()) .append("\n\tFully Qualified Domain Name: ").append(springApp.fqdn()) .append("\n\tActive Deployment Name: ").append(springApp.activeDeploymentName()); if (springApp.temporaryDisk() != null) { info.append("\n\tTemporary Disk:") .append("\n\t\tSize In GB: ").append(springApp.temporaryDisk().sizeInGB()) .append("\n\t\tMount Path: ").append(springApp.temporaryDisk().mountPath()); } if (springApp.persistentDisk() != null) { info.append("\n\tPersistent Disk:") .append("\n\t\tSize In GB: ").append(springApp.persistentDisk().sizeInGB()) .append("\n\t\tMount Path: ").append(springApp.persistentDisk().mountPath()); } if (springApp.identity() != null) { info.append("\n\tIdentity:") .append("\n\t\tType: ").append(springApp.identity().type()) .append("\n\t\tPrincipal Id: ").append(springApp.identity().principalId()) .append("\n\t\tTenant Id: ").append(springApp.identity().tenantId()); } System.out.println(info.toString()); } /** * Sends a GET request to target URL. * <p> * The method does not handle 301 redirect. * * @param urlString the target URL. * @return Content of the HTTP response. */ public static String sendGetRequest(String urlString) { try { Mono<Response<Flux<ByteBuffer>>> response = HTTP_CLIENT.getString(getHost(urlString), getPathAndQuery(urlString)) .retryWhen(Retry .fixedDelay(3, Duration.ofSeconds(30)) .filter(t -> { if (t instanceof TimeoutException) { return true; } else if (t instanceof HttpResponseException && ((HttpResponseException) t).getResponse().getStatusCode() == 503) { return true; } return false; })); Response<String> ret = stringResponse(response).block(); return ret == null ? null : ret.getValue(); } catch (MalformedURLException e) { return null; } } /** * Sends a POST request to target URL. * * @param urlString the target URL. * @param body the request body. * @return Content of the HTTP response. * */ public static String sendPostRequest(String urlString, String body) { try { Response<String> response = stringResponse(HTTP_CLIENT.postString(getHost(urlString), getPathAndQuery(urlString), body)).block(); if (response != null) { return response.getValue(); } else { return null; } } catch (Exception e) { return null; } } private static Mono<Response<String>> stringResponse(Mono<Response<Flux<ByteBuffer>>> responseMono) { return responseMono.flatMap(response -> FluxUtil.collectBytesInByteBufferStream(response.getValue()) .map(bytes -> new String(bytes, StandardCharsets.UTF_8)) .map(str -> new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), str))); } private static String getHost(String urlString) throws MalformedURLException { URL url = new URL(urlString); String protocol = url.getProtocol(); String host = url.getAuthority(); return protocol + ": } private static String getPathAndQuery(String urlString) throws MalformedURLException { URL url = new URL(urlString); String path = url.getPath(); String query = url.getQuery(); if (query != null && !query.isEmpty()) { path = path + "?" + query; } return path; } private static final WebAppTestClient HTTP_CLIENT = RestProxy.create( WebAppTestClient.class, new HttpPipelineBuilder() .policies( new HttpLoggingPolicy(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BASIC)), new RetryPolicy("Retry-After", ChronoUnit.SECONDS)) .build()); @Host("{$host}") @ServiceInterface(name = "WebAppTestClient") private interface WebAppTestClient { @Get("{path}") @ExpectedResponses({200, 400, 404}) Mono<Response<Flux<ByteBuffer>>> getString(@HostParam("$host") String host, @PathParam(value = "path", encoded = true) String path); @Post("{path}") @ExpectedResponses({200, 400, 404}) Mono<Response<Flux<ByteBuffer>>> postString(@HostParam("$host") String host, @PathParam(value = "path", encoded = true) String path, @BodyParam("text/plain") String body); } public static <T> int getSize(Iterable<T> iterable) { int res = 0; Iterator<T> iterator = iterable.iterator(); while (iterator.hasNext()) { iterator.next(); } return res; } }
public static String sendPostRequest(String urlString, String body) {
public static String getSecondaryServicePrincipalClientID(String envSecondaryServicePrincipal) throws IOException { String content = new String(Files.readAllBytes(new File(envSecondaryServicePrincipal).toPath()), StandardCharsets.UTF_8).trim(); HashMap<String, String> auth = new HashMap<>(); if (content.startsWith("{")) { auth = new JacksonAdapter().deserialize(content, auth.getClass(), SerializerEncoding.JSON); return auth.get("clientId"); } else { Properties authSettings = new Properties(); try (FileInputStream credentialsFileStream = new FileInputStream(new File(envSecondaryServicePrincipal))) { authSettings.load(credentialsFileStream); } return authSettings.getProperty("client"); } } /** * Retrieve the secondary service principal secret. * * @param envSecondaryServicePrincipal an Azure Container Registry * @return a service principal secret * @throws Exception exception */ public static String getSecondaryServicePrincipalSecret(String envSecondaryServicePrincipal) throws IOException { String content = new String(Files.readAllBytes(new File(envSecondaryServicePrincipal).toPath()), StandardCharsets.UTF_8).trim(); HashMap<String, String> auth = new HashMap<>(); if (content.startsWith("{")) { auth = new JacksonAdapter().deserialize(content, auth.getClass(), SerializerEncoding.JSON); return auth.get("clientSecret"); } else { Properties authSettings = new Properties(); try (FileInputStream credentialsFileStream = new FileInputStream(new File(envSecondaryServicePrincipal))) { authSettings.load(credentialsFileStream); } return authSettings.getProperty("key"); } } /** * This method creates a certificate for given password. * * @param certPath location of certificate file * @param pfxPath location of pfx file * @param alias User alias * @param password alias password * @param cnName domain name * @throws Exception exceptions from the creation * @throws IOException IO Exception */ public static void createCertificate(String certPath, String pfxPath, String alias, String password, String cnName) throws IOException { if (new File(pfxPath).exists()) { return; } String validityInDays = "3650"; String keyAlg = "RSA"; String sigAlg = "SHA1withRSA"; String keySize = "2048"; String storeType = "pkcs12"; String command = "keytool"; String jdkPath = System.getProperty("java.home"); if (jdkPath != null && !jdkPath.isEmpty()) { jdkPath = jdkPath.concat("\\bin"); if (new File(jdkPath).isDirectory()) { command = String.format("%s%s%s", jdkPath, File.separator, command); } } else { return; } String[] commandArgs = {command, "-genkey", "-alias", alias, "-keystore", pfxPath, "-storepass", password, "-validity", validityInDays, "-keyalg", keyAlg, "-sigalg", sigAlg, "-keysize", keySize, "-storetype", storeType, "-dname", "CN=" + cnName, "-ext", "EKU=1.3.6.1.5.5.7.3.1"}; Utils.cmdInvocation(commandArgs, true); File pfxFile = new File(pfxPath); if (pfxFile.exists()) { String[] certCommandArgs = {command, "-export", "-alias", alias, "-storetype", storeType, "-keystore", pfxPath, "-storepass", password, "-rfc", "-file", certPath}; Utils.cmdInvocation(certCommandArgs, true); File cerFile = new File(pfxPath); if (!cerFile.exists()) { throw new IOException( "Error occurred while creating certificate" + String.join(" ", certCommandArgs)); } } else { throw new IOException("Error occurred while creating certificates" + String.join(" ", commandArgs)); } } /** * This method is used for invoking native commands. * * @param command :- command to invoke. * @param ignoreErrorStream : Boolean which controls whether to throw exception or not * based on error stream. * @return result :- depending on the method invocation. * @throws Exception exceptions thrown from the execution */ public static String cmdInvocation(String[] command, boolean ignoreErrorStream) throws IOException { String result = ""; String error = ""; Process process = new ProcessBuilder(command).start(); try ( InputStream inputStream = process.getInputStream(); InputStream errorStream = process.getErrorStream(); BufferedReader br = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8)); BufferedReader ebr = new BufferedReader(new InputStreamReader(errorStream, StandardCharsets.UTF_8)); ) { result = br.readLine(); process.waitFor(); error = ebr.readLine(); if (error != null && (!error.equals(""))) { if (!ignoreErrorStream) { throw new IOException(error, null); } } } catch (Exception e) { throw new RuntimeException("Exception occurred while invoking command", e); } return result; } /** * Prints information for passed SQL Server. * * @param sqlServer sqlServer to be printed */ public static void print(SqlServer sqlServer) { StringBuilder builder = new StringBuilder().append("Sql Server: ").append(sqlServer.id()) .append("Name: ").append(sqlServer.name()) .append("\n\tResource group: ").append(sqlServer.resourceGroupName()) .append("\n\tRegion: ").append(sqlServer.region()) .append("\n\tSqlServer version: ").append(sqlServer.version()) .append("\n\tFully qualified name for Sql Server: ").append(sqlServer.fullyQualifiedDomainName()); System.out.println(builder.toString()); } /** * Prints information for the passed SQL Database. * * @param database database to be printed */ public static void print(SqlDatabase database) { StringBuilder builder = new StringBuilder().append("Sql Database: ").append(database.id()) .append("Name: ").append(database.name()) .append("\n\tResource group: ").append(database.resourceGroupName()) .append("\n\tRegion: ").append(database.region()) .append("\n\tSqlServer Name: ").append(database.sqlServerName()) .append("\n\tEdition of SQL database: ").append(database.edition()) .append("\n\tCollation of SQL database: ").append(database.collation()) .append("\n\tCreation date of SQL database: ").append(database.creationDate()) .append("\n\tIs data warehouse: ").append(database.isDataWarehouse()) .append("\n\tRequested service objective of SQL database: ").append(database.requestedServiceObjectiveName()) .append("\n\tName of current service objective of SQL database: ").append(database.currentServiceObjectiveName()) .append("\n\tMax size bytes of SQL database: ").append(database.maxSizeBytes()) .append("\n\tDefault secondary location of SQL database: ").append(database.defaultSecondaryLocation()); System.out.println(builder.toString()); } /** * Prints information for the passed firewall rule. * * @param firewallRule firewall rule to be printed. */ public static void print(SqlFirewallRule firewallRule) { StringBuilder builder = new StringBuilder().append("Sql firewall rule: ").append(firewallRule.id()) .append("Name: ").append(firewallRule.name()) .append("\n\tResource group: ").append(firewallRule.resourceGroupName()) .append("\n\tRegion: ").append(firewallRule.region()) .append("\n\tSqlServer Name: ").append(firewallRule.sqlServerName()) .append("\n\tStart IP Address of the firewall rule: ").append(firewallRule.startIpAddress()) .append("\n\tEnd IP Address of the firewall rule: ").append(firewallRule.endIpAddress()); System.out.println(builder.toString()); } /** * Prints information for the passed virtual network rule. * * @param virtualNetworkRule virtual network rule to be printed. */ public static void print(SqlVirtualNetworkRule virtualNetworkRule) { StringBuilder builder = new StringBuilder().append("SQL virtual network rule: ").append(virtualNetworkRule.id()) .append("Name: ").append(virtualNetworkRule.name()) .append("\n\tResource group: ").append(virtualNetworkRule.resourceGroupName()) .append("\n\tSqlServer Name: ").append(virtualNetworkRule.sqlServerName()) .append("\n\tSubnet ID: ").append(virtualNetworkRule.subnetId()) .append("\n\tState: ").append(virtualNetworkRule.state()); System.out.println(builder.toString()); } /** * Prints information for the passed SQL subscription usage metric. * * @param subscriptionUsageMetric metric to be printed. */ public static void print(SqlSubscriptionUsageMetric subscriptionUsageMetric) { StringBuilder builder = new StringBuilder().append("SQL Subscription Usage Metric: ").append(subscriptionUsageMetric.id()) .append("Name: ").append(subscriptionUsageMetric.name()) .append("\n\tDisplay Name: ").append(subscriptionUsageMetric.displayName()) .append("\n\tCurrent Value: ").append(subscriptionUsageMetric.currentValue()) .append("\n\tLimit: ").append(subscriptionUsageMetric.limit()) .append("\n\tUnit: ").append(subscriptionUsageMetric.unit()) .append("\n\tType: ").append(subscriptionUsageMetric.type()); System.out.println(builder.toString()); } /** * Prints information for the passed SQL database usage metric. * * @param dbUsageMetric metric to be printed. */ public static void print(SqlDatabaseUsageMetric dbUsageMetric) { StringBuilder builder = new StringBuilder().append("SQL Database Usage Metric") .append("Name: ").append(dbUsageMetric.name()) .append("\n\tResource Name: ").append(dbUsageMetric.resourceName()) .append("\n\tDisplay Name: ").append(dbUsageMetric.displayName()) .append("\n\tCurrent Value: ").append(dbUsageMetric.currentValue()) .append("\n\tLimit: ").append(dbUsageMetric.limit()) .append("\n\tUnit: ").append(dbUsageMetric.unit()) .append("\n\tNext Reset Time: ").append(dbUsageMetric.nextResetTime()); System.out.println(builder.toString()); } /** * Prints information for the passed SQL database metric. * * @param dbMetric metric to be printed. */ public static void print(SqlDatabaseMetric dbMetric) { StringBuilder builder = new StringBuilder().append("SQL Database Metric") .append("Name: ").append(dbMetric.name()) .append("\n\tStart Time: ").append(dbMetric.startTime()) .append("\n\tEnd Time: ").append(dbMetric.endTime()) .append("\n\tTime Grain: ").append(dbMetric.timeGrain()) .append("\n\tUnit: ").append(dbMetric.unit()); for (SqlDatabaseMetricValue metricValue : dbMetric.metricValues()) { builder .append("\n\tMetric Value: ") .append("\n\t\tCount: ").append(metricValue.count()) .append("\n\t\tAverage: ").append(metricValue.average()) .append("\n\t\tMaximum: ").append(metricValue.maximum()) .append("\n\t\tMinimum: ").append(metricValue.minimum()) .append("\n\t\tTimestamp: ").append(metricValue.timestamp()) .append("\n\t\tTotal: ").append(metricValue.total()); } System.out.println(builder.toString()); } /** * Prints information for the passed Failover Group. * * @param failoverGroup the SQL Failover Group to be printed. */ public static void print(SqlFailoverGroup failoverGroup) { StringBuilder builder = new StringBuilder().append("SQL Failover Group: ").append(failoverGroup.id()) .append("Name: ").append(failoverGroup.name()) .append("\n\tResource group: ").append(failoverGroup.resourceGroupName()) .append("\n\tSqlServer Name: ").append(failoverGroup.sqlServerName()) .append("\n\tRead-write endpoint policy: ").append(failoverGroup.readWriteEndpointPolicy()) .append("\n\tData loss grace period: ").append(failoverGroup.readWriteEndpointDataLossGracePeriodMinutes()) .append("\n\tRead-only endpoint policy: ").append(failoverGroup.readOnlyEndpointPolicy()) .append("\n\tReplication state: ").append(failoverGroup.replicationState()) .append("\n\tReplication role: ").append(failoverGroup.replicationRole()); builder.append("\n\tPartner Servers: "); for (PartnerInfo item : failoverGroup.partnerServers()) { builder .append("\n\t\tId: ").append(item.id()) .append("\n\t\tLocation: ").append(item.location()) .append("\n\t\tReplication role: ").append(item.replicationRole()); } builder.append("\n\tDatabases: "); for (String databaseId : failoverGroup.databases()) { builder.append("\n\t\tID: ").append(databaseId); } System.out.println(builder.toString()); } /** * Prints information for the passed SQL server key. * * @param serverKey virtual network rule to be printed. */ public static void print(SqlServerKey serverKey) { StringBuilder builder = new StringBuilder().append("SQL server key: ").append(serverKey.id()) .append("Name: ").append(serverKey.name()) .append("\n\tResource group: ").append(serverKey.resourceGroupName()) .append("\n\tSqlServer Name: ").append(serverKey.sqlServerName()) .append("\n\tRegion: ").append(serverKey.region() != null ? serverKey.region().name() : "") .append("\n\tServer Key Type: ").append(serverKey.serverKeyType()) .append("\n\tServer Key URI: ").append(serverKey.uri()) .append("\n\tServer Key Thumbprint: ").append(serverKey.thumbprint()) .append("\n\tServer Key Creation Date: ").append(serverKey.creationDate() != null ? serverKey.creationDate().toString() : ""); System.out.println(builder.toString()); } /** * Prints information of the elastic pool passed in. * * @param elasticPool elastic pool to be printed */ public static void print(SqlElasticPool elasticPool) { StringBuilder builder = new StringBuilder().append("Sql elastic pool: ").append(elasticPool.id()) .append("Name: ").append(elasticPool.name()) .append("\n\tResource group: ").append(elasticPool.resourceGroupName()) .append("\n\tRegion: ").append(elasticPool.region()) .append("\n\tSqlServer Name: ").append(elasticPool.sqlServerName()) .append("\n\tEdition of elastic pool: ").append(elasticPool.edition()) .append("\n\tTotal number of DTUs in the elastic pool: ").append(elasticPool.dtu()) .append("\n\tMaximum DTUs a database can get in elastic pool: ").append(elasticPool.databaseDtuMax()) .append("\n\tMinimum DTUs a database is guaranteed in elastic pool: ").append(elasticPool.databaseDtuMin()) .append("\n\tCreation date for the elastic pool: ").append(elasticPool.creationDate()) .append("\n\tState of the elastic pool: ").append(elasticPool.state()) .append("\n\tStorage capacity in MBs for the elastic pool: ").append(elasticPool.storageCapacity()); System.out.println(builder.toString()); } /** * Prints information of the elastic pool activity. * * @param elasticPoolActivity elastic pool activity to be printed */ public static void print(ElasticPoolActivity elasticPoolActivity) { StringBuilder builder = new StringBuilder().append("Sql elastic pool activity: ").append(elasticPoolActivity.id()) .append("Name: ").append(elasticPoolActivity.name()) .append("\n\tResource group: ").append(elasticPoolActivity.resourceGroupName()) .append("\n\tState: ").append(elasticPoolActivity.state()) .append("\n\tElastic pool name: ").append(elasticPoolActivity.elasticPoolName()) .append("\n\tStart time of activity: ").append(elasticPoolActivity.startTime()) .append("\n\tEnd time of activity: ").append(elasticPoolActivity.endTime()) .append("\n\tError code of activity: ").append(elasticPoolActivity.errorCode()) .append("\n\tError message of activity: ").append(elasticPoolActivity.errorMessage()) .append("\n\tError severity of activity: ").append(elasticPoolActivity.errorSeverity()) .append("\n\tOperation: ").append(elasticPoolActivity.operation()) .append("\n\tCompleted percentage of activity: ").append(elasticPoolActivity.percentComplete()) .append("\n\tRequested DTU max limit in activity: ").append(elasticPoolActivity.requestedDatabaseDtuMax()) .append("\n\tRequested DTU min limit in activity: ").append(elasticPoolActivity.requestedDatabaseDtuMin()) .append("\n\tRequested DTU limit in activity: ").append(elasticPoolActivity.requestedDtu()); System.out.println(builder.toString()); } /** * Prints information of the database activity. * * @param databaseActivity database activity to be printed */ public static void print(ElasticPoolDatabaseActivity databaseActivity) { StringBuilder builder = new StringBuilder().append("Sql elastic pool database activity: ").append(databaseActivity.id()) .append("Name: ").append(databaseActivity.name()) .append("\n\tResource group: ").append(databaseActivity.resourceGroupName()) .append("\n\tSQL Server Name: ").append(databaseActivity.serverName()) .append("\n\tDatabase name name: ").append(databaseActivity.databaseName()) .append("\n\tCurrent elastic pool name of the database: ").append(databaseActivity.currentElasticPoolName()) .append("\n\tState: ").append(databaseActivity.state()) .append("\n\tStart time of activity: ").append(databaseActivity.startTime()) .append("\n\tEnd time of activity: ").append(databaseActivity.endTime()) .append("\n\tCompleted percentage: ").append(databaseActivity.percentComplete()) .append("\n\tError code of activity: ").append(databaseActivity.errorCode()) .append("\n\tError message of activity: ").append(databaseActivity.errorMessage()) .append("\n\tError severity of activity: ").append(databaseActivity.errorSeverity()); System.out.println(builder.toString()); } /** * Print an application gateway. * * @param resource an application gateway */ public static void print(ApplicationGateway resource) { StringBuilder info = new StringBuilder(); info.append("Application gateway: ").append(resource.id()) .append("Name: ").append(resource.name()) .append("\n\tResource group: ").append(resource.resourceGroupName()) .append("\n\tRegion: ").append(resource.region()) .append("\n\tTags: ").append(resource.tags()) .append("\n\tSKU: ").append(resource.sku().toString()) .append("\n\tOperational state: ").append(resource.operationalState()) .append("\n\tInternet-facing? ").append(resource.isPublic()) .append("\n\tInternal? ").append(resource.isPrivate()) .append("\n\tDefault private IP address: ").append(resource.privateIpAddress()) .append("\n\tPrivate IP address allocation method: ").append(resource.privateIpAllocationMethod()) .append("\n\tDisabled SSL protocols: ").append(resource.disabledSslProtocols().toString()); Map<String, ApplicationGatewayIpConfiguration> ipConfigs = resource.ipConfigurations(); info.append("\n\tIP configurations: ").append(ipConfigs.size()); for (ApplicationGatewayIpConfiguration ipConfig : ipConfigs.values()) { info.append("\n\t\tName: ").append(ipConfig.name()) .append("\n\t\t\tNetwork id: ").append(ipConfig.networkId()) .append("\n\t\t\tSubnet name: ").append(ipConfig.subnetName()); } Map<String, ApplicationGatewayFrontend> frontends = resource.frontends(); info.append("\n\tFrontends: ").append(frontends.size()); for (ApplicationGatewayFrontend frontend : frontends.values()) { info.append("\n\t\tName: ").append(frontend.name()) .append("\n\t\t\tPublic? ").append(frontend.isPublic()); if (frontend.isPublic()) { info.append("\n\t\t\tPublic IP address ID: ").append(frontend.publicIpAddressId()); } if (frontend.isPrivate()) { info.append("\n\t\t\tPrivate IP address: ").append(frontend.privateIpAddress()) .append("\n\t\t\tPrivate IP allocation method: ").append(frontend.privateIpAllocationMethod()) .append("\n\t\t\tSubnet name: ").append(frontend.subnetName()) .append("\n\t\t\tVirtual network ID: ").append(frontend.networkId()); } } Map<String, ApplicationGatewayBackend> backends = resource.backends(); info.append("\n\tBackends: ").append(backends.size()); for (ApplicationGatewayBackend backend : backends.values()) { info.append("\n\t\tName: ").append(backend.name()) .append("\n\t\t\tAssociated NIC IP configuration IDs: ").append(backend.backendNicIPConfigurationNames().keySet()); Collection<ApplicationGatewayBackendAddress> addresses = backend.addresses(); info.append("\n\t\t\tAddresses: ").append(addresses.size()); for (ApplicationGatewayBackendAddress address : addresses) { info.append("\n\t\t\t\tFQDN: ").append(address.fqdn()) .append("\n\t\t\t\tIP: ").append(address.ipAddress()); } } Map<String, ApplicationGatewayBackendHttpConfiguration> httpConfigs = resource.backendHttpConfigurations(); info.append("\n\tHTTP Configurations: ").append(httpConfigs.size()); for (ApplicationGatewayBackendHttpConfiguration httpConfig : httpConfigs.values()) { info.append("\n\t\tName: ").append(httpConfig.name()) .append("\n\t\t\tCookie based affinity: ").append(httpConfig.cookieBasedAffinity()) .append("\n\t\t\tPort: ").append(httpConfig.port()) .append("\n\t\t\tRequest timeout in seconds: ").append(httpConfig.requestTimeout()) .append("\n\t\t\tProtocol: ").append(httpConfig.protocol()) .append("\n\t\tHost header: ").append(httpConfig.hostHeader()) .append("\n\t\tHost header comes from backend? ").append(httpConfig.isHostHeaderFromBackend()) .append("\n\t\tConnection draining timeout in seconds: ").append(httpConfig.connectionDrainingTimeoutInSeconds()) .append("\n\t\tAffinity cookie name: ").append(httpConfig.affinityCookieName()) .append("\n\t\tPath: ").append(httpConfig.path()); ApplicationGatewayProbe probe = httpConfig.probe(); if (probe != null) { info.append("\n\t\tProbe: " + probe.name()); } info.append("\n\t\tIs probe enabled? ").append(httpConfig.isProbeEnabled()); } Map<String, ApplicationGatewaySslCertificate> sslCerts = resource.sslCertificates(); info.append("\n\tSSL certificates: ").append(sslCerts.size()); for (ApplicationGatewaySslCertificate cert : sslCerts.values()) { info.append("\n\t\tName: ").append(cert.name()) .append("\n\t\t\tCert data: ").append(cert.publicData()); } Map<String, ApplicationGatewayRedirectConfiguration> redirects = resource.redirectConfigurations(); info.append("\n\tRedirect configurations: ").append(redirects.size()); for (ApplicationGatewayRedirectConfiguration redirect : redirects.values()) { info.append("\n\t\tName: ").append(redirect.name()) .append("\n\t\tTarget URL: ").append(redirect.type()) .append("\n\t\tTarget URL: ").append(redirect.targetUrl()) .append("\n\t\tTarget listener: ").append(redirect.targetListener() != null ? redirect.targetListener().name() : null) .append("\n\t\tIs path included? ").append(redirect.isPathIncluded()) .append("\n\t\tIs query string included? ").append(redirect.isQueryStringIncluded()) .append("\n\t\tReferencing request routing rules: ").append(redirect.requestRoutingRules().values()); } Map<String, ApplicationGatewayListener> listeners = resource.listeners(); info.append("\n\tHTTP listeners: ").append(listeners.size()); for (ApplicationGatewayListener listener : listeners.values()) { info.append("\n\t\tName: ").append(listener.name()) .append("\n\t\t\tHost name: ").append(listener.hostname()) .append("\n\t\t\tServer name indication required? ").append(listener.requiresServerNameIndication()) .append("\n\t\t\tAssociated frontend name: ").append(listener.frontend().name()) .append("\n\t\t\tFrontend port name: ").append(listener.frontendPortName()) .append("\n\t\t\tFrontend port number: ").append(listener.frontendPortNumber()) .append("\n\t\t\tProtocol: ").append(listener.protocol().toString()); if (listener.sslCertificate() != null) { info.append("\n\t\t\tAssociated SSL certificate: ").append(listener.sslCertificate().name()); } } Map<String, ApplicationGatewayProbe> probes = resource.probes(); info.append("\n\tProbes: ").append(probes.size()); for (ApplicationGatewayProbe probe : probes.values()) { info.append("\n\t\tName: ").append(probe.name()) .append("\n\t\tProtocol:").append(probe.protocol().toString()) .append("\n\t\tInterval in seconds: ").append(probe.timeBetweenProbesInSeconds()) .append("\n\t\tRetries: ").append(probe.retriesBeforeUnhealthy()) .append("\n\t\tTimeout: ").append(probe.timeoutInSeconds()) .append("\n\t\tHost: ").append(probe.host()) .append("\n\t\tHealthy HTTP response status code ranges: ").append(probe.healthyHttpResponseStatusCodeRanges()) .append("\n\t\tHealthy HTTP response body contents: ").append(probe.healthyHttpResponseBodyContents()); } Map<String, ApplicationGatewayRequestRoutingRule> rules = resource.requestRoutingRules(); info.append("\n\tRequest routing rules: ").append(rules.size()); for (ApplicationGatewayRequestRoutingRule rule : rules.values()) { info.append("\n\t\tName: ").append(rule.name()) .append("\n\t\tType: ").append(rule.ruleType()) .append("\n\t\tPublic IP address ID: ").append(rule.publicIpAddressId()) .append("\n\t\tHost name: ").append(rule.hostname()) .append("\n\t\tServer name indication required? ").append(rule.requiresServerNameIndication()) .append("\n\t\tFrontend port: ").append(rule.frontendPort()) .append("\n\t\tFrontend protocol: ").append(rule.frontendProtocol().toString()) .append("\n\t\tBackend port: ").append(rule.backendPort()) .append("\n\t\tCookie based affinity enabled? ").append(rule.cookieBasedAffinity()) .append("\n\t\tRedirect configuration: ").append(rule.redirectConfiguration() != null ? rule.redirectConfiguration().name() : "(none)"); Collection<ApplicationGatewayBackendAddress> addresses = rule.backendAddresses(); info.append("\n\t\t\tBackend addresses: ").append(addresses.size()); for (ApplicationGatewayBackendAddress address : addresses) { info.append("\n\t\t\t\t") .append(address.fqdn()) .append(" [").append(address.ipAddress()).append("]"); } info.append("\n\t\t\tSSL certificate name: "); ApplicationGatewaySslCertificate cert = rule.sslCertificate(); if (cert == null) { info.append("(None)"); } else { info.append(cert.name()); } info.append("\n\t\t\tAssociated backend address pool: "); ApplicationGatewayBackend backend = rule.backend(); if (backend == null) { info.append("(None)"); } else { info.append(backend.name()); } info.append("\n\t\t\tAssociated backend HTTP settings configuration: "); ApplicationGatewayBackendHttpConfiguration config = rule.backendHttpConfiguration(); if (config == null) { info.append("(None)"); } else { info.append(config.name()); } info.append("\n\t\t\tAssociated frontend listener: "); ApplicationGatewayListener listener = rule.listener(); if (listener == null) { info.append("(None)"); } else { info.append(config.name()); } } System.out.println(info.toString()); } /** * Prints information of a virtual machine custom image. * * @param image the image */ public static void print(VirtualMachineCustomImage image) { StringBuilder builder = new StringBuilder().append("Virtual machine custom image: ").append(image.id()) .append("Name: ").append(image.name()) .append("\n\tResource group: ").append(image.resourceGroupName()) .append("\n\tCreated from virtual machine: ").append(image.sourceVirtualMachineId()); builder.append("\n\tOS disk image: ") .append("\n\t\tOperating system: ").append(image.osDiskImage().osType()) .append("\n\t\tOperating system state: ").append(image.osDiskImage().osState()) .append("\n\t\tCaching: ").append(image.osDiskImage().caching()) .append("\n\t\tSize (GB): ").append(image.osDiskImage().diskSizeGB()); if (image.isCreatedFromVirtualMachine()) { builder.append("\n\t\tSource virtual machine: ").append(image.sourceVirtualMachineId()); } if (image.osDiskImage().managedDisk() != null) { builder.append("\n\t\tSource managed disk: ").append(image.osDiskImage().managedDisk().id()); } if (image.osDiskImage().snapshot() != null) { builder.append("\n\t\tSource snapshot: ").append(image.osDiskImage().snapshot().id()); } if (image.osDiskImage().blobUri() != null) { builder.append("\n\t\tSource un-managed vhd: ").append(image.osDiskImage().blobUri()); } if (image.dataDiskImages() != null) { for (ImageDataDisk diskImage : image.dataDiskImages().values()) { builder.append("\n\tDisk Image (Lun) .append("\n\t\tCaching: ").append(diskImage.caching()) .append("\n\t\tSize (GB): ").append(diskImage.diskSizeGB()); if (image.isCreatedFromVirtualMachine()) { builder.append("\n\t\tSource virtual machine: ").append(image.sourceVirtualMachineId()); } if (diskImage.managedDisk() != null) { builder.append("\n\t\tSource managed disk: ").append(diskImage.managedDisk().id()); } if (diskImage.snapshot() != null) { builder.append("\n\t\tSource snapshot: ").append(diskImage.snapshot().id()); } if (diskImage.blobUri() != null) { builder.append("\n\t\tSource un-managed vhd: ").append(diskImage.blobUri()); } } } System.out.println(builder.toString()); } /** * Uploads a file to an Azure app service for Web App. * * @param profile the publishing profile for the app service. * @param fileName the name of the file on server * @param file the local file */ public static void uploadFileViaFtp(PublishingProfile profile, String fileName, InputStream file) { String path = "./site/wwwroot/webapps"; uploadFileViaFtp(profile, fileName, file, path); } /** * Uploads a file to an Azure app service for Function App. * * @param profile the publishing profile for the app service. * @param fileName the name of the file on server * @param file the local file */ public static void uploadFileForFunctionViaFtp(PublishingProfile profile, String fileName, InputStream file) { String path = "./site/wwwroot"; uploadFileViaFtp(profile, fileName, file, path); } private static void uploadFileViaFtp(PublishingProfile profile, String fileName, InputStream file, String path) { FTPClient ftpClient = new FTPClient(); String[] ftpUrlSegments = profile.ftpUrl().split("/", 2); String server = ftpUrlSegments[0]; if (fileName.contains("/")) { int lastslash = fileName.lastIndexOf('/'); path = path + "/" + fileName.substring(0, lastslash); fileName = fileName.substring(lastslash + 1); } try { ftpClient.connect(server); ftpClient.enterLocalPassiveMode(); ftpClient.login(profile.ftpUsername(), profile.ftpPassword()); ftpClient.setFileType(FTP.BINARY_FILE_TYPE); for (String segment : path.split("/")) { if (!ftpClient.changeWorkingDirectory(segment)) { ftpClient.makeDirectory(segment); ftpClient.changeWorkingDirectory(segment); } } ftpClient.storeFile(fileName, file); ftpClient.disconnect(); } catch (IOException e) { e.printStackTrace(); } } /** * Print service bus namespace info. * * @param serviceBusNamespace a service bus namespace */ public static void print(ServiceBusNamespace serviceBusNamespace) { StringBuilder builder = new StringBuilder() .append("Service bus Namespace: ").append(serviceBusNamespace.id()) .append("\n\tName: ").append(serviceBusNamespace.name()) .append("\n\tRegion: ").append(serviceBusNamespace.regionName()) .append("\n\tResourceGroupName: ").append(serviceBusNamespace.resourceGroupName()) .append("\n\tCreatedAt: ").append(serviceBusNamespace.createdAt()) .append("\n\tUpdatedAt: ").append(serviceBusNamespace.updatedAt()) .append("\n\tDnsLabel: ").append(serviceBusNamespace.dnsLabel()) .append("\n\tFQDN: ").append(serviceBusNamespace.fqdn()) .append("\n\tSku: ") .append("\n\t\tCapacity: ").append(serviceBusNamespace.sku().capacity()) .append("\n\t\tSkuName: ").append(serviceBusNamespace.sku().name()) .append("\n\t\tTier: ").append(serviceBusNamespace.sku().tier()); System.out.println(builder.toString()); } /** * Print service bus queue info. * * @param queue a service bus queue */ public static void print(Queue queue) { StringBuilder builder = new StringBuilder() .append("Service bus Queue: ").append(queue.id()) .append("\n\tName: ").append(queue.name()) .append("\n\tResourceGroupName: ").append(queue.resourceGroupName()) .append("\n\tCreatedAt: ").append(queue.createdAt()) .append("\n\tUpdatedAt: ").append(queue.updatedAt()) .append("\n\tAccessedAt: ").append(queue.accessedAt()) .append("\n\tActiveMessageCount: ").append(queue.activeMessageCount()) .append("\n\tCurrentSizeInBytes: ").append(queue.currentSizeInBytes()) .append("\n\tDeadLetterMessageCount: ").append(queue.deadLetterMessageCount()) .append("\n\tDefaultMessageTtlDuration: ").append(queue.defaultMessageTtlDuration()) .append("\n\tDuplicateMessageDetectionHistoryDuration: ").append(queue.duplicateMessageDetectionHistoryDuration()) .append("\n\tIsBatchedOperationsEnabled: ").append(queue.isBatchedOperationsEnabled()) .append("\n\tIsDeadLetteringEnabledForExpiredMessages: ").append(queue.isDeadLetteringEnabledForExpiredMessages()) .append("\n\tIsDuplicateDetectionEnabled: ").append(queue.isDuplicateDetectionEnabled()) .append("\n\tIsExpressEnabled: ").append(queue.isExpressEnabled()) .append("\n\tIsPartitioningEnabled: ").append(queue.isPartitioningEnabled()) .append("\n\tIsSessionEnabled: ").append(queue.isSessionEnabled()) .append("\n\tDeleteOnIdleDurationInMinutes: ").append(queue.deleteOnIdleDurationInMinutes()) .append("\n\tMaxDeliveryCountBeforeDeadLetteringMessage: ").append(queue.maxDeliveryCountBeforeDeadLetteringMessage()) .append("\n\tMaxSizeInMB: ").append(queue.maxSizeInMB()) .append("\n\tMessageCount: ").append(queue.messageCount()) .append("\n\tScheduledMessageCount: ").append(queue.scheduledMessageCount()) .append("\n\tStatus: ").append(queue.status()) .append("\n\tTransferMessageCount: ").append(queue.transferMessageCount()) .append("\n\tLockDurationInSeconds: ").append(queue.lockDurationInSeconds()) .append("\n\tTransferDeadLetterMessageCount: ").append(queue.transferDeadLetterMessageCount()); System.out.println(builder.toString()); } /** * Print service bus queue authorization keys info. * * @param queueAuthorizationRule a service bus queue authorization keys */ public static void print(QueueAuthorizationRule queueAuthorizationRule) { StringBuilder builder = new StringBuilder() .append("Service bus queue authorization rule: ").append(queueAuthorizationRule.id()) .append("\n\tName: ").append(queueAuthorizationRule.name()) .append("\n\tResourceGroupName: ").append(queueAuthorizationRule.resourceGroupName()) .append("\n\tNamespace Name: ").append(queueAuthorizationRule.namespaceName()) .append("\n\tQueue Name: ").append(queueAuthorizationRule.queueName()); List<com.azure.resourcemanager.servicebus.models.AccessRights> rights = queueAuthorizationRule.rights(); builder.append("\n\tNumber of access rights in queue: ").append(rights.size()); for (com.azure.resourcemanager.servicebus.models.AccessRights right : rights) { builder.append("\n\t\tAccessRight: ") .append("\n\t\t\tName :").append(right.name()); } System.out.println(builder.toString()); } /** * Print service bus namespace authorization keys info. * * @param keys a service bus namespace authorization keys */ public static void print(AuthorizationKeys keys) { StringBuilder builder = new StringBuilder() .append("Authorization keys: ") .append("\n\tPrimaryKey: ").append(keys.primaryKey()) .append("\n\tPrimaryConnectionString: ").append(keys.primaryConnectionString()) .append("\n\tSecondaryKey: ").append(keys.secondaryKey()) .append("\n\tSecondaryConnectionString: ").append(keys.secondaryConnectionString()); System.out.println(builder.toString()); } /** * Print service bus namespace authorization rule info. * * @param namespaceAuthorizationRule a service bus namespace authorization rule */ public static void print(NamespaceAuthorizationRule namespaceAuthorizationRule) { StringBuilder builder = new StringBuilder() .append("Service bus queue authorization rule: ").append(namespaceAuthorizationRule.id()) .append("\n\tName: ").append(namespaceAuthorizationRule.name()) .append("\n\tResourceGroupName: ").append(namespaceAuthorizationRule.resourceGroupName()) .append("\n\tNamespace Name: ").append(namespaceAuthorizationRule.namespaceName()); List<com.azure.resourcemanager.servicebus.models.AccessRights> rights = namespaceAuthorizationRule.rights(); builder.append("\n\tNumber of access rights in queue: ").append(rights.size()); for (com.azure.resourcemanager.servicebus.models.AccessRights right : rights) { builder.append("\n\t\tAccessRight: ") .append("\n\t\t\tName :").append(right.name()); } System.out.println(builder.toString()); } /** * Print service bus topic info. * * @param topic a service bus topic */ public static void print(Topic topic) { StringBuilder builder = new StringBuilder() .append("Service bus topic: ").append(topic.id()) .append("\n\tName: ").append(topic.name()) .append("\n\tResourceGroupName: ").append(topic.resourceGroupName()) .append("\n\tCreatedAt: ").append(topic.createdAt()) .append("\n\tUpdatedAt: ").append(topic.updatedAt()) .append("\n\tAccessedAt: ").append(topic.accessedAt()) .append("\n\tActiveMessageCount: ").append(topic.activeMessageCount()) .append("\n\tCurrentSizeInBytes: ").append(topic.currentSizeInBytes()) .append("\n\tDeadLetterMessageCount: ").append(topic.deadLetterMessageCount()) .append("\n\tDefaultMessageTtlDuration: ").append(topic.defaultMessageTtlDuration()) .append("\n\tDuplicateMessageDetectionHistoryDuration: ").append(topic.duplicateMessageDetectionHistoryDuration()) .append("\n\tIsBatchedOperationsEnabled: ").append(topic.isBatchedOperationsEnabled()) .append("\n\tIsDuplicateDetectionEnabled: ").append(topic.isDuplicateDetectionEnabled()) .append("\n\tIsExpressEnabled: ").append(topic.isExpressEnabled()) .append("\n\tIsPartitioningEnabled: ").append(topic.isPartitioningEnabled()) .append("\n\tDeleteOnIdleDurationInMinutes: ").append(topic.deleteOnIdleDurationInMinutes()) .append("\n\tMaxSizeInMB: ").append(topic.maxSizeInMB()) .append("\n\tScheduledMessageCount: ").append(topic.scheduledMessageCount()) .append("\n\tStatus: ").append(topic.status()) .append("\n\tTransferMessageCount: ").append(topic.transferMessageCount()) .append("\n\tSubscriptionCount: ").append(topic.subscriptionCount()) .append("\n\tTransferDeadLetterMessageCount: ").append(topic.transferDeadLetterMessageCount()); System.out.println(builder.toString()); } /** * Print service bus subscription info. * * @param serviceBusSubscription a service bus subscription */ public static void print(ServiceBusSubscription serviceBusSubscription) { StringBuilder builder = new StringBuilder() .append("Service bus subscription: ").append(serviceBusSubscription.id()) .append("\n\tName: ").append(serviceBusSubscription.name()) .append("\n\tResourceGroupName: ").append(serviceBusSubscription.resourceGroupName()) .append("\n\tCreatedAt: ").append(serviceBusSubscription.createdAt()) .append("\n\tUpdatedAt: ").append(serviceBusSubscription.updatedAt()) .append("\n\tAccessedAt: ").append(serviceBusSubscription.accessedAt()) .append("\n\tActiveMessageCount: ").append(serviceBusSubscription.activeMessageCount()) .append("\n\tDeadLetterMessageCount: ").append(serviceBusSubscription.deadLetterMessageCount()) .append("\n\tDefaultMessageTtlDuration: ").append(serviceBusSubscription.defaultMessageTtlDuration()) .append("\n\tIsBatchedOperationsEnabled: ").append(serviceBusSubscription.isBatchedOperationsEnabled()) .append("\n\tDeleteOnIdleDurationInMinutes: ").append(serviceBusSubscription.deleteOnIdleDurationInMinutes()) .append("\n\tScheduledMessageCount: ").append(serviceBusSubscription.scheduledMessageCount()) .append("\n\tStatus: ").append(serviceBusSubscription.status()) .append("\n\tTransferMessageCount: ").append(serviceBusSubscription.transferMessageCount()) .append("\n\tIsDeadLetteringEnabledForExpiredMessages: ").append(serviceBusSubscription.isDeadLetteringEnabledForExpiredMessages()) .append("\n\tIsSessionEnabled: ").append(serviceBusSubscription.isSessionEnabled()) .append("\n\tLockDurationInSeconds: ").append(serviceBusSubscription.lockDurationInSeconds()) .append("\n\tMaxDeliveryCountBeforeDeadLetteringMessage: ").append(serviceBusSubscription.maxDeliveryCountBeforeDeadLetteringMessage()) .append("\n\tIsDeadLetteringEnabledForFilterEvaluationFailedMessages: ").append(serviceBusSubscription.isDeadLetteringEnabledForFilterEvaluationFailedMessages()) .append("\n\tTransferMessageCount: ").append(serviceBusSubscription.transferMessageCount()) .append("\n\tTransferDeadLetterMessageCount: ").append(serviceBusSubscription.transferDeadLetterMessageCount()); System.out.println(builder.toString()); } /** * Print topic Authorization Rule info. * * @param topicAuthorizationRule a topic Authorization Rule */ public static void print(TopicAuthorizationRule topicAuthorizationRule) { StringBuilder builder = new StringBuilder() .append("Service bus topic authorization rule: ").append(topicAuthorizationRule.id()) .append("\n\tName: ").append(topicAuthorizationRule.name()) .append("\n\tResourceGroupName: ").append(topicAuthorizationRule.resourceGroupName()) .append("\n\tNamespace Name: ").append(topicAuthorizationRule.namespaceName()) .append("\n\tTopic Name: ").append(topicAuthorizationRule.topicName()); List<com.azure.resourcemanager.servicebus.models.AccessRights> rights = topicAuthorizationRule.rights(); builder.append("\n\tNumber of access rights in queue: ").append(rights.size()); for (com.azure.resourcemanager.servicebus.models.AccessRights right : rights) { builder.append("\n\t\tAccessRight: ") .append("\n\t\t\tName :").append(right.name()); } System.out.println(builder.toString()); } /** * Print CosmosDB info. * * @param cosmosDBAccount a CosmosDB */ public static void print(CosmosDBAccount cosmosDBAccount) { StringBuilder builder = new StringBuilder() .append("CosmosDB: ").append(cosmosDBAccount.id()) .append("\n\tName: ").append(cosmosDBAccount.name()) .append("\n\tResourceGroupName: ").append(cosmosDBAccount.resourceGroupName()) .append("\n\tKind: ").append(cosmosDBAccount.kind().toString()) .append("\n\tDefault consistency level: ").append(cosmosDBAccount.consistencyPolicy().defaultConsistencyLevel()) .append("\n\tIP range filter: ").append(cosmosDBAccount.ipRangeFilter()); DatabaseAccountListKeysResult keys = cosmosDBAccount.listKeys(); DatabaseAccountListReadOnlyKeysResult readOnlyKeys = cosmosDBAccount.listReadOnlyKeys(); builder .append("\n\tPrimary Master Key: ").append(keys.primaryMasterKey()) .append("\n\tSecondary Master Key: ").append(keys.secondaryMasterKey()) .append("\n\tPrimary Read-Only Key: ").append(readOnlyKeys.primaryReadonlyMasterKey()) .append("\n\tSecondary Read-Only Key: ").append(readOnlyKeys.secondaryReadonlyMasterKey()); for (Location writeReplica : cosmosDBAccount.writableReplications()) { builder.append("\n\t\tWrite replication: ") .append("\n\t\t\tName :").append(writeReplica.locationName()); } builder.append("\n\tNumber of read replications: ").append(cosmosDBAccount.readableReplications().size()); for (Location readReplica : cosmosDBAccount.readableReplications()) { builder.append("\n\t\tRead replication: ") .append("\n\t\t\tName :").append(readReplica.locationName()); } } /** * Print Active Directory User info. * * @param user active directory user */ public static void print(ActiveDirectoryUser user) { StringBuilder builder = new StringBuilder() .append("Active Directory User: ").append(user.id()) .append("\n\tName: ").append(user.name()) .append("\n\tMail: ").append(user.mail()) .append("\n\tMail Nickname: ").append(user.mailNickname()) .append("\n\tSign In Name: ").append(user.signInName()) .append("\n\tUser Principal Name: ").append(user.userPrincipalName()); System.out.println(builder.toString()); } /** * Print Active Directory User info. * * @param role role definition */ public static void print(RoleDefinition role) { StringBuilder builder = new StringBuilder() .append("Role Definition: ").append(role.id()) .append("\n\tName: ").append(role.name()) .append("\n\tRole Name: ").append(role.roleName()) .append("\n\tType: ").append(role.type()) .append("\n\tDescription: ").append(role.description()) .append("\n\tType: ").append(role.type()); Set<Permission> permissions = role.permissions(); builder.append("\n\tPermissions: ").append(permissions.size()); for (Permission permission : permissions) { builder.append("\n\t\tPermission Actions: " + permission.actions().size()); for (String action : permission.actions()) { builder.append("\n\t\t\tName :").append(action); } builder.append("\n\t\tPermission Not Actions: " + permission.notActions().size()); for (String notAction : permission.notActions()) { builder.append("\n\t\t\tName :").append(notAction); } } Set<String> assignableScopes = role.assignableScopes(); builder.append("\n\tAssignable scopes: ").append(assignableScopes.size()); for (String scope : assignableScopes) { builder.append("\n\t\tAssignable Scope: ") .append("\n\t\t\tName :").append(scope); } System.out.println(builder.toString()); } /** * Print Role Assignment info. * * @param roleAssignment role assignment */ public static void print(RoleAssignment roleAssignment) { StringBuilder builder = new StringBuilder() .append("Role Assignment: ") .append("\n\tScope: ").append(roleAssignment.scope()) .append("\n\tPrincipal Id: ").append(roleAssignment.principalId()) .append("\n\tRole Definition Id: ").append(roleAssignment.roleDefinitionId()); System.out.println(builder.toString()); } /** * Print Active Directory Group info. * * @param group active directory group */ public static void print(ActiveDirectoryGroup group) { StringBuilder builder = new StringBuilder() .append("Active Directory Group: ").append(group.id()) .append("\n\tName: ").append(group.name()) .append("\n\tMail: ").append(group.mail()) .append("\n\tSecurity Enabled: ").append(group.securityEnabled()) .append("\n\tGroup members:"); for (ActiveDirectoryObject object : group.listMembers()) { builder.append("\n\t\tType: ").append(object.getClass().getSimpleName()) .append("\tName: ").append(object.name()); } System.out.println(builder.toString()); } /** * Print Active Directory Application info. * * @param application active directory application */ public static void print(ActiveDirectoryApplication application) { StringBuilder builder = new StringBuilder() .append("Active Directory Application: ").append(application.id()) .append("\n\tName: ").append(application.name()) .append("\n\tSign on URL: ").append(application.signOnUrl()) .append("\n\tReply URLs:"); for (String replyUrl : application.replyUrls()) { builder.append("\n\t\t").append(replyUrl); } System.out.println(builder.toString()); } /** * Print Service Principal info. * * @param servicePrincipal service principal */ public static void print(ServicePrincipal servicePrincipal) { StringBuilder builder = new StringBuilder() .append("Service Principal: ").append(servicePrincipal.id()) .append("\n\tName: ").append(servicePrincipal.name()) .append("\n\tApplication Id: ").append(servicePrincipal.applicationId()); List<String> names = servicePrincipal.servicePrincipalNames(); builder.append("\n\tNames: ").append(names.size()); for (String name : names) { builder.append("\n\t\tName: ").append(name); } System.out.println(builder.toString()); } /** * Print Network Watcher info. * * @param nw network watcher */ public static void print(NetworkWatcher nw) { StringBuilder builder = new StringBuilder() .append("Network Watcher: ").append(nw.id()) .append("\n\tName: ").append(nw.name()) .append("\n\tResource group name: ").append(nw.resourceGroupName()) .append("\n\tRegion name: ").append(nw.regionName()); System.out.println(builder.toString()); } /** * Print packet capture info. * * @param resource packet capture */ public static void print(PacketCapture resource) { StringBuilder sb = new StringBuilder().append("Packet Capture: ").append(resource.id()) .append("\n\tName: ").append(resource.name()) .append("\n\tTarget id: ").append(resource.targetId()) .append("\n\tTime limit in seconds: ").append(resource.timeLimitInSeconds()) .append("\n\tBytes to capture per packet: ").append(resource.bytesToCapturePerPacket()) .append("\n\tProvisioning state: ").append(resource.provisioningState()) .append("\n\tStorage location:") .append("\n\tStorage account id: ").append(resource.storageLocation().storageId()) .append("\n\tStorage account path: ").append(resource.storageLocation().storagePath()) .append("\n\tFile path: ").append(resource.storageLocation().filePath()) .append("\n\t Packet capture filters: ").append(resource.filters().size()); for (PacketCaptureFilter filter : resource.filters()) { sb.append("\n\t\tProtocol: ").append(filter.protocol()); sb.append("\n\t\tLocal IP address: ").append(filter.localIpAddress()); sb.append("\n\t\tRemote IP address: ").append(filter.remoteIpAddress()); sb.append("\n\t\tLocal port: ").append(filter.localPort()); sb.append("\n\t\tRemote port: ").append(filter.remotePort()); } System.out.println(sb.toString()); } /** * Print verification IP flow info. * * @param resource IP flow verification info */ public static void print(VerificationIPFlow resource) { System.out.println(new StringBuilder("IP flow verification: ") .append("\n\tAccess: ").append(resource.access()) .append("\n\tRule name: ").append(resource.ruleName()) .toString()); } /** * Print topology info. * * @param resource topology */ public static void print(Topology resource) { StringBuilder sb = new StringBuilder().append("Topology: ").append(resource.id()) .append("\n\tTopology parameters: ") .append("\n\t\tResource group: ").append(resource.topologyParameters().targetResourceGroupName()) .append("\n\t\tVirtual network: ").append(resource.topologyParameters().targetVirtualNetwork() == null ? "" : resource.topologyParameters().targetVirtualNetwork().id()) .append("\n\t\tSubnet id: ").append(resource.topologyParameters().targetSubnet() == null ? "" : resource.topologyParameters().targetSubnet().id()) .append("\n\tCreated time: ").append(resource.createdTime()) .append("\n\tLast modified time: ").append(resource.lastModifiedTime()); for (TopologyResource tr : resource.resources().values()) { sb.append("\n\tTopology resource: ").append(tr.id()) .append("\n\t\tName: ").append(tr.name()) .append("\n\t\tLocation: ").append(tr.location()) .append("\n\t\tAssociations:"); for (TopologyAssociation association : tr.associations()) { sb.append("\n\t\t\tName:").append(association.name()) .append("\n\t\t\tResource id:").append(association.resourceId()) .append("\n\t\t\tAssociation type:").append(association.associationType()); } } System.out.println(sb.toString()); } /** * Print flow log settings info. * * @param resource flow log settings */ public static void print(FlowLogSettings resource) { System.out.println(new StringBuilder().append("Flow log settings: ") .append("Target resource id: ").append(resource.targetResourceId()) .append("\n\tFlow log enabled: ").append(resource.enabled()) .append("\n\tStorage account id: ").append(resource.storageId()) .append("\n\tRetention policy enabled: ").append(resource.isRetentionEnabled()) .append("\n\tRetention policy days: ").append(resource.retentionDays()) .toString()); } /** * Print availability set info. * * @param resource an availability set */ public static void print(SecurityGroupView resource) { StringBuilder sb = new StringBuilder().append("Security group view: ") .append("\n\tVirtual machine id: ").append(resource.vmId()); for (SecurityGroupNetworkInterface sgni : resource.networkInterfaces().values()) { sb.append("\n\tSecurity group network interface:").append(sgni.id()) .append("\n\t\tSecurity group network interface:") .append("\n\t\tEffective security rules:"); for (EffectiveNetworkSecurityRule rule : sgni.securityRuleAssociations().effectiveSecurityRules()) { sb.append("\n\t\t\tName: ").append(rule.name()) .append("\n\t\t\tDirection: ").append(rule.direction()) .append("\n\t\t\tAccess: ").append(rule.access()) .append("\n\t\t\tPriority: ").append(rule.priority()) .append("\n\t\t\tSource address prefix: ").append(rule.sourceAddressPrefix()) .append("\n\t\t\tSource port range: ").append(rule.sourcePortRange()) .append("\n\t\t\tDestination address prefix: ").append(rule.destinationAddressPrefix()) .append("\n\t\t\tDestination port range: ").append(rule.destinationPortRange()) .append("\n\t\t\tProtocol: ").append(rule.protocol()); } sb.append("\n\t\tSubnet:").append(sgni.securityRuleAssociations().subnetAssociation().id()); printSecurityRule(sb, sgni.securityRuleAssociations().subnetAssociation().securityRules()); if (sgni.securityRuleAssociations().networkInterfaceAssociation() != null) { sb.append("\n\t\tNetwork interface:").append(sgni.securityRuleAssociations().networkInterfaceAssociation().id()); printSecurityRule(sb, sgni.securityRuleAssociations().networkInterfaceAssociation().securityRules()); } sb.append("\n\t\tDefault security rules:"); printSecurityRule(sb, sgni.securityRuleAssociations().defaultSecurityRules()); } System.out.println(sb.toString()); } private static void printSecurityRule(StringBuilder sb, List<SecurityRuleInner> rules) { for (SecurityRuleInner rule : rules) { sb.append("\n\t\t\tName: ").append(rule.name()) .append("\n\t\t\tDirection: ").append(rule.direction()) .append("\n\t\t\tAccess: ").append(rule.access()) .append("\n\t\t\tPriority: ").append(rule.priority()) .append("\n\t\t\tSource address prefix: ").append(rule.sourceAddressPrefix()) .append("\n\t\t\tSource port range: ").append(rule.sourcePortRange()) .append("\n\t\t\tDestination address prefix: ").append(rule.destinationAddressPrefix()) .append("\n\t\t\tDestination port range: ").append(rule.destinationPortRange()) .append("\n\t\t\tProtocol: ").append(rule.protocol()) .append("\n\t\t\tDescription: ").append(rule.description()) .append("\n\t\t\tProvisioning state: ").append(rule.provisioningState()); } } /** * Print next hop info. * * @param resource an availability set */ public static void print(NextHop resource) { System.out.println(new StringBuilder("Next hop: ") .append("Next hop type: ").append(resource.nextHopType()) .append("\n\tNext hop ip address: ").append(resource.nextHopIpAddress()) .append("\n\tRoute table id: ").append(resource.routeTableId()) .toString()); } /** * Print container group info. * * @param resource a container group */ public static void print(ContainerGroup resource) { StringBuilder info = new StringBuilder().append("Container Group: ").append(resource.id()) .append("Name: ").append(resource.name()) .append("\n\tResource group: ").append(resource.resourceGroupName()) .append("\n\tRegion: ").append(resource.region()) .append("\n\tTags: ").append(resource.tags()) .append("\n\tOS type: ").append(resource.osType()); if (resource.ipAddress() != null) { info.append("\n\tPublic IP address: ").append(resource.ipAddress()); } if (resource.externalTcpPorts() != null) { info.append("\n\tExternal TCP ports:"); for (int port : resource.externalTcpPorts()) { info.append(" ").append(port); } } if (resource.externalUdpPorts() != null) { info.append("\n\tExternal UDP ports:"); for (int port : resource.externalUdpPorts()) { info.append(" ").append(port); } } if (resource.imageRegistryServers() != null) { info.append("\n\tPrivate Docker image registries:"); for (String server : resource.imageRegistryServers()) { info.append(" ").append(server); } } if (resource.volumes() != null) { info.append("\n\tVolume mapping: "); for (Map.Entry<String, Volume> entry : resource.volumes().entrySet()) { info.append("\n\t\tName: ").append(entry.getKey()).append(" -> ") .append(entry.getValue().azureFile() != null ? entry.getValue().azureFile().shareName() : "empty direcory volume"); } } if (resource.containers() != null) { info.append("\n\tContainer instances: "); for (Map.Entry<String, Container> entry : resource.containers().entrySet()) { Container container = entry.getValue(); info.append("\n\t\tName: ").append(entry.getKey()).append(" -> ").append(container.image()); info.append("\n\t\t\tResources: "); info.append(container.resources().requests().cpu()).append("CPUs "); info.append(container.resources().requests().memoryInGB()).append("GB"); info.append("\n\t\t\tPorts:"); for (ContainerPort port : container.ports()) { info.append(" ").append(port.port()); } if (container.volumeMounts() != null) { info.append("\n\t\t\tVolume mounts:"); for (VolumeMount volumeMount : container.volumeMounts()) { info.append(" ").append(volumeMount.name()).append("->").append(volumeMount.mountPath()); } } if (container.command() != null) { info.append("\n\t\t\tStart commands:"); for (String command : container.command()) { info.append("\n\t\t\t\t").append(command); } } if (container.environmentVariables() != null) { info.append("\n\t\t\tENV vars:"); for (EnvironmentVariable envVar : container.environmentVariables()) { info.append("\n\t\t\t\t").append(envVar.name()).append("=").append(envVar.value()); } } } } System.out.println(info.toString()); } /** * Print event hub namespace. * * @param resource a virtual machine */ public static void print(EventHubNamespace resource) { StringBuilder info = new StringBuilder(); info.append("Eventhub Namespace: ").append(resource.id()) .append("\n\tName: ").append(resource.name()) .append("\n\tRegion: ").append(resource.region()) .append("\n\tTags: ").append(resource.tags()) .append("\n\tAzureInsightMetricId: ").append(resource.azureInsightMetricId()) .append("\n\tIsAutoScale enabled: ").append(resource.isAutoScaleEnabled()) .append("\n\tServiceBus endpoint: ").append(resource.serviceBusEndpoint()) .append("\n\tThroughPut upper limit: ").append(resource.throughputUnitsUpperLimit()) .append("\n\tCurrent ThroughPut: ").append(resource.currentThroughputUnits()) .append("\n\tCreated time: ").append(resource.createdAt()) .append("\n\tUpdated time: ").append(resource.updatedAt()); System.out.println(info.toString()); } /** * Print event hub. * * @param resource event hub */ public static void print(EventHub resource) { StringBuilder info = new StringBuilder(); info.append("Eventhub: ").append(resource.id()) .append("\n\tName: ").append(resource.name()) .append("\n\tNamespace resource group: ").append(resource.namespaceResourceGroupName()) .append("\n\tNamespace: ").append(resource.namespaceName()) .append("\n\tIs data capture enabled: ").append(resource.isDataCaptureEnabled()) .append("\n\tPartition ids: ").append(resource.partitionIds()); if (resource.isDataCaptureEnabled()) { info.append("\n\t\t\tData capture window size in MB: ").append(resource.dataCaptureWindowSizeInMB()); info.append("\n\t\t\tData capture window size in seconds: ").append(resource.dataCaptureWindowSizeInSeconds()); if (resource.captureDestination() != null) { info.append("\n\t\t\tData capture storage account: ").append(resource.captureDestination().storageAccountResourceId()); info.append("\n\t\t\tData capture storage container: ").append(resource.captureDestination().blobContainer()); } } System.out.println(info.toString()); } /** * Print event hub namespace recovery pairing. * * @param resource event hub namespace disaster recovery pairing */ public static void print(EventHubDisasterRecoveryPairing resource) { StringBuilder info = new StringBuilder(); info.append("DisasterRecoveryPairing: ").append(resource.id()) .append("\n\tName: ").append(resource.name()) .append("\n\tPrimary namespace resource group name: ").append(resource.primaryNamespaceResourceGroupName()) .append("\n\tPrimary namespace name: ").append(resource.primaryNamespaceName()) .append("\n\tSecondary namespace: ").append(resource.secondaryNamespaceId()) .append("\n\tNamespace role: ").append(resource.namespaceRole()); System.out.println(info.toString()); } /** * Print event hub namespace recovery pairing auth rules. * * @param resource event hub namespace disaster recovery pairing auth rule */ public static void print(DisasterRecoveryPairingAuthorizationRule resource) { StringBuilder info = new StringBuilder(); info.append("DisasterRecoveryPairing auth rule: ").append(resource.name()); List<String> rightsStr = new ArrayList<>(); for (AccessRights rights : resource.rights()) { rightsStr.add(rights.toString()); } info.append("\n\tRights: ").append(rightsStr); System.out.println(info.toString()); } /** * Print event hub namespace recovery pairing auth rule key. * * @param resource event hub namespace disaster recovery pairing auth rule key */ public static void print(DisasterRecoveryPairingAuthorizationKey resource) { StringBuilder info = new StringBuilder(); info.append("DisasterRecoveryPairing auth key: ") .append("\n\t Alias primary connection string: ").append(resource.aliasPrimaryConnectionString()) .append("\n\t Alias secondary connection string: ").append(resource.aliasSecondaryConnectionString()) .append("\n\t Primary key: ").append(resource.primaryKey()) .append("\n\t Secondary key: ").append(resource.secondaryKey()) .append("\n\t Primary connection string: ").append(resource.primaryConnectionString()) .append("\n\t Secondary connection string: ").append(resource.secondaryConnectionString()); System.out.println(info.toString()); } /** * Print event hub consumer group. * * @param resource event hub consumer group */ public static void print(EventHubConsumerGroup resource) { StringBuilder info = new StringBuilder(); info.append("Event hub consumer group: ").append(resource.id()) .append("\n\tName: ").append(resource.name()) .append("\n\tNamespace resource group: ").append(resource.namespaceResourceGroupName()) .append("\n\tNamespace: ").append(resource.namespaceName()) .append("\n\tEvent hub name: ").append(resource.eventHubName()) .append("\n\tUser metadata: ").append(resource.userMetadata()); System.out.println(info.toString()); } /** * Print Diagnostic Setting. * * @param resource Diagnostic Setting instance */ public static void print(DiagnosticSetting resource) { StringBuilder info = new StringBuilder("Diagnostic Setting: ") .append("\n\tId: ").append(resource.id()) .append("\n\tAssociated resource Id: ").append(resource.resourceId()) .append("\n\tName: ").append(resource.name()) .append("\n\tStorage Account Id: ").append(resource.storageAccountId()) .append("\n\tEventHub Namespace Autorization Rule Id: ").append(resource.eventHubAuthorizationRuleId()) .append("\n\tEventHub name: ").append(resource.eventHubName()) .append("\n\tLog Analytics workspace Id: ").append(resource.workspaceId()); if (resource.logs() != null && !resource.logs().isEmpty()) { info.append("\n\tLog Settings: "); for (LogSettings ls : resource.logs()) { info.append("\n\t\tCategory: ").append(ls.category()); info.append("\n\t\tRetention policy: "); if (ls.retentionPolicy() != null) { info.append(ls.retentionPolicy().days() + " days"); } else { info.append("NONE"); } } } if (resource.metrics() != null && !resource.metrics().isEmpty()) { info.append("\n\tMetric Settings: "); for (MetricSettings ls : resource.metrics()) { info.append("\n\t\tCategory: ").append(ls.category()); info.append("\n\t\tTimegrain: ").append(ls.timeGrain()); info.append("\n\t\tRetention policy: "); if (ls.retentionPolicy() != null) { info.append(ls.retentionPolicy().days() + " days"); } else { info.append("NONE"); } } } System.out.println(info.toString()); } /** * Print Action group settings. * * @param actionGroup action group instance */ public static void print(ActionGroup actionGroup) { StringBuilder info = new StringBuilder("Action Group: ") .append("\n\tId: ").append(actionGroup.id()) .append("\n\tName: ").append(actionGroup.name()) .append("\n\tShort Name: ").append(actionGroup.shortName()); if (actionGroup.emailReceivers() != null && !actionGroup.emailReceivers().isEmpty()) { info.append("\n\tEmail receivers: "); for (EmailReceiver er : actionGroup.emailReceivers()) { info.append("\n\t\tName: ").append(er.name()); info.append("\n\t\tEMail: ").append(er.emailAddress()); info.append("\n\t\tStatus: ").append(er.status()); info.append("\n\t\t==="); } } if (actionGroup.smsReceivers() != null && !actionGroup.smsReceivers().isEmpty()) { info.append("\n\tSMS text message receivers: "); for (SmsReceiver er : actionGroup.smsReceivers()) { info.append("\n\t\tName: ").append(er.name()); info.append("\n\t\tPhone: ").append(er.countryCode() + er.phoneNumber()); info.append("\n\t\tStatus: ").append(er.status()); info.append("\n\t\t==="); } } if (actionGroup.webhookReceivers() != null && !actionGroup.webhookReceivers().isEmpty()) { info.append("\n\tWebhook receivers: "); for (WebhookReceiver er : actionGroup.webhookReceivers()) { info.append("\n\t\tName: ").append(er.name()); info.append("\n\t\tURI: ").append(er.serviceUri()); info.append("\n\t\t==="); } } if (actionGroup.pushNotificationReceivers() != null && !actionGroup.pushNotificationReceivers().isEmpty()) { info.append("\n\tApp Push Notification receivers: "); for (AzureAppPushReceiver er : actionGroup.pushNotificationReceivers()) { info.append("\n\t\tName: ").append(er.name()); info.append("\n\t\tEmail: ").append(er.emailAddress()); info.append("\n\t\t==="); } } if (actionGroup.voiceReceivers() != null && !actionGroup.voiceReceivers().isEmpty()) { info.append("\n\tVoice Message receivers: "); for (VoiceReceiver er : actionGroup.voiceReceivers()) { info.append("\n\t\tName: ").append(er.name()); info.append("\n\t\tPhone: ").append(er.countryCode() + er.phoneNumber()); info.append("\n\t\t==="); } } if (actionGroup.automationRunbookReceivers() != null && !actionGroup.automationRunbookReceivers().isEmpty()) { info.append("\n\tAutomation Runbook receivers: "); for (AutomationRunbookReceiver er : actionGroup.automationRunbookReceivers()) { info.append("\n\t\tName: ").append(er.name()); info.append("\n\t\tRunbook Name: ").append(er.runbookName()); info.append("\n\t\tAccount Id: ").append(er.automationAccountId()); info.append("\n\t\tIs Global: ").append(er.isGlobalRunbook()); info.append("\n\t\tService URI: ").append(er.serviceUri()); info.append("\n\t\tWebhook resource Id: ").append(er.webhookResourceId()); info.append("\n\t\t==="); } } if (actionGroup.azureFunctionReceivers() != null && !actionGroup.azureFunctionReceivers().isEmpty()) { info.append("\n\tAzure Functions receivers: "); for (AzureFunctionReceiver er : actionGroup.azureFunctionReceivers()) { info.append("\n\t\tName: ").append(er.name()); info.append("\n\t\tFunction Name: ").append(er.functionName()); info.append("\n\t\tFunction App Resource Id: ").append(er.functionAppResourceId()); info.append("\n\t\tFunction Trigger URI: ").append(er.httpTriggerUrl()); info.append("\n\t\t==="); } } if (actionGroup.logicAppReceivers() != null && !actionGroup.logicAppReceivers().isEmpty()) { info.append("\n\tLogic App receivers: "); for (LogicAppReceiver er : actionGroup.logicAppReceivers()) { info.append("\n\t\tName: ").append(er.name()); info.append("\n\t\tResource Id: ").append(er.resourceId()); info.append("\n\t\tCallback URL: ").append(er.callbackUrl()); info.append("\n\t\t==="); } } if (actionGroup.itsmReceivers() != null && !actionGroup.itsmReceivers().isEmpty()) { info.append("\n\tITSM receivers: "); for (ItsmReceiver er : actionGroup.itsmReceivers()) { info.append("\n\t\tName: ").append(er.name()); info.append("\n\t\tWorkspace Id: ").append(er.workspaceId()); info.append("\n\t\tConnection Id: ").append(er.connectionId()); info.append("\n\t\tRegion: ").append(er.region()); info.append("\n\t\tTicket Configuration: ").append(er.ticketConfiguration()); info.append("\n\t\t==="); } } System.out.println(info.toString()); } /** * Print activity log alert settings. * * @param activityLogAlert activity log instance */ public static void print(ActivityLogAlert activityLogAlert) { StringBuilder info = new StringBuilder("Activity Log Alert: ") .append("\n\tId: ").append(activityLogAlert.id()) .append("\n\tName: ").append(activityLogAlert.name()) .append("\n\tDescription: ").append(activityLogAlert.description()) .append("\n\tIs Enabled: ").append(activityLogAlert.enabled()); if (activityLogAlert.scopes() != null && !activityLogAlert.scopes().isEmpty()) { info.append("\n\tScopes: "); for (String er : activityLogAlert.scopes()) { info.append("\n\t\tId: ").append(er); } } if (activityLogAlert.actionGroupIds() != null && !activityLogAlert.actionGroupIds().isEmpty()) { info.append("\n\tAction Groups: "); for (String er : activityLogAlert.actionGroupIds()) { info.append("\n\t\tAction Group Id: ").append(er); } } if (activityLogAlert.equalsConditions() != null && !activityLogAlert.equalsConditions().isEmpty()) { info.append("\n\tAlert conditions (when all of is true): "); for (Map.Entry<String, String> er : activityLogAlert.equalsConditions().entrySet()) { info.append("\n\t\t'").append(er.getKey()).append("' equals '").append(er.getValue()).append("'"); } } System.out.println(info.toString()); } /** * Print metric alert settings. * * @param metricAlert metric alert instance */ public static void print(MetricAlert metricAlert) { StringBuilder info = new StringBuilder("Metric Alert: ") .append("\n\tId: ").append(metricAlert.id()) .append("\n\tName: ").append(metricAlert.name()) .append("\n\tDescription: ").append(metricAlert.description()) .append("\n\tIs Enabled: ").append(metricAlert.enabled()) .append("\n\tIs Auto Mitigated: ").append(metricAlert.autoMitigate()) .append("\n\tSeverity: ").append(metricAlert.severity()) .append("\n\tWindow Size: ").append(metricAlert.windowSize()) .append("\n\tEvaluation Frequency: ").append(metricAlert.evaluationFrequency()); if (metricAlert.scopes() != null && !metricAlert.scopes().isEmpty()) { info.append("\n\tScopes: "); for (String er : metricAlert.scopes()) { info.append("\n\t\tId: ").append(er); } } if (metricAlert.actionGroupIds() != null && !metricAlert.actionGroupIds().isEmpty()) { info.append("\n\tAction Groups: "); for (String er : metricAlert.actionGroupIds()) { info.append("\n\t\tAction Group Id: ").append(er); } } if (metricAlert.alertCriterias() != null && !metricAlert.alertCriterias().isEmpty()) { info.append("\n\tAlert conditions (when all of is true): "); for (Map.Entry<String, MetricAlertCondition> er : metricAlert.alertCriterias().entrySet()) { MetricAlertCondition alertCondition = er.getValue(); info.append("\n\t\tCondition name: ").append(er.getKey()) .append("\n\t\tSignal name: ").append(alertCondition.metricName()) .append("\n\t\tMetric Namespace: ").append(alertCondition.metricNamespace()) .append("\n\t\tOperator: ").append(alertCondition.condition()) .append("\n\t\tThreshold: ").append(alertCondition.threshold()) .append("\n\t\tTime Aggregation: ").append(alertCondition.timeAggregation()); if (alertCondition.dimensions() != null && !alertCondition.dimensions().isEmpty()) { for (MetricDimension dimon : alertCondition.dimensions()) { info.append("\n\t\tDimension Filter: ").append("Name [").append(dimon.name()).append("] operator [Include] values["); for (String vals : dimon.values()) { info.append(vals).append(", "); } info.append("]"); } } } } System.out.println(info.toString()); } /** * Print spring service settings. * * @param springService spring service instance */ public static void print(SpringService springService) { StringBuilder info = new StringBuilder("Spring Service: ") .append("\n\tId: ").append(springService.id()) .append("\n\tName: ").append(springService.name()) .append("\n\tResource Group: ").append(springService.resourceGroupName()) .append("\n\tRegion: ").append(springService.region()) .append("\n\tTags: ").append(springService.tags()); ConfigServerProperties serverProperties = springService.getServerProperties(); if (serverProperties != null && serverProperties.provisioningState() != null && serverProperties.provisioningState().equals(ConfigServerState.SUCCEEDED) && serverProperties.configServer() != null) { info.append("\n\tProperties: "); if (serverProperties.configServer().gitProperty() != null) { info.append("\n\t\tGit: ").append(serverProperties.configServer().gitProperty().uri()); } } if (springService.sku() != null) { info.append("\n\tSku: ") .append("\n\t\tName: ").append(springService.sku().name()) .append("\n\t\tTier: ").append(springService.sku().tier()) .append("\n\t\tCapacity: ").append(springService.sku().capacity()); } MonitoringSettingProperties monitoringSettingProperties = springService.getMonitoringSetting(); if (monitoringSettingProperties != null && monitoringSettingProperties.provisioningState() != null && monitoringSettingProperties.provisioningState().equals(MonitoringSettingState.SUCCEEDED)) { info.append("\n\tTrace: ") .append("\n\t\tEnabled: ").append(monitoringSettingProperties.traceEnabled()) .append("\n\t\tApp Insight Instrumentation Key: ").append(monitoringSettingProperties.appInsightsInstrumentationKey()); } System.out.println(info.toString()); } /** * Print spring app settings. * * @param springApp spring app instance */ public static void print(SpringApp springApp) { StringBuilder info = new StringBuilder("Spring Service: ") .append("\n\tId: ").append(springApp.id()) .append("\n\tName: ").append(springApp.name()) .append("\n\tCreated Time: ").append(springApp.createdTime()) .append("\n\tPublic Endpoint: ").append(springApp.isPublic()) .append("\n\tUrl: ").append(springApp.url()) .append("\n\tHttps Only: ").append(springApp.isHttpsOnly()) .append("\n\tFully Qualified Domain Name: ").append(springApp.fqdn()) .append("\n\tActive Deployment Name: ").append(springApp.activeDeploymentName()); if (springApp.temporaryDisk() != null) { info.append("\n\tTemporary Disk:") .append("\n\t\tSize In GB: ").append(springApp.temporaryDisk().sizeInGB()) .append("\n\t\tMount Path: ").append(springApp.temporaryDisk().mountPath()); } if (springApp.persistentDisk() != null) { info.append("\n\tPersistent Disk:") .append("\n\t\tSize In GB: ").append(springApp.persistentDisk().sizeInGB()) .append("\n\t\tMount Path: ").append(springApp.persistentDisk().mountPath()); } if (springApp.identity() != null) { info.append("\n\tIdentity:") .append("\n\t\tType: ").append(springApp.identity().type()) .append("\n\t\tPrincipal Id: ").append(springApp.identity().principalId()) .append("\n\t\tTenant Id: ").append(springApp.identity().tenantId()); } System.out.println(info.toString()); } /** * Sends a GET request to target URL. * <p> * Retry logic tuned for AppService. * The method does not handle 301 redirect. * * @param urlString the target URL. * @return Content of the HTTP response. */ public static String sendGetRequest(String urlString) { ClientLogger logger = new ClientLogger(Utils.class); try { Mono<Response<Flux<ByteBuffer>>> response = HTTP_CLIENT.getString(getHost(urlString), getPathAndQuery(urlString)) .retryWhen(Retry .fixedDelay(5, Duration.ofSeconds(30)) .filter(t -> { boolean retry = false; if (t instanceof TimeoutException) { retry = true; } else if (t instanceof HttpResponseException && ((HttpResponseException) t).getResponse().getStatusCode() == 503) { retry = true; } if (retry) { logger.info("retry GET request to {}", urlString); } return retry; })); Response<String> ret = stringResponse(response).block(); return ret == null ? null : ret.getValue(); } catch (MalformedURLException e) { logger.logThrowableAsError(e); return null; } } /** * Sends a POST request to target URL. * <p> * Retry logic tuned for AppService. * * @param urlString the target URL. * @param body the request body. * @return Content of the HTTP response. * */ public static String sendPostRequest(String urlString, String body) { ClientLogger logger = new ClientLogger(Utils.class); try { Mono<Response<String>> response = stringResponse(HTTP_CLIENT.postString(getHost(urlString), getPathAndQuery(urlString), body)) .retryWhen(Retry .fixedDelay(5, Duration.ofSeconds(30)) .filter(t -> { boolean retry = false; if (t instanceof TimeoutException) { retry = true; } if (retry) { logger.info("retry POST request to {}", urlString); } return retry; })); Response<String> ret = response.block(); return ret == null ? null : ret.getValue(); } catch (Exception e) { logger.logThrowableAsError(e); return null; } } private static Mono<Response<String>> stringResponse(Mono<Response<Flux<ByteBuffer>>> responseMono) { return responseMono.flatMap(response -> FluxUtil.collectBytesInByteBufferStream(response.getValue()) .map(bytes -> new String(bytes, StandardCharsets.UTF_8)) .map(str -> new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), str))); } private static String getHost(String urlString) throws MalformedURLException { URL url = new URL(urlString); String protocol = url.getProtocol(); String host = url.getAuthority(); return protocol + ": } private static String getPathAndQuery(String urlString) throws MalformedURLException { URL url = new URL(urlString); String path = url.getPath(); String query = url.getQuery(); if (query != null && !query.isEmpty()) { path = path + "?" + query; } return path; } private static final WebAppTestClient HTTP_CLIENT = RestProxy.create( WebAppTestClient.class, new HttpPipelineBuilder() .policies( new HttpLoggingPolicy(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BASIC)), new RetryPolicy("Retry-After", ChronoUnit.SECONDS)) .build()); @Host("{$host}") @ServiceInterface(name = "WebAppTestClient") private interface WebAppTestClient { @Get("{path}") @ExpectedResponses({200, 400, 404}) Mono<Response<Flux<ByteBuffer>>> getString(@HostParam("$host") String host, @PathParam(value = "path", encoded = true) String path); @Post("{path}") @ExpectedResponses({200, 400, 404}) Mono<Response<Flux<ByteBuffer>>> postString(@HostParam("$host") String host, @PathParam(value = "path", encoded = true) String path, @BodyParam("text/plain") String body); } public static <T> int getSize(Iterable<T> iterable) { int res = 0; Iterator<T> iterator = iterable.iterator(); while (iterator.hasNext()) { iterator.next(); } return res; } }
class Utils { /** @return a generated password */ public static String password() { String password = new ResourceManagerUtils.InternalRuntimeContext().randomResourceName("Pa5$", 12); System.out.printf("Password: %s%n", password); return password; } /** * Creates a randomized resource name. * Please provider your own implementation, or avoid using the method, if code is to be used in production. * * @param azure the AzureResourceManager instance. * @param prefix the prefix to the name. * @param maxLen the max length of the name. * @return the randomized resource name. */ public static String randomResourceName(AzureResourceManager azure, String prefix, int maxLen) { return azure.resourceGroups().manager().internalContext().randomResourceName(prefix, maxLen); } /** * Generates the specified number of random resource names with the same prefix. * Please provider your own implementation, or avoid using the method, if code is to be used in production. * * @param azure the AzureResourceManager instance. * @param prefix the prefix to be used if possible * @param maxLen the maximum length for the random generated name * @param count the number of names to generate * @return the randomized resource names. */ public static String[] randomResourceNames(AzureResourceManager azure, String prefix, int maxLen, int count) { String[] names = new String[count]; for (int i = 0; i < count; i++) { names[i] = randomResourceName(azure, prefix, maxLen); } return names; } /** * Creates a random UUID. * Please provider your own implementation, or avoid using the method, if code is to be used in production. * * @param azure the AzureResourceManager instance. * @return the random UUID. */ public static String randomUuid(AzureResourceManager azure) { return azure.resourceGroups().manager().internalContext().randomUuid(); } /** * Print resource group info. * * @param resource a resource group */ public static void print(ResourceGroup resource) { StringBuilder info = new StringBuilder(); info.append("Resource Group: ").append(resource.id()) .append("\n\tName: ").append(resource.name()) .append("\n\tRegion: ").append(resource.region()) .append("\n\tTags: ").append(resource.tags()); System.out.println(info.toString()); } /** * Print User Assigned MSI info. * * @param resource a User Assigned MSI */ public static void print(Identity resource) { StringBuilder info = new StringBuilder(); info.append("Resource Group: ").append(resource.id()) .append("\n\tName: ").append(resource.name()) .append("\n\tRegion: ").append(resource.region()) .append("\n\tTags: ").append(resource.tags()) .append("\n\tService Principal Id: ").append(resource.principalId()) .append("\n\tClient Id: ").append(resource.clientId()) .append("\n\tTenant Id: ").append(resource.tenantId()); System.out.println(info.toString()); } /** * Print virtual machine info. * * @param resource a virtual machine */ public static void print(VirtualMachine resource) { StringBuilder storageProfile = new StringBuilder().append("\n\tStorageProfile: "); if (resource.storageProfile().imageReference() != null) { storageProfile.append("\n\t\tImageReference:"); storageProfile.append("\n\t\t\tPublisher: ").append(resource.storageProfile().imageReference().publisher()); storageProfile.append("\n\t\t\tOffer: ").append(resource.storageProfile().imageReference().offer()); storageProfile.append("\n\t\t\tSKU: ").append(resource.storageProfile().imageReference().sku()); storageProfile.append("\n\t\t\tVersion: ").append(resource.storageProfile().imageReference().version()); } if (resource.storageProfile().osDisk() != null) { storageProfile.append("\n\t\tOSDisk:"); storageProfile.append("\n\t\t\tOSType: ").append(resource.storageProfile().osDisk().osType()); storageProfile.append("\n\t\t\tName: ").append(resource.storageProfile().osDisk().name()); storageProfile.append("\n\t\t\tCaching: ").append(resource.storageProfile().osDisk().caching()); storageProfile.append("\n\t\t\tCreateOption: ").append(resource.storageProfile().osDisk().createOption()); storageProfile.append("\n\t\t\tDiskSizeGB: ").append(resource.storageProfile().osDisk().diskSizeGB()); if (resource.storageProfile().osDisk().image() != null) { storageProfile.append("\n\t\t\tImage Uri: ").append(resource.storageProfile().osDisk().image().uri()); } if (resource.storageProfile().osDisk().vhd() != null) { storageProfile.append("\n\t\t\tVhd Uri: ").append(resource.storageProfile().osDisk().vhd().uri()); } if (resource.storageProfile().osDisk().encryptionSettings() != null) { storageProfile.append("\n\t\t\tEncryptionSettings: "); storageProfile.append("\n\t\t\t\tEnabled: ").append(resource.storageProfile().osDisk().encryptionSettings().enabled()); storageProfile.append("\n\t\t\t\tDiskEncryptionKey Uri: ").append(resource .storageProfile() .osDisk() .encryptionSettings() .diskEncryptionKey().secretUrl()); storageProfile.append("\n\t\t\t\tKeyEncryptionKey Uri: ").append(resource .storageProfile() .osDisk() .encryptionSettings() .keyEncryptionKey().keyUrl()); } } if (resource.storageProfile().dataDisks() != null) { int i = 0; for (DataDisk disk : resource.storageProfile().dataDisks()) { storageProfile.append("\n\t\tDataDisk: storageProfile.append("\n\t\t\tName: ").append(disk.name()); storageProfile.append("\n\t\t\tCaching: ").append(disk.caching()); storageProfile.append("\n\t\t\tCreateOption: ").append(disk.createOption()); storageProfile.append("\n\t\t\tDiskSizeGB: ").append(disk.diskSizeGB()); storageProfile.append("\n\t\t\tLun: ").append(disk.lun()); if (resource.isManagedDiskEnabled()) { if (disk.managedDisk() != null) { storageProfile.append("\n\t\t\tManaged Disk Id: ").append(disk.managedDisk().id()); } } else { if (disk.vhd().uri() != null) { storageProfile.append("\n\t\t\tVhd Uri: ").append(disk.vhd().uri()); } } if (disk.image() != null) { storageProfile.append("\n\t\t\tImage Uri: ").append(disk.image().uri()); } } } StringBuilder osProfile = new StringBuilder().append("\n\tOSProfile: "); if (resource.osProfile() != null) { osProfile.append("\n\t\tComputerName:").append(resource.osProfile().computerName()); if (resource.osProfile().windowsConfiguration() != null) { osProfile.append("\n\t\t\tWindowsConfiguration: "); osProfile.append("\n\t\t\t\tProvisionVMAgent: ") .append(resource.osProfile().windowsConfiguration().provisionVMAgent()); osProfile.append("\n\t\t\t\tEnableAutomaticUpdates: ") .append(resource.osProfile().windowsConfiguration().enableAutomaticUpdates()); osProfile.append("\n\t\t\t\tTimeZone: ") .append(resource.osProfile().windowsConfiguration().timeZone()); } if (resource.osProfile().linuxConfiguration() != null) { osProfile.append("\n\t\t\tLinuxConfiguration: "); osProfile.append("\n\t\t\t\tDisablePasswordAuthentication: ") .append(resource.osProfile().linuxConfiguration().disablePasswordAuthentication()); } } else { osProfile.append("null"); } StringBuilder networkProfile = new StringBuilder().append("\n\tNetworkProfile: "); for (String networkInterfaceId : resource.networkInterfaceIds()) { networkProfile.append("\n\t\tId:").append(networkInterfaceId); } StringBuilder extensions = new StringBuilder().append("\n\tExtensions: "); for (Map.Entry<String, VirtualMachineExtension> extensionEntry : resource.listExtensions().entrySet()) { VirtualMachineExtension extension = extensionEntry.getValue(); extensions.append("\n\t\tExtension: ").append(extension.id()) .append("\n\t\t\tName: ").append(extension.name()) .append("\n\t\t\tTags: ").append(extension.tags()) .append("\n\t\t\tProvisioningState: ").append(extension.provisioningState()) .append("\n\t\t\tAuto upgrade minor version enabled: ").append(extension.autoUpgradeMinorVersionEnabled()) .append("\n\t\t\tPublisher: ").append(extension.publisherName()) .append("\n\t\t\tType: ").append(extension.typeName()) .append("\n\t\t\tVersion: ").append(extension.versionName()) .append("\n\t\t\tPublic Settings: ").append(extension.publicSettingsAsJsonString()); } StringBuilder msi = new StringBuilder().append("\n\tMSI: "); msi.append("\n\t\t\tMSI enabled:").append(resource.isManagedServiceIdentityEnabled()); msi.append("\n\t\t\tSystem Assigned MSI Active Directory Service Principal Id:").append(resource.systemAssignedManagedServiceIdentityPrincipalId()); msi.append("\n\t\t\tSystem Assigned MSI Active Directory Tenant Id:").append(resource.systemAssignedManagedServiceIdentityTenantId()); StringBuilder zones = new StringBuilder().append("\n\tZones: "); zones.append(resource.availabilityZones()); System.out.println(new StringBuilder().append("Virtual Machine: ").append(resource.id()) .append("Name: ").append(resource.name()) .append("\n\tResource group: ").append(resource.resourceGroupName()) .append("\n\tRegion: ").append(resource.region()) .append("\n\tTags: ").append(resource.tags()) .append("\n\tHardwareProfile: ") .append("\n\t\tSize: ").append(resource.size()) .append(storageProfile) .append(osProfile) .append(networkProfile) .append(extensions) .append(msi) .append(zones) .toString()); } /** * Print availability set info. * * @param resource an availability set */ public static void print(AvailabilitySet resource) { System.out.println(new StringBuilder().append("Availability Set: ").append(resource.id()) .append("Name: ").append(resource.name()) .append("\n\tResource group: ").append(resource.resourceGroupName()) .append("\n\tRegion: ").append(resource.region()) .append("\n\tTags: ").append(resource.tags()) .append("\n\tFault domain count: ").append(resource.faultDomainCount()) .append("\n\tUpdate domain count: ").append(resource.updateDomainCount()) .toString()); } /** * Print network info. * * @param resource a network * @throws ManagementException Cloud errors */ public static void print(Network resource) { StringBuilder info = new StringBuilder(); info.append("Network: ").append(resource.id()) .append("Name: ").append(resource.name()) .append("\n\tResource group: ").append(resource.resourceGroupName()) .append("\n\tRegion: ").append(resource.region()) .append("\n\tTags: ").append(resource.tags()) .append("\n\tAddress spaces: ").append(resource.addressSpaces()) .append("\n\tDNS server IPs: ").append(resource.dnsServerIPs()); for (Subnet subnet : resource.subnets().values()) { info.append("\n\tSubnet: ").append(subnet.name()) .append("\n\t\tAddress prefix: ").append(subnet.addressPrefix()); NetworkSecurityGroup subnetNsg = subnet.getNetworkSecurityGroup(); if (subnetNsg != null) { info.append("\n\t\tNetwork security group ID: ").append(subnetNsg.id()); } RouteTable routeTable = subnet.getRouteTable(); if (routeTable != null) { info.append("\n\tRoute table ID: ").append(routeTable.id()); } Map<ServiceEndpointType, List<Region>> services = subnet.servicesWithAccess(); if (services.size() > 0) { info.append("\n\tServices with access"); for (Map.Entry<ServiceEndpointType, List<Region>> service : services.entrySet()) { info.append("\n\t\tService: ") .append(service.getKey()) .append(" Regions: " + service.getValue() + ""); } } } for (NetworkPeering peering : resource.peerings().list()) { info.append("\n\tPeering: ").append(peering.name()) .append("\n\t\tRemote network ID: ").append(peering.remoteNetworkId()) .append("\n\t\tPeering state: ").append(peering.state()) .append("\n\t\tIs traffic forwarded from remote network allowed? ").append(peering.isTrafficForwardingFromRemoteNetworkAllowed()) .append("\n\t\tGateway use: ").append(peering.gatewayUse()); } System.out.println(info.toString()); } /** * Print network interface. * * @param resource a network interface */ public static void print(NetworkInterface resource) { StringBuilder info = new StringBuilder(); info.append("NetworkInterface: ").append(resource.id()) .append("Name: ").append(resource.name()) .append("\n\tResource group: ").append(resource.resourceGroupName()) .append("\n\tRegion: ").append(resource.region()) .append("\n\tTags: ").append(resource.tags()) .append("\n\tInternal DNS name label: ").append(resource.internalDnsNameLabel()) .append("\n\tInternal FQDN: ").append(resource.internalFqdn()) .append("\n\tInternal domain name suffix: ").append(resource.internalDomainNameSuffix()) .append("\n\tNetwork security group: ").append(resource.networkSecurityGroupId()) .append("\n\tApplied DNS servers: ").append(resource.appliedDnsServers().toString()) .append("\n\tDNS server IPs: "); for (String dnsServerIp : resource.dnsServers()) { info.append("\n\t\t").append(dnsServerIp); } info.append("\n\tIP forwarding enabled? ").append(resource.isIPForwardingEnabled()) .append("\n\tAccelerated networking enabled? ").append(resource.isAcceleratedNetworkingEnabled()) .append("\n\tMAC Address:").append(resource.macAddress()) .append("\n\tPrivate IP:").append(resource.primaryPrivateIP()) .append("\n\tPrivate allocation method:").append(resource.primaryPrivateIpAllocationMethod()) .append("\n\tPrimary virtual network ID: ").append(resource.primaryIPConfiguration().networkId()) .append("\n\tPrimary subnet name:").append(resource.primaryIPConfiguration().subnetName()); System.out.println(info.toString()); } /** * Print network security group. * * @param resource a network security group */ public static void print(NetworkSecurityGroup resource) { StringBuilder info = new StringBuilder(); info.append("NSG: ").append(resource.id()) .append("Name: ").append(resource.name()) .append("\n\tResource group: ").append(resource.resourceGroupName()) .append("\n\tRegion: ").append(resource.region()) .append("\n\tTags: ").append(resource.tags()); for (NetworkSecurityRule rule : resource.securityRules().values()) { info.append("\n\tRule: ").append(rule.name()) .append("\n\t\tAccess: ").append(rule.access()) .append("\n\t\tDirection: ").append(rule.direction()) .append("\n\t\tFrom address: ").append(rule.sourceAddressPrefix()) .append("\n\t\tFrom port range: ").append(rule.sourcePortRange()) .append("\n\t\tTo address: ").append(rule.destinationAddressPrefix()) .append("\n\t\tTo port: ").append(rule.destinationPortRange()) .append("\n\t\tProtocol: ").append(rule.protocol()) .append("\n\t\tPriority: ").append(rule.priority()); } System.out.println(info.toString()); } /** * Print public IP address. * * @param resource a public IP address */ public static void print(PublicIpAddress resource) { System.out.println(new StringBuilder().append("Public IP Address: ").append(resource.id()) .append("Name: ").append(resource.name()) .append("\n\tResource group: ").append(resource.resourceGroupName()) .append("\n\tRegion: ").append(resource.region()) .append("\n\tTags: ").append(resource.tags()) .append("\n\tIP Address: ").append(resource.ipAddress()) .append("\n\tLeaf domain label: ").append(resource.leafDomainLabel()) .append("\n\tFQDN: ").append(resource.fqdn()) .append("\n\tReverse FQDN: ").append(resource.reverseFqdn()) .append("\n\tIdle timeout (minutes): ").append(resource.idleTimeoutInMinutes()) .append("\n\tIP allocation method: ").append(resource.ipAllocationMethod()) .append("\n\tZones: ").append(resource.availabilityZones()) .toString()); } /** * Print a key vault. * * @param vault the key vault resource */ public static void print(Vault vault) { StringBuilder info = new StringBuilder().append("Key Vault: ").append(vault.id()) .append("Name: ").append(vault.name()) .append("\n\tResource group: ").append(vault.resourceGroupName()) .append("\n\tRegion: ").append(vault.region()) .append("\n\tSku: ").append(vault.sku().name()).append(" - ").append(vault.sku().family()) .append("\n\tVault URI: ").append(vault.vaultUri()) .append("\n\tAccess policies: "); for (AccessPolicy accessPolicy : vault.accessPolicies()) { info.append("\n\t\tIdentity:").append(accessPolicy.objectId()); if (accessPolicy.permissions() != null) { if (accessPolicy.permissions().keys() != null) { info.append("\n\t\tKey permissions: ").append(accessPolicy.permissions().keys().stream().map(KeyPermissions::toString).collect(Collectors.joining(", "))); } if (accessPolicy.permissions().secrets() != null) { info.append("\n\t\tSecret permissions: ").append(accessPolicy.permissions().secrets().stream().map(SecretPermissions::toString).collect(Collectors.joining(", "))); } if (accessPolicy.permissions().certificates() != null) { info.append("\n\t\tCertificate permissions: ").append(accessPolicy.permissions().certificates().stream().map(CertificatePermissions::toString).collect(Collectors.joining(", "))); } } } System.out.println(info.toString()); } /** * Print storage account. * * @param storageAccount a storage account */ public static void print(StorageAccount storageAccount) { System.out.println(storageAccount.name() + " created @ " + storageAccount.creationTime()); StringBuilder info = new StringBuilder().append("Storage Account: ").append(storageAccount.id()) .append("Name: ").append(storageAccount.name()) .append("\n\tResource group: ").append(storageAccount.resourceGroupName()) .append("\n\tRegion: ").append(storageAccount.region()) .append("\n\tSKU: ").append(storageAccount.skuType().name().toString()) .append("\n\tAccessTier: ").append(storageAccount.accessTier()) .append("\n\tKind: ").append(storageAccount.kind()); info.append("\n\tNetwork Rule Configuration: ") .append("\n\t\tAllow reading logs from any network: ").append(storageAccount.canReadLogEntriesFromAnyNetwork()) .append("\n\t\tAllow reading metrics from any network: ").append(storageAccount.canReadMetricsFromAnyNetwork()) .append("\n\t\tAllow access from all azure services: ").append(storageAccount.canAccessFromAzureServices()); if (storageAccount.networkSubnetsWithAccess().size() > 0) { info.append("\n\t\tNetwork subnets with access: "); for (String subnetId : storageAccount.networkSubnetsWithAccess()) { info.append("\n\t\t\t").append(subnetId); } } if (storageAccount.ipAddressesWithAccess().size() > 0) { info.append("\n\t\tIP addresses with access: "); for (String ipAddress : storageAccount.ipAddressesWithAccess()) { info.append("\n\t\t\t").append(ipAddress); } } if (storageAccount.ipAddressRangesWithAccess().size() > 0) { info.append("\n\t\tIP address-ranges with access: "); for (String ipAddressRange : storageAccount.ipAddressRangesWithAccess()) { info.append("\n\t\t\t").append(ipAddressRange); } } info.append("\n\t\tTraffic allowed from only HTTPS: ").append(storageAccount.innerModel().enableHttpsTrafficOnly()); info.append("\n\tEncryption status: "); for (Map.Entry<StorageService, StorageAccountEncryptionStatus> eStatus : storageAccount.encryptionStatuses().entrySet()) { info.append("\n\t\t").append(eStatus.getValue().storageService()).append(": ").append(eStatus.getValue().isEnabled() ? "Enabled" : "Disabled"); } System.out.println(info.toString()); } /** * Print storage account keys. * * @param storageAccountKeys a list of storage account keys */ public static void print(List<StorageAccountKey> storageAccountKeys) { for (int i = 0; i < storageAccountKeys.size(); i++) { StorageAccountKey storageAccountKey = storageAccountKeys.get(i); System.out.println("Key (" + i + ") " + storageAccountKey.keyName() + "=" + storageAccountKey.value()); } } /** * Print Redis Cache. * * @param redisCache a Redis cache. */ public static void print(RedisCache redisCache) { StringBuilder redisInfo = new StringBuilder() .append("Redis Cache Name: ").append(redisCache.name()) .append("\n\tResource group: ").append(redisCache.resourceGroupName()) .append("\n\tRegion: ").append(redisCache.region()) .append("\n\tSKU Name: ").append(redisCache.sku().name()) .append("\n\tSKU Family: ").append(redisCache.sku().family()) .append("\n\tHostname: ").append(redisCache.hostname()) .append("\n\tSSL port: ").append(redisCache.sslPort()) .append("\n\tNon-SSL port (6379) enabled: ").append(redisCache.nonSslPort()); if (redisCache.redisConfiguration() != null && !redisCache.redisConfiguration().isEmpty()) { redisInfo.append("\n\tRedis Configuration:"); for (Map.Entry<String, String> redisConfiguration : redisCache.redisConfiguration().entrySet()) { redisInfo.append("\n\t '").append(redisConfiguration.getKey()) .append("' : '").append(redisConfiguration.getValue()).append("'"); } } if (redisCache.isPremium()) { RedisCachePremium premium = redisCache.asPremium(); List<ScheduleEntry> scheduleEntries = premium.listPatchSchedules(); if (scheduleEntries != null && !scheduleEntries.isEmpty()) { redisInfo.append("\n\tRedis Patch Schedule:"); for (ScheduleEntry schedule : scheduleEntries) { redisInfo.append("\n\t\tDay: '").append(schedule.dayOfWeek()) .append("', start at: '").append(schedule.startHourUtc()) .append("', maintenance window: '").append(schedule.maintenanceWindow()) .append("'"); } } } System.out.println(redisInfo.toString()); } /** * Print Redis Cache access keys. * * @param redisAccessKeys a keys for Redis Cache */ public static void print(RedisAccessKeys redisAccessKeys) { StringBuilder redisKeys = new StringBuilder() .append("Redis Access Keys: ") .append("\n\tPrimary Key: '").append(redisAccessKeys.primaryKey()).append("', ") .append("\n\tSecondary Key: '").append(redisAccessKeys.secondaryKey()).append("', "); System.out.println(redisKeys.toString()); } /** * Print load balancer. * * @param resource a load balancer */ public static void print(LoadBalancer resource) { StringBuilder info = new StringBuilder(); info.append("Load balancer: ").append(resource.id()) .append("Name: ").append(resource.name()) .append("\n\tResource group: ").append(resource.resourceGroupName()) .append("\n\tRegion: ").append(resource.region()) .append("\n\tTags: ").append(resource.tags()) .append("\n\tBackends: ").append(resource.backends().keySet().toString()); info.append("\n\tPublic IP address IDs: ") .append(resource.publicIpAddressIds().size()); for (String pipId : resource.publicIpAddressIds()) { info.append("\n\t\tPIP id: ").append(pipId); } info.append("\n\tTCP probes: ") .append(resource.tcpProbes().size()); for (LoadBalancerTcpProbe probe : resource.tcpProbes().values()) { info.append("\n\t\tProbe name: ").append(probe.name()) .append("\n\t\t\tPort: ").append(probe.port()) .append("\n\t\t\tInterval in seconds: ").append(probe.intervalInSeconds()) .append("\n\t\t\tRetries before unhealthy: ").append(probe.numberOfProbes()); info.append("\n\t\t\tReferenced from load balancing rules: ") .append(probe.loadBalancingRules().size()); for (LoadBalancingRule rule : probe.loadBalancingRules().values()) { info.append("\n\t\t\t\tName: ").append(rule.name()); } } info.append("\n\tHTTP probes: ") .append(resource.httpProbes().size()); for (LoadBalancerHttpProbe probe : resource.httpProbes().values()) { info.append("\n\t\tProbe name: ").append(probe.name()) .append("\n\t\t\tPort: ").append(probe.port()) .append("\n\t\t\tInterval in seconds: ").append(probe.intervalInSeconds()) .append("\n\t\t\tRetries before unhealthy: ").append(probe.numberOfProbes()) .append("\n\t\t\tHTTP request path: ").append(probe.requestPath()); info.append("\n\t\t\tReferenced from load balancing rules: ") .append(probe.loadBalancingRules().size()); for (LoadBalancingRule rule : probe.loadBalancingRules().values()) { info.append("\n\t\t\t\tName: ").append(rule.name()); } } info.append("\n\tHTTPS probes: ") .append(resource.httpsProbes().size()); for (LoadBalancerHttpProbe probe : resource.httpsProbes().values()) { info.append("\n\t\tProbe name: ").append(probe.name()) .append("\n\t\t\tPort: ").append(probe.port()) .append("\n\t\t\tInterval in seconds: ").append(probe.intervalInSeconds()) .append("\n\t\t\tRetries before unhealthy: ").append(probe.numberOfProbes()) .append("\n\t\t\tHTTPS request path: ").append(probe.requestPath()); info.append("\n\t\t\tReferenced from load balancing rules: ") .append(probe.loadBalancingRules().size()); for (LoadBalancingRule rule : probe.loadBalancingRules().values()) { info.append("\n\t\t\t\tName: ").append(rule.name()); } } info.append("\n\tLoad balancing rules: ") .append(resource.loadBalancingRules().size()); for (LoadBalancingRule rule : resource.loadBalancingRules().values()) { info.append("\n\t\tLB rule name: ").append(rule.name()) .append("\n\t\t\tProtocol: ").append(rule.protocol()) .append("\n\t\t\tFloating IP enabled? ").append(rule.floatingIPEnabled()) .append("\n\t\t\tIdle timeout in minutes: ").append(rule.idleTimeoutInMinutes()) .append("\n\t\t\tLoad distribution method: ").append(rule.loadDistribution().toString()); LoadBalancerFrontend frontend = rule.frontend(); info.append("\n\t\t\tFrontend: "); if (frontend != null) { info.append(frontend.name()); } else { info.append("(None)"); } info.append("\n\t\t\tFrontend port: ").append(rule.frontendPort()); LoadBalancerBackend backend = rule.backend(); info.append("\n\t\t\tBackend: "); if (backend != null) { info.append(backend.name()); } else { info.append("(None)"); } info.append("\n\t\t\tBackend port: ").append(rule.backendPort()); LoadBalancerProbe probe = rule.probe(); info.append("\n\t\t\tProbe: "); if (probe == null) { info.append("(None)"); } else { info.append(probe.name()).append(" [").append(probe.protocol().toString()).append("]"); } } info.append("\n\tFrontends: ") .append(resource.frontends().size()); for (LoadBalancerFrontend frontend : resource.frontends().values()) { info.append("\n\t\tFrontend name: ").append(frontend.name()) .append("\n\t\t\tInternet facing: ").append(frontend.isPublic()); if (frontend.isPublic()) { info.append("\n\t\t\tPublic IP Address ID: ").append(((LoadBalancerPublicFrontend) frontend).publicIpAddressId()); } else { info.append("\n\t\t\tVirtual network ID: ").append(((LoadBalancerPrivateFrontend) frontend).networkId()) .append("\n\t\t\tSubnet name: ").append(((LoadBalancerPrivateFrontend) frontend).subnetName()) .append("\n\t\t\tPrivate IP address: ").append(((LoadBalancerPrivateFrontend) frontend).privateIpAddress()) .append("\n\t\t\tPrivate IP allocation method: ").append(((LoadBalancerPrivateFrontend) frontend).privateIpAllocationMethod()); } info.append("\n\t\t\tReferenced inbound NAT pools: ") .append(frontend.inboundNatPools().size()); for (LoadBalancerInboundNatPool pool : frontend.inboundNatPools().values()) { info.append("\n\t\t\t\tName: ").append(pool.name()); } info.append("\n\t\t\tReferenced inbound NAT rules: ") .append(frontend.inboundNatRules().size()); for (LoadBalancerInboundNatRule rule : frontend.inboundNatRules().values()) { info.append("\n\t\t\t\tName: ").append(rule.name()); } info.append("\n\t\t\tReferenced load balancing rules: ") .append(frontend.loadBalancingRules().size()); for (LoadBalancingRule rule : frontend.loadBalancingRules().values()) { info.append("\n\t\t\t\tName: ").append(rule.name()); } } info.append("\n\tInbound NAT rules: ") .append(resource.inboundNatRules().size()); for (LoadBalancerInboundNatRule natRule : resource.inboundNatRules().values()) { info.append("\n\t\tInbound NAT rule name: ").append(natRule.name()) .append("\n\t\t\tProtocol: ").append(natRule.protocol().toString()) .append("\n\t\t\tFrontend: ").append(natRule.frontend().name()) .append("\n\t\t\tFrontend port: ").append(natRule.frontendPort()) .append("\n\t\t\tBackend port: ").append(natRule.backendPort()) .append("\n\t\t\tBackend NIC ID: ").append(natRule.backendNetworkInterfaceId()) .append("\n\t\t\tBackend NIC IP config name: ").append(natRule.backendNicIpConfigurationName()) .append("\n\t\t\tFloating IP? ").append(natRule.floatingIPEnabled()) .append("\n\t\t\tIdle timeout in minutes: ").append(natRule.idleTimeoutInMinutes()); } info.append("\n\tInbound NAT pools: ") .append(resource.inboundNatPools().size()); for (LoadBalancerInboundNatPool natPool : resource.inboundNatPools().values()) { info.append("\n\t\tInbound NAT pool name: ").append(natPool.name()) .append("\n\t\t\tProtocol: ").append(natPool.protocol().toString()) .append("\n\t\t\tFrontend: ").append(natPool.frontend().name()) .append("\n\t\t\tFrontend port range: ") .append(natPool.frontendPortRangeStart()) .append("-") .append(natPool.frontendPortRangeEnd()) .append("\n\t\t\tBackend port: ").append(natPool.backendPort()); } info.append("\n\tBackends: ") .append(resource.backends().size()); for (LoadBalancerBackend backend : resource.backends().values()) { info.append("\n\t\tBackend name: ").append(backend.name()); info.append("\n\t\t\tReferenced NICs: ") .append(backend.backendNicIPConfigurationNames().entrySet().size()); for (Map.Entry<String, String> entry : backend.backendNicIPConfigurationNames().entrySet()) { info.append("\n\t\t\t\tNIC ID: ").append(entry.getKey()) .append(" - IP Config: ").append(entry.getValue()); } Set<String> vmIds = backend.getVirtualMachineIds(); info.append("\n\t\t\tReferenced virtual machine ids: ") .append(vmIds.size()); for (String vmId : vmIds) { info.append("\n\t\t\t\tVM ID: ").append(vmId); } info.append("\n\t\t\tReferenced load balancing rules: ") .append(new ArrayList<String>(backend.loadBalancingRules().keySet())); } System.out.println(info.toString()); } /** * Print app service domain. * * @param resource an app service domain */ public static void print(AppServiceDomain resource) { StringBuilder builder = new StringBuilder().append("Domain: ").append(resource.id()) .append("Name: ").append(resource.name()) .append("\n\tResource group: ").append(resource.resourceGroupName()) .append("\n\tRegion: ").append(resource.region()) .append("\n\tCreated time: ").append(resource.createdTime()) .append("\n\tExpiration time: ").append(resource.expirationTime()) .append("\n\tContact: "); Contact contact = resource.registrantContact(); if (contact == null) { builder = builder.append("Private"); } else { builder = builder.append("\n\t\tName: ").append(contact.nameFirst() + " " + contact.nameLast()); } builder = builder.append("\n\tName servers: "); for (String nameServer : resource.nameServers()) { builder = builder.append("\n\t\t" + nameServer); } System.out.println(builder.toString()); } /** * Print app service certificate order. * * @param resource an app service certificate order */ public static void print(AppServiceCertificateOrder resource) { StringBuilder builder = new StringBuilder().append("App service certificate order: ").append(resource.id()) .append("Name: ").append(resource.name()) .append("\n\tResource group: ").append(resource.resourceGroupName()) .append("\n\tRegion: ").append(resource.region()) .append("\n\tDistinguished name: ").append(resource.distinguishedName()) .append("\n\tProduct type: ").append(resource.productType()) .append("\n\tValid years: ").append(resource.validityInYears()) .append("\n\tStatus: ").append(resource.status()) .append("\n\tIssuance time: ").append(resource.lastCertificateIssuanceTime()) .append("\n\tSigned certificate: ").append(resource.signedCertificate() == null ? null : resource.signedCertificate().thumbprint()); System.out.println(builder.toString()); } /** * Print app service plan. * * @param resource an app service plan */ public static void print(AppServicePlan resource) { StringBuilder builder = new StringBuilder().append("App service certificate order: ").append(resource.id()) .append("Name: ").append(resource.name()) .append("\n\tResource group: ").append(resource.resourceGroupName()) .append("\n\tRegion: ").append(resource.region()) .append("\n\tPricing tier: ").append(resource.pricingTier()); System.out.println(builder.toString()); } /** * Print a web app. * * @param resource a web app */ public static void print(WebAppBase resource) { StringBuilder builder = new StringBuilder().append("Web app: ").append(resource.id()) .append("\n\tName: ").append(resource.name()) .append("\n\tState: ").append(resource.state()) .append("\n\tResource group: ").append(resource.resourceGroupName()) .append("\n\tRegion: ").append(resource.region()) .append("\n\tDefault hostname: ").append(resource.defaultHostname()) .append("\n\tApp service plan: ").append(resource.appServicePlanId()) .append("\n\tHost name bindings: "); for (HostnameBinding binding : resource.getHostnameBindings().values()) { builder = builder.append("\n\t\t" + binding.toString()); } builder = builder.append("\n\tSSL bindings: "); for (HostnameSslState binding : resource.hostnameSslStates().values()) { builder = builder.append("\n\t\t" + binding.name() + ": " + binding.sslState()); if (binding.sslState() != null && binding.sslState() != SslState.DISABLED) { builder = builder.append(" - " + binding.thumbprint()); } } builder = builder.append("\n\tApp settings: "); for (AppSetting setting : resource.getAppSettings().values()) { builder = builder.append("\n\t\t" + setting.key() + ": " + setting.value() + (setting.sticky() ? " - slot setting" : "")); } builder = builder.append("\n\tConnection strings: "); for (ConnectionString conn : resource.getConnectionStrings().values()) { builder = builder.append("\n\t\t" + conn.name() + ": " + conn.value() + " - " + conn.type() + (conn.sticky() ? " - slot setting" : "")); } System.out.println(builder.toString()); } /** * Print a web site. * * @param resource a web site */ public static void print(WebSiteBase resource) { StringBuilder builder = new StringBuilder().append("Web app: ").append(resource.id()) .append("\n\tName: ").append(resource.name()) .append("\n\tState: ").append(resource.state()) .append("\n\tResource group: ").append(resource.resourceGroupName()) .append("\n\tRegion: ").append(resource.region()) .append("\n\tDefault hostname: ").append(resource.defaultHostname()) .append("\n\tApp service plan: ").append(resource.appServicePlanId()); builder = builder.append("\n\tSSL bindings: "); for (HostnameSslState binding : resource.hostnameSslStates().values()) { builder = builder.append("\n\t\t" + binding.name() + ": " + binding.sslState()); if (binding.sslState() != null && binding.sslState() != SslState.DISABLED) { builder = builder.append(" - " + binding.thumbprint()); } } System.out.println(builder.toString()); } /** * Print a traffic manager profile. * * @param profile a traffic manager profile */ public static void print(TrafficManagerProfile profile) { StringBuilder info = new StringBuilder(); info.append("Traffic Manager Profile: ").append(profile.id()) .append("\n\tName: ").append(profile.name()) .append("\n\tResource group: ").append(profile.resourceGroupName()) .append("\n\tRegion: ").append(profile.regionName()) .append("\n\tTags: ").append(profile.tags()) .append("\n\tDNSLabel: ").append(profile.dnsLabel()) .append("\n\tFQDN: ").append(profile.fqdn()) .append("\n\tTTL: ").append(profile.timeToLive()) .append("\n\tEnabled: ").append(profile.isEnabled()) .append("\n\tRoutingMethod: ").append(profile.trafficRoutingMethod()) .append("\n\tMonitor status: ").append(profile.monitorStatus()) .append("\n\tMonitoring port: ").append(profile.monitoringPort()) .append("\n\tMonitoring path: ").append(profile.monitoringPath()); Map<String, TrafficManagerAzureEndpoint> azureEndpoints = profile.azureEndpoints(); if (!azureEndpoints.isEmpty()) { info.append("\n\tAzure endpoints:"); int idx = 1; for (TrafficManagerAzureEndpoint endpoint : azureEndpoints.values()) { info.append("\n\t\tAzure endpoint: .append("\n\t\t\tId: ").append(endpoint.id()) .append("\n\t\t\tType: ").append(endpoint.endpointType()) .append("\n\t\t\tTarget resourceId: ").append(endpoint.targetAzureResourceId()) .append("\n\t\t\tTarget resourceType: ").append(endpoint.targetResourceType()) .append("\n\t\t\tMonitor status: ").append(endpoint.monitorStatus()) .append("\n\t\t\tEnabled: ").append(endpoint.isEnabled()) .append("\n\t\t\tRouting priority: ").append(endpoint.routingPriority()) .append("\n\t\t\tRouting weight: ").append(endpoint.routingWeight()); } } Map<String, TrafficManagerExternalEndpoint> externalEndpoints = profile.externalEndpoints(); if (!externalEndpoints.isEmpty()) { info.append("\n\tExternal endpoints:"); int idx = 1; for (TrafficManagerExternalEndpoint endpoint : externalEndpoints.values()) { info.append("\n\t\tExternal endpoint: .append("\n\t\t\tId: ").append(endpoint.id()) .append("\n\t\t\tType: ").append(endpoint.endpointType()) .append("\n\t\t\tFQDN: ").append(endpoint.fqdn()) .append("\n\t\t\tSource Traffic Location: ").append(endpoint.sourceTrafficLocation()) .append("\n\t\t\tMonitor status: ").append(endpoint.monitorStatus()) .append("\n\t\t\tEnabled: ").append(endpoint.isEnabled()) .append("\n\t\t\tRouting priority: ").append(endpoint.routingPriority()) .append("\n\t\t\tRouting weight: ").append(endpoint.routingWeight()); } } Map<String, TrafficManagerNestedProfileEndpoint> nestedProfileEndpoints = profile.nestedProfileEndpoints(); if (!nestedProfileEndpoints.isEmpty()) { info.append("\n\tNested profile endpoints:"); int idx = 1; for (TrafficManagerNestedProfileEndpoint endpoint : nestedProfileEndpoints.values()) { info.append("\n\t\tNested profile endpoint: .append("\n\t\t\tId: ").append(endpoint.id()) .append("\n\t\t\tType: ").append(endpoint.endpointType()) .append("\n\t\t\tNested profileId: ").append(endpoint.nestedProfileId()) .append("\n\t\t\tMinimum child threshold: ").append(endpoint.minimumChildEndpointCount()) .append("\n\t\t\tSource Traffic Location: ").append(endpoint.sourceTrafficLocation()) .append("\n\t\t\tMonitor status: ").append(endpoint.monitorStatus()) .append("\n\t\t\tEnabled: ").append(endpoint.isEnabled()) .append("\n\t\t\tRouting priority: ").append(endpoint.routingPriority()) .append("\n\t\t\tRouting weight: ").append(endpoint.routingWeight()); } } System.out.println(info.toString()); } /** * Print a dns zone. * * @param dnsZone a dns zone */ public static void print(DnsZone dnsZone) { StringBuilder info = new StringBuilder(); info.append("DNS Zone: ").append(dnsZone.id()) .append("\n\tName (Top level domain): ").append(dnsZone.name()) .append("\n\tResource group: ").append(dnsZone.resourceGroupName()) .append("\n\tRegion: ").append(dnsZone.regionName()) .append("\n\tTags: ").append(dnsZone.tags()) .append("\n\tName servers:"); for (String nameServer : dnsZone.nameServers()) { info.append("\n\t\t").append(nameServer); } SoaRecordSet soaRecordSet = dnsZone.getSoaRecordSet(); SoaRecord soaRecord = soaRecordSet.record(); info.append("\n\tSOA Record:") .append("\n\t\tHost:").append(soaRecord.host()) .append("\n\t\tEmail:").append(soaRecord.email()) .append("\n\t\tExpire time (seconds):").append(soaRecord.expireTime()) .append("\n\t\tRefresh time (seconds):").append(soaRecord.refreshTime()) .append("\n\t\tRetry time (seconds):").append(soaRecord.retryTime()) .append("\n\t\tNegative response cache ttl (seconds):").append(soaRecord.minimumTtl()) .append("\n\t\tTTL (seconds):").append(soaRecordSet.timeToLive()); PagedIterable<ARecordSet> aRecordSets = dnsZone.aRecordSets().list(); info.append("\n\tA Record sets:"); for (ARecordSet aRecordSet : aRecordSets) { info.append("\n\t\tId: ").append(aRecordSet.id()) .append("\n\t\tName: ").append(aRecordSet.name()) .append("\n\t\tTTL (seconds): ").append(aRecordSet.timeToLive()) .append("\n\t\tIP v4 addresses: "); for (String ipAddress : aRecordSet.ipv4Addresses()) { info.append("\n\t\t\t").append(ipAddress); } } PagedIterable<AaaaRecordSet> aaaaRecordSets = dnsZone.aaaaRecordSets().list(); info.append("\n\tAAAA Record sets:"); for (AaaaRecordSet aaaaRecordSet : aaaaRecordSets) { info.append("\n\t\tId: ").append(aaaaRecordSet.id()) .append("\n\t\tName: ").append(aaaaRecordSet.name()) .append("\n\t\tTTL (seconds): ").append(aaaaRecordSet.timeToLive()) .append("\n\t\tIP v6 addresses: "); for (String ipAddress : aaaaRecordSet.ipv6Addresses()) { info.append("\n\t\t\t").append(ipAddress); } } PagedIterable<CnameRecordSet> cnameRecordSets = dnsZone.cNameRecordSets().list(); info.append("\n\tCNAME Record sets:"); for (CnameRecordSet cnameRecordSet : cnameRecordSets) { info.append("\n\t\tId: ").append(cnameRecordSet.id()) .append("\n\t\tName: ").append(cnameRecordSet.name()) .append("\n\t\tTTL (seconds): ").append(cnameRecordSet.timeToLive()) .append("\n\t\tCanonical name: ").append(cnameRecordSet.canonicalName()); } PagedIterable<MxRecordSet> mxRecordSets = dnsZone.mxRecordSets().list(); info.append("\n\tMX Record sets:"); for (MxRecordSet mxRecordSet : mxRecordSets) { info.append("\n\t\tId: ").append(mxRecordSet.id()) .append("\n\t\tName: ").append(mxRecordSet.name()) .append("\n\t\tTTL (seconds): ").append(mxRecordSet.timeToLive()) .append("\n\t\tRecords: "); for (MxRecord mxRecord : mxRecordSet.records()) { info.append("\n\t\t\tExchange server, Preference: ") .append(mxRecord.exchange()) .append(" ") .append(mxRecord.preference()); } } PagedIterable<NsRecordSet> nsRecordSets = dnsZone.nsRecordSets().list(); info.append("\n\tNS Record sets:"); for (NsRecordSet nsRecordSet : nsRecordSets) { info.append("\n\t\tId: ").append(nsRecordSet.id()) .append("\n\t\tName: ").append(nsRecordSet.name()) .append("\n\t\tTTL (seconds): ").append(nsRecordSet.timeToLive()) .append("\n\t\tName servers: "); for (String nameServer : nsRecordSet.nameServers()) { info.append("\n\t\t\t").append(nameServer); } } PagedIterable<PtrRecordSet> ptrRecordSets = dnsZone.ptrRecordSets().list(); info.append("\n\tPTR Record sets:"); for (PtrRecordSet ptrRecordSet : ptrRecordSets) { info.append("\n\t\tId: ").append(ptrRecordSet.id()) .append("\n\t\tName: ").append(ptrRecordSet.name()) .append("\n\t\tTTL (seconds): ").append(ptrRecordSet.timeToLive()) .append("\n\t\tTarget domain names: "); for (String domainNames : ptrRecordSet.targetDomainNames()) { info.append("\n\t\t\t").append(domainNames); } } PagedIterable<SrvRecordSet> srvRecordSets = dnsZone.srvRecordSets().list(); info.append("\n\tSRV Record sets:"); for (SrvRecordSet srvRecordSet : srvRecordSets) { info.append("\n\t\tId: ").append(srvRecordSet.id()) .append("\n\t\tName: ").append(srvRecordSet.name()) .append("\n\t\tTTL (seconds): ").append(srvRecordSet.timeToLive()) .append("\n\t\tRecords: "); for (SrvRecord srvRecord : srvRecordSet.records()) { info.append("\n\t\t\tTarget, Port, Priority, Weight: ") .append(srvRecord.target()) .append(", ") .append(srvRecord.port()) .append(", ") .append(srvRecord.priority()) .append(", ") .append(srvRecord.weight()); } } PagedIterable<TxtRecordSet> txtRecordSets = dnsZone.txtRecordSets().list(); info.append("\n\tTXT Record sets:"); for (TxtRecordSet txtRecordSet : txtRecordSets) { info.append("\n\t\tId: ").append(txtRecordSet.id()) .append("\n\t\tName: ").append(txtRecordSet.name()) .append("\n\t\tTTL (seconds): ").append(txtRecordSet.timeToLive()) .append("\n\t\tRecords: "); for (TxtRecord txtRecord : txtRecordSet.records()) { if (txtRecord.value().size() > 0) { info.append("\n\t\t\tValue: ").append(txtRecord.value().get(0)); } } } System.out.println(info.toString()); } /** * Print a private dns zone. * * @param privateDnsZone a private dns zone */ public static void print(PrivateDnsZone privateDnsZone) { StringBuilder info = new StringBuilder(); info.append("Private DNS Zone: ").append(privateDnsZone.id()) .append("\n\tName (Top level domain): ").append(privateDnsZone.name()) .append("\n\tResource group: ").append(privateDnsZone.resourceGroupName()) .append("\n\tRegion: ").append(privateDnsZone.regionName()) .append("\n\tTags: ").append(privateDnsZone.tags()) .append("\n\tName servers:"); com.azure.resourcemanager.privatedns.models.SoaRecordSet soaRecordSet = privateDnsZone.getSoaRecordSet(); com.azure.resourcemanager.privatedns.models.SoaRecord soaRecord = soaRecordSet.record(); info.append("\n\tSOA Record:") .append("\n\t\tHost:").append(soaRecord.host()) .append("\n\t\tEmail:").append(soaRecord.email()) .append("\n\t\tExpire time (seconds):").append(soaRecord.expireTime()) .append("\n\t\tRefresh time (seconds):").append(soaRecord.refreshTime()) .append("\n\t\tRetry time (seconds):").append(soaRecord.retryTime()) .append("\n\t\tNegative response cache ttl (seconds):").append(soaRecord.minimumTtl()) .append("\n\t\tTTL (seconds):").append(soaRecordSet.timeToLive()); PagedIterable<com.azure.resourcemanager.privatedns.models.ARecordSet> aRecordSets = privateDnsZone .aRecordSets().list(); info.append("\n\tA Record sets:"); for (com.azure.resourcemanager.privatedns.models.ARecordSet aRecordSet : aRecordSets) { info.append("\n\t\tId: ").append(aRecordSet.id()) .append("\n\t\tName: ").append(aRecordSet.name()) .append("\n\t\tTTL (seconds): ").append(aRecordSet.timeToLive()) .append("\n\t\tIP v4 addresses: "); for (String ipAddress : aRecordSet.ipv4Addresses()) { info.append("\n\t\t\t").append(ipAddress); } } PagedIterable<com.azure.resourcemanager.privatedns.models.AaaaRecordSet> aaaaRecordSets = privateDnsZone .aaaaRecordSets().list(); info.append("\n\tAAAA Record sets:"); for (com.azure.resourcemanager.privatedns.models.AaaaRecordSet aaaaRecordSet : aaaaRecordSets) { info.append("\n\t\tId: ").append(aaaaRecordSet.id()) .append("\n\t\tName: ").append(aaaaRecordSet.name()) .append("\n\t\tTTL (seconds): ").append(aaaaRecordSet.timeToLive()) .append("\n\t\tIP v6 addresses: "); for (String ipAddress : aaaaRecordSet.ipv6Addresses()) { info.append("\n\t\t\t").append(ipAddress); } } PagedIterable<com.azure.resourcemanager.privatedns.models.CnameRecordSet> cnameRecordSets = privateDnsZone.cnameRecordSets().list(); info.append("\n\tCNAME Record sets:"); for (com.azure.resourcemanager.privatedns.models.CnameRecordSet cnameRecordSet : cnameRecordSets) { info.append("\n\t\tId: ").append(cnameRecordSet.id()) .append("\n\t\tName: ").append(cnameRecordSet.name()) .append("\n\t\tTTL (seconds): ").append(cnameRecordSet.timeToLive()) .append("\n\t\tCanonical name: ").append(cnameRecordSet.canonicalName()); } PagedIterable<com.azure.resourcemanager.privatedns.models.MxRecordSet> mxRecordSets = privateDnsZone.mxRecordSets().list(); info.append("\n\tMX Record sets:"); for (com.azure.resourcemanager.privatedns.models.MxRecordSet mxRecordSet : mxRecordSets) { info.append("\n\t\tId: ").append(mxRecordSet.id()) .append("\n\t\tName: ").append(mxRecordSet.name()) .append("\n\t\tTTL (seconds): ").append(mxRecordSet.timeToLive()) .append("\n\t\tRecords: "); for (com.azure.resourcemanager.privatedns.models.MxRecord mxRecord : mxRecordSet.records()) { info.append("\n\t\t\tExchange server, Preference: ") .append(mxRecord.exchange()) .append(" ") .append(mxRecord.preference()); } } PagedIterable<com.azure.resourcemanager.privatedns.models.PtrRecordSet> ptrRecordSets = privateDnsZone .ptrRecordSets().list(); info.append("\n\tPTR Record sets:"); for (com.azure.resourcemanager.privatedns.models.PtrRecordSet ptrRecordSet : ptrRecordSets) { info.append("\n\t\tId: ").append(ptrRecordSet.id()) .append("\n\t\tName: ").append(ptrRecordSet.name()) .append("\n\t\tTTL (seconds): ").append(ptrRecordSet.timeToLive()) .append("\n\t\tTarget domain names: "); for (String domainNames : ptrRecordSet.targetDomainNames()) { info.append("\n\t\t\t").append(domainNames); } } PagedIterable<com.azure.resourcemanager.privatedns.models.SrvRecordSet> srvRecordSets = privateDnsZone .srvRecordSets().list(); info.append("\n\tSRV Record sets:"); for (com.azure.resourcemanager.privatedns.models.SrvRecordSet srvRecordSet : srvRecordSets) { info.append("\n\t\tId: ").append(srvRecordSet.id()) .append("\n\t\tName: ").append(srvRecordSet.name()) .append("\n\t\tTTL (seconds): ").append(srvRecordSet.timeToLive()) .append("\n\t\tRecords: "); for (com.azure.resourcemanager.privatedns.models.SrvRecord srvRecord : srvRecordSet.records()) { info.append("\n\t\t\tTarget, Port, Priority, Weight: ") .append(srvRecord.target()) .append(", ") .append(srvRecord.port()) .append(", ") .append(srvRecord.priority()) .append(", ") .append(srvRecord.weight()); } } PagedIterable<com.azure.resourcemanager.privatedns.models.TxtRecordSet> txtRecordSets = privateDnsZone .txtRecordSets().list(); info.append("\n\tTXT Record sets:"); for (com.azure.resourcemanager.privatedns.models.TxtRecordSet txtRecordSet : txtRecordSets) { info.append("\n\t\tId: ").append(txtRecordSet.id()) .append("\n\t\tName: ").append(txtRecordSet.name()) .append("\n\t\tTTL (seconds): ").append(txtRecordSet.timeToLive()) .append("\n\t\tRecords: "); for (com.azure.resourcemanager.privatedns.models.TxtRecord txtRecord : txtRecordSet.records()) { if (txtRecord.value().size() > 0) { info.append("\n\t\t\tValue: ").append(txtRecord.value().get(0)); } } } PagedIterable<VirtualNetworkLink> virtualNetworkLinks = privateDnsZone.virtualNetworkLinks().list(); info.append("\n\tVirtual Network Links:"); for (VirtualNetworkLink virtualNetworkLink : virtualNetworkLinks) { info.append("\n\tId: ").append(virtualNetworkLink.id()) .append("\n\tName: ").append(virtualNetworkLink.name()) .append("\n\tReference of Virtual Network: ").append(virtualNetworkLink.referencedVirtualNetworkId()) .append("\n\tRegistration enabled: ").append(virtualNetworkLink.isAutoRegistrationEnabled()); } System.out.println(info.toString()); } /** * Print an Azure Container Registry. * * @param azureRegistry an Azure Container Registry */ public static void print(Registry azureRegistry) { StringBuilder info = new StringBuilder(); RegistryCredentials acrCredentials = azureRegistry.getCredentials(); info.append("Azure Container Registry: ").append(azureRegistry.id()) .append("\n\tName: ").append(azureRegistry.name()) .append("\n\tServer Url: ").append(azureRegistry.loginServerUrl()) .append("\n\tUser: ").append(acrCredentials.username()) .append("\n\tFirst Password: ").append(acrCredentials.accessKeys().get(AccessKeyType.PRIMARY)) .append("\n\tSecond Password: ").append(acrCredentials.accessKeys().get(AccessKeyType.SECONDARY)); System.out.println(info.toString()); } /** * Print an Azure Container Service (AKS). * * @param kubernetesCluster a managed container service */ public static void print(KubernetesCluster kubernetesCluster) { StringBuilder info = new StringBuilder(); info.append("Azure Container Service: ").append(kubernetesCluster.id()) .append("\n\tName: ").append(kubernetesCluster.name()) .append("\n\tFQDN: ").append(kubernetesCluster.fqdn()) .append("\n\tDNS prefix label: ").append(kubernetesCluster.dnsPrefix()) .append("\n\t\tWith Agent pool name: ").append(new ArrayList<>(kubernetesCluster.agentPools().keySet()).get(0)) .append("\n\t\tAgent pool count: ").append(new ArrayList<>(kubernetesCluster.agentPools().values()).get(0).count()) .append("\n\t\tAgent pool VM size: ").append(new ArrayList<>(kubernetesCluster.agentPools().values()).get(0).vmSize().toString()) .append("\n\tLinux user name: ").append(kubernetesCluster.linuxRootUsername()) .append("\n\tSSH key: ").append(kubernetesCluster.sshKey()) .append("\n\tService principal client ID: ").append(kubernetesCluster.servicePrincipalClientId()); System.out.println(info.toString()); } /** * Retrieve the secondary service principal client ID. * * @param envSecondaryServicePrincipal an Azure Container Registry * @return a service principal client ID * @throws Exception exception */
class Utils { private Utils() { } /** @return a generated password */ public static String password() { String password = new ResourceManagerUtils.InternalRuntimeContext().randomResourceName("Pa5$", 12); System.out.printf("Password: %s%n", password); return password; } /** * Creates a randomized resource name. * Please provider your own implementation, or avoid using the method, if code is to be used in production. * * @param azure the AzureResourceManager instance. * @param prefix the prefix to the name. * @param maxLen the max length of the name. * @return the randomized resource name. */ public static String randomResourceName(AzureResourceManager azure, String prefix, int maxLen) { return azure.resourceGroups().manager().internalContext().randomResourceName(prefix, maxLen); } /** * Generates the specified number of random resource names with the same prefix. * Please provider your own implementation, or avoid using the method, if code is to be used in production. * * @param azure the AzureResourceManager instance. * @param prefix the prefix to be used if possible * @param maxLen the maximum length for the random generated name * @param count the number of names to generate * @return the randomized resource names. */ public static String[] randomResourceNames(AzureResourceManager azure, String prefix, int maxLen, int count) { String[] names = new String[count]; for (int i = 0; i < count; i++) { names[i] = randomResourceName(azure, prefix, maxLen); } return names; } /** * Creates a random UUID. * Please provider your own implementation, or avoid using the method, if code is to be used in production. * * @param azure the AzureResourceManager instance. * @return the random UUID. */ public static String randomUuid(AzureResourceManager azure) { return azure.resourceGroups().manager().internalContext().randomUuid(); } /** * Creates a randomized resource name. * Please provider your own implementation, or avoid using the method, if code is to be used in production. * * @param authenticated the AzureResourceManager.Authenticated instance. * @param prefix the prefix to the name. * @param maxLen the max length of the name. * @return the randomized resource name. */ public static String randomResourceName(AzureResourceManager.Authenticated authenticated, String prefix, int maxLen) { return authenticated.roleAssignments().manager().internalContext().randomResourceName(prefix, maxLen); } /** * Creates a random UUID. * Please provider your own implementation, or avoid using the method, if code is to be used in production. * * @param authenticated the AzureResourceManager.Authenticated instance. * @return the random UUID. */ public static String randomUuid(AzureResourceManager.Authenticated authenticated) { return authenticated.roleAssignments().manager().internalContext().randomUuid(); } /** * Print resource group info. * * @param resource a resource group */ public static void print(ResourceGroup resource) { StringBuilder info = new StringBuilder(); info.append("Resource Group: ").append(resource.id()) .append("\n\tName: ").append(resource.name()) .append("\n\tRegion: ").append(resource.region()) .append("\n\tTags: ").append(resource.tags()); System.out.println(info.toString()); } /** * Print User Assigned MSI info. * * @param resource a User Assigned MSI */ public static void print(Identity resource) { StringBuilder info = new StringBuilder(); info.append("Resource Group: ").append(resource.id()) .append("\n\tName: ").append(resource.name()) .append("\n\tRegion: ").append(resource.region()) .append("\n\tTags: ").append(resource.tags()) .append("\n\tService Principal Id: ").append(resource.principalId()) .append("\n\tClient Id: ").append(resource.clientId()) .append("\n\tTenant Id: ").append(resource.tenantId()); System.out.println(info.toString()); } /** * Print virtual machine info. * * @param resource a virtual machine */ public static void print(VirtualMachine resource) { StringBuilder storageProfile = new StringBuilder().append("\n\tStorageProfile: "); if (resource.storageProfile().imageReference() != null) { storageProfile.append("\n\t\tImageReference:"); storageProfile.append("\n\t\t\tPublisher: ").append(resource.storageProfile().imageReference().publisher()); storageProfile.append("\n\t\t\tOffer: ").append(resource.storageProfile().imageReference().offer()); storageProfile.append("\n\t\t\tSKU: ").append(resource.storageProfile().imageReference().sku()); storageProfile.append("\n\t\t\tVersion: ").append(resource.storageProfile().imageReference().version()); } if (resource.storageProfile().osDisk() != null) { storageProfile.append("\n\t\tOSDisk:"); storageProfile.append("\n\t\t\tOSType: ").append(resource.storageProfile().osDisk().osType()); storageProfile.append("\n\t\t\tName: ").append(resource.storageProfile().osDisk().name()); storageProfile.append("\n\t\t\tCaching: ").append(resource.storageProfile().osDisk().caching()); storageProfile.append("\n\t\t\tCreateOption: ").append(resource.storageProfile().osDisk().createOption()); storageProfile.append("\n\t\t\tDiskSizeGB: ").append(resource.storageProfile().osDisk().diskSizeGB()); if (resource.storageProfile().osDisk().image() != null) { storageProfile.append("\n\t\t\tImage Uri: ").append(resource.storageProfile().osDisk().image().uri()); } if (resource.storageProfile().osDisk().vhd() != null) { storageProfile.append("\n\t\t\tVhd Uri: ").append(resource.storageProfile().osDisk().vhd().uri()); } if (resource.storageProfile().osDisk().encryptionSettings() != null) { storageProfile.append("\n\t\t\tEncryptionSettings: "); storageProfile.append("\n\t\t\t\tEnabled: ").append(resource.storageProfile().osDisk().encryptionSettings().enabled()); storageProfile.append("\n\t\t\t\tDiskEncryptionKey Uri: ").append(resource .storageProfile() .osDisk() .encryptionSettings() .diskEncryptionKey().secretUrl()); storageProfile.append("\n\t\t\t\tKeyEncryptionKey Uri: ").append(resource .storageProfile() .osDisk() .encryptionSettings() .keyEncryptionKey().keyUrl()); } } if (resource.storageProfile().dataDisks() != null) { int i = 0; for (DataDisk disk : resource.storageProfile().dataDisks()) { storageProfile.append("\n\t\tDataDisk: storageProfile.append("\n\t\t\tName: ").append(disk.name()); storageProfile.append("\n\t\t\tCaching: ").append(disk.caching()); storageProfile.append("\n\t\t\tCreateOption: ").append(disk.createOption()); storageProfile.append("\n\t\t\tDiskSizeGB: ").append(disk.diskSizeGB()); storageProfile.append("\n\t\t\tLun: ").append(disk.lun()); if (resource.isManagedDiskEnabled()) { if (disk.managedDisk() != null) { storageProfile.append("\n\t\t\tManaged Disk Id: ").append(disk.managedDisk().id()); } } else { if (disk.vhd().uri() != null) { storageProfile.append("\n\t\t\tVhd Uri: ").append(disk.vhd().uri()); } } if (disk.image() != null) { storageProfile.append("\n\t\t\tImage Uri: ").append(disk.image().uri()); } } } StringBuilder osProfile = new StringBuilder().append("\n\tOSProfile: "); if (resource.osProfile() != null) { osProfile.append("\n\t\tComputerName:").append(resource.osProfile().computerName()); if (resource.osProfile().windowsConfiguration() != null) { osProfile.append("\n\t\t\tWindowsConfiguration: "); osProfile.append("\n\t\t\t\tProvisionVMAgent: ") .append(resource.osProfile().windowsConfiguration().provisionVMAgent()); osProfile.append("\n\t\t\t\tEnableAutomaticUpdates: ") .append(resource.osProfile().windowsConfiguration().enableAutomaticUpdates()); osProfile.append("\n\t\t\t\tTimeZone: ") .append(resource.osProfile().windowsConfiguration().timeZone()); } if (resource.osProfile().linuxConfiguration() != null) { osProfile.append("\n\t\t\tLinuxConfiguration: "); osProfile.append("\n\t\t\t\tDisablePasswordAuthentication: ") .append(resource.osProfile().linuxConfiguration().disablePasswordAuthentication()); } } else { osProfile.append("null"); } StringBuilder networkProfile = new StringBuilder().append("\n\tNetworkProfile: "); for (String networkInterfaceId : resource.networkInterfaceIds()) { networkProfile.append("\n\t\tId:").append(networkInterfaceId); } StringBuilder extensions = new StringBuilder().append("\n\tExtensions: "); for (Map.Entry<String, VirtualMachineExtension> extensionEntry : resource.listExtensions().entrySet()) { VirtualMachineExtension extension = extensionEntry.getValue(); extensions.append("\n\t\tExtension: ").append(extension.id()) .append("\n\t\t\tName: ").append(extension.name()) .append("\n\t\t\tTags: ").append(extension.tags()) .append("\n\t\t\tProvisioningState: ").append(extension.provisioningState()) .append("\n\t\t\tAuto upgrade minor version enabled: ").append(extension.autoUpgradeMinorVersionEnabled()) .append("\n\t\t\tPublisher: ").append(extension.publisherName()) .append("\n\t\t\tType: ").append(extension.typeName()) .append("\n\t\t\tVersion: ").append(extension.versionName()) .append("\n\t\t\tPublic Settings: ").append(extension.publicSettingsAsJsonString()); } StringBuilder msi = new StringBuilder().append("\n\tMSI: "); msi.append("\n\t\t\tMSI enabled:").append(resource.isManagedServiceIdentityEnabled()); msi.append("\n\t\t\tSystem Assigned MSI Active Directory Service Principal Id:").append(resource.systemAssignedManagedServiceIdentityPrincipalId()); msi.append("\n\t\t\tSystem Assigned MSI Active Directory Tenant Id:").append(resource.systemAssignedManagedServiceIdentityTenantId()); StringBuilder zones = new StringBuilder().append("\n\tZones: "); zones.append(resource.availabilityZones()); System.out.println(new StringBuilder().append("Virtual Machine: ").append(resource.id()) .append("Name: ").append(resource.name()) .append("\n\tResource group: ").append(resource.resourceGroupName()) .append("\n\tRegion: ").append(resource.region()) .append("\n\tTags: ").append(resource.tags()) .append("\n\tHardwareProfile: ") .append("\n\t\tSize: ").append(resource.size()) .append(storageProfile) .append(osProfile) .append(networkProfile) .append(extensions) .append(msi) .append(zones) .toString()); } /** * Print availability set info. * * @param resource an availability set */ public static void print(AvailabilitySet resource) { System.out.println(new StringBuilder().append("Availability Set: ").append(resource.id()) .append("Name: ").append(resource.name()) .append("\n\tResource group: ").append(resource.resourceGroupName()) .append("\n\tRegion: ").append(resource.region()) .append("\n\tTags: ").append(resource.tags()) .append("\n\tFault domain count: ").append(resource.faultDomainCount()) .append("\n\tUpdate domain count: ").append(resource.updateDomainCount()) .toString()); } /** * Print network info. * * @param resource a network * @throws ManagementException Cloud errors */ public static void print(Network resource) { StringBuilder info = new StringBuilder(); info.append("Network: ").append(resource.id()) .append("Name: ").append(resource.name()) .append("\n\tResource group: ").append(resource.resourceGroupName()) .append("\n\tRegion: ").append(resource.region()) .append("\n\tTags: ").append(resource.tags()) .append("\n\tAddress spaces: ").append(resource.addressSpaces()) .append("\n\tDNS server IPs: ").append(resource.dnsServerIPs()); for (Subnet subnet : resource.subnets().values()) { info.append("\n\tSubnet: ").append(subnet.name()) .append("\n\t\tAddress prefix: ").append(subnet.addressPrefix()); NetworkSecurityGroup subnetNsg = subnet.getNetworkSecurityGroup(); if (subnetNsg != null) { info.append("\n\t\tNetwork security group ID: ").append(subnetNsg.id()); } RouteTable routeTable = subnet.getRouteTable(); if (routeTable != null) { info.append("\n\tRoute table ID: ").append(routeTable.id()); } Map<ServiceEndpointType, List<Region>> services = subnet.servicesWithAccess(); if (services.size() > 0) { info.append("\n\tServices with access"); for (Map.Entry<ServiceEndpointType, List<Region>> service : services.entrySet()) { info.append("\n\t\tService: ") .append(service.getKey()) .append(" Regions: " + service.getValue() + ""); } } } for (NetworkPeering peering : resource.peerings().list()) { info.append("\n\tPeering: ").append(peering.name()) .append("\n\t\tRemote network ID: ").append(peering.remoteNetworkId()) .append("\n\t\tPeering state: ").append(peering.state()) .append("\n\t\tIs traffic forwarded from remote network allowed? ").append(peering.isTrafficForwardingFromRemoteNetworkAllowed()) .append("\n\t\tGateway use: ").append(peering.gatewayUse()); } System.out.println(info.toString()); } /** * Print network interface. * * @param resource a network interface */ public static void print(NetworkInterface resource) { StringBuilder info = new StringBuilder(); info.append("NetworkInterface: ").append(resource.id()) .append("Name: ").append(resource.name()) .append("\n\tResource group: ").append(resource.resourceGroupName()) .append("\n\tRegion: ").append(resource.region()) .append("\n\tTags: ").append(resource.tags()) .append("\n\tInternal DNS name label: ").append(resource.internalDnsNameLabel()) .append("\n\tInternal FQDN: ").append(resource.internalFqdn()) .append("\n\tInternal domain name suffix: ").append(resource.internalDomainNameSuffix()) .append("\n\tNetwork security group: ").append(resource.networkSecurityGroupId()) .append("\n\tApplied DNS servers: ").append(resource.appliedDnsServers().toString()) .append("\n\tDNS server IPs: "); for (String dnsServerIp : resource.dnsServers()) { info.append("\n\t\t").append(dnsServerIp); } info.append("\n\tIP forwarding enabled? ").append(resource.isIPForwardingEnabled()) .append("\n\tAccelerated networking enabled? ").append(resource.isAcceleratedNetworkingEnabled()) .append("\n\tMAC Address:").append(resource.macAddress()) .append("\n\tPrivate IP:").append(resource.primaryPrivateIP()) .append("\n\tPrivate allocation method:").append(resource.primaryPrivateIpAllocationMethod()) .append("\n\tPrimary virtual network ID: ").append(resource.primaryIPConfiguration().networkId()) .append("\n\tPrimary subnet name:").append(resource.primaryIPConfiguration().subnetName()); System.out.println(info.toString()); } /** * Print network security group. * * @param resource a network security group */ public static void print(NetworkSecurityGroup resource) { StringBuilder info = new StringBuilder(); info.append("NSG: ").append(resource.id()) .append("Name: ").append(resource.name()) .append("\n\tResource group: ").append(resource.resourceGroupName()) .append("\n\tRegion: ").append(resource.region()) .append("\n\tTags: ").append(resource.tags()); for (NetworkSecurityRule rule : resource.securityRules().values()) { info.append("\n\tRule: ").append(rule.name()) .append("\n\t\tAccess: ").append(rule.access()) .append("\n\t\tDirection: ").append(rule.direction()) .append("\n\t\tFrom address: ").append(rule.sourceAddressPrefix()) .append("\n\t\tFrom port range: ").append(rule.sourcePortRange()) .append("\n\t\tTo address: ").append(rule.destinationAddressPrefix()) .append("\n\t\tTo port: ").append(rule.destinationPortRange()) .append("\n\t\tProtocol: ").append(rule.protocol()) .append("\n\t\tPriority: ").append(rule.priority()); } System.out.println(info.toString()); } /** * Print public IP address. * * @param resource a public IP address */ public static void print(PublicIpAddress resource) { System.out.println(new StringBuilder().append("Public IP Address: ").append(resource.id()) .append("Name: ").append(resource.name()) .append("\n\tResource group: ").append(resource.resourceGroupName()) .append("\n\tRegion: ").append(resource.region()) .append("\n\tTags: ").append(resource.tags()) .append("\n\tIP Address: ").append(resource.ipAddress()) .append("\n\tLeaf domain label: ").append(resource.leafDomainLabel()) .append("\n\tFQDN: ").append(resource.fqdn()) .append("\n\tReverse FQDN: ").append(resource.reverseFqdn()) .append("\n\tIdle timeout (minutes): ").append(resource.idleTimeoutInMinutes()) .append("\n\tIP allocation method: ").append(resource.ipAllocationMethod()) .append("\n\tZones: ").append(resource.availabilityZones()) .toString()); } /** * Print a key vault. * * @param vault the key vault resource */ public static void print(Vault vault) { StringBuilder info = new StringBuilder().append("Key Vault: ").append(vault.id()) .append("Name: ").append(vault.name()) .append("\n\tResource group: ").append(vault.resourceGroupName()) .append("\n\tRegion: ").append(vault.region()) .append("\n\tSku: ").append(vault.sku().name()).append(" - ").append(vault.sku().family()) .append("\n\tVault URI: ").append(vault.vaultUri()) .append("\n\tAccess policies: "); for (AccessPolicy accessPolicy : vault.accessPolicies()) { info.append("\n\t\tIdentity:").append(accessPolicy.objectId()); if (accessPolicy.permissions() != null) { if (accessPolicy.permissions().keys() != null) { info.append("\n\t\tKey permissions: ").append(accessPolicy.permissions().keys().stream().map(KeyPermissions::toString).collect(Collectors.joining(", "))); } if (accessPolicy.permissions().secrets() != null) { info.append("\n\t\tSecret permissions: ").append(accessPolicy.permissions().secrets().stream().map(SecretPermissions::toString).collect(Collectors.joining(", "))); } if (accessPolicy.permissions().certificates() != null) { info.append("\n\t\tCertificate permissions: ").append(accessPolicy.permissions().certificates().stream().map(CertificatePermissions::toString).collect(Collectors.joining(", "))); } } } System.out.println(info.toString()); } /** * Print storage account. * * @param storageAccount a storage account */ public static void print(StorageAccount storageAccount) { System.out.println(storageAccount.name() + " created @ " + storageAccount.creationTime()); StringBuilder info = new StringBuilder().append("Storage Account: ").append(storageAccount.id()) .append("Name: ").append(storageAccount.name()) .append("\n\tResource group: ").append(storageAccount.resourceGroupName()) .append("\n\tRegion: ").append(storageAccount.region()) .append("\n\tSKU: ").append(storageAccount.skuType().name().toString()) .append("\n\tAccessTier: ").append(storageAccount.accessTier()) .append("\n\tKind: ").append(storageAccount.kind()); info.append("\n\tNetwork Rule Configuration: ") .append("\n\t\tAllow reading logs from any network: ").append(storageAccount.canReadLogEntriesFromAnyNetwork()) .append("\n\t\tAllow reading metrics from any network: ").append(storageAccount.canReadMetricsFromAnyNetwork()) .append("\n\t\tAllow access from all azure services: ").append(storageAccount.canAccessFromAzureServices()); if (storageAccount.networkSubnetsWithAccess().size() > 0) { info.append("\n\t\tNetwork subnets with access: "); for (String subnetId : storageAccount.networkSubnetsWithAccess()) { info.append("\n\t\t\t").append(subnetId); } } if (storageAccount.ipAddressesWithAccess().size() > 0) { info.append("\n\t\tIP addresses with access: "); for (String ipAddress : storageAccount.ipAddressesWithAccess()) { info.append("\n\t\t\t").append(ipAddress); } } if (storageAccount.ipAddressRangesWithAccess().size() > 0) { info.append("\n\t\tIP address-ranges with access: "); for (String ipAddressRange : storageAccount.ipAddressRangesWithAccess()) { info.append("\n\t\t\t").append(ipAddressRange); } } info.append("\n\t\tTraffic allowed from only HTTPS: ").append(storageAccount.innerModel().enableHttpsTrafficOnly()); info.append("\n\tEncryption status: "); for (Map.Entry<StorageService, StorageAccountEncryptionStatus> eStatus : storageAccount.encryptionStatuses().entrySet()) { info.append("\n\t\t").append(eStatus.getValue().storageService()).append(": ").append(eStatus.getValue().isEnabled() ? "Enabled" : "Disabled"); } System.out.println(info.toString()); } /** * Print storage account keys. * * @param storageAccountKeys a list of storage account keys */ public static void print(List<StorageAccountKey> storageAccountKeys) { for (int i = 0; i < storageAccountKeys.size(); i++) { StorageAccountKey storageAccountKey = storageAccountKeys.get(i); System.out.println("Key (" + i + ") " + storageAccountKey.keyName() + "=" + storageAccountKey.value()); } } /** * Print Redis Cache. * * @param redisCache a Redis cache. */ public static void print(RedisCache redisCache) { StringBuilder redisInfo = new StringBuilder() .append("Redis Cache Name: ").append(redisCache.name()) .append("\n\tResource group: ").append(redisCache.resourceGroupName()) .append("\n\tRegion: ").append(redisCache.region()) .append("\n\tSKU Name: ").append(redisCache.sku().name()) .append("\n\tSKU Family: ").append(redisCache.sku().family()) .append("\n\tHostname: ").append(redisCache.hostname()) .append("\n\tSSL port: ").append(redisCache.sslPort()) .append("\n\tNon-SSL port (6379) enabled: ").append(redisCache.nonSslPort()); if (redisCache.redisConfiguration() != null && !redisCache.redisConfiguration().isEmpty()) { redisInfo.append("\n\tRedis Configuration:"); for (Map.Entry<String, String> redisConfiguration : redisCache.redisConfiguration().entrySet()) { redisInfo.append("\n\t '").append(redisConfiguration.getKey()) .append("' : '").append(redisConfiguration.getValue()).append("'"); } } if (redisCache.isPremium()) { RedisCachePremium premium = redisCache.asPremium(); List<ScheduleEntry> scheduleEntries = premium.listPatchSchedules(); if (scheduleEntries != null && !scheduleEntries.isEmpty()) { redisInfo.append("\n\tRedis Patch Schedule:"); for (ScheduleEntry schedule : scheduleEntries) { redisInfo.append("\n\t\tDay: '").append(schedule.dayOfWeek()) .append("', start at: '").append(schedule.startHourUtc()) .append("', maintenance window: '").append(schedule.maintenanceWindow()) .append("'"); } } } System.out.println(redisInfo.toString()); } /** * Print Redis Cache access keys. * * @param redisAccessKeys a keys for Redis Cache */ public static void print(RedisAccessKeys redisAccessKeys) { StringBuilder redisKeys = new StringBuilder() .append("Redis Access Keys: ") .append("\n\tPrimary Key: '").append(redisAccessKeys.primaryKey()).append("', ") .append("\n\tSecondary Key: '").append(redisAccessKeys.secondaryKey()).append("', "); System.out.println(redisKeys.toString()); } /** * Print load balancer. * * @param resource a load balancer */ public static void print(LoadBalancer resource) { StringBuilder info = new StringBuilder(); info.append("Load balancer: ").append(resource.id()) .append("Name: ").append(resource.name()) .append("\n\tResource group: ").append(resource.resourceGroupName()) .append("\n\tRegion: ").append(resource.region()) .append("\n\tTags: ").append(resource.tags()) .append("\n\tBackends: ").append(resource.backends().keySet().toString()); info.append("\n\tPublic IP address IDs: ") .append(resource.publicIpAddressIds().size()); for (String pipId : resource.publicIpAddressIds()) { info.append("\n\t\tPIP id: ").append(pipId); } info.append("\n\tTCP probes: ") .append(resource.tcpProbes().size()); for (LoadBalancerTcpProbe probe : resource.tcpProbes().values()) { info.append("\n\t\tProbe name: ").append(probe.name()) .append("\n\t\t\tPort: ").append(probe.port()) .append("\n\t\t\tInterval in seconds: ").append(probe.intervalInSeconds()) .append("\n\t\t\tRetries before unhealthy: ").append(probe.numberOfProbes()); info.append("\n\t\t\tReferenced from load balancing rules: ") .append(probe.loadBalancingRules().size()); for (LoadBalancingRule rule : probe.loadBalancingRules().values()) { info.append("\n\t\t\t\tName: ").append(rule.name()); } } info.append("\n\tHTTP probes: ") .append(resource.httpProbes().size()); for (LoadBalancerHttpProbe probe : resource.httpProbes().values()) { info.append("\n\t\tProbe name: ").append(probe.name()) .append("\n\t\t\tPort: ").append(probe.port()) .append("\n\t\t\tInterval in seconds: ").append(probe.intervalInSeconds()) .append("\n\t\t\tRetries before unhealthy: ").append(probe.numberOfProbes()) .append("\n\t\t\tHTTP request path: ").append(probe.requestPath()); info.append("\n\t\t\tReferenced from load balancing rules: ") .append(probe.loadBalancingRules().size()); for (LoadBalancingRule rule : probe.loadBalancingRules().values()) { info.append("\n\t\t\t\tName: ").append(rule.name()); } } info.append("\n\tHTTPS probes: ") .append(resource.httpsProbes().size()); for (LoadBalancerHttpProbe probe : resource.httpsProbes().values()) { info.append("\n\t\tProbe name: ").append(probe.name()) .append("\n\t\t\tPort: ").append(probe.port()) .append("\n\t\t\tInterval in seconds: ").append(probe.intervalInSeconds()) .append("\n\t\t\tRetries before unhealthy: ").append(probe.numberOfProbes()) .append("\n\t\t\tHTTPS request path: ").append(probe.requestPath()); info.append("\n\t\t\tReferenced from load balancing rules: ") .append(probe.loadBalancingRules().size()); for (LoadBalancingRule rule : probe.loadBalancingRules().values()) { info.append("\n\t\t\t\tName: ").append(rule.name()); } } info.append("\n\tLoad balancing rules: ") .append(resource.loadBalancingRules().size()); for (LoadBalancingRule rule : resource.loadBalancingRules().values()) { info.append("\n\t\tLB rule name: ").append(rule.name()) .append("\n\t\t\tProtocol: ").append(rule.protocol()) .append("\n\t\t\tFloating IP enabled? ").append(rule.floatingIPEnabled()) .append("\n\t\t\tIdle timeout in minutes: ").append(rule.idleTimeoutInMinutes()) .append("\n\t\t\tLoad distribution method: ").append(rule.loadDistribution().toString()); LoadBalancerFrontend frontend = rule.frontend(); info.append("\n\t\t\tFrontend: "); if (frontend != null) { info.append(frontend.name()); } else { info.append("(None)"); } info.append("\n\t\t\tFrontend port: ").append(rule.frontendPort()); LoadBalancerBackend backend = rule.backend(); info.append("\n\t\t\tBackend: "); if (backend != null) { info.append(backend.name()); } else { info.append("(None)"); } info.append("\n\t\t\tBackend port: ").append(rule.backendPort()); LoadBalancerProbe probe = rule.probe(); info.append("\n\t\t\tProbe: "); if (probe == null) { info.append("(None)"); } else { info.append(probe.name()).append(" [").append(probe.protocol().toString()).append("]"); } } info.append("\n\tFrontends: ") .append(resource.frontends().size()); for (LoadBalancerFrontend frontend : resource.frontends().values()) { info.append("\n\t\tFrontend name: ").append(frontend.name()) .append("\n\t\t\tInternet facing: ").append(frontend.isPublic()); if (frontend.isPublic()) { info.append("\n\t\t\tPublic IP Address ID: ").append(((LoadBalancerPublicFrontend) frontend).publicIpAddressId()); } else { info.append("\n\t\t\tVirtual network ID: ").append(((LoadBalancerPrivateFrontend) frontend).networkId()) .append("\n\t\t\tSubnet name: ").append(((LoadBalancerPrivateFrontend) frontend).subnetName()) .append("\n\t\t\tPrivate IP address: ").append(((LoadBalancerPrivateFrontend) frontend).privateIpAddress()) .append("\n\t\t\tPrivate IP allocation method: ").append(((LoadBalancerPrivateFrontend) frontend).privateIpAllocationMethod()); } info.append("\n\t\t\tReferenced inbound NAT pools: ") .append(frontend.inboundNatPools().size()); for (LoadBalancerInboundNatPool pool : frontend.inboundNatPools().values()) { info.append("\n\t\t\t\tName: ").append(pool.name()); } info.append("\n\t\t\tReferenced inbound NAT rules: ") .append(frontend.inboundNatRules().size()); for (LoadBalancerInboundNatRule rule : frontend.inboundNatRules().values()) { info.append("\n\t\t\t\tName: ").append(rule.name()); } info.append("\n\t\t\tReferenced load balancing rules: ") .append(frontend.loadBalancingRules().size()); for (LoadBalancingRule rule : frontend.loadBalancingRules().values()) { info.append("\n\t\t\t\tName: ").append(rule.name()); } } info.append("\n\tInbound NAT rules: ") .append(resource.inboundNatRules().size()); for (LoadBalancerInboundNatRule natRule : resource.inboundNatRules().values()) { info.append("\n\t\tInbound NAT rule name: ").append(natRule.name()) .append("\n\t\t\tProtocol: ").append(natRule.protocol().toString()) .append("\n\t\t\tFrontend: ").append(natRule.frontend().name()) .append("\n\t\t\tFrontend port: ").append(natRule.frontendPort()) .append("\n\t\t\tBackend port: ").append(natRule.backendPort()) .append("\n\t\t\tBackend NIC ID: ").append(natRule.backendNetworkInterfaceId()) .append("\n\t\t\tBackend NIC IP config name: ").append(natRule.backendNicIpConfigurationName()) .append("\n\t\t\tFloating IP? ").append(natRule.floatingIPEnabled()) .append("\n\t\t\tIdle timeout in minutes: ").append(natRule.idleTimeoutInMinutes()); } info.append("\n\tInbound NAT pools: ") .append(resource.inboundNatPools().size()); for (LoadBalancerInboundNatPool natPool : resource.inboundNatPools().values()) { info.append("\n\t\tInbound NAT pool name: ").append(natPool.name()) .append("\n\t\t\tProtocol: ").append(natPool.protocol().toString()) .append("\n\t\t\tFrontend: ").append(natPool.frontend().name()) .append("\n\t\t\tFrontend port range: ") .append(natPool.frontendPortRangeStart()) .append("-") .append(natPool.frontendPortRangeEnd()) .append("\n\t\t\tBackend port: ").append(natPool.backendPort()); } info.append("\n\tBackends: ") .append(resource.backends().size()); for (LoadBalancerBackend backend : resource.backends().values()) { info.append("\n\t\tBackend name: ").append(backend.name()); info.append("\n\t\t\tReferenced NICs: ") .append(backend.backendNicIPConfigurationNames().entrySet().size()); for (Map.Entry<String, String> entry : backend.backendNicIPConfigurationNames().entrySet()) { info.append("\n\t\t\t\tNIC ID: ").append(entry.getKey()) .append(" - IP Config: ").append(entry.getValue()); } Set<String> vmIds = backend.getVirtualMachineIds(); info.append("\n\t\t\tReferenced virtual machine ids: ") .append(vmIds.size()); for (String vmId : vmIds) { info.append("\n\t\t\t\tVM ID: ").append(vmId); } info.append("\n\t\t\tReferenced load balancing rules: ") .append(new ArrayList<String>(backend.loadBalancingRules().keySet())); } System.out.println(info.toString()); } /** * Print app service domain. * * @param resource an app service domain */ public static void print(AppServiceDomain resource) { StringBuilder builder = new StringBuilder().append("Domain: ").append(resource.id()) .append("Name: ").append(resource.name()) .append("\n\tResource group: ").append(resource.resourceGroupName()) .append("\n\tRegion: ").append(resource.region()) .append("\n\tCreated time: ").append(resource.createdTime()) .append("\n\tExpiration time: ").append(resource.expirationTime()) .append("\n\tContact: "); Contact contact = resource.registrantContact(); if (contact == null) { builder = builder.append("Private"); } else { builder = builder.append("\n\t\tName: ").append(contact.nameFirst() + " " + contact.nameLast()); } builder = builder.append("\n\tName servers: "); for (String nameServer : resource.nameServers()) { builder = builder.append("\n\t\t" + nameServer); } System.out.println(builder.toString()); } /** * Print app service certificate order. * * @param resource an app service certificate order */ public static void print(AppServiceCertificateOrder resource) { StringBuilder builder = new StringBuilder().append("App service certificate order: ").append(resource.id()) .append("Name: ").append(resource.name()) .append("\n\tResource group: ").append(resource.resourceGroupName()) .append("\n\tRegion: ").append(resource.region()) .append("\n\tDistinguished name: ").append(resource.distinguishedName()) .append("\n\tProduct type: ").append(resource.productType()) .append("\n\tValid years: ").append(resource.validityInYears()) .append("\n\tStatus: ").append(resource.status()) .append("\n\tIssuance time: ").append(resource.lastCertificateIssuanceTime()) .append("\n\tSigned certificate: ").append(resource.signedCertificate() == null ? null : resource.signedCertificate().thumbprint()); System.out.println(builder.toString()); } /** * Print app service plan. * * @param resource an app service plan */ public static void print(AppServicePlan resource) { StringBuilder builder = new StringBuilder().append("App service certificate order: ").append(resource.id()) .append("Name: ").append(resource.name()) .append("\n\tResource group: ").append(resource.resourceGroupName()) .append("\n\tRegion: ").append(resource.region()) .append("\n\tPricing tier: ").append(resource.pricingTier()); System.out.println(builder.toString()); } /** * Print a web app. * * @param resource a web app */ public static void print(WebAppBase resource) { StringBuilder builder = new StringBuilder().append("Web app: ").append(resource.id()) .append("\n\tName: ").append(resource.name()) .append("\n\tState: ").append(resource.state()) .append("\n\tResource group: ").append(resource.resourceGroupName()) .append("\n\tRegion: ").append(resource.region()) .append("\n\tDefault hostname: ").append(resource.defaultHostname()) .append("\n\tApp service plan: ").append(resource.appServicePlanId()) .append("\n\tHost name bindings: "); for (HostnameBinding binding : resource.getHostnameBindings().values()) { builder = builder.append("\n\t\t" + binding.toString()); } builder = builder.append("\n\tSSL bindings: "); for (HostnameSslState binding : resource.hostnameSslStates().values()) { builder = builder.append("\n\t\t" + binding.name() + ": " + binding.sslState()); if (binding.sslState() != null && binding.sslState() != SslState.DISABLED) { builder = builder.append(" - " + binding.thumbprint()); } } builder = builder.append("\n\tApp settings: "); for (AppSetting setting : resource.getAppSettings().values()) { builder = builder.append("\n\t\t" + setting.key() + ": " + setting.value() + (setting.sticky() ? " - slot setting" : "")); } builder = builder.append("\n\tConnection strings: "); for (ConnectionString conn : resource.getConnectionStrings().values()) { builder = builder.append("\n\t\t" + conn.name() + ": " + conn.value() + " - " + conn.type() + (conn.sticky() ? " - slot setting" : "")); } System.out.println(builder.toString()); } /** * Print a web site. * * @param resource a web site */ public static void print(WebSiteBase resource) { StringBuilder builder = new StringBuilder().append("Web app: ").append(resource.id()) .append("\n\tName: ").append(resource.name()) .append("\n\tState: ").append(resource.state()) .append("\n\tResource group: ").append(resource.resourceGroupName()) .append("\n\tRegion: ").append(resource.region()) .append("\n\tDefault hostname: ").append(resource.defaultHostname()) .append("\n\tApp service plan: ").append(resource.appServicePlanId()); builder = builder.append("\n\tSSL bindings: "); for (HostnameSslState binding : resource.hostnameSslStates().values()) { builder = builder.append("\n\t\t" + binding.name() + ": " + binding.sslState()); if (binding.sslState() != null && binding.sslState() != SslState.DISABLED) { builder = builder.append(" - " + binding.thumbprint()); } } System.out.println(builder.toString()); } /** * Print a traffic manager profile. * * @param profile a traffic manager profile */ public static void print(TrafficManagerProfile profile) { StringBuilder info = new StringBuilder(); info.append("Traffic Manager Profile: ").append(profile.id()) .append("\n\tName: ").append(profile.name()) .append("\n\tResource group: ").append(profile.resourceGroupName()) .append("\n\tRegion: ").append(profile.regionName()) .append("\n\tTags: ").append(profile.tags()) .append("\n\tDNSLabel: ").append(profile.dnsLabel()) .append("\n\tFQDN: ").append(profile.fqdn()) .append("\n\tTTL: ").append(profile.timeToLive()) .append("\n\tEnabled: ").append(profile.isEnabled()) .append("\n\tRoutingMethod: ").append(profile.trafficRoutingMethod()) .append("\n\tMonitor status: ").append(profile.monitorStatus()) .append("\n\tMonitoring port: ").append(profile.monitoringPort()) .append("\n\tMonitoring path: ").append(profile.monitoringPath()); Map<String, TrafficManagerAzureEndpoint> azureEndpoints = profile.azureEndpoints(); if (!azureEndpoints.isEmpty()) { info.append("\n\tAzure endpoints:"); int idx = 1; for (TrafficManagerAzureEndpoint endpoint : azureEndpoints.values()) { info.append("\n\t\tAzure endpoint: .append("\n\t\t\tId: ").append(endpoint.id()) .append("\n\t\t\tType: ").append(endpoint.endpointType()) .append("\n\t\t\tTarget resourceId: ").append(endpoint.targetAzureResourceId()) .append("\n\t\t\tTarget resourceType: ").append(endpoint.targetResourceType()) .append("\n\t\t\tMonitor status: ").append(endpoint.monitorStatus()) .append("\n\t\t\tEnabled: ").append(endpoint.isEnabled()) .append("\n\t\t\tRouting priority: ").append(endpoint.routingPriority()) .append("\n\t\t\tRouting weight: ").append(endpoint.routingWeight()); } } Map<String, TrafficManagerExternalEndpoint> externalEndpoints = profile.externalEndpoints(); if (!externalEndpoints.isEmpty()) { info.append("\n\tExternal endpoints:"); int idx = 1; for (TrafficManagerExternalEndpoint endpoint : externalEndpoints.values()) { info.append("\n\t\tExternal endpoint: .append("\n\t\t\tId: ").append(endpoint.id()) .append("\n\t\t\tType: ").append(endpoint.endpointType()) .append("\n\t\t\tFQDN: ").append(endpoint.fqdn()) .append("\n\t\t\tSource Traffic Location: ").append(endpoint.sourceTrafficLocation()) .append("\n\t\t\tMonitor status: ").append(endpoint.monitorStatus()) .append("\n\t\t\tEnabled: ").append(endpoint.isEnabled()) .append("\n\t\t\tRouting priority: ").append(endpoint.routingPriority()) .append("\n\t\t\tRouting weight: ").append(endpoint.routingWeight()); } } Map<String, TrafficManagerNestedProfileEndpoint> nestedProfileEndpoints = profile.nestedProfileEndpoints(); if (!nestedProfileEndpoints.isEmpty()) { info.append("\n\tNested profile endpoints:"); int idx = 1; for (TrafficManagerNestedProfileEndpoint endpoint : nestedProfileEndpoints.values()) { info.append("\n\t\tNested profile endpoint: .append("\n\t\t\tId: ").append(endpoint.id()) .append("\n\t\t\tType: ").append(endpoint.endpointType()) .append("\n\t\t\tNested profileId: ").append(endpoint.nestedProfileId()) .append("\n\t\t\tMinimum child threshold: ").append(endpoint.minimumChildEndpointCount()) .append("\n\t\t\tSource Traffic Location: ").append(endpoint.sourceTrafficLocation()) .append("\n\t\t\tMonitor status: ").append(endpoint.monitorStatus()) .append("\n\t\t\tEnabled: ").append(endpoint.isEnabled()) .append("\n\t\t\tRouting priority: ").append(endpoint.routingPriority()) .append("\n\t\t\tRouting weight: ").append(endpoint.routingWeight()); } } System.out.println(info.toString()); } /** * Print a dns zone. * * @param dnsZone a dns zone */ public static void print(DnsZone dnsZone) { StringBuilder info = new StringBuilder(); info.append("DNS Zone: ").append(dnsZone.id()) .append("\n\tName (Top level domain): ").append(dnsZone.name()) .append("\n\tResource group: ").append(dnsZone.resourceGroupName()) .append("\n\tRegion: ").append(dnsZone.regionName()) .append("\n\tTags: ").append(dnsZone.tags()) .append("\n\tName servers:"); for (String nameServer : dnsZone.nameServers()) { info.append("\n\t\t").append(nameServer); } SoaRecordSet soaRecordSet = dnsZone.getSoaRecordSet(); SoaRecord soaRecord = soaRecordSet.record(); info.append("\n\tSOA Record:") .append("\n\t\tHost:").append(soaRecord.host()) .append("\n\t\tEmail:").append(soaRecord.email()) .append("\n\t\tExpire time (seconds):").append(soaRecord.expireTime()) .append("\n\t\tRefresh time (seconds):").append(soaRecord.refreshTime()) .append("\n\t\tRetry time (seconds):").append(soaRecord.retryTime()) .append("\n\t\tNegative response cache ttl (seconds):").append(soaRecord.minimumTtl()) .append("\n\t\tTTL (seconds):").append(soaRecordSet.timeToLive()); PagedIterable<ARecordSet> aRecordSets = dnsZone.aRecordSets().list(); info.append("\n\tA Record sets:"); for (ARecordSet aRecordSet : aRecordSets) { info.append("\n\t\tId: ").append(aRecordSet.id()) .append("\n\t\tName: ").append(aRecordSet.name()) .append("\n\t\tTTL (seconds): ").append(aRecordSet.timeToLive()) .append("\n\t\tIP v4 addresses: "); for (String ipAddress : aRecordSet.ipv4Addresses()) { info.append("\n\t\t\t").append(ipAddress); } } PagedIterable<AaaaRecordSet> aaaaRecordSets = dnsZone.aaaaRecordSets().list(); info.append("\n\tAAAA Record sets:"); for (AaaaRecordSet aaaaRecordSet : aaaaRecordSets) { info.append("\n\t\tId: ").append(aaaaRecordSet.id()) .append("\n\t\tName: ").append(aaaaRecordSet.name()) .append("\n\t\tTTL (seconds): ").append(aaaaRecordSet.timeToLive()) .append("\n\t\tIP v6 addresses: "); for (String ipAddress : aaaaRecordSet.ipv6Addresses()) { info.append("\n\t\t\t").append(ipAddress); } } PagedIterable<CnameRecordSet> cnameRecordSets = dnsZone.cNameRecordSets().list(); info.append("\n\tCNAME Record sets:"); for (CnameRecordSet cnameRecordSet : cnameRecordSets) { info.append("\n\t\tId: ").append(cnameRecordSet.id()) .append("\n\t\tName: ").append(cnameRecordSet.name()) .append("\n\t\tTTL (seconds): ").append(cnameRecordSet.timeToLive()) .append("\n\t\tCanonical name: ").append(cnameRecordSet.canonicalName()); } PagedIterable<MxRecordSet> mxRecordSets = dnsZone.mxRecordSets().list(); info.append("\n\tMX Record sets:"); for (MxRecordSet mxRecordSet : mxRecordSets) { info.append("\n\t\tId: ").append(mxRecordSet.id()) .append("\n\t\tName: ").append(mxRecordSet.name()) .append("\n\t\tTTL (seconds): ").append(mxRecordSet.timeToLive()) .append("\n\t\tRecords: "); for (MxRecord mxRecord : mxRecordSet.records()) { info.append("\n\t\t\tExchange server, Preference: ") .append(mxRecord.exchange()) .append(" ") .append(mxRecord.preference()); } } PagedIterable<NsRecordSet> nsRecordSets = dnsZone.nsRecordSets().list(); info.append("\n\tNS Record sets:"); for (NsRecordSet nsRecordSet : nsRecordSets) { info.append("\n\t\tId: ").append(nsRecordSet.id()) .append("\n\t\tName: ").append(nsRecordSet.name()) .append("\n\t\tTTL (seconds): ").append(nsRecordSet.timeToLive()) .append("\n\t\tName servers: "); for (String nameServer : nsRecordSet.nameServers()) { info.append("\n\t\t\t").append(nameServer); } } PagedIterable<PtrRecordSet> ptrRecordSets = dnsZone.ptrRecordSets().list(); info.append("\n\tPTR Record sets:"); for (PtrRecordSet ptrRecordSet : ptrRecordSets) { info.append("\n\t\tId: ").append(ptrRecordSet.id()) .append("\n\t\tName: ").append(ptrRecordSet.name()) .append("\n\t\tTTL (seconds): ").append(ptrRecordSet.timeToLive()) .append("\n\t\tTarget domain names: "); for (String domainNames : ptrRecordSet.targetDomainNames()) { info.append("\n\t\t\t").append(domainNames); } } PagedIterable<SrvRecordSet> srvRecordSets = dnsZone.srvRecordSets().list(); info.append("\n\tSRV Record sets:"); for (SrvRecordSet srvRecordSet : srvRecordSets) { info.append("\n\t\tId: ").append(srvRecordSet.id()) .append("\n\t\tName: ").append(srvRecordSet.name()) .append("\n\t\tTTL (seconds): ").append(srvRecordSet.timeToLive()) .append("\n\t\tRecords: "); for (SrvRecord srvRecord : srvRecordSet.records()) { info.append("\n\t\t\tTarget, Port, Priority, Weight: ") .append(srvRecord.target()) .append(", ") .append(srvRecord.port()) .append(", ") .append(srvRecord.priority()) .append(", ") .append(srvRecord.weight()); } } PagedIterable<TxtRecordSet> txtRecordSets = dnsZone.txtRecordSets().list(); info.append("\n\tTXT Record sets:"); for (TxtRecordSet txtRecordSet : txtRecordSets) { info.append("\n\t\tId: ").append(txtRecordSet.id()) .append("\n\t\tName: ").append(txtRecordSet.name()) .append("\n\t\tTTL (seconds): ").append(txtRecordSet.timeToLive()) .append("\n\t\tRecords: "); for (TxtRecord txtRecord : txtRecordSet.records()) { if (txtRecord.value().size() > 0) { info.append("\n\t\t\tValue: ").append(txtRecord.value().get(0)); } } } System.out.println(info.toString()); } /** * Print a private dns zone. * * @param privateDnsZone a private dns zone */ public static void print(PrivateDnsZone privateDnsZone) { StringBuilder info = new StringBuilder(); info.append("Private DNS Zone: ").append(privateDnsZone.id()) .append("\n\tName (Top level domain): ").append(privateDnsZone.name()) .append("\n\tResource group: ").append(privateDnsZone.resourceGroupName()) .append("\n\tRegion: ").append(privateDnsZone.regionName()) .append("\n\tTags: ").append(privateDnsZone.tags()) .append("\n\tName servers:"); com.azure.resourcemanager.privatedns.models.SoaRecordSet soaRecordSet = privateDnsZone.getSoaRecordSet(); com.azure.resourcemanager.privatedns.models.SoaRecord soaRecord = soaRecordSet.record(); info.append("\n\tSOA Record:") .append("\n\t\tHost:").append(soaRecord.host()) .append("\n\t\tEmail:").append(soaRecord.email()) .append("\n\t\tExpire time (seconds):").append(soaRecord.expireTime()) .append("\n\t\tRefresh time (seconds):").append(soaRecord.refreshTime()) .append("\n\t\tRetry time (seconds):").append(soaRecord.retryTime()) .append("\n\t\tNegative response cache ttl (seconds):").append(soaRecord.minimumTtl()) .append("\n\t\tTTL (seconds):").append(soaRecordSet.timeToLive()); PagedIterable<com.azure.resourcemanager.privatedns.models.ARecordSet> aRecordSets = privateDnsZone .aRecordSets().list(); info.append("\n\tA Record sets:"); for (com.azure.resourcemanager.privatedns.models.ARecordSet aRecordSet : aRecordSets) { info.append("\n\t\tId: ").append(aRecordSet.id()) .append("\n\t\tName: ").append(aRecordSet.name()) .append("\n\t\tTTL (seconds): ").append(aRecordSet.timeToLive()) .append("\n\t\tIP v4 addresses: "); for (String ipAddress : aRecordSet.ipv4Addresses()) { info.append("\n\t\t\t").append(ipAddress); } } PagedIterable<com.azure.resourcemanager.privatedns.models.AaaaRecordSet> aaaaRecordSets = privateDnsZone .aaaaRecordSets().list(); info.append("\n\tAAAA Record sets:"); for (com.azure.resourcemanager.privatedns.models.AaaaRecordSet aaaaRecordSet : aaaaRecordSets) { info.append("\n\t\tId: ").append(aaaaRecordSet.id()) .append("\n\t\tName: ").append(aaaaRecordSet.name()) .append("\n\t\tTTL (seconds): ").append(aaaaRecordSet.timeToLive()) .append("\n\t\tIP v6 addresses: "); for (String ipAddress : aaaaRecordSet.ipv6Addresses()) { info.append("\n\t\t\t").append(ipAddress); } } PagedIterable<com.azure.resourcemanager.privatedns.models.CnameRecordSet> cnameRecordSets = privateDnsZone.cnameRecordSets().list(); info.append("\n\tCNAME Record sets:"); for (com.azure.resourcemanager.privatedns.models.CnameRecordSet cnameRecordSet : cnameRecordSets) { info.append("\n\t\tId: ").append(cnameRecordSet.id()) .append("\n\t\tName: ").append(cnameRecordSet.name()) .append("\n\t\tTTL (seconds): ").append(cnameRecordSet.timeToLive()) .append("\n\t\tCanonical name: ").append(cnameRecordSet.canonicalName()); } PagedIterable<com.azure.resourcemanager.privatedns.models.MxRecordSet> mxRecordSets = privateDnsZone.mxRecordSets().list(); info.append("\n\tMX Record sets:"); for (com.azure.resourcemanager.privatedns.models.MxRecordSet mxRecordSet : mxRecordSets) { info.append("\n\t\tId: ").append(mxRecordSet.id()) .append("\n\t\tName: ").append(mxRecordSet.name()) .append("\n\t\tTTL (seconds): ").append(mxRecordSet.timeToLive()) .append("\n\t\tRecords: "); for (com.azure.resourcemanager.privatedns.models.MxRecord mxRecord : mxRecordSet.records()) { info.append("\n\t\t\tExchange server, Preference: ") .append(mxRecord.exchange()) .append(" ") .append(mxRecord.preference()); } } PagedIterable<com.azure.resourcemanager.privatedns.models.PtrRecordSet> ptrRecordSets = privateDnsZone .ptrRecordSets().list(); info.append("\n\tPTR Record sets:"); for (com.azure.resourcemanager.privatedns.models.PtrRecordSet ptrRecordSet : ptrRecordSets) { info.append("\n\t\tId: ").append(ptrRecordSet.id()) .append("\n\t\tName: ").append(ptrRecordSet.name()) .append("\n\t\tTTL (seconds): ").append(ptrRecordSet.timeToLive()) .append("\n\t\tTarget domain names: "); for (String domainNames : ptrRecordSet.targetDomainNames()) { info.append("\n\t\t\t").append(domainNames); } } PagedIterable<com.azure.resourcemanager.privatedns.models.SrvRecordSet> srvRecordSets = privateDnsZone .srvRecordSets().list(); info.append("\n\tSRV Record sets:"); for (com.azure.resourcemanager.privatedns.models.SrvRecordSet srvRecordSet : srvRecordSets) { info.append("\n\t\tId: ").append(srvRecordSet.id()) .append("\n\t\tName: ").append(srvRecordSet.name()) .append("\n\t\tTTL (seconds): ").append(srvRecordSet.timeToLive()) .append("\n\t\tRecords: "); for (com.azure.resourcemanager.privatedns.models.SrvRecord srvRecord : srvRecordSet.records()) { info.append("\n\t\t\tTarget, Port, Priority, Weight: ") .append(srvRecord.target()) .append(", ") .append(srvRecord.port()) .append(", ") .append(srvRecord.priority()) .append(", ") .append(srvRecord.weight()); } } PagedIterable<com.azure.resourcemanager.privatedns.models.TxtRecordSet> txtRecordSets = privateDnsZone .txtRecordSets().list(); info.append("\n\tTXT Record sets:"); for (com.azure.resourcemanager.privatedns.models.TxtRecordSet txtRecordSet : txtRecordSets) { info.append("\n\t\tId: ").append(txtRecordSet.id()) .append("\n\t\tName: ").append(txtRecordSet.name()) .append("\n\t\tTTL (seconds): ").append(txtRecordSet.timeToLive()) .append("\n\t\tRecords: "); for (com.azure.resourcemanager.privatedns.models.TxtRecord txtRecord : txtRecordSet.records()) { if (txtRecord.value().size() > 0) { info.append("\n\t\t\tValue: ").append(txtRecord.value().get(0)); } } } PagedIterable<VirtualNetworkLink> virtualNetworkLinks = privateDnsZone.virtualNetworkLinks().list(); info.append("\n\tVirtual Network Links:"); for (VirtualNetworkLink virtualNetworkLink : virtualNetworkLinks) { info.append("\n\tId: ").append(virtualNetworkLink.id()) .append("\n\tName: ").append(virtualNetworkLink.name()) .append("\n\tReference of Virtual Network: ").append(virtualNetworkLink.referencedVirtualNetworkId()) .append("\n\tRegistration enabled: ").append(virtualNetworkLink.isAutoRegistrationEnabled()); } System.out.println(info.toString()); } /** * Print an Azure Container Registry. * * @param azureRegistry an Azure Container Registry */ public static void print(Registry azureRegistry) { StringBuilder info = new StringBuilder(); RegistryCredentials acrCredentials = azureRegistry.getCredentials(); info.append("Azure Container Registry: ").append(azureRegistry.id()) .append("\n\tName: ").append(azureRegistry.name()) .append("\n\tServer Url: ").append(azureRegistry.loginServerUrl()) .append("\n\tUser: ").append(acrCredentials.username()) .append("\n\tFirst Password: ").append(acrCredentials.accessKeys().get(AccessKeyType.PRIMARY)) .append("\n\tSecond Password: ").append(acrCredentials.accessKeys().get(AccessKeyType.SECONDARY)); System.out.println(info.toString()); } /** * Print an Azure Container Service (AKS). * * @param kubernetesCluster a managed container service */ public static void print(KubernetesCluster kubernetesCluster) { StringBuilder info = new StringBuilder(); info.append("Azure Container Service: ").append(kubernetesCluster.id()) .append("\n\tName: ").append(kubernetesCluster.name()) .append("\n\tFQDN: ").append(kubernetesCluster.fqdn()) .append("\n\tDNS prefix label: ").append(kubernetesCluster.dnsPrefix()) .append("\n\t\tWith Agent pool name: ").append(new ArrayList<>(kubernetesCluster.agentPools().keySet()).get(0)) .append("\n\t\tAgent pool count: ").append(new ArrayList<>(kubernetesCluster.agentPools().values()).get(0).count()) .append("\n\t\tAgent pool VM size: ").append(new ArrayList<>(kubernetesCluster.agentPools().values()).get(0).vmSize().toString()) .append("\n\tLinux user name: ").append(kubernetesCluster.linuxRootUsername()) .append("\n\tSSH key: ").append(kubernetesCluster.sshKey()) .append("\n\tService principal client ID: ").append(kubernetesCluster.servicePrincipalClientId()); System.out.println(info.toString()); } /** * Retrieve the secondary service principal client ID. * * @param envSecondaryServicePrincipal an Azure Container Registry * @return a service principal client ID * @throws Exception exception */
This done, we added the retry utility.
public Mono<ShouldRetryResult> shouldRetry(Exception e) { logger.debug("retry count {}, isReadRequest {}, canUseMultipleWriteLocations {}, due to failure:", cnt.incrementAndGet(), isReadRequest, canUseMultipleWriteLocations, e); if (this.locationEndpoint == null) { logger.error("locationEndpoint is null because ClientRetryPolicy::onBeforeRequest(.) is not invoked, " + "probably request creation failed due to invalid options, serialization setting, etc."); return Mono.just(ShouldRetryResult.error(e)); } this.retryContext = null; CosmosException clientException = Utils.as(e, CosmosException.class); if (clientException != null && clientException.getDiagnostics() != null) { this.cosmosDiagnostics = clientException.getDiagnostics(); } if (clientException != null && Exceptions.isStatusCode(clientException, HttpConstants.StatusCodes.FORBIDDEN) && Exceptions.isSubStatusCode(clientException, HttpConstants.SubStatusCodes.FORBIDDEN_WRITEFORBIDDEN)) { logger.warn("Endpoint not writable. Will refresh cache and retry ", e); return this.shouldRetryOnEndpointFailureAsync(false, true); } if (clientException != null && Exceptions.isStatusCode(clientException, HttpConstants.StatusCodes.FORBIDDEN) && Exceptions.isSubStatusCode(clientException, HttpConstants.SubStatusCodes.DATABASE_ACCOUNT_NOTFOUND) && this.isReadRequest) { logger.warn("Endpoint not available for reads. Will refresh cache and retry. ", e); return this.shouldRetryOnEndpointFailureAsync(true, false); } if (WebExceptionUtility.isNetworkFailure(e)) { if (clientException != null && Exceptions.isSubStatusCode(clientException, HttpConstants.SubStatusCodes.GATEWAY_ENDPOINT_UNAVAILABLE)) { if (this.isReadRequest || WebExceptionUtility.isWebExceptionRetriable(e)) { logger.warn("Gateway endpoint not reachable. Will refresh cache and retry. ", e); return this.shouldRetryOnEndpointFailureAsync(this.isReadRequest, false); } else { return this.shouldNotRetryOnEndpointFailureAsync(this.isReadRequest, false); } } else if (clientException != null && clientException.getCause() instanceof ReadTimeoutException) { if (this.operationType == OperationType.QueryPlan || this.operationType == OperationType.AddressRefresh) { return shouldRetryQueryPlanAndAddress(); } } else { logger.warn("Backend endpoint not reachable. ", e); return this.shouldRetryOnBackendServiceUnavailableAsync(this.isReadRequest, WebExceptionUtility .isWebExceptionRetriable(e)); } } if (clientException != null && Exceptions.isStatusCode(clientException, HttpConstants.StatusCodes.NOTFOUND) && Exceptions.isSubStatusCode(clientException, HttpConstants.SubStatusCodes.READ_SESSION_NOT_AVAILABLE)) { return Mono.just(this.shouldRetryOnSessionNotAvailable()); } return this.throttlingRetry.shouldRetry(e); }
} else if (clientException != null && clientException.getCause() instanceof ReadTimeoutException) {
public Mono<ShouldRetryResult> shouldRetry(Exception e) { logger.debug("retry count {}, isReadRequest {}, canUseMultipleWriteLocations {}, due to failure:", cnt.incrementAndGet(), isReadRequest, canUseMultipleWriteLocations, e); if (this.locationEndpoint == null) { logger.error("locationEndpoint is null because ClientRetryPolicy::onBeforeRequest(.) is not invoked, " + "probably request creation failed due to invalid options, serialization setting, etc."); return Mono.just(ShouldRetryResult.error(e)); } this.retryContext = null; CosmosException clientException = Utils.as(e, CosmosException.class); if (clientException != null && clientException.getDiagnostics() != null) { this.cosmosDiagnostics = clientException.getDiagnostics(); } if (clientException != null && Exceptions.isStatusCode(clientException, HttpConstants.StatusCodes.FORBIDDEN) && Exceptions.isSubStatusCode(clientException, HttpConstants.SubStatusCodes.FORBIDDEN_WRITEFORBIDDEN)) { logger.warn("Endpoint not writable. Will refresh cache and retry ", e); return this.shouldRetryOnEndpointFailureAsync(false, true); } if (clientException != null && Exceptions.isStatusCode(clientException, HttpConstants.StatusCodes.FORBIDDEN) && Exceptions.isSubStatusCode(clientException, HttpConstants.SubStatusCodes.DATABASE_ACCOUNT_NOTFOUND) && this.isReadRequest) { logger.warn("Endpoint not available for reads. Will refresh cache and retry. ", e); return this.shouldRetryOnEndpointFailureAsync(true, false); } if (WebExceptionUtility.isNetworkFailure(e)) { if (clientException != null && Exceptions.isSubStatusCode(clientException, HttpConstants.SubStatusCodes.GATEWAY_ENDPOINT_UNAVAILABLE)) { if (this.isReadRequest || WebExceptionUtility.isWebExceptionRetriable(e)) { logger.warn("Gateway endpoint not reachable. Will refresh cache and retry. ", e); return this.shouldRetryOnEndpointFailureAsync(this.isReadRequest, false); } else { return this.shouldNotRetryOnEndpointFailureAsync(this.isReadRequest, false); } } else if (clientException != null && WebExceptionUtility.isReadTimeoutException(clientException) && Exceptions.isSubStatusCode(clientException, HttpConstants.SubStatusCodes.GATEWAY_ENDPOINT_READ_TIMEOUT)) { if (this.request.getOperationType() == OperationType.QueryPlan || this.request.isAddressRefresh()) { return shouldRetryQueryPlanAndAddress(); } } else { logger.warn("Backend endpoint not reachable. ", e); return this.shouldRetryOnBackendServiceUnavailableAsync(this.isReadRequest, WebExceptionUtility .isWebExceptionRetriable(e)); } } if (clientException != null && Exceptions.isStatusCode(clientException, HttpConstants.StatusCodes.NOTFOUND) && Exceptions.isSubStatusCode(clientException, HttpConstants.SubStatusCodes.READ_SESSION_NOT_AVAILABLE)) { return Mono.just(this.shouldRetryOnSessionNotAvailable()); } return this.throttlingRetry.shouldRetry(e); }
class ClientRetryPolicy extends DocumentClientRetryPolicy { private final static Logger logger = LoggerFactory.getLogger(ClientRetryPolicy.class); final static int RetryIntervalInMS = 1000; final static int MaxRetryCount = 120; private final static int MaxServiceUnavailableRetryCount = 1; private final static int MAX_QUERYPLAN_ADDRESS_RETRY_COUNT = 2; private final DocumentClientRetryPolicy throttlingRetry; private final GlobalEndpointManager globalEndpointManager; private final boolean enableEndpointDiscovery; private int failoverRetryCount; private int sessionTokenRetryCount; private boolean isReadRequest; private boolean canUseMultipleWriteLocations; private URI locationEndpoint; private RetryContext retryContext; private CosmosDiagnostics cosmosDiagnostics; private AtomicInteger cnt = new AtomicInteger(0); private int serviceUnavailableRetryCount; private int queryplanAddressRefreshCount; private OperationType operationType; public ClientRetryPolicy(GlobalEndpointManager globalEndpointManager, boolean enableEndpointDiscovery, ThrottlingRetryOptions throttlingRetryOptions) { this.throttlingRetry = new ResourceThrottleRetryPolicy( throttlingRetryOptions.getMaxRetryAttemptsOnThrottledRequests(), throttlingRetryOptions.getMaxRetryWaitTime()); this.globalEndpointManager = globalEndpointManager; this.failoverRetryCount = 0; this.enableEndpointDiscovery = enableEndpointDiscovery; this.sessionTokenRetryCount = 0; this.canUseMultipleWriteLocations = false; this.cosmosDiagnostics = BridgeInternal.createCosmosDiagnostics(); } @Override private Mono<ShouldRetryResult> shouldRetryQueryPlanAndAddress() { if (this.queryplanAddressRefreshCount++ > MAX_QUERYPLAN_ADDRESS_RETRY_COUNT) { logger .warn("shouldRetryQueryPlanAndAddress() Not retrying. Retry count = {}", this.serviceUnavailableRetryCount); return Mono.just(ShouldRetryResult.noRetry()); } Duration retryDelay = Duration.ZERO; return Mono.just(ShouldRetryResult.retryAfter(retryDelay)); } private ShouldRetryResult shouldRetryOnSessionNotAvailable() { this.sessionTokenRetryCount++; if (!this.enableEndpointDiscovery) { return ShouldRetryResult.noRetry(); } else { if (this.canUseMultipleWriteLocations) { UnmodifiableList<URI> endpoints = this.isReadRequest ? this.globalEndpointManager.getReadEndpoints() : this.globalEndpointManager.getWriteEndpoints(); if (this.sessionTokenRetryCount > endpoints.size()) { return ShouldRetryResult.noRetry(); } else { this.retryContext = new RetryContext(this.sessionTokenRetryCount - 1, this.sessionTokenRetryCount > 1); return ShouldRetryResult.retryAfter(Duration.ZERO); } } else { if (this.sessionTokenRetryCount > 1) { return ShouldRetryResult.noRetry(); } else { this.retryContext = new RetryContext(this.sessionTokenRetryCount - 1, false); return ShouldRetryResult.retryAfter(Duration.ZERO); } } } } private Mono<ShouldRetryResult> shouldRetryOnEndpointFailureAsync(boolean isReadRequest , boolean forceRefresh) { if (!this.enableEndpointDiscovery || this.failoverRetryCount > MaxRetryCount) { logger.warn("ShouldRetryOnEndpointFailureAsync() Not retrying. Retry count = {}", this.failoverRetryCount); return Mono.just(ShouldRetryResult.noRetry()); } Mono<Void> refreshLocationCompletable = this.refreshLocation(isReadRequest, forceRefresh); Duration retryDelay = Duration.ZERO; if (!isReadRequest) { logger.debug("Failover happening. retryCount {}", this.failoverRetryCount); if (this.failoverRetryCount > 1) { retryDelay = Duration.ofMillis(ClientRetryPolicy.RetryIntervalInMS); } } else { retryDelay = Duration.ofMillis(ClientRetryPolicy.RetryIntervalInMS); } return refreshLocationCompletable.then(Mono.just(ShouldRetryResult.retryAfter(retryDelay))); } private Mono<ShouldRetryResult> shouldNotRetryOnEndpointFailureAsync(boolean isReadRequest , boolean forceRefresh) { if (!this.enableEndpointDiscovery || this.failoverRetryCount > MaxRetryCount) { logger.warn("ShouldRetryOnEndpointFailureAsync() Not retrying. Retry count = {}", this.failoverRetryCount); return Mono.just(ShouldRetryResult.noRetry()); } Mono<Void> refreshLocationCompletable = this.refreshLocation(isReadRequest, forceRefresh); return refreshLocationCompletable.then(Mono.just(ShouldRetryResult.noRetry())); } private Mono<Void> refreshLocation(boolean isReadRequest, boolean forceRefresh) { this.failoverRetryCount++; if (isReadRequest) { logger.warn("marking the endpoint {} as unavailable for read",this.locationEndpoint); this.globalEndpointManager.markEndpointUnavailableForRead(this.locationEndpoint); } else { logger.warn("marking the endpoint {} as unavailable for write",this.locationEndpoint); this.globalEndpointManager.markEndpointUnavailableForWrite(this.locationEndpoint); } this.retryContext = new RetryContext(this.failoverRetryCount, false); return this.globalEndpointManager.refreshLocationAsync(null, forceRefresh); } private Mono<ShouldRetryResult> shouldRetryOnBackendServiceUnavailableAsync(boolean isReadRequest, boolean isWebExceptionRetriable) { if (!isReadRequest && !isWebExceptionRetriable) { logger.warn("shouldRetryOnBackendServiceUnavailableAsync() Not retrying on write with non retriable exception. Retry count = {}", this.serviceUnavailableRetryCount); return Mono.just(ShouldRetryResult.noRetry()); } if (this.serviceUnavailableRetryCount++ > MaxServiceUnavailableRetryCount) { logger.warn("shouldRetryOnBackendServiceUnavailableAsync() Not retrying. Retry count = {}", this.serviceUnavailableRetryCount); return Mono.just(ShouldRetryResult.noRetry()); } if (!this.canUseMultipleWriteLocations && !isReadRequest) { return Mono.just(ShouldRetryResult.noRetry()); } int availablePreferredLocations = this.globalEndpointManager.getPreferredLocationCount(); if (availablePreferredLocations <= 1) { logger.warn("shouldRetryOnServiceUnavailable() Not retrying. No other regions available for the request. AvailablePreferredLocations = {}", availablePreferredLocations); return Mono.just(ShouldRetryResult.noRetry()); } logger.warn("shouldRetryOnServiceUnavailable() Retrying. Received on endpoint {}, IsReadRequest = {}", this.locationEndpoint, isReadRequest); this.retryContext = new RetryContext(this.serviceUnavailableRetryCount, true); return Mono.just(ShouldRetryResult.retryAfter(Duration.ZERO)); } @Override public void onBeforeSendRequest(RxDocumentServiceRequest request) { this.operationType = request.getOperationType(); this.isReadRequest = request.isReadOnlyRequest(); this.canUseMultipleWriteLocations = this.globalEndpointManager.canUseMultipleWriteLocations(request); if (request.requestContext != null) { request.requestContext.cosmosDiagnostics = this.cosmosDiagnostics; } if (request.requestContext != null) { request.requestContext.clearRouteToLocation(); } if (this.retryContext != null) { request.requestContext.routeToLocation(this.retryContext.retryCount, this.retryContext.retryRequestOnPreferredLocations); } this.locationEndpoint = this.globalEndpointManager.resolveServiceEndpoint(request); if (request.requestContext != null) { request.requestContext.routeToLocation(this.locationEndpoint); } } private static class RetryContext { public int retryCount; public boolean retryRequestOnPreferredLocations; public RetryContext(int retryCount, boolean retryRequestOnPreferredLocations) { this.retryCount = retryCount; this.retryRequestOnPreferredLocations = retryRequestOnPreferredLocations; } } }
class ClientRetryPolicy extends DocumentClientRetryPolicy { private final static Logger logger = LoggerFactory.getLogger(ClientRetryPolicy.class); final static int RetryIntervalInMS = 1000; final static int MaxRetryCount = 120; private final static int MaxServiceUnavailableRetryCount = 1; private final static int MAX_QUERY_PLAN_AND_ADDRESS_RETRY_COUNT = 2; private final DocumentClientRetryPolicy throttlingRetry; private final GlobalEndpointManager globalEndpointManager; private final boolean enableEndpointDiscovery; private int failoverRetryCount; private int sessionTokenRetryCount; private boolean isReadRequest; private boolean canUseMultipleWriteLocations; private URI locationEndpoint; private RetryContext retryContext; private CosmosDiagnostics cosmosDiagnostics; private AtomicInteger cnt = new AtomicInteger(0); private int serviceUnavailableRetryCount; private int queryPlanAddressRefreshCount; private RxDocumentServiceRequest request; public ClientRetryPolicy(GlobalEndpointManager globalEndpointManager, boolean enableEndpointDiscovery, ThrottlingRetryOptions throttlingRetryOptions) { this.throttlingRetry = new ResourceThrottleRetryPolicy( throttlingRetryOptions.getMaxRetryAttemptsOnThrottledRequests(), throttlingRetryOptions.getMaxRetryWaitTime()); this.globalEndpointManager = globalEndpointManager; this.failoverRetryCount = 0; this.enableEndpointDiscovery = enableEndpointDiscovery; this.sessionTokenRetryCount = 0; this.canUseMultipleWriteLocations = false; this.cosmosDiagnostics = BridgeInternal.createCosmosDiagnostics(); } @Override private Mono<ShouldRetryResult> shouldRetryQueryPlanAndAddress() { if (this.queryPlanAddressRefreshCount++ > MAX_QUERY_PLAN_AND_ADDRESS_RETRY_COUNT) { logger .warn( "shouldRetryQueryPlanAndAddress() No more retrying on endpoint {}, operationType = {}, count = {}, " + "isAddressRefresh = {}", this.locationEndpoint, this.request.getOperationType(), this.queryPlanAddressRefreshCount, this.request.isAddressRefresh()); return Mono.just(ShouldRetryResult.noRetry()); } logger .warn("shouldRetryQueryPlanAndAddress() Retrying on endpoint {}, operationType = {}, count = {}, " + "isAddressRefresh = {}", this.locationEndpoint, this.request.getOperationType(), this.queryPlanAddressRefreshCount, this.request.isAddressRefresh()); Duration retryDelay = Duration.ZERO; return Mono.just(ShouldRetryResult.retryAfter(retryDelay)); } private ShouldRetryResult shouldRetryOnSessionNotAvailable() { this.sessionTokenRetryCount++; if (!this.enableEndpointDiscovery) { return ShouldRetryResult.noRetry(); } else { if (this.canUseMultipleWriteLocations) { UnmodifiableList<URI> endpoints = this.isReadRequest ? this.globalEndpointManager.getReadEndpoints() : this.globalEndpointManager.getWriteEndpoints(); if (this.sessionTokenRetryCount > endpoints.size()) { return ShouldRetryResult.noRetry(); } else { this.retryContext = new RetryContext(this.sessionTokenRetryCount - 1, this.sessionTokenRetryCount > 1); return ShouldRetryResult.retryAfter(Duration.ZERO); } } else { if (this.sessionTokenRetryCount > 1) { return ShouldRetryResult.noRetry(); } else { this.retryContext = new RetryContext(this.sessionTokenRetryCount - 1, false); return ShouldRetryResult.retryAfter(Duration.ZERO); } } } } private Mono<ShouldRetryResult> shouldRetryOnEndpointFailureAsync(boolean isReadRequest , boolean forceRefresh) { if (!this.enableEndpointDiscovery || this.failoverRetryCount > MaxRetryCount) { logger.warn("ShouldRetryOnEndpointFailureAsync() Not retrying. Retry count = {}", this.failoverRetryCount); return Mono.just(ShouldRetryResult.noRetry()); } Mono<Void> refreshLocationCompletable = this.refreshLocation(isReadRequest, forceRefresh); Duration retryDelay = Duration.ZERO; if (!isReadRequest) { logger.debug("Failover happening. retryCount {}", this.failoverRetryCount); if (this.failoverRetryCount > 1) { retryDelay = Duration.ofMillis(ClientRetryPolicy.RetryIntervalInMS); } } else { retryDelay = Duration.ofMillis(ClientRetryPolicy.RetryIntervalInMS); } return refreshLocationCompletable.then(Mono.just(ShouldRetryResult.retryAfter(retryDelay))); } private Mono<ShouldRetryResult> shouldNotRetryOnEndpointFailureAsync(boolean isReadRequest , boolean forceRefresh) { if (!this.enableEndpointDiscovery || this.failoverRetryCount > MaxRetryCount) { logger.warn("ShouldRetryOnEndpointFailureAsync() Not retrying. Retry count = {}", this.failoverRetryCount); return Mono.just(ShouldRetryResult.noRetry()); } Mono<Void> refreshLocationCompletable = this.refreshLocation(isReadRequest, forceRefresh); return refreshLocationCompletable.then(Mono.just(ShouldRetryResult.noRetry())); } private Mono<Void> refreshLocation(boolean isReadRequest, boolean forceRefresh) { this.failoverRetryCount++; if (isReadRequest) { logger.warn("marking the endpoint {} as unavailable for read",this.locationEndpoint); this.globalEndpointManager.markEndpointUnavailableForRead(this.locationEndpoint); } else { logger.warn("marking the endpoint {} as unavailable for write",this.locationEndpoint); this.globalEndpointManager.markEndpointUnavailableForWrite(this.locationEndpoint); } this.retryContext = new RetryContext(this.failoverRetryCount, false); return this.globalEndpointManager.refreshLocationAsync(null, forceRefresh); } private Mono<ShouldRetryResult> shouldRetryOnBackendServiceUnavailableAsync(boolean isReadRequest, boolean isWebExceptionRetriable) { if (!isReadRequest && !isWebExceptionRetriable) { logger.warn("shouldRetryOnBackendServiceUnavailableAsync() Not retrying on write with non retriable exception. Retry count = {}", this.serviceUnavailableRetryCount); return Mono.just(ShouldRetryResult.noRetry()); } if (this.serviceUnavailableRetryCount++ > MaxServiceUnavailableRetryCount) { logger.warn("shouldRetryOnBackendServiceUnavailableAsync() Not retrying. Retry count = {}", this.serviceUnavailableRetryCount); return Mono.just(ShouldRetryResult.noRetry()); } if (!this.canUseMultipleWriteLocations && !isReadRequest) { return Mono.just(ShouldRetryResult.noRetry()); } int availablePreferredLocations = this.globalEndpointManager.getPreferredLocationCount(); if (availablePreferredLocations <= 1) { logger.warn("shouldRetryOnServiceUnavailable() Not retrying. No other regions available for the request. AvailablePreferredLocations = {}", availablePreferredLocations); return Mono.just(ShouldRetryResult.noRetry()); } logger.warn("shouldRetryOnServiceUnavailable() Retrying. Received on endpoint {}, IsReadRequest = {}", this.locationEndpoint, isReadRequest); this.retryContext = new RetryContext(this.serviceUnavailableRetryCount, true); return Mono.just(ShouldRetryResult.retryAfter(Duration.ZERO)); } @Override public void onBeforeSendRequest(RxDocumentServiceRequest request) { this.request = request; this.isReadRequest = request.isReadOnlyRequest(); this.canUseMultipleWriteLocations = this.globalEndpointManager.canUseMultipleWriteLocations(request); if (request.requestContext != null) { request.requestContext.cosmosDiagnostics = this.cosmosDiagnostics; } if (request.requestContext != null) { request.requestContext.clearRouteToLocation(); } if (this.retryContext != null) { request.requestContext.routeToLocation(this.retryContext.retryCount, this.retryContext.retryRequestOnPreferredLocations); } this.locationEndpoint = this.globalEndpointManager.resolveServiceEndpoint(request); if (request.requestContext != null) { request.requestContext.routeToLocation(this.locationEndpoint); } } private static class RetryContext { public int retryCount; public boolean retryRequestOnPreferredLocations; public RetryContext(int retryCount, boolean retryRequestOnPreferredLocations) { this.retryCount = retryCount; this.retryRequestOnPreferredLocations = retryRequestOnPreferredLocations; } } }
Hide these to Utils.
public static boolean runSample(AzureResourceManager azureResourceManager, String clientId) throws IOException, KeyStoreException, CertificateException, NoSuchAlgorithmException { final String rgName = Utils.randomResourceName(azureResourceManager, "rg", 24); final String serviceName = Utils.randomResourceName(azureResourceManager, "service", 24); final Region region = Region.US_EAST; final String domainName = Utils.randomResourceName(azureResourceManager, "jsdkdemo-", 20) + ".com"; final String certOrderName = Utils.randomResourceName(azureResourceManager, "cert", 15); final String vaultName = Utils.randomResourceName(azureResourceManager, "vault", 15); final String certName = Utils.randomResourceName(azureResourceManager, "cert", 15); try { azureResourceManager.resourceGroups().define(rgName) .withRegion(region) .create(); System.out.printf("Creating spring cloud service %s in resource group %s ...%n", serviceName, rgName); SpringService service = azureResourceManager.springServices().define(serviceName) .withRegion(region) .withExistingResourceGroup(rgName) .create(); System.out.printf("Created spring cloud service %s%n", service.name()); Utils.print(service); File gzFile = new File("piggymetrics.tar.gz"); if (!gzFile.exists()) { HttpURLConnection connection = (HttpURLConnection) new URL(PIGGYMETRICS_TAR_GZ_URL).openConnection(); connection.connect(); try (InputStream inputStream = connection.getInputStream(); OutputStream outputStream = new FileOutputStream(gzFile)) { IOUtils.copy(inputStream, outputStream); } connection.disconnect(); } System.out.printf("Creating spring cloud app gateway in resource group %s ...%n", rgName); SpringApp gateway = service.apps().define("gateway") .defineActiveDeployment("default") .withSourceCodeTarGzFile(gzFile) .withTargetModule("gateway") .attach() .withDefaultPublicEndpoint() .withHttpsOnly() .create(); System.out.println("Created spring cloud service gateway"); Utils.print(gateway); System.out.printf("Creating spring cloud app auth-service in resource group %s ...%n", rgName); SpringApp authService = service.apps().define("auth-service") .defineActiveDeployment("default") .withSourceCodeTarGzFile(gzFile) .withTargetModule("auth-service") .attach() .create(); System.out.println("Created spring cloud service auth-service"); Utils.print(authService); System.out.printf("Creating spring cloud app account-service in resource group %s ...%n", rgName); SpringApp accountService = service.apps().define("account-service") .defineActiveDeployment("default") .withSourceCodeTarGzFile(gzFile) .withTargetModule("account-service") .attach() .create(); System.out.println("Created spring cloud service account-service"); Utils.print(accountService); System.out.println("Purchasing a domain " + domainName + "..."); AppServiceDomain domain = azureResourceManager.appServiceDomains().define(domainName) .withExistingResourceGroup(rgName) .defineRegistrantContact() .withFirstName("Jon") .withLastName("Doe") .withEmail("jondoe@contoso.com") .withAddressLine1("123 4th Ave") .withCity("Redmond") .withStateOrProvince("WA") .withCountry(CountryIsoCode.UNITED_STATES) .withPostalCode("98052") .withPhoneCountryCode(CountryPhoneCode.UNITED_STATES) .withPhoneNumber("4258828080") .attach() .withDomainPrivacyEnabled(true) .withAutoRenewEnabled(false) .create(); System.out.println("Purchased domain " + domain.name()); Utils.print(domain); DnsZone dnsZone = azureResourceManager.dnsZones().getById(domain.dnsZoneId()); gateway.refresh(); System.out.printf("Updating dns with CNAME ssl.%s to %s%n", domainName, gateway.fqdn()); dnsZone.update() .withCNameRecordSet("ssl", gateway.fqdn()) .apply(); System.out.printf("Purchasing a certificate for *.%s and save to %s in key vault named %s ...%n", domainName, certOrderName, vaultName); AppServiceCertificateOrder certificateOrder = azureResourceManager.appServiceCertificateOrders().define(certOrderName) .withExistingResourceGroup(rgName) .withHostName(String.format("*.%s", domainName)) .withWildcardSku() .withDomainVerification(domain) .withNewKeyVault(vaultName, region) .withAutoRenew(true) .create(); System.out.printf("Purchased certificate: *.%s ...%n", domain.name()); Utils.print(certificateOrder); System.out.printf("Updating key vault %s with access from %s, %s%n", vaultName, clientId, SPRING_CLOUD_SERVICE_PRINCIPAL); Vault vault = azureResourceManager.vaults().getByResourceGroup(rgName, vaultName); vault.update() .defineAccessPolicy() .forServicePrincipal(clientId) .allowSecretAllPermissions() .allowCertificateAllPermissions() .attach() .defineAccessPolicy() .forServicePrincipal(SPRING_CLOUD_SERVICE_PRINCIPAL) .allowCertificatePermissions(CertificatePermissions.GET, CertificatePermissions.LIST) .allowSecretPermissions(SecretPermissions.GET, SecretPermissions.LIST) .attach() .apply(); System.out.printf("Updated key vault %s%n", vault.name()); Utils.print(vault); Secret secret = vault.secrets().getByName(certOrderName); byte[] certificate = Base64.getDecoder().decode(secret.value()); String thumbprint = secret.tags().get("Thumbprint"); if (thumbprint == null || thumbprint.isEmpty()) { KeyStore store = KeyStore.getInstance("PKCS12"); store.load(new ByteArrayInputStream(certificate), null); String alias = Collections.list(store.aliases()).get(0); thumbprint = DatatypeConverter.printHexBinary(MessageDigest.getInstance("SHA-1").digest(store.getCertificate(alias).getEncoded())); } System.out.printf("Get certificate: %s%n", secret.value()); System.out.printf("Certificate Thumbprint: %s%n", thumbprint); CertificateClient certificateClient = new CertificateClientBuilder() .vaultUrl(vault.vaultUri()) .pipeline(service.manager().httpPipeline()) .buildClient(); System.out.printf("Uploading certificate to %s in key vault ...%n", certName); certificateClient.importCertificate( new ImportCertificateOptions(certName, certificate) .setEnabled(true) ); System.out.println("Updating Spring Cloud Service with certificate ..."); service.update() .withCertificate(certName, vault.vaultUri(), certName) .apply(); System.out.printf("Updating Spring Cloud App with domain ssl.%s ...%n", domainName); gateway.update() .withCustomDomain(String.format("ssl.%s", domainName), thumbprint) .apply(); System.out.printf("Successfully expose domain ssl.%s%n", domainName); return true; } finally { try { System.out.println("Delete Resource Group: " + rgName); azureResourceManager.resourceGroups().beginDeleteByName(rgName); } catch (NullPointerException npe) { System.out.println("Did not create any resources in Azure. No clean up is necessary"); } catch (Exception g) { g.printStackTrace(); } } }
final String rgName = Utils.randomResourceName(azureResourceManager, "rg", 24);
public static boolean runSample(AzureResourceManager azureResourceManager, String clientId) throws IOException, KeyStoreException, CertificateException, NoSuchAlgorithmException { final String rgName = Utils.randomResourceName(azureResourceManager, "rg", 24); final String serviceName = Utils.randomResourceName(azureResourceManager, "service", 24); final Region region = Region.US_EAST; final String domainName = Utils.randomResourceName(azureResourceManager, "jsdkdemo-", 20) + ".com"; final String certOrderName = Utils.randomResourceName(azureResourceManager, "cert", 15); final String vaultName = Utils.randomResourceName(azureResourceManager, "vault", 15); final String certName = Utils.randomResourceName(azureResourceManager, "cert", 15); try { azureResourceManager.resourceGroups().define(rgName) .withRegion(region) .create(); System.out.printf("Creating spring cloud service %s in resource group %s ...%n", serviceName, rgName); SpringService service = azureResourceManager.springServices().define(serviceName) .withRegion(region) .withExistingResourceGroup(rgName) .create(); System.out.printf("Created spring cloud service %s%n", service.name()); Utils.print(service); File gzFile = new File("piggymetrics.tar.gz"); if (!gzFile.exists()) { HttpURLConnection connection = (HttpURLConnection) new URL(PIGGYMETRICS_TAR_GZ_URL).openConnection(); connection.connect(); try (InputStream inputStream = connection.getInputStream(); OutputStream outputStream = new FileOutputStream(gzFile)) { IOUtils.copy(inputStream, outputStream); } connection.disconnect(); } System.out.printf("Creating spring cloud app gateway in resource group %s ...%n", rgName); SpringApp gateway = service.apps().define("gateway") .defineActiveDeployment("default") .withSourceCodeTarGzFile(gzFile) .withTargetModule("gateway") .attach() .withDefaultPublicEndpoint() .withHttpsOnly() .create(); System.out.println("Created spring cloud service gateway"); Utils.print(gateway); System.out.printf("Creating spring cloud app auth-service in resource group %s ...%n", rgName); SpringApp authService = service.apps().define("auth-service") .defineActiveDeployment("default") .withSourceCodeTarGzFile(gzFile) .withTargetModule("auth-service") .attach() .create(); System.out.println("Created spring cloud service auth-service"); Utils.print(authService); System.out.printf("Creating spring cloud app account-service in resource group %s ...%n", rgName); SpringApp accountService = service.apps().define("account-service") .defineActiveDeployment("default") .withSourceCodeTarGzFile(gzFile) .withTargetModule("account-service") .attach() .create(); System.out.println("Created spring cloud service account-service"); Utils.print(accountService); System.out.println("Purchasing a domain " + domainName + "..."); AppServiceDomain domain = azureResourceManager.appServiceDomains().define(domainName) .withExistingResourceGroup(rgName) .defineRegistrantContact() .withFirstName("Jon") .withLastName("Doe") .withEmail("jondoe@contoso.com") .withAddressLine1("123 4th Ave") .withCity("Redmond") .withStateOrProvince("WA") .withCountry(CountryIsoCode.UNITED_STATES) .withPostalCode("98052") .withPhoneCountryCode(CountryPhoneCode.UNITED_STATES) .withPhoneNumber("4258828080") .attach() .withDomainPrivacyEnabled(true) .withAutoRenewEnabled(false) .create(); System.out.println("Purchased domain " + domain.name()); Utils.print(domain); DnsZone dnsZone = azureResourceManager.dnsZones().getById(domain.dnsZoneId()); gateway.refresh(); System.out.printf("Updating dns with CNAME ssl.%s to %s%n", domainName, gateway.fqdn()); dnsZone.update() .withCNameRecordSet("ssl", gateway.fqdn()) .apply(); System.out.printf("Purchasing a certificate for *.%s and save to %s in key vault named %s ...%n", domainName, certOrderName, vaultName); AppServiceCertificateOrder certificateOrder = azureResourceManager.appServiceCertificateOrders().define(certOrderName) .withExistingResourceGroup(rgName) .withHostName(String.format("*.%s", domainName)) .withWildcardSku() .withDomainVerification(domain) .withNewKeyVault(vaultName, region) .withAutoRenew(true) .create(); System.out.printf("Purchased certificate: *.%s ...%n", domain.name()); Utils.print(certificateOrder); System.out.printf("Updating key vault %s with access from %s, %s%n", vaultName, clientId, SPRING_CLOUD_SERVICE_PRINCIPAL); Vault vault = azureResourceManager.vaults().getByResourceGroup(rgName, vaultName); vault.update() .defineAccessPolicy() .forServicePrincipal(clientId) .allowSecretAllPermissions() .allowCertificateAllPermissions() .attach() .defineAccessPolicy() .forServicePrincipal(SPRING_CLOUD_SERVICE_PRINCIPAL) .allowCertificatePermissions(CertificatePermissions.GET, CertificatePermissions.LIST) .allowSecretPermissions(SecretPermissions.GET, SecretPermissions.LIST) .attach() .apply(); System.out.printf("Updated key vault %s%n", vault.name()); Utils.print(vault); Secret secret = vault.secrets().getByName(certOrderName); byte[] certificate = Base64.getDecoder().decode(secret.value()); String thumbprint = secret.tags().get("Thumbprint"); if (thumbprint == null || thumbprint.isEmpty()) { KeyStore store = KeyStore.getInstance("PKCS12"); store.load(new ByteArrayInputStream(certificate), null); String alias = Collections.list(store.aliases()).get(0); thumbprint = DatatypeConverter.printHexBinary(MessageDigest.getInstance("SHA-1").digest(store.getCertificate(alias).getEncoded())); } System.out.printf("Get certificate: %s%n", secret.value()); System.out.printf("Certificate Thumbprint: %s%n", thumbprint); CertificateClient certificateClient = new CertificateClientBuilder() .vaultUrl(vault.vaultUri()) .pipeline(service.manager().httpPipeline()) .buildClient(); System.out.printf("Uploading certificate to %s in key vault ...%n", certName); certificateClient.importCertificate( new ImportCertificateOptions(certName, certificate) .setEnabled(true) ); System.out.println("Updating Spring Cloud Service with certificate ..."); service.update() .withCertificate(certName, vault.vaultUri(), certName) .apply(); System.out.printf("Updating Spring Cloud App with domain ssl.%s ...%n", domainName); gateway.update() .withCustomDomain(String.format("ssl.%s", domainName), thumbprint) .apply(); System.out.printf("Successfully expose domain ssl.%s%n", domainName); return true; } finally { try { System.out.println("Delete Resource Group: " + rgName); azureResourceManager.resourceGroups().beginDeleteByName(rgName); } catch (NullPointerException npe) { System.out.println("Did not create any resources in Azure. No clean up is necessary"); } catch (Exception g) { g.printStackTrace(); } } }
class ManageSpringCloud { private static final String PIGGYMETRICS_TAR_GZ_URL = "https: private static final String SPRING_CLOUD_SERVICE_PRINCIPAL = "03b39d0f-4213-4864-a245-b1476ec03169"; /** * Main function which runs the actual sample. * @param azureResourceManager instance of the azure client * @param clientId the aad client id in azure instance * @return true if sample runs successfully * @throws IllegalStateException unexcepted state */ /** * Main entry point. * @param args the parameters */ public static void main(String[] args) { try { final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); final TokenCredential credential = new DefaultAzureCredentialBuilder() .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); AzureResourceManager azureResourceManager = AzureResourceManager .configure() .withLogLevel(HttpLogDetailLevel.BASIC) .authenticate(credential, profile) .withDefaultSubscription(); System.out.println("Selected subscription: " + azureResourceManager.subscriptionId()); runSample(azureResourceManager, Configuration.getGlobalConfiguration().get(Configuration.PROPERTY_AZURE_CLIENT_ID)); } catch (Exception e) { System.out.println(e.getMessage()); e.printStackTrace(); } } public static void extraTarGzSource(File folder, URL url) throws IOException { HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.connect(); try (TarArchiveInputStream inputStream = new TarArchiveInputStream(new GzipCompressorInputStream(connection.getInputStream()))) { TarArchiveEntry entry; while ((entry = inputStream.getNextTarEntry()) != null) { if (entry.isDirectory()) { continue; } File file = new File(folder, entry.getName()); File parent = file.getParentFile(); if (parent.exists() || parent.mkdirs()) { try (OutputStream outputStream = new FileOutputStream(file)) { IOUtils.copy(inputStream, outputStream); } } else { throw new IllegalStateException("Cannot create directory: " + parent.getAbsolutePath()); } } } finally { connection.disconnect(); } } }
class ManageSpringCloud { private static final String PIGGYMETRICS_TAR_GZ_URL = "https: private static final String SPRING_CLOUD_SERVICE_PRINCIPAL = "03b39d0f-4213-4864-a245-b1476ec03169"; /** * Main function which runs the actual sample. * @param azureResourceManager instance of the azure client * @param clientId the aad client id in azure instance * @return true if sample runs successfully * @throws IllegalStateException unexcepted state */ /** * Main entry point. * @param args the parameters */ public static void main(String[] args) { try { final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); final TokenCredential credential = new DefaultAzureCredentialBuilder() .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); AzureResourceManager azureResourceManager = AzureResourceManager .configure() .withLogLevel(HttpLogDetailLevel.BASIC) .authenticate(credential, profile) .withDefaultSubscription(); System.out.println("Selected subscription: " + azureResourceManager.subscriptionId()); runSample(azureResourceManager, Configuration.getGlobalConfiguration().get(Configuration.PROPERTY_AZURE_CLIENT_ID)); } catch (Exception e) { System.out.println(e.getMessage()); e.printStackTrace(); } } public static void extraTarGzSource(File folder, URL url) throws IOException { HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.connect(); try (TarArchiveInputStream inputStream = new TarArchiveInputStream(new GzipCompressorInputStream(connection.getInputStream()))) { TarArchiveEntry entry; while ((entry = inputStream.getNextTarEntry()) != null) { if (entry.isDirectory()) { continue; } File file = new File(folder, entry.getName()); File parent = file.getParentFile(); if (parent.exists() || parent.mkdirs()) { try (OutputStream outputStream = new FileOutputStream(file)) { IOUtils.copy(inputStream, outputStream); } } else { throw new IllegalStateException("Cannot create directory: " + parent.getAbsolutePath()); } } } finally { connection.disconnect(); } } }
Rename it to `sendGetRequest`.
public static String getSecondaryServicePrincipalClientID(String envSecondaryServicePrincipal) throws IOException { String content = new String(Files.readAllBytes(new File(envSecondaryServicePrincipal).toPath()), StandardCharsets.UTF_8).trim(); HashMap<String, String> auth = new HashMap<>(); if (content.startsWith("{")) { auth = new JacksonAdapter().deserialize(content, auth.getClass(), SerializerEncoding.JSON); return auth.get("clientId"); } else { Properties authSettings = new Properties(); try (FileInputStream credentialsFileStream = new FileInputStream(new File(envSecondaryServicePrincipal))) { authSettings.load(credentialsFileStream); } return authSettings.getProperty("client"); } } /** * Retrieve the secondary service principal secret. * * @param envSecondaryServicePrincipal an Azure Container Registry * @return a service principal secret * @throws Exception exception */ public static String getSecondaryServicePrincipalSecret(String envSecondaryServicePrincipal) throws IOException { String content = new String(Files.readAllBytes(new File(envSecondaryServicePrincipal).toPath()), StandardCharsets.UTF_8).trim(); HashMap<String, String> auth = new HashMap<>(); if (content.startsWith("{")) { auth = new JacksonAdapter().deserialize(content, auth.getClass(), SerializerEncoding.JSON); return auth.get("clientSecret"); } else { Properties authSettings = new Properties(); try (FileInputStream credentialsFileStream = new FileInputStream(new File(envSecondaryServicePrincipal))) { authSettings.load(credentialsFileStream); } return authSettings.getProperty("key"); } } /** * This method creates a certificate for given password. * * @param certPath location of certificate file * @param pfxPath location of pfx file * @param alias User alias * @param password alias password * @param cnName domain name * @throws Exception exceptions from the creation * @throws IOException IO Exception */ public static void createCertificate(String certPath, String pfxPath, String alias, String password, String cnName) throws IOException { if (new File(pfxPath).exists()) { return; } String validityInDays = "3650"; String keyAlg = "RSA"; String sigAlg = "SHA1withRSA"; String keySize = "2048"; String storeType = "pkcs12"; String command = "keytool"; String jdkPath = System.getProperty("java.home"); if (jdkPath != null && !jdkPath.isEmpty()) { jdkPath = jdkPath.concat("\\bin"); if (new File(jdkPath).isDirectory()) { command = String.format("%s%s%s", jdkPath, File.separator, command); } } else { return; } String[] commandArgs = {command, "-genkey", "-alias", alias, "-keystore", pfxPath, "-storepass", password, "-validity", validityInDays, "-keyalg", keyAlg, "-sigalg", sigAlg, "-keysize", keySize, "-storetype", storeType, "-dname", "CN=" + cnName, "-ext", "EKU=1.3.6.1.5.5.7.3.1"}; Utils.cmdInvocation(commandArgs, true); File pfxFile = new File(pfxPath); if (pfxFile.exists()) { String[] certCommandArgs = {command, "-export", "-alias", alias, "-storetype", storeType, "-keystore", pfxPath, "-storepass", password, "-rfc", "-file", certPath}; Utils.cmdInvocation(certCommandArgs, true); File cerFile = new File(pfxPath); if (!cerFile.exists()) { throw new IOException( "Error occurred while creating certificate" + String.join(" ", certCommandArgs)); } } else { throw new IOException("Error occurred while creating certificates" + String.join(" ", commandArgs)); } } /** * This method is used for invoking native commands. * * @param command :- command to invoke. * @param ignoreErrorStream : Boolean which controls whether to throw exception or not * based on error stream. * @return result :- depending on the method invocation. * @throws Exception exceptions thrown from the execution */ public static String cmdInvocation(String[] command, boolean ignoreErrorStream) throws IOException { String result = ""; String error = ""; Process process = new ProcessBuilder(command).start(); try ( InputStream inputStream = process.getInputStream(); InputStream errorStream = process.getErrorStream(); BufferedReader br = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8)); BufferedReader ebr = new BufferedReader(new InputStreamReader(errorStream, StandardCharsets.UTF_8)); ) { result = br.readLine(); process.waitFor(); error = ebr.readLine(); if (error != null && (!error.equals(""))) { if (!ignoreErrorStream) { throw new IOException(error, null); } } } catch (Exception e) { throw new RuntimeException("Exception occurred while invoking command", e); } return result; } /** * Prints information for passed SQL Server. * * @param sqlServer sqlServer to be printed */ public static void print(SqlServer sqlServer) { StringBuilder builder = new StringBuilder().append("Sql Server: ").append(sqlServer.id()) .append("Name: ").append(sqlServer.name()) .append("\n\tResource group: ").append(sqlServer.resourceGroupName()) .append("\n\tRegion: ").append(sqlServer.region()) .append("\n\tSqlServer version: ").append(sqlServer.version()) .append("\n\tFully qualified name for Sql Server: ").append(sqlServer.fullyQualifiedDomainName()); System.out.println(builder.toString()); } /** * Prints information for the passed SQL Database. * * @param database database to be printed */ public static void print(SqlDatabase database) { StringBuilder builder = new StringBuilder().append("Sql Database: ").append(database.id()) .append("Name: ").append(database.name()) .append("\n\tResource group: ").append(database.resourceGroupName()) .append("\n\tRegion: ").append(database.region()) .append("\n\tSqlServer Name: ").append(database.sqlServerName()) .append("\n\tEdition of SQL database: ").append(database.edition()) .append("\n\tCollation of SQL database: ").append(database.collation()) .append("\n\tCreation date of SQL database: ").append(database.creationDate()) .append("\n\tIs data warehouse: ").append(database.isDataWarehouse()) .append("\n\tRequested service objective of SQL database: ").append(database.requestedServiceObjectiveName()) .append("\n\tName of current service objective of SQL database: ").append(database.currentServiceObjectiveName()) .append("\n\tMax size bytes of SQL database: ").append(database.maxSizeBytes()) .append("\n\tDefault secondary location of SQL database: ").append(database.defaultSecondaryLocation()); System.out.println(builder.toString()); } /** * Prints information for the passed firewall rule. * * @param firewallRule firewall rule to be printed. */ public static void print(SqlFirewallRule firewallRule) { StringBuilder builder = new StringBuilder().append("Sql firewall rule: ").append(firewallRule.id()) .append("Name: ").append(firewallRule.name()) .append("\n\tResource group: ").append(firewallRule.resourceGroupName()) .append("\n\tRegion: ").append(firewallRule.region()) .append("\n\tSqlServer Name: ").append(firewallRule.sqlServerName()) .append("\n\tStart IP Address of the firewall rule: ").append(firewallRule.startIpAddress()) .append("\n\tEnd IP Address of the firewall rule: ").append(firewallRule.endIpAddress()); System.out.println(builder.toString()); } /** * Prints information for the passed virtual network rule. * * @param virtualNetworkRule virtual network rule to be printed. */ public static void print(SqlVirtualNetworkRule virtualNetworkRule) { StringBuilder builder = new StringBuilder().append("SQL virtual network rule: ").append(virtualNetworkRule.id()) .append("Name: ").append(virtualNetworkRule.name()) .append("\n\tResource group: ").append(virtualNetworkRule.resourceGroupName()) .append("\n\tSqlServer Name: ").append(virtualNetworkRule.sqlServerName()) .append("\n\tSubnet ID: ").append(virtualNetworkRule.subnetId()) .append("\n\tState: ").append(virtualNetworkRule.state()); System.out.println(builder.toString()); } /** * Prints information for the passed SQL subscription usage metric. * * @param subscriptionUsageMetric metric to be printed. */ public static void print(SqlSubscriptionUsageMetric subscriptionUsageMetric) { StringBuilder builder = new StringBuilder().append("SQL Subscription Usage Metric: ").append(subscriptionUsageMetric.id()) .append("Name: ").append(subscriptionUsageMetric.name()) .append("\n\tDisplay Name: ").append(subscriptionUsageMetric.displayName()) .append("\n\tCurrent Value: ").append(subscriptionUsageMetric.currentValue()) .append("\n\tLimit: ").append(subscriptionUsageMetric.limit()) .append("\n\tUnit: ").append(subscriptionUsageMetric.unit()) .append("\n\tType: ").append(subscriptionUsageMetric.type()); System.out.println(builder.toString()); } /** * Prints information for the passed SQL database usage metric. * * @param dbUsageMetric metric to be printed. */ public static void print(SqlDatabaseUsageMetric dbUsageMetric) { StringBuilder builder = new StringBuilder().append("SQL Database Usage Metric") .append("Name: ").append(dbUsageMetric.name()) .append("\n\tResource Name: ").append(dbUsageMetric.resourceName()) .append("\n\tDisplay Name: ").append(dbUsageMetric.displayName()) .append("\n\tCurrent Value: ").append(dbUsageMetric.currentValue()) .append("\n\tLimit: ").append(dbUsageMetric.limit()) .append("\n\tUnit: ").append(dbUsageMetric.unit()) .append("\n\tNext Reset Time: ").append(dbUsageMetric.nextResetTime()); System.out.println(builder.toString()); } /** * Prints information for the passed SQL database metric. * * @param dbMetric metric to be printed. */ public static void print(SqlDatabaseMetric dbMetric) { StringBuilder builder = new StringBuilder().append("SQL Database Metric") .append("Name: ").append(dbMetric.name()) .append("\n\tStart Time: ").append(dbMetric.startTime()) .append("\n\tEnd Time: ").append(dbMetric.endTime()) .append("\n\tTime Grain: ").append(dbMetric.timeGrain()) .append("\n\tUnit: ").append(dbMetric.unit()); for (SqlDatabaseMetricValue metricValue : dbMetric.metricValues()) { builder .append("\n\tMetric Value: ") .append("\n\t\tCount: ").append(metricValue.count()) .append("\n\t\tAverage: ").append(metricValue.average()) .append("\n\t\tMaximum: ").append(metricValue.maximum()) .append("\n\t\tMinimum: ").append(metricValue.minimum()) .append("\n\t\tTimestamp: ").append(metricValue.timestamp()) .append("\n\t\tTotal: ").append(metricValue.total()); } System.out.println(builder.toString()); } /** * Prints information for the passed Failover Group. * * @param failoverGroup the SQL Failover Group to be printed. */ public static void print(SqlFailoverGroup failoverGroup) { StringBuilder builder = new StringBuilder().append("SQL Failover Group: ").append(failoverGroup.id()) .append("Name: ").append(failoverGroup.name()) .append("\n\tResource group: ").append(failoverGroup.resourceGroupName()) .append("\n\tSqlServer Name: ").append(failoverGroup.sqlServerName()) .append("\n\tRead-write endpoint policy: ").append(failoverGroup.readWriteEndpointPolicy()) .append("\n\tData loss grace period: ").append(failoverGroup.readWriteEndpointDataLossGracePeriodMinutes()) .append("\n\tRead-only endpoint policy: ").append(failoverGroup.readOnlyEndpointPolicy()) .append("\n\tReplication state: ").append(failoverGroup.replicationState()) .append("\n\tReplication role: ").append(failoverGroup.replicationRole()); builder.append("\n\tPartner Servers: "); for (PartnerInfo item : failoverGroup.partnerServers()) { builder .append("\n\t\tId: ").append(item.id()) .append("\n\t\tLocation: ").append(item.location()) .append("\n\t\tReplication role: ").append(item.replicationRole()); } builder.append("\n\tDatabases: "); for (String databaseId : failoverGroup.databases()) { builder.append("\n\t\tID: ").append(databaseId); } System.out.println(builder.toString()); } /** * Prints information for the passed SQL server key. * * @param serverKey virtual network rule to be printed. */ public static void print(SqlServerKey serverKey) { StringBuilder builder = new StringBuilder().append("SQL server key: ").append(serverKey.id()) .append("Name: ").append(serverKey.name()) .append("\n\tResource group: ").append(serverKey.resourceGroupName()) .append("\n\tSqlServer Name: ").append(serverKey.sqlServerName()) .append("\n\tRegion: ").append(serverKey.region() != null ? serverKey.region().name() : "") .append("\n\tServer Key Type: ").append(serverKey.serverKeyType()) .append("\n\tServer Key URI: ").append(serverKey.uri()) .append("\n\tServer Key Thumbprint: ").append(serverKey.thumbprint()) .append("\n\tServer Key Creation Date: ").append(serverKey.creationDate() != null ? serverKey.creationDate().toString() : ""); System.out.println(builder.toString()); } /** * Prints information of the elastic pool passed in. * * @param elasticPool elastic pool to be printed */ public static void print(SqlElasticPool elasticPool) { StringBuilder builder = new StringBuilder().append("Sql elastic pool: ").append(elasticPool.id()) .append("Name: ").append(elasticPool.name()) .append("\n\tResource group: ").append(elasticPool.resourceGroupName()) .append("\n\tRegion: ").append(elasticPool.region()) .append("\n\tSqlServer Name: ").append(elasticPool.sqlServerName()) .append("\n\tEdition of elastic pool: ").append(elasticPool.edition()) .append("\n\tTotal number of DTUs in the elastic pool: ").append(elasticPool.dtu()) .append("\n\tMaximum DTUs a database can get in elastic pool: ").append(elasticPool.databaseDtuMax()) .append("\n\tMinimum DTUs a database is guaranteed in elastic pool: ").append(elasticPool.databaseDtuMin()) .append("\n\tCreation date for the elastic pool: ").append(elasticPool.creationDate()) .append("\n\tState of the elastic pool: ").append(elasticPool.state()) .append("\n\tStorage capacity in MBs for the elastic pool: ").append(elasticPool.storageCapacity()); System.out.println(builder.toString()); } /** * Prints information of the elastic pool activity. * * @param elasticPoolActivity elastic pool activity to be printed */ public static void print(ElasticPoolActivity elasticPoolActivity) { StringBuilder builder = new StringBuilder().append("Sql elastic pool activity: ").append(elasticPoolActivity.id()) .append("Name: ").append(elasticPoolActivity.name()) .append("\n\tResource group: ").append(elasticPoolActivity.resourceGroupName()) .append("\n\tState: ").append(elasticPoolActivity.state()) .append("\n\tElastic pool name: ").append(elasticPoolActivity.elasticPoolName()) .append("\n\tStart time of activity: ").append(elasticPoolActivity.startTime()) .append("\n\tEnd time of activity: ").append(elasticPoolActivity.endTime()) .append("\n\tError code of activity: ").append(elasticPoolActivity.errorCode()) .append("\n\tError message of activity: ").append(elasticPoolActivity.errorMessage()) .append("\n\tError severity of activity: ").append(elasticPoolActivity.errorSeverity()) .append("\n\tOperation: ").append(elasticPoolActivity.operation()) .append("\n\tCompleted percentage of activity: ").append(elasticPoolActivity.percentComplete()) .append("\n\tRequested DTU max limit in activity: ").append(elasticPoolActivity.requestedDatabaseDtuMax()) .append("\n\tRequested DTU min limit in activity: ").append(elasticPoolActivity.requestedDatabaseDtuMin()) .append("\n\tRequested DTU limit in activity: ").append(elasticPoolActivity.requestedDtu()); System.out.println(builder.toString()); } /** * Prints information of the database activity. * * @param databaseActivity database activity to be printed */ public static void print(ElasticPoolDatabaseActivity databaseActivity) { StringBuilder builder = new StringBuilder().append("Sql elastic pool database activity: ").append(databaseActivity.id()) .append("Name: ").append(databaseActivity.name()) .append("\n\tResource group: ").append(databaseActivity.resourceGroupName()) .append("\n\tSQL Server Name: ").append(databaseActivity.serverName()) .append("\n\tDatabase name name: ").append(databaseActivity.databaseName()) .append("\n\tCurrent elastic pool name of the database: ").append(databaseActivity.currentElasticPoolName()) .append("\n\tState: ").append(databaseActivity.state()) .append("\n\tStart time of activity: ").append(databaseActivity.startTime()) .append("\n\tEnd time of activity: ").append(databaseActivity.endTime()) .append("\n\tCompleted percentage: ").append(databaseActivity.percentComplete()) .append("\n\tError code of activity: ").append(databaseActivity.errorCode()) .append("\n\tError message of activity: ").append(databaseActivity.errorMessage()) .append("\n\tError severity of activity: ").append(databaseActivity.errorSeverity()); System.out.println(builder.toString()); } /** * Print an application gateway. * * @param resource an application gateway */ public static void print(ApplicationGateway resource) { StringBuilder info = new StringBuilder(); info.append("Application gateway: ").append(resource.id()) .append("Name: ").append(resource.name()) .append("\n\tResource group: ").append(resource.resourceGroupName()) .append("\n\tRegion: ").append(resource.region()) .append("\n\tTags: ").append(resource.tags()) .append("\n\tSKU: ").append(resource.sku().toString()) .append("\n\tOperational state: ").append(resource.operationalState()) .append("\n\tInternet-facing? ").append(resource.isPublic()) .append("\n\tInternal? ").append(resource.isPrivate()) .append("\n\tDefault private IP address: ").append(resource.privateIpAddress()) .append("\n\tPrivate IP address allocation method: ").append(resource.privateIpAllocationMethod()) .append("\n\tDisabled SSL protocols: ").append(resource.disabledSslProtocols().toString()); Map<String, ApplicationGatewayIpConfiguration> ipConfigs = resource.ipConfigurations(); info.append("\n\tIP configurations: ").append(ipConfigs.size()); for (ApplicationGatewayIpConfiguration ipConfig : ipConfigs.values()) { info.append("\n\t\tName: ").append(ipConfig.name()) .append("\n\t\t\tNetwork id: ").append(ipConfig.networkId()) .append("\n\t\t\tSubnet name: ").append(ipConfig.subnetName()); } Map<String, ApplicationGatewayFrontend> frontends = resource.frontends(); info.append("\n\tFrontends: ").append(frontends.size()); for (ApplicationGatewayFrontend frontend : frontends.values()) { info.append("\n\t\tName: ").append(frontend.name()) .append("\n\t\t\tPublic? ").append(frontend.isPublic()); if (frontend.isPublic()) { info.append("\n\t\t\tPublic IP address ID: ").append(frontend.publicIpAddressId()); } if (frontend.isPrivate()) { info.append("\n\t\t\tPrivate IP address: ").append(frontend.privateIpAddress()) .append("\n\t\t\tPrivate IP allocation method: ").append(frontend.privateIpAllocationMethod()) .append("\n\t\t\tSubnet name: ").append(frontend.subnetName()) .append("\n\t\t\tVirtual network ID: ").append(frontend.networkId()); } } Map<String, ApplicationGatewayBackend> backends = resource.backends(); info.append("\n\tBackends: ").append(backends.size()); for (ApplicationGatewayBackend backend : backends.values()) { info.append("\n\t\tName: ").append(backend.name()) .append("\n\t\t\tAssociated NIC IP configuration IDs: ").append(backend.backendNicIPConfigurationNames().keySet()); Collection<ApplicationGatewayBackendAddress> addresses = backend.addresses(); info.append("\n\t\t\tAddresses: ").append(addresses.size()); for (ApplicationGatewayBackendAddress address : addresses) { info.append("\n\t\t\t\tFQDN: ").append(address.fqdn()) .append("\n\t\t\t\tIP: ").append(address.ipAddress()); } } Map<String, ApplicationGatewayBackendHttpConfiguration> httpConfigs = resource.backendHttpConfigurations(); info.append("\n\tHTTP Configurations: ").append(httpConfigs.size()); for (ApplicationGatewayBackendHttpConfiguration httpConfig : httpConfigs.values()) { info.append("\n\t\tName: ").append(httpConfig.name()) .append("\n\t\t\tCookie based affinity: ").append(httpConfig.cookieBasedAffinity()) .append("\n\t\t\tPort: ").append(httpConfig.port()) .append("\n\t\t\tRequest timeout in seconds: ").append(httpConfig.requestTimeout()) .append("\n\t\t\tProtocol: ").append(httpConfig.protocol()) .append("\n\t\tHost header: ").append(httpConfig.hostHeader()) .append("\n\t\tHost header comes from backend? ").append(httpConfig.isHostHeaderFromBackend()) .append("\n\t\tConnection draining timeout in seconds: ").append(httpConfig.connectionDrainingTimeoutInSeconds()) .append("\n\t\tAffinity cookie name: ").append(httpConfig.affinityCookieName()) .append("\n\t\tPath: ").append(httpConfig.path()); ApplicationGatewayProbe probe = httpConfig.probe(); if (probe != null) { info.append("\n\t\tProbe: " + probe.name()); } info.append("\n\t\tIs probe enabled? ").append(httpConfig.isProbeEnabled()); } Map<String, ApplicationGatewaySslCertificate> sslCerts = resource.sslCertificates(); info.append("\n\tSSL certificates: ").append(sslCerts.size()); for (ApplicationGatewaySslCertificate cert : sslCerts.values()) { info.append("\n\t\tName: ").append(cert.name()) .append("\n\t\t\tCert data: ").append(cert.publicData()); } Map<String, ApplicationGatewayRedirectConfiguration> redirects = resource.redirectConfigurations(); info.append("\n\tRedirect configurations: ").append(redirects.size()); for (ApplicationGatewayRedirectConfiguration redirect : redirects.values()) { info.append("\n\t\tName: ").append(redirect.name()) .append("\n\t\tTarget URL: ").append(redirect.type()) .append("\n\t\tTarget URL: ").append(redirect.targetUrl()) .append("\n\t\tTarget listener: ").append(redirect.targetListener() != null ? redirect.targetListener().name() : null) .append("\n\t\tIs path included? ").append(redirect.isPathIncluded()) .append("\n\t\tIs query string included? ").append(redirect.isQueryStringIncluded()) .append("\n\t\tReferencing request routing rules: ").append(redirect.requestRoutingRules().values()); } Map<String, ApplicationGatewayListener> listeners = resource.listeners(); info.append("\n\tHTTP listeners: ").append(listeners.size()); for (ApplicationGatewayListener listener : listeners.values()) { info.append("\n\t\tName: ").append(listener.name()) .append("\n\t\t\tHost name: ").append(listener.hostname()) .append("\n\t\t\tServer name indication required? ").append(listener.requiresServerNameIndication()) .append("\n\t\t\tAssociated frontend name: ").append(listener.frontend().name()) .append("\n\t\t\tFrontend port name: ").append(listener.frontendPortName()) .append("\n\t\t\tFrontend port number: ").append(listener.frontendPortNumber()) .append("\n\t\t\tProtocol: ").append(listener.protocol().toString()); if (listener.sslCertificate() != null) { info.append("\n\t\t\tAssociated SSL certificate: ").append(listener.sslCertificate().name()); } } Map<String, ApplicationGatewayProbe> probes = resource.probes(); info.append("\n\tProbes: ").append(probes.size()); for (ApplicationGatewayProbe probe : probes.values()) { info.append("\n\t\tName: ").append(probe.name()) .append("\n\t\tProtocol:").append(probe.protocol().toString()) .append("\n\t\tInterval in seconds: ").append(probe.timeBetweenProbesInSeconds()) .append("\n\t\tRetries: ").append(probe.retriesBeforeUnhealthy()) .append("\n\t\tTimeout: ").append(probe.timeoutInSeconds()) .append("\n\t\tHost: ").append(probe.host()) .append("\n\t\tHealthy HTTP response status code ranges: ").append(probe.healthyHttpResponseStatusCodeRanges()) .append("\n\t\tHealthy HTTP response body contents: ").append(probe.healthyHttpResponseBodyContents()); } Map<String, ApplicationGatewayRequestRoutingRule> rules = resource.requestRoutingRules(); info.append("\n\tRequest routing rules: ").append(rules.size()); for (ApplicationGatewayRequestRoutingRule rule : rules.values()) { info.append("\n\t\tName: ").append(rule.name()) .append("\n\t\tType: ").append(rule.ruleType()) .append("\n\t\tPublic IP address ID: ").append(rule.publicIpAddressId()) .append("\n\t\tHost name: ").append(rule.hostname()) .append("\n\t\tServer name indication required? ").append(rule.requiresServerNameIndication()) .append("\n\t\tFrontend port: ").append(rule.frontendPort()) .append("\n\t\tFrontend protocol: ").append(rule.frontendProtocol().toString()) .append("\n\t\tBackend port: ").append(rule.backendPort()) .append("\n\t\tCookie based affinity enabled? ").append(rule.cookieBasedAffinity()) .append("\n\t\tRedirect configuration: ").append(rule.redirectConfiguration() != null ? rule.redirectConfiguration().name() : "(none)"); Collection<ApplicationGatewayBackendAddress> addresses = rule.backendAddresses(); info.append("\n\t\t\tBackend addresses: ").append(addresses.size()); for (ApplicationGatewayBackendAddress address : addresses) { info.append("\n\t\t\t\t") .append(address.fqdn()) .append(" [").append(address.ipAddress()).append("]"); } info.append("\n\t\t\tSSL certificate name: "); ApplicationGatewaySslCertificate cert = rule.sslCertificate(); if (cert == null) { info.append("(None)"); } else { info.append(cert.name()); } info.append("\n\t\t\tAssociated backend address pool: "); ApplicationGatewayBackend backend = rule.backend(); if (backend == null) { info.append("(None)"); } else { info.append(backend.name()); } info.append("\n\t\t\tAssociated backend HTTP settings configuration: "); ApplicationGatewayBackendHttpConfiguration config = rule.backendHttpConfiguration(); if (config == null) { info.append("(None)"); } else { info.append(config.name()); } info.append("\n\t\t\tAssociated frontend listener: "); ApplicationGatewayListener listener = rule.listener(); if (listener == null) { info.append("(None)"); } else { info.append(config.name()); } } System.out.println(info.toString()); } /** * Prints information of a virtual machine custom image. * * @param image the image */ public static void print(VirtualMachineCustomImage image) { StringBuilder builder = new StringBuilder().append("Virtual machine custom image: ").append(image.id()) .append("Name: ").append(image.name()) .append("\n\tResource group: ").append(image.resourceGroupName()) .append("\n\tCreated from virtual machine: ").append(image.sourceVirtualMachineId()); builder.append("\n\tOS disk image: ") .append("\n\t\tOperating system: ").append(image.osDiskImage().osType()) .append("\n\t\tOperating system state: ").append(image.osDiskImage().osState()) .append("\n\t\tCaching: ").append(image.osDiskImage().caching()) .append("\n\t\tSize (GB): ").append(image.osDiskImage().diskSizeGB()); if (image.isCreatedFromVirtualMachine()) { builder.append("\n\t\tSource virtual machine: ").append(image.sourceVirtualMachineId()); } if (image.osDiskImage().managedDisk() != null) { builder.append("\n\t\tSource managed disk: ").append(image.osDiskImage().managedDisk().id()); } if (image.osDiskImage().snapshot() != null) { builder.append("\n\t\tSource snapshot: ").append(image.osDiskImage().snapshot().id()); } if (image.osDiskImage().blobUri() != null) { builder.append("\n\t\tSource un-managed vhd: ").append(image.osDiskImage().blobUri()); } if (image.dataDiskImages() != null) { for (ImageDataDisk diskImage : image.dataDiskImages().values()) { builder.append("\n\tDisk Image (Lun) .append("\n\t\tCaching: ").append(diskImage.caching()) .append("\n\t\tSize (GB): ").append(diskImage.diskSizeGB()); if (image.isCreatedFromVirtualMachine()) { builder.append("\n\t\tSource virtual machine: ").append(image.sourceVirtualMachineId()); } if (diskImage.managedDisk() != null) { builder.append("\n\t\tSource managed disk: ").append(diskImage.managedDisk().id()); } if (diskImage.snapshot() != null) { builder.append("\n\t\tSource snapshot: ").append(diskImage.snapshot().id()); } if (diskImage.blobUri() != null) { builder.append("\n\t\tSource un-managed vhd: ").append(diskImage.blobUri()); } } } System.out.println(builder.toString()); } /** * Uploads a file to an Azure app service. * * @param profile the publishing profile for the app service. * @param fileName the name of the file on server * @param file the local file */ public static void uploadFileViaFtp(PublishingProfile profile, String fileName, InputStream file) { FTPClient ftpClient = new FTPClient(); String[] ftpUrlSegments = profile.ftpUrl().split("/", 2); String server = ftpUrlSegments[0]; String path = "./site/wwwroot/webapps"; if (fileName.contains("/")) { int lastslash = fileName.lastIndexOf('/'); path = path + "/" + fileName.substring(0, lastslash); fileName = fileName.substring(lastslash + 1); } try { ftpClient.connect(server); ftpClient.enterLocalPassiveMode(); ftpClient.login(profile.ftpUsername(), profile.ftpPassword()); ftpClient.setFileType(FTP.BINARY_FILE_TYPE); for (String segment : path.split("/")) { if (!ftpClient.changeWorkingDirectory(segment)) { ftpClient.makeDirectory(segment); ftpClient.changeWorkingDirectory(segment); } } ftpClient.storeFile(fileName, file); ftpClient.disconnect(); } catch (IOException e) { e.printStackTrace(); } } private Utils() { } /** * Print service bus namespace info. * * @param serviceBusNamespace a service bus namespace */ public static void print(ServiceBusNamespace serviceBusNamespace) { StringBuilder builder = new StringBuilder() .append("Service bus Namespace: ").append(serviceBusNamespace.id()) .append("\n\tName: ").append(serviceBusNamespace.name()) .append("\n\tRegion: ").append(serviceBusNamespace.regionName()) .append("\n\tResourceGroupName: ").append(serviceBusNamespace.resourceGroupName()) .append("\n\tCreatedAt: ").append(serviceBusNamespace.createdAt()) .append("\n\tUpdatedAt: ").append(serviceBusNamespace.updatedAt()) .append("\n\tDnsLabel: ").append(serviceBusNamespace.dnsLabel()) .append("\n\tFQDN: ").append(serviceBusNamespace.fqdn()) .append("\n\tSku: ") .append("\n\t\tCapacity: ").append(serviceBusNamespace.sku().capacity()) .append("\n\t\tSkuName: ").append(serviceBusNamespace.sku().name()) .append("\n\t\tTier: ").append(serviceBusNamespace.sku().tier()); System.out.println(builder.toString()); } /** * Print service bus queue info. * * @param queue a service bus queue */ public static void print(Queue queue) { StringBuilder builder = new StringBuilder() .append("Service bus Queue: ").append(queue.id()) .append("\n\tName: ").append(queue.name()) .append("\n\tResourceGroupName: ").append(queue.resourceGroupName()) .append("\n\tCreatedAt: ").append(queue.createdAt()) .append("\n\tUpdatedAt: ").append(queue.updatedAt()) .append("\n\tAccessedAt: ").append(queue.accessedAt()) .append("\n\tActiveMessageCount: ").append(queue.activeMessageCount()) .append("\n\tCurrentSizeInBytes: ").append(queue.currentSizeInBytes()) .append("\n\tDeadLetterMessageCount: ").append(queue.deadLetterMessageCount()) .append("\n\tDefaultMessageTtlDuration: ").append(queue.defaultMessageTtlDuration()) .append("\n\tDuplicateMessageDetectionHistoryDuration: ").append(queue.duplicateMessageDetectionHistoryDuration()) .append("\n\tIsBatchedOperationsEnabled: ").append(queue.isBatchedOperationsEnabled()) .append("\n\tIsDeadLetteringEnabledForExpiredMessages: ").append(queue.isDeadLetteringEnabledForExpiredMessages()) .append("\n\tIsDuplicateDetectionEnabled: ").append(queue.isDuplicateDetectionEnabled()) .append("\n\tIsExpressEnabled: ").append(queue.isExpressEnabled()) .append("\n\tIsPartitioningEnabled: ").append(queue.isPartitioningEnabled()) .append("\n\tIsSessionEnabled: ").append(queue.isSessionEnabled()) .append("\n\tDeleteOnIdleDurationInMinutes: ").append(queue.deleteOnIdleDurationInMinutes()) .append("\n\tMaxDeliveryCountBeforeDeadLetteringMessage: ").append(queue.maxDeliveryCountBeforeDeadLetteringMessage()) .append("\n\tMaxSizeInMB: ").append(queue.maxSizeInMB()) .append("\n\tMessageCount: ").append(queue.messageCount()) .append("\n\tScheduledMessageCount: ").append(queue.scheduledMessageCount()) .append("\n\tStatus: ").append(queue.status()) .append("\n\tTransferMessageCount: ").append(queue.transferMessageCount()) .append("\n\tLockDurationInSeconds: ").append(queue.lockDurationInSeconds()) .append("\n\tTransferDeadLetterMessageCount: ").append(queue.transferDeadLetterMessageCount()); System.out.println(builder.toString()); } /** * Print service bus queue authorization keys info. * * @param queueAuthorizationRule a service bus queue authorization keys */ public static void print(QueueAuthorizationRule queueAuthorizationRule) { StringBuilder builder = new StringBuilder() .append("Service bus queue authorization rule: ").append(queueAuthorizationRule.id()) .append("\n\tName: ").append(queueAuthorizationRule.name()) .append("\n\tResourceGroupName: ").append(queueAuthorizationRule.resourceGroupName()) .append("\n\tNamespace Name: ").append(queueAuthorizationRule.namespaceName()) .append("\n\tQueue Name: ").append(queueAuthorizationRule.queueName()); List<com.azure.resourcemanager.servicebus.models.AccessRights> rights = queueAuthorizationRule.rights(); builder.append("\n\tNumber of access rights in queue: ").append(rights.size()); for (com.azure.resourcemanager.servicebus.models.AccessRights right : rights) { builder.append("\n\t\tAccessRight: ") .append("\n\t\t\tName :").append(right.name()); } System.out.println(builder.toString()); } /** * Print service bus namespace authorization keys info. * * @param keys a service bus namespace authorization keys */ public static void print(AuthorizationKeys keys) { StringBuilder builder = new StringBuilder() .append("Authorization keys: ") .append("\n\tPrimaryKey: ").append(keys.primaryKey()) .append("\n\tPrimaryConnectionString: ").append(keys.primaryConnectionString()) .append("\n\tSecondaryKey: ").append(keys.secondaryKey()) .append("\n\tSecondaryConnectionString: ").append(keys.secondaryConnectionString()); System.out.println(builder.toString()); } /** * Print service bus namespace authorization rule info. * * @param namespaceAuthorizationRule a service bus namespace authorization rule */ public static void print(NamespaceAuthorizationRule namespaceAuthorizationRule) { StringBuilder builder = new StringBuilder() .append("Service bus queue authorization rule: ").append(namespaceAuthorizationRule.id()) .append("\n\tName: ").append(namespaceAuthorizationRule.name()) .append("\n\tResourceGroupName: ").append(namespaceAuthorizationRule.resourceGroupName()) .append("\n\tNamespace Name: ").append(namespaceAuthorizationRule.namespaceName()); List<com.azure.resourcemanager.servicebus.models.AccessRights> rights = namespaceAuthorizationRule.rights(); builder.append("\n\tNumber of access rights in queue: ").append(rights.size()); for (com.azure.resourcemanager.servicebus.models.AccessRights right : rights) { builder.append("\n\t\tAccessRight: ") .append("\n\t\t\tName :").append(right.name()); } System.out.println(builder.toString()); } /** * Print service bus topic info. * * @param topic a service bus topic */ public static void print(Topic topic) { StringBuilder builder = new StringBuilder() .append("Service bus topic: ").append(topic.id()) .append("\n\tName: ").append(topic.name()) .append("\n\tResourceGroupName: ").append(topic.resourceGroupName()) .append("\n\tCreatedAt: ").append(topic.createdAt()) .append("\n\tUpdatedAt: ").append(topic.updatedAt()) .append("\n\tAccessedAt: ").append(topic.accessedAt()) .append("\n\tActiveMessageCount: ").append(topic.activeMessageCount()) .append("\n\tCurrentSizeInBytes: ").append(topic.currentSizeInBytes()) .append("\n\tDeadLetterMessageCount: ").append(topic.deadLetterMessageCount()) .append("\n\tDefaultMessageTtlDuration: ").append(topic.defaultMessageTtlDuration()) .append("\n\tDuplicateMessageDetectionHistoryDuration: ").append(topic.duplicateMessageDetectionHistoryDuration()) .append("\n\tIsBatchedOperationsEnabled: ").append(topic.isBatchedOperationsEnabled()) .append("\n\tIsDuplicateDetectionEnabled: ").append(topic.isDuplicateDetectionEnabled()) .append("\n\tIsExpressEnabled: ").append(topic.isExpressEnabled()) .append("\n\tIsPartitioningEnabled: ").append(topic.isPartitioningEnabled()) .append("\n\tDeleteOnIdleDurationInMinutes: ").append(topic.deleteOnIdleDurationInMinutes()) .append("\n\tMaxSizeInMB: ").append(topic.maxSizeInMB()) .append("\n\tScheduledMessageCount: ").append(topic.scheduledMessageCount()) .append("\n\tStatus: ").append(topic.status()) .append("\n\tTransferMessageCount: ").append(topic.transferMessageCount()) .append("\n\tSubscriptionCount: ").append(topic.subscriptionCount()) .append("\n\tTransferDeadLetterMessageCount: ").append(topic.transferDeadLetterMessageCount()); System.out.println(builder.toString()); } /** * Print service bus subscription info. * * @param serviceBusSubscription a service bus subscription */ public static void print(ServiceBusSubscription serviceBusSubscription) { StringBuilder builder = new StringBuilder() .append("Service bus subscription: ").append(serviceBusSubscription.id()) .append("\n\tName: ").append(serviceBusSubscription.name()) .append("\n\tResourceGroupName: ").append(serviceBusSubscription.resourceGroupName()) .append("\n\tCreatedAt: ").append(serviceBusSubscription.createdAt()) .append("\n\tUpdatedAt: ").append(serviceBusSubscription.updatedAt()) .append("\n\tAccessedAt: ").append(serviceBusSubscription.accessedAt()) .append("\n\tActiveMessageCount: ").append(serviceBusSubscription.activeMessageCount()) .append("\n\tDeadLetterMessageCount: ").append(serviceBusSubscription.deadLetterMessageCount()) .append("\n\tDefaultMessageTtlDuration: ").append(serviceBusSubscription.defaultMessageTtlDuration()) .append("\n\tIsBatchedOperationsEnabled: ").append(serviceBusSubscription.isBatchedOperationsEnabled()) .append("\n\tDeleteOnIdleDurationInMinutes: ").append(serviceBusSubscription.deleteOnIdleDurationInMinutes()) .append("\n\tScheduledMessageCount: ").append(serviceBusSubscription.scheduledMessageCount()) .append("\n\tStatus: ").append(serviceBusSubscription.status()) .append("\n\tTransferMessageCount: ").append(serviceBusSubscription.transferMessageCount()) .append("\n\tIsDeadLetteringEnabledForExpiredMessages: ").append(serviceBusSubscription.isDeadLetteringEnabledForExpiredMessages()) .append("\n\tIsSessionEnabled: ").append(serviceBusSubscription.isSessionEnabled()) .append("\n\tLockDurationInSeconds: ").append(serviceBusSubscription.lockDurationInSeconds()) .append("\n\tMaxDeliveryCountBeforeDeadLetteringMessage: ").append(serviceBusSubscription.maxDeliveryCountBeforeDeadLetteringMessage()) .append("\n\tIsDeadLetteringEnabledForFilterEvaluationFailedMessages: ").append(serviceBusSubscription.isDeadLetteringEnabledForFilterEvaluationFailedMessages()) .append("\n\tTransferMessageCount: ").append(serviceBusSubscription.transferMessageCount()) .append("\n\tTransferDeadLetterMessageCount: ").append(serviceBusSubscription.transferDeadLetterMessageCount()); System.out.println(builder.toString()); } /** * Print topic Authorization Rule info. * * @param topicAuthorizationRule a topic Authorization Rule */ public static void print(TopicAuthorizationRule topicAuthorizationRule) { StringBuilder builder = new StringBuilder() .append("Service bus topic authorization rule: ").append(topicAuthorizationRule.id()) .append("\n\tName: ").append(topicAuthorizationRule.name()) .append("\n\tResourceGroupName: ").append(topicAuthorizationRule.resourceGroupName()) .append("\n\tNamespace Name: ").append(topicAuthorizationRule.namespaceName()) .append("\n\tTopic Name: ").append(topicAuthorizationRule.topicName()); List<com.azure.resourcemanager.servicebus.models.AccessRights> rights = topicAuthorizationRule.rights(); builder.append("\n\tNumber of access rights in queue: ").append(rights.size()); for (com.azure.resourcemanager.servicebus.models.AccessRights right : rights) { builder.append("\n\t\tAccessRight: ") .append("\n\t\t\tName :").append(right.name()); } System.out.println(builder.toString()); } /** * Print CosmosDB info. * * @param cosmosDBAccount a CosmosDB */ public static void print(CosmosDBAccount cosmosDBAccount) { StringBuilder builder = new StringBuilder() .append("CosmosDB: ").append(cosmosDBAccount.id()) .append("\n\tName: ").append(cosmosDBAccount.name()) .append("\n\tResourceGroupName: ").append(cosmosDBAccount.resourceGroupName()) .append("\n\tKind: ").append(cosmosDBAccount.kind().toString()) .append("\n\tDefault consistency level: ").append(cosmosDBAccount.consistencyPolicy().defaultConsistencyLevel()) .append("\n\tIP range filter: ").append(cosmosDBAccount.ipRangeFilter()); DatabaseAccountListKeysResult keys = cosmosDBAccount.listKeys(); DatabaseAccountListReadOnlyKeysResult readOnlyKeys = cosmosDBAccount.listReadOnlyKeys(); builder .append("\n\tPrimary Master Key: ").append(keys.primaryMasterKey()) .append("\n\tSecondary Master Key: ").append(keys.secondaryMasterKey()) .append("\n\tPrimary Read-Only Key: ").append(readOnlyKeys.primaryReadonlyMasterKey()) .append("\n\tSecondary Read-Only Key: ").append(readOnlyKeys.secondaryReadonlyMasterKey()); for (Location writeReplica : cosmosDBAccount.writableReplications()) { builder.append("\n\t\tWrite replication: ") .append("\n\t\t\tName :").append(writeReplica.locationName()); } builder.append("\n\tNumber of read replications: ").append(cosmosDBAccount.readableReplications().size()); for (Location readReplica : cosmosDBAccount.readableReplications()) { builder.append("\n\t\tRead replication: ") .append("\n\t\t\tName :").append(readReplica.locationName()); } } /** * Print Active Directory User info. * * @param user active directory user */ public static void print(ActiveDirectoryUser user) { StringBuilder builder = new StringBuilder() .append("Active Directory User: ").append(user.id()) .append("\n\tName: ").append(user.name()) .append("\n\tMail: ").append(user.mail()) .append("\n\tMail Nickname: ").append(user.mailNickname()) .append("\n\tSign In Name: ").append(user.signInName()) .append("\n\tUser Principal Name: ").append(user.userPrincipalName()); System.out.println(builder.toString()); } /** * Print Active Directory User info. * * @param role role definition */ public static void print(RoleDefinition role) { StringBuilder builder = new StringBuilder() .append("Role Definition: ").append(role.id()) .append("\n\tName: ").append(role.name()) .append("\n\tRole Name: ").append(role.roleName()) .append("\n\tType: ").append(role.type()) .append("\n\tDescription: ").append(role.description()) .append("\n\tType: ").append(role.type()); Set<Permission> permissions = role.permissions(); builder.append("\n\tPermissions: ").append(permissions.size()); for (Permission permission : permissions) { builder.append("\n\t\tPermission Actions: " + permission.actions().size()); for (String action : permission.actions()) { builder.append("\n\t\t\tName :").append(action); } builder.append("\n\t\tPermission Not Actions: " + permission.notActions().size()); for (String notAction : permission.notActions()) { builder.append("\n\t\t\tName :").append(notAction); } } Set<String> assignableScopes = role.assignableScopes(); builder.append("\n\tAssignable scopes: ").append(assignableScopes.size()); for (String scope : assignableScopes) { builder.append("\n\t\tAssignable Scope: ") .append("\n\t\t\tName :").append(scope); } System.out.println(builder.toString()); } /** * Print Role Assignment info. * * @param roleAssignment role assignment */ public static void print(RoleAssignment roleAssignment) { StringBuilder builder = new StringBuilder() .append("Role Assignment: ") .append("\n\tScope: ").append(roleAssignment.scope()) .append("\n\tPrincipal Id: ").append(roleAssignment.principalId()) .append("\n\tRole Definition Id: ").append(roleAssignment.roleDefinitionId()); System.out.println(builder.toString()); } /** * Print Active Directory Group info. * * @param group active directory group */ public static void print(ActiveDirectoryGroup group) { StringBuilder builder = new StringBuilder() .append("Active Directory Group: ").append(group.id()) .append("\n\tName: ").append(group.name()) .append("\n\tMail: ").append(group.mail()) .append("\n\tSecurity Enabled: ").append(group.securityEnabled()) .append("\n\tGroup members:"); for (ActiveDirectoryObject object : group.listMembers()) { builder.append("\n\t\tType: ").append(object.getClass().getSimpleName()) .append("\tName: ").append(object.name()); } System.out.println(builder.toString()); } /** * Print Active Directory Application info. * * @param application active directory application */ public static void print(ActiveDirectoryApplication application) { StringBuilder builder = new StringBuilder() .append("Active Directory Application: ").append(application.id()) .append("\n\tName: ").append(application.name()) .append("\n\tSign on URL: ").append(application.signOnUrl()) .append("\n\tReply URLs:"); for (String replyUrl : application.replyUrls()) { builder.append("\n\t\t").append(replyUrl); } System.out.println(builder.toString()); } /** * Print Service Principal info. * * @param servicePrincipal service principal */ public static void print(ServicePrincipal servicePrincipal) { StringBuilder builder = new StringBuilder() .append("Service Principal: ").append(servicePrincipal.id()) .append("\n\tName: ").append(servicePrincipal.name()) .append("\n\tApplication Id: ").append(servicePrincipal.applicationId()); List<String> names = servicePrincipal.servicePrincipalNames(); builder.append("\n\tNames: ").append(names.size()); for (String name : names) { builder.append("\n\t\tName: ").append(name); } System.out.println(builder.toString()); } /** * Print Network Watcher info. * * @param nw network watcher */ public static void print(NetworkWatcher nw) { StringBuilder builder = new StringBuilder() .append("Network Watcher: ").append(nw.id()) .append("\n\tName: ").append(nw.name()) .append("\n\tResource group name: ").append(nw.resourceGroupName()) .append("\n\tRegion name: ").append(nw.regionName()); System.out.println(builder.toString()); } /** * Print packet capture info. * * @param resource packet capture */ public static void print(PacketCapture resource) { StringBuilder sb = new StringBuilder().append("Packet Capture: ").append(resource.id()) .append("\n\tName: ").append(resource.name()) .append("\n\tTarget id: ").append(resource.targetId()) .append("\n\tTime limit in seconds: ").append(resource.timeLimitInSeconds()) .append("\n\tBytes to capture per packet: ").append(resource.bytesToCapturePerPacket()) .append("\n\tProvisioning state: ").append(resource.provisioningState()) .append("\n\tStorage location:") .append("\n\tStorage account id: ").append(resource.storageLocation().storageId()) .append("\n\tStorage account path: ").append(resource.storageLocation().storagePath()) .append("\n\tFile path: ").append(resource.storageLocation().filePath()) .append("\n\t Packet capture filters: ").append(resource.filters().size()); for (PacketCaptureFilter filter : resource.filters()) { sb.append("\n\t\tProtocol: ").append(filter.protocol()); sb.append("\n\t\tLocal IP address: ").append(filter.localIpAddress()); sb.append("\n\t\tRemote IP address: ").append(filter.remoteIpAddress()); sb.append("\n\t\tLocal port: ").append(filter.localPort()); sb.append("\n\t\tRemote port: ").append(filter.remotePort()); } System.out.println(sb.toString()); } /** * Print verification IP flow info. * * @param resource IP flow verification info */ public static void print(VerificationIPFlow resource) { System.out.println(new StringBuilder("IP flow verification: ") .append("\n\tAccess: ").append(resource.access()) .append("\n\tRule name: ").append(resource.ruleName()) .toString()); } /** * Print topology info. * * @param resource topology */ public static void print(Topology resource) { StringBuilder sb = new StringBuilder().append("Topology: ").append(resource.id()) .append("\n\tTopology parameters: ") .append("\n\t\tResource group: ").append(resource.topologyParameters().targetResourceGroupName()) .append("\n\t\tVirtual network: ").append(resource.topologyParameters().targetVirtualNetwork() == null ? "" : resource.topologyParameters().targetVirtualNetwork().id()) .append("\n\t\tSubnet id: ").append(resource.topologyParameters().targetSubnet() == null ? "" : resource.topologyParameters().targetSubnet().id()) .append("\n\tCreated time: ").append(resource.createdTime()) .append("\n\tLast modified time: ").append(resource.lastModifiedTime()); for (TopologyResource tr : resource.resources().values()) { sb.append("\n\tTopology resource: ").append(tr.id()) .append("\n\t\tName: ").append(tr.name()) .append("\n\t\tLocation: ").append(tr.location()) .append("\n\t\tAssociations:"); for (TopologyAssociation association : tr.associations()) { sb.append("\n\t\t\tName:").append(association.name()) .append("\n\t\t\tResource id:").append(association.resourceId()) .append("\n\t\t\tAssociation type:").append(association.associationType()); } } System.out.println(sb.toString()); } /** * Print flow log settings info. * * @param resource flow log settings */ public static void print(FlowLogSettings resource) { System.out.println(new StringBuilder().append("Flow log settings: ") .append("Target resource id: ").append(resource.targetResourceId()) .append("\n\tFlow log enabled: ").append(resource.enabled()) .append("\n\tStorage account id: ").append(resource.storageId()) .append("\n\tRetention policy enabled: ").append(resource.isRetentionEnabled()) .append("\n\tRetention policy days: ").append(resource.retentionDays()) .toString()); } /** * Print availability set info. * * @param resource an availability set */ public static void print(SecurityGroupView resource) { StringBuilder sb = new StringBuilder().append("Security group view: ") .append("\n\tVirtual machine id: ").append(resource.vmId()); for (SecurityGroupNetworkInterface sgni : resource.networkInterfaces().values()) { sb.append("\n\tSecurity group network interface:").append(sgni.id()) .append("\n\t\tSecurity group network interface:") .append("\n\t\tEffective security rules:"); for (EffectiveNetworkSecurityRule rule : sgni.securityRuleAssociations().effectiveSecurityRules()) { sb.append("\n\t\t\tName: ").append(rule.name()) .append("\n\t\t\tDirection: ").append(rule.direction()) .append("\n\t\t\tAccess: ").append(rule.access()) .append("\n\t\t\tPriority: ").append(rule.priority()) .append("\n\t\t\tSource address prefix: ").append(rule.sourceAddressPrefix()) .append("\n\t\t\tSource port range: ").append(rule.sourcePortRange()) .append("\n\t\t\tDestination address prefix: ").append(rule.destinationAddressPrefix()) .append("\n\t\t\tDestination port range: ").append(rule.destinationPortRange()) .append("\n\t\t\tProtocol: ").append(rule.protocol()); } sb.append("\n\t\tSubnet:").append(sgni.securityRuleAssociations().subnetAssociation().id()); printSecurityRule(sb, sgni.securityRuleAssociations().subnetAssociation().securityRules()); if (sgni.securityRuleAssociations().networkInterfaceAssociation() != null) { sb.append("\n\t\tNetwork interface:").append(sgni.securityRuleAssociations().networkInterfaceAssociation().id()); printSecurityRule(sb, sgni.securityRuleAssociations().networkInterfaceAssociation().securityRules()); } sb.append("\n\t\tDefault security rules:"); printSecurityRule(sb, sgni.securityRuleAssociations().defaultSecurityRules()); } System.out.println(sb.toString()); } private static void printSecurityRule(StringBuilder sb, List<SecurityRuleInner> rules) { for (SecurityRuleInner rule : rules) { sb.append("\n\t\t\tName: ").append(rule.name()) .append("\n\t\t\tDirection: ").append(rule.direction()) .append("\n\t\t\tAccess: ").append(rule.access()) .append("\n\t\t\tPriority: ").append(rule.priority()) .append("\n\t\t\tSource address prefix: ").append(rule.sourceAddressPrefix()) .append("\n\t\t\tSource port range: ").append(rule.sourcePortRange()) .append("\n\t\t\tDestination address prefix: ").append(rule.destinationAddressPrefix()) .append("\n\t\t\tDestination port range: ").append(rule.destinationPortRange()) .append("\n\t\t\tProtocol: ").append(rule.protocol()) .append("\n\t\t\tDescription: ").append(rule.description()) .append("\n\t\t\tProvisioning state: ").append(rule.provisioningState()); } } /** * Print next hop info. * * @param resource an availability set */ public static void print(NextHop resource) { System.out.println(new StringBuilder("Next hop: ") .append("Next hop type: ").append(resource.nextHopType()) .append("\n\tNext hop ip address: ").append(resource.nextHopIpAddress()) .append("\n\tRoute table id: ").append(resource.routeTableId()) .toString()); } /** * Print container group info. * * @param resource a container group */ public static void print(ContainerGroup resource) { StringBuilder info = new StringBuilder().append("Container Group: ").append(resource.id()) .append("Name: ").append(resource.name()) .append("\n\tResource group: ").append(resource.resourceGroupName()) .append("\n\tRegion: ").append(resource.region()) .append("\n\tTags: ").append(resource.tags()) .append("\n\tOS type: ").append(resource.osType()); if (resource.ipAddress() != null) { info.append("\n\tPublic IP address: ").append(resource.ipAddress()); } if (resource.externalTcpPorts() != null) { info.append("\n\tExternal TCP ports:"); for (int port : resource.externalTcpPorts()) { info.append(" ").append(port); } } if (resource.externalUdpPorts() != null) { info.append("\n\tExternal UDP ports:"); for (int port : resource.externalUdpPorts()) { info.append(" ").append(port); } } if (resource.imageRegistryServers() != null) { info.append("\n\tPrivate Docker image registries:"); for (String server : resource.imageRegistryServers()) { info.append(" ").append(server); } } if (resource.volumes() != null) { info.append("\n\tVolume mapping: "); for (Map.Entry<String, Volume> entry : resource.volumes().entrySet()) { info.append("\n\t\tName: ").append(entry.getKey()).append(" -> ") .append(entry.getValue().azureFile() != null ? entry.getValue().azureFile().shareName() : "empty direcory volume"); } } if (resource.containers() != null) { info.append("\n\tContainer instances: "); for (Map.Entry<String, Container> entry : resource.containers().entrySet()) { Container container = entry.getValue(); info.append("\n\t\tName: ").append(entry.getKey()).append(" -> ").append(container.image()); info.append("\n\t\t\tResources: "); info.append(container.resources().requests().cpu()).append("CPUs "); info.append(container.resources().requests().memoryInGB()).append("GB"); info.append("\n\t\t\tPorts:"); for (ContainerPort port : container.ports()) { info.append(" ").append(port.port()); } if (container.volumeMounts() != null) { info.append("\n\t\t\tVolume mounts:"); for (VolumeMount volumeMount : container.volumeMounts()) { info.append(" ").append(volumeMount.name()).append("->").append(volumeMount.mountPath()); } } if (container.command() != null) { info.append("\n\t\t\tStart commands:"); for (String command : container.command()) { info.append("\n\t\t\t\t").append(command); } } if (container.environmentVariables() != null) { info.append("\n\t\t\tENV vars:"); for (EnvironmentVariable envVar : container.environmentVariables()) { info.append("\n\t\t\t\t").append(envVar.name()).append("=").append(envVar.value()); } } } } System.out.println(info.toString()); } /** * Print event hub namespace. * * @param resource a virtual machine */ public static void print(EventHubNamespace resource) { StringBuilder info = new StringBuilder(); info.append("Eventhub Namespace: ").append(resource.id()) .append("\n\tName: ").append(resource.name()) .append("\n\tRegion: ").append(resource.region()) .append("\n\tTags: ").append(resource.tags()) .append("\n\tAzureInsightMetricId: ").append(resource.azureInsightMetricId()) .append("\n\tIsAutoScale enabled: ").append(resource.isAutoScaleEnabled()) .append("\n\tServiceBus endpoint: ").append(resource.serviceBusEndpoint()) .append("\n\tThroughPut upper limit: ").append(resource.throughputUnitsUpperLimit()) .append("\n\tCurrent ThroughPut: ").append(resource.currentThroughputUnits()) .append("\n\tCreated time: ").append(resource.createdAt()) .append("\n\tUpdated time: ").append(resource.updatedAt()); System.out.println(info.toString()); } /** * Print event hub. * * @param resource event hub */ public static void print(EventHub resource) { StringBuilder info = new StringBuilder(); info.append("Eventhub: ").append(resource.id()) .append("\n\tName: ").append(resource.name()) .append("\n\tNamespace resource group: ").append(resource.namespaceResourceGroupName()) .append("\n\tNamespace: ").append(resource.namespaceName()) .append("\n\tIs data capture enabled: ").append(resource.isDataCaptureEnabled()) .append("\n\tPartition ids: ").append(resource.partitionIds()); if (resource.isDataCaptureEnabled()) { info.append("\n\t\t\tData capture window size in MB: ").append(resource.dataCaptureWindowSizeInMB()); info.append("\n\t\t\tData capture window size in seconds: ").append(resource.dataCaptureWindowSizeInSeconds()); if (resource.captureDestination() != null) { info.append("\n\t\t\tData capture storage account: ").append(resource.captureDestination().storageAccountResourceId()); info.append("\n\t\t\tData capture storage container: ").append(resource.captureDestination().blobContainer()); } } System.out.println(info.toString()); } /** * Print event hub namespace recovery pairing. * * @param resource event hub namespace disaster recovery pairing */ public static void print(EventHubDisasterRecoveryPairing resource) { StringBuilder info = new StringBuilder(); info.append("DisasterRecoveryPairing: ").append(resource.id()) .append("\n\tName: ").append(resource.name()) .append("\n\tPrimary namespace resource group name: ").append(resource.primaryNamespaceResourceGroupName()) .append("\n\tPrimary namespace name: ").append(resource.primaryNamespaceName()) .append("\n\tSecondary namespace: ").append(resource.secondaryNamespaceId()) .append("\n\tNamespace role: ").append(resource.namespaceRole()); System.out.println(info.toString()); } /** * Print event hub namespace recovery pairing auth rules. * * @param resource event hub namespace disaster recovery pairing auth rule */ public static void print(DisasterRecoveryPairingAuthorizationRule resource) { StringBuilder info = new StringBuilder(); info.append("DisasterRecoveryPairing auth rule: ").append(resource.name()); List<String> rightsStr = new ArrayList<>(); for (AccessRights rights : resource.rights()) { rightsStr.add(rights.toString()); } info.append("\n\tRights: ").append(rightsStr); System.out.println(info.toString()); } /** * Print event hub namespace recovery pairing auth rule key. * * @param resource event hub namespace disaster recovery pairing auth rule key */ public static void print(DisasterRecoveryPairingAuthorizationKey resource) { StringBuilder info = new StringBuilder(); info.append("DisasterRecoveryPairing auth key: ") .append("\n\t Alias primary connection string: ").append(resource.aliasPrimaryConnectionString()) .append("\n\t Alias secondary connection string: ").append(resource.aliasSecondaryConnectionString()) .append("\n\t Primary key: ").append(resource.primaryKey()) .append("\n\t Secondary key: ").append(resource.secondaryKey()) .append("\n\t Primary connection string: ").append(resource.primaryConnectionString()) .append("\n\t Secondary connection string: ").append(resource.secondaryConnectionString()); System.out.println(info.toString()); } /** * Print event hub consumer group. * * @param resource event hub consumer group */ public static void print(EventHubConsumerGroup resource) { StringBuilder info = new StringBuilder(); info.append("Event hub consumer group: ").append(resource.id()) .append("\n\tName: ").append(resource.name()) .append("\n\tNamespace resource group: ").append(resource.namespaceResourceGroupName()) .append("\n\tNamespace: ").append(resource.namespaceName()) .append("\n\tEvent hub name: ").append(resource.eventHubName()) .append("\n\tUser metadata: ").append(resource.userMetadata()); System.out.println(info.toString()); } /** * Print Diagnostic Setting. * * @param resource Diagnostic Setting instance */ public static void print(DiagnosticSetting resource) { StringBuilder info = new StringBuilder("Diagnostic Setting: ") .append("\n\tId: ").append(resource.id()) .append("\n\tAssociated resource Id: ").append(resource.resourceId()) .append("\n\tName: ").append(resource.name()) .append("\n\tStorage Account Id: ").append(resource.storageAccountId()) .append("\n\tEventHub Namespace Autorization Rule Id: ").append(resource.eventHubAuthorizationRuleId()) .append("\n\tEventHub name: ").append(resource.eventHubName()) .append("\n\tLog Analytics workspace Id: ").append(resource.workspaceId()); if (resource.logs() != null && !resource.logs().isEmpty()) { info.append("\n\tLog Settings: "); for (LogSettings ls : resource.logs()) { info.append("\n\t\tCategory: ").append(ls.category()); info.append("\n\t\tRetention policy: "); if (ls.retentionPolicy() != null) { info.append(ls.retentionPolicy().days() + " days"); } else { info.append("NONE"); } } } if (resource.metrics() != null && !resource.metrics().isEmpty()) { info.append("\n\tMetric Settings: "); for (MetricSettings ls : resource.metrics()) { info.append("\n\t\tCategory: ").append(ls.category()); info.append("\n\t\tTimegrain: ").append(ls.timeGrain()); info.append("\n\t\tRetention policy: "); if (ls.retentionPolicy() != null) { info.append(ls.retentionPolicy().days() + " days"); } else { info.append("NONE"); } } } System.out.println(info.toString()); } /** * Print Action group settings. * * @param actionGroup action group instance */ public static void print(ActionGroup actionGroup) { StringBuilder info = new StringBuilder("Action Group: ") .append("\n\tId: ").append(actionGroup.id()) .append("\n\tName: ").append(actionGroup.name()) .append("\n\tShort Name: ").append(actionGroup.shortName()); if (actionGroup.emailReceivers() != null && !actionGroup.emailReceivers().isEmpty()) { info.append("\n\tEmail receivers: "); for (EmailReceiver er : actionGroup.emailReceivers()) { info.append("\n\t\tName: ").append(er.name()); info.append("\n\t\tEMail: ").append(er.emailAddress()); info.append("\n\t\tStatus: ").append(er.status()); info.append("\n\t\t==="); } } if (actionGroup.smsReceivers() != null && !actionGroup.smsReceivers().isEmpty()) { info.append("\n\tSMS text message receivers: "); for (SmsReceiver er : actionGroup.smsReceivers()) { info.append("\n\t\tName: ").append(er.name()); info.append("\n\t\tPhone: ").append(er.countryCode() + er.phoneNumber()); info.append("\n\t\tStatus: ").append(er.status()); info.append("\n\t\t==="); } } if (actionGroup.webhookReceivers() != null && !actionGroup.webhookReceivers().isEmpty()) { info.append("\n\tWebhook receivers: "); for (WebhookReceiver er : actionGroup.webhookReceivers()) { info.append("\n\t\tName: ").append(er.name()); info.append("\n\t\tURI: ").append(er.serviceUri()); info.append("\n\t\t==="); } } if (actionGroup.pushNotificationReceivers() != null && !actionGroup.pushNotificationReceivers().isEmpty()) { info.append("\n\tApp Push Notification receivers: "); for (AzureAppPushReceiver er : actionGroup.pushNotificationReceivers()) { info.append("\n\t\tName: ").append(er.name()); info.append("\n\t\tEmail: ").append(er.emailAddress()); info.append("\n\t\t==="); } } if (actionGroup.voiceReceivers() != null && !actionGroup.voiceReceivers().isEmpty()) { info.append("\n\tVoice Message receivers: "); for (VoiceReceiver er : actionGroup.voiceReceivers()) { info.append("\n\t\tName: ").append(er.name()); info.append("\n\t\tPhone: ").append(er.countryCode() + er.phoneNumber()); info.append("\n\t\t==="); } } if (actionGroup.automationRunbookReceivers() != null && !actionGroup.automationRunbookReceivers().isEmpty()) { info.append("\n\tAutomation Runbook receivers: "); for (AutomationRunbookReceiver er : actionGroup.automationRunbookReceivers()) { info.append("\n\t\tName: ").append(er.name()); info.append("\n\t\tRunbook Name: ").append(er.runbookName()); info.append("\n\t\tAccount Id: ").append(er.automationAccountId()); info.append("\n\t\tIs Global: ").append(er.isGlobalRunbook()); info.append("\n\t\tService URI: ").append(er.serviceUri()); info.append("\n\t\tWebhook resource Id: ").append(er.webhookResourceId()); info.append("\n\t\t==="); } } if (actionGroup.azureFunctionReceivers() != null && !actionGroup.azureFunctionReceivers().isEmpty()) { info.append("\n\tAzure Functions receivers: "); for (AzureFunctionReceiver er : actionGroup.azureFunctionReceivers()) { info.append("\n\t\tName: ").append(er.name()); info.append("\n\t\tFunction Name: ").append(er.functionName()); info.append("\n\t\tFunction App Resource Id: ").append(er.functionAppResourceId()); info.append("\n\t\tFunction Trigger URI: ").append(er.httpTriggerUrl()); info.append("\n\t\t==="); } } if (actionGroup.logicAppReceivers() != null && !actionGroup.logicAppReceivers().isEmpty()) { info.append("\n\tLogic App receivers: "); for (LogicAppReceiver er : actionGroup.logicAppReceivers()) { info.append("\n\t\tName: ").append(er.name()); info.append("\n\t\tResource Id: ").append(er.resourceId()); info.append("\n\t\tCallback URL: ").append(er.callbackUrl()); info.append("\n\t\t==="); } } if (actionGroup.itsmReceivers() != null && !actionGroup.itsmReceivers().isEmpty()) { info.append("\n\tITSM receivers: "); for (ItsmReceiver er : actionGroup.itsmReceivers()) { info.append("\n\t\tName: ").append(er.name()); info.append("\n\t\tWorkspace Id: ").append(er.workspaceId()); info.append("\n\t\tConnection Id: ").append(er.connectionId()); info.append("\n\t\tRegion: ").append(er.region()); info.append("\n\t\tTicket Configuration: ").append(er.ticketConfiguration()); info.append("\n\t\t==="); } } System.out.println(info.toString()); } /** * Print activity log alert settings. * * @param activityLogAlert activity log instance */ public static void print(ActivityLogAlert activityLogAlert) { StringBuilder info = new StringBuilder("Activity Log Alert: ") .append("\n\tId: ").append(activityLogAlert.id()) .append("\n\tName: ").append(activityLogAlert.name()) .append("\n\tDescription: ").append(activityLogAlert.description()) .append("\n\tIs Enabled: ").append(activityLogAlert.enabled()); if (activityLogAlert.scopes() != null && !activityLogAlert.scopes().isEmpty()) { info.append("\n\tScopes: "); for (String er : activityLogAlert.scopes()) { info.append("\n\t\tId: ").append(er); } } if (activityLogAlert.actionGroupIds() != null && !activityLogAlert.actionGroupIds().isEmpty()) { info.append("\n\tAction Groups: "); for (String er : activityLogAlert.actionGroupIds()) { info.append("\n\t\tAction Group Id: ").append(er); } } if (activityLogAlert.equalsConditions() != null && !activityLogAlert.equalsConditions().isEmpty()) { info.append("\n\tAlert conditions (when all of is true): "); for (Map.Entry<String, String> er : activityLogAlert.equalsConditions().entrySet()) { info.append("\n\t\t'").append(er.getKey()).append("' equals '").append(er.getValue()).append("'"); } } System.out.println(info.toString()); } /** * Print metric alert settings. * * @param metricAlert metric alert instance */ public static void print(MetricAlert metricAlert) { StringBuilder info = new StringBuilder("Metric Alert: ") .append("\n\tId: ").append(metricAlert.id()) .append("\n\tName: ").append(metricAlert.name()) .append("\n\tDescription: ").append(metricAlert.description()) .append("\n\tIs Enabled: ").append(metricAlert.enabled()) .append("\n\tIs Auto Mitigated: ").append(metricAlert.autoMitigate()) .append("\n\tSeverity: ").append(metricAlert.severity()) .append("\n\tWindow Size: ").append(metricAlert.windowSize()) .append("\n\tEvaluation Frequency: ").append(metricAlert.evaluationFrequency()); if (metricAlert.scopes() != null && !metricAlert.scopes().isEmpty()) { info.append("\n\tScopes: "); for (String er : metricAlert.scopes()) { info.append("\n\t\tId: ").append(er); } } if (metricAlert.actionGroupIds() != null && !metricAlert.actionGroupIds().isEmpty()) { info.append("\n\tAction Groups: "); for (String er : metricAlert.actionGroupIds()) { info.append("\n\t\tAction Group Id: ").append(er); } } if (metricAlert.alertCriterias() != null && !metricAlert.alertCriterias().isEmpty()) { info.append("\n\tAlert conditions (when all of is true): "); for (Map.Entry<String, MetricAlertCondition> er : metricAlert.alertCriterias().entrySet()) { MetricAlertCondition alertCondition = er.getValue(); info.append("\n\t\tCondition name: ").append(er.getKey()) .append("\n\t\tSignal name: ").append(alertCondition.metricName()) .append("\n\t\tMetric Namespace: ").append(alertCondition.metricNamespace()) .append("\n\t\tOperator: ").append(alertCondition.condition()) .append("\n\t\tThreshold: ").append(alertCondition.threshold()) .append("\n\t\tTime Aggregation: ").append(alertCondition.timeAggregation()); if (alertCondition.dimensions() != null && !alertCondition.dimensions().isEmpty()) { for (MetricDimension dimon : alertCondition.dimensions()) { info.append("\n\t\tDimension Filter: ").append("Name [").append(dimon.name()).append("] operator [Include] values["); for (String vals : dimon.values()) { info.append(vals).append(", "); } info.append("]"); } } } } System.out.println(info.toString()); } /** * Print spring service settings. * * @param springService spring service instance */ public static void print(SpringService springService) { StringBuilder info = new StringBuilder("Spring Service: ") .append("\n\tId: ").append(springService.id()) .append("\n\tName: ").append(springService.name()) .append("\n\tResource Group: ").append(springService.resourceGroupName()) .append("\n\tRegion: ").append(springService.region()) .append("\n\tTags: ").append(springService.tags()); ConfigServerProperties serverProperties = springService.getServerProperties(); if (serverProperties != null && serverProperties.provisioningState() != null && serverProperties.provisioningState().equals(ConfigServerState.SUCCEEDED) && serverProperties.configServer() != null) { info.append("\n\tProperties: "); if (serverProperties.configServer().gitProperty() != null) { info.append("\n\t\tGit: ").append(serverProperties.configServer().gitProperty().uri()); } } if (springService.sku() != null) { info.append("\n\tSku: ") .append("\n\t\tName: ").append(springService.sku().name()) .append("\n\t\tTier: ").append(springService.sku().tier()) .append("\n\t\tCapacity: ").append(springService.sku().capacity()); } MonitoringSettingProperties monitoringSettingProperties = springService.getMonitoringSetting(); if (monitoringSettingProperties != null && monitoringSettingProperties.provisioningState() != null && monitoringSettingProperties.provisioningState().equals(MonitoringSettingState.SUCCEEDED)) { info.append("\n\tTrace: ") .append("\n\t\tEnabled: ").append(monitoringSettingProperties.traceEnabled()) .append("\n\t\tApp Insight Instrumentation Key: ").append(monitoringSettingProperties.appInsightsInstrumentationKey()); } System.out.println(info.toString()); } /** * Print spring app settings. * * @param springApp spring app instance */ public static void print(SpringApp springApp) { StringBuilder info = new StringBuilder("Spring Service: ") .append("\n\tId: ").append(springApp.id()) .append("\n\tName: ").append(springApp.name()) .append("\n\tCreated Time: ").append(springApp.createdTime()) .append("\n\tPublic Endpoint: ").append(springApp.isPublic()) .append("\n\tUrl: ").append(springApp.url()) .append("\n\tHttps Only: ").append(springApp.isHttpsOnly()) .append("\n\tFully Qualified Domain Name: ").append(springApp.fqdn()) .append("\n\tActive Deployment Name: ").append(springApp.activeDeploymentName()); if (springApp.temporaryDisk() != null) { info.append("\n\tTemporary Disk:") .append("\n\t\tSize In GB: ").append(springApp.temporaryDisk().sizeInGB()) .append("\n\t\tMount Path: ").append(springApp.temporaryDisk().mountPath()); } if (springApp.persistentDisk() != null) { info.append("\n\tPersistent Disk:") .append("\n\t\tSize In GB: ").append(springApp.persistentDisk().sizeInGB()) .append("\n\t\tMount Path: ").append(springApp.persistentDisk().mountPath()); } if (springApp.identity() != null) { info.append("\n\tIdentity:") .append("\n\t\tType: ").append(springApp.identity().type()) .append("\n\t\tPrincipal Id: ").append(springApp.identity().principalId()) .append("\n\t\tTenant Id: ").append(springApp.identity().tenantId()); } System.out.println(info.toString()); } /** * Sends a GET request to target URL. * <p> * The method does not handle 301 redirect. * * @param urlString the target URL. * @return Content of the HTTP response. */ public static String sendGetRequest(String urlString) { try { Mono<Response<Flux<ByteBuffer>>> response = HTTP_CLIENT.getString(getHost(urlString), getPathAndQuery(urlString)) .retryWhen(Retry .fixedDelay(3, Duration.ofSeconds(30)) .filter(t -> { if (t instanceof TimeoutException) { return true; } else if (t instanceof HttpResponseException && ((HttpResponseException) t).getResponse().getStatusCode() == 503) { return true; } return false; })); Response<String> ret = stringResponse(response).block(); return ret == null ? null : ret.getValue(); } catch (MalformedURLException e) { return null; } } /** * Sends a POST request to target URL. * * @param urlString the target URL. * @param body the request body. * @return Content of the HTTP response. * */ public static String sendPostRequest(String urlString, String body) { try { Response<String> response = stringResponse(HTTP_CLIENT.postString(getHost(urlString), getPathAndQuery(urlString), body)).block(); if (response != null) { return response.getValue(); } else { return null; } } catch (Exception e) { return null; } } private static Mono<Response<String>> stringResponse(Mono<Response<Flux<ByteBuffer>>> responseMono) { return responseMono.flatMap(response -> FluxUtil.collectBytesInByteBufferStream(response.getValue()) .map(bytes -> new String(bytes, StandardCharsets.UTF_8)) .map(str -> new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), str))); } private static String getHost(String urlString) throws MalformedURLException { URL url = new URL(urlString); String protocol = url.getProtocol(); String host = url.getAuthority(); return protocol + ": } private static String getPathAndQuery(String urlString) throws MalformedURLException { URL url = new URL(urlString); String path = url.getPath(); String query = url.getQuery(); if (query != null && !query.isEmpty()) { path = path + "?" + query; } return path; } private static final WebAppTestClient HTTP_CLIENT = RestProxy.create( WebAppTestClient.class, new HttpPipelineBuilder() .policies( new HttpLoggingPolicy(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BASIC)), new RetryPolicy("Retry-After", ChronoUnit.SECONDS)) .build()); @Host("{$host}") @ServiceInterface(name = "WebAppTestClient") private interface WebAppTestClient { @Get("{path}") @ExpectedResponses({200, 400, 404}) Mono<Response<Flux<ByteBuffer>>> getString(@HostParam("$host") String host, @PathParam(value = "path", encoded = true) String path); @Post("{path}") @ExpectedResponses({200, 400, 404}) Mono<Response<Flux<ByteBuffer>>> postString(@HostParam("$host") String host, @PathParam(value = "path", encoded = true) String path, @BodyParam("text/plain") String body); } public static <T> int getSize(Iterable<T> iterable) { int res = 0; Iterator<T> iterator = iterable.iterator(); while (iterator.hasNext()) { iterator.next(); } return res; } }
public static String sendGetRequest(String urlString) {
public static String getSecondaryServicePrincipalClientID(String envSecondaryServicePrincipal) throws IOException { String content = new String(Files.readAllBytes(new File(envSecondaryServicePrincipal).toPath()), StandardCharsets.UTF_8).trim(); HashMap<String, String> auth = new HashMap<>(); if (content.startsWith("{")) { auth = new JacksonAdapter().deserialize(content, auth.getClass(), SerializerEncoding.JSON); return auth.get("clientId"); } else { Properties authSettings = new Properties(); try (FileInputStream credentialsFileStream = new FileInputStream(new File(envSecondaryServicePrincipal))) { authSettings.load(credentialsFileStream); } return authSettings.getProperty("client"); } } /** * Retrieve the secondary service principal secret. * * @param envSecondaryServicePrincipal an Azure Container Registry * @return a service principal secret * @throws Exception exception */ public static String getSecondaryServicePrincipalSecret(String envSecondaryServicePrincipal) throws IOException { String content = new String(Files.readAllBytes(new File(envSecondaryServicePrincipal).toPath()), StandardCharsets.UTF_8).trim(); HashMap<String, String> auth = new HashMap<>(); if (content.startsWith("{")) { auth = new JacksonAdapter().deserialize(content, auth.getClass(), SerializerEncoding.JSON); return auth.get("clientSecret"); } else { Properties authSettings = new Properties(); try (FileInputStream credentialsFileStream = new FileInputStream(new File(envSecondaryServicePrincipal))) { authSettings.load(credentialsFileStream); } return authSettings.getProperty("key"); } } /** * This method creates a certificate for given password. * * @param certPath location of certificate file * @param pfxPath location of pfx file * @param alias User alias * @param password alias password * @param cnName domain name * @throws Exception exceptions from the creation * @throws IOException IO Exception */ public static void createCertificate(String certPath, String pfxPath, String alias, String password, String cnName) throws IOException { if (new File(pfxPath).exists()) { return; } String validityInDays = "3650"; String keyAlg = "RSA"; String sigAlg = "SHA1withRSA"; String keySize = "2048"; String storeType = "pkcs12"; String command = "keytool"; String jdkPath = System.getProperty("java.home"); if (jdkPath != null && !jdkPath.isEmpty()) { jdkPath = jdkPath.concat("\\bin"); if (new File(jdkPath).isDirectory()) { command = String.format("%s%s%s", jdkPath, File.separator, command); } } else { return; } String[] commandArgs = {command, "-genkey", "-alias", alias, "-keystore", pfxPath, "-storepass", password, "-validity", validityInDays, "-keyalg", keyAlg, "-sigalg", sigAlg, "-keysize", keySize, "-storetype", storeType, "-dname", "CN=" + cnName, "-ext", "EKU=1.3.6.1.5.5.7.3.1"}; Utils.cmdInvocation(commandArgs, true); File pfxFile = new File(pfxPath); if (pfxFile.exists()) { String[] certCommandArgs = {command, "-export", "-alias", alias, "-storetype", storeType, "-keystore", pfxPath, "-storepass", password, "-rfc", "-file", certPath}; Utils.cmdInvocation(certCommandArgs, true); File cerFile = new File(pfxPath); if (!cerFile.exists()) { throw new IOException( "Error occurred while creating certificate" + String.join(" ", certCommandArgs)); } } else { throw new IOException("Error occurred while creating certificates" + String.join(" ", commandArgs)); } } /** * This method is used for invoking native commands. * * @param command :- command to invoke. * @param ignoreErrorStream : Boolean which controls whether to throw exception or not * based on error stream. * @return result :- depending on the method invocation. * @throws Exception exceptions thrown from the execution */ public static String cmdInvocation(String[] command, boolean ignoreErrorStream) throws IOException { String result = ""; String error = ""; Process process = new ProcessBuilder(command).start(); try ( InputStream inputStream = process.getInputStream(); InputStream errorStream = process.getErrorStream(); BufferedReader br = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8)); BufferedReader ebr = new BufferedReader(new InputStreamReader(errorStream, StandardCharsets.UTF_8)); ) { result = br.readLine(); process.waitFor(); error = ebr.readLine(); if (error != null && (!error.equals(""))) { if (!ignoreErrorStream) { throw new IOException(error, null); } } } catch (Exception e) { throw new RuntimeException("Exception occurred while invoking command", e); } return result; } /** * Prints information for passed SQL Server. * * @param sqlServer sqlServer to be printed */ public static void print(SqlServer sqlServer) { StringBuilder builder = new StringBuilder().append("Sql Server: ").append(sqlServer.id()) .append("Name: ").append(sqlServer.name()) .append("\n\tResource group: ").append(sqlServer.resourceGroupName()) .append("\n\tRegion: ").append(sqlServer.region()) .append("\n\tSqlServer version: ").append(sqlServer.version()) .append("\n\tFully qualified name for Sql Server: ").append(sqlServer.fullyQualifiedDomainName()); System.out.println(builder.toString()); } /** * Prints information for the passed SQL Database. * * @param database database to be printed */ public static void print(SqlDatabase database) { StringBuilder builder = new StringBuilder().append("Sql Database: ").append(database.id()) .append("Name: ").append(database.name()) .append("\n\tResource group: ").append(database.resourceGroupName()) .append("\n\tRegion: ").append(database.region()) .append("\n\tSqlServer Name: ").append(database.sqlServerName()) .append("\n\tEdition of SQL database: ").append(database.edition()) .append("\n\tCollation of SQL database: ").append(database.collation()) .append("\n\tCreation date of SQL database: ").append(database.creationDate()) .append("\n\tIs data warehouse: ").append(database.isDataWarehouse()) .append("\n\tRequested service objective of SQL database: ").append(database.requestedServiceObjectiveName()) .append("\n\tName of current service objective of SQL database: ").append(database.currentServiceObjectiveName()) .append("\n\tMax size bytes of SQL database: ").append(database.maxSizeBytes()) .append("\n\tDefault secondary location of SQL database: ").append(database.defaultSecondaryLocation()); System.out.println(builder.toString()); } /** * Prints information for the passed firewall rule. * * @param firewallRule firewall rule to be printed. */ public static void print(SqlFirewallRule firewallRule) { StringBuilder builder = new StringBuilder().append("Sql firewall rule: ").append(firewallRule.id()) .append("Name: ").append(firewallRule.name()) .append("\n\tResource group: ").append(firewallRule.resourceGroupName()) .append("\n\tRegion: ").append(firewallRule.region()) .append("\n\tSqlServer Name: ").append(firewallRule.sqlServerName()) .append("\n\tStart IP Address of the firewall rule: ").append(firewallRule.startIpAddress()) .append("\n\tEnd IP Address of the firewall rule: ").append(firewallRule.endIpAddress()); System.out.println(builder.toString()); } /** * Prints information for the passed virtual network rule. * * @param virtualNetworkRule virtual network rule to be printed. */ public static void print(SqlVirtualNetworkRule virtualNetworkRule) { StringBuilder builder = new StringBuilder().append("SQL virtual network rule: ").append(virtualNetworkRule.id()) .append("Name: ").append(virtualNetworkRule.name()) .append("\n\tResource group: ").append(virtualNetworkRule.resourceGroupName()) .append("\n\tSqlServer Name: ").append(virtualNetworkRule.sqlServerName()) .append("\n\tSubnet ID: ").append(virtualNetworkRule.subnetId()) .append("\n\tState: ").append(virtualNetworkRule.state()); System.out.println(builder.toString()); } /** * Prints information for the passed SQL subscription usage metric. * * @param subscriptionUsageMetric metric to be printed. */ public static void print(SqlSubscriptionUsageMetric subscriptionUsageMetric) { StringBuilder builder = new StringBuilder().append("SQL Subscription Usage Metric: ").append(subscriptionUsageMetric.id()) .append("Name: ").append(subscriptionUsageMetric.name()) .append("\n\tDisplay Name: ").append(subscriptionUsageMetric.displayName()) .append("\n\tCurrent Value: ").append(subscriptionUsageMetric.currentValue()) .append("\n\tLimit: ").append(subscriptionUsageMetric.limit()) .append("\n\tUnit: ").append(subscriptionUsageMetric.unit()) .append("\n\tType: ").append(subscriptionUsageMetric.type()); System.out.println(builder.toString()); } /** * Prints information for the passed SQL database usage metric. * * @param dbUsageMetric metric to be printed. */ public static void print(SqlDatabaseUsageMetric dbUsageMetric) { StringBuilder builder = new StringBuilder().append("SQL Database Usage Metric") .append("Name: ").append(dbUsageMetric.name()) .append("\n\tResource Name: ").append(dbUsageMetric.resourceName()) .append("\n\tDisplay Name: ").append(dbUsageMetric.displayName()) .append("\n\tCurrent Value: ").append(dbUsageMetric.currentValue()) .append("\n\tLimit: ").append(dbUsageMetric.limit()) .append("\n\tUnit: ").append(dbUsageMetric.unit()) .append("\n\tNext Reset Time: ").append(dbUsageMetric.nextResetTime()); System.out.println(builder.toString()); } /** * Prints information for the passed SQL database metric. * * @param dbMetric metric to be printed. */ public static void print(SqlDatabaseMetric dbMetric) { StringBuilder builder = new StringBuilder().append("SQL Database Metric") .append("Name: ").append(dbMetric.name()) .append("\n\tStart Time: ").append(dbMetric.startTime()) .append("\n\tEnd Time: ").append(dbMetric.endTime()) .append("\n\tTime Grain: ").append(dbMetric.timeGrain()) .append("\n\tUnit: ").append(dbMetric.unit()); for (SqlDatabaseMetricValue metricValue : dbMetric.metricValues()) { builder .append("\n\tMetric Value: ") .append("\n\t\tCount: ").append(metricValue.count()) .append("\n\t\tAverage: ").append(metricValue.average()) .append("\n\t\tMaximum: ").append(metricValue.maximum()) .append("\n\t\tMinimum: ").append(metricValue.minimum()) .append("\n\t\tTimestamp: ").append(metricValue.timestamp()) .append("\n\t\tTotal: ").append(metricValue.total()); } System.out.println(builder.toString()); } /** * Prints information for the passed Failover Group. * * @param failoverGroup the SQL Failover Group to be printed. */ public static void print(SqlFailoverGroup failoverGroup) { StringBuilder builder = new StringBuilder().append("SQL Failover Group: ").append(failoverGroup.id()) .append("Name: ").append(failoverGroup.name()) .append("\n\tResource group: ").append(failoverGroup.resourceGroupName()) .append("\n\tSqlServer Name: ").append(failoverGroup.sqlServerName()) .append("\n\tRead-write endpoint policy: ").append(failoverGroup.readWriteEndpointPolicy()) .append("\n\tData loss grace period: ").append(failoverGroup.readWriteEndpointDataLossGracePeriodMinutes()) .append("\n\tRead-only endpoint policy: ").append(failoverGroup.readOnlyEndpointPolicy()) .append("\n\tReplication state: ").append(failoverGroup.replicationState()) .append("\n\tReplication role: ").append(failoverGroup.replicationRole()); builder.append("\n\tPartner Servers: "); for (PartnerInfo item : failoverGroup.partnerServers()) { builder .append("\n\t\tId: ").append(item.id()) .append("\n\t\tLocation: ").append(item.location()) .append("\n\t\tReplication role: ").append(item.replicationRole()); } builder.append("\n\tDatabases: "); for (String databaseId : failoverGroup.databases()) { builder.append("\n\t\tID: ").append(databaseId); } System.out.println(builder.toString()); } /** * Prints information for the passed SQL server key. * * @param serverKey virtual network rule to be printed. */ public static void print(SqlServerKey serverKey) { StringBuilder builder = new StringBuilder().append("SQL server key: ").append(serverKey.id()) .append("Name: ").append(serverKey.name()) .append("\n\tResource group: ").append(serverKey.resourceGroupName()) .append("\n\tSqlServer Name: ").append(serverKey.sqlServerName()) .append("\n\tRegion: ").append(serverKey.region() != null ? serverKey.region().name() : "") .append("\n\tServer Key Type: ").append(serverKey.serverKeyType()) .append("\n\tServer Key URI: ").append(serverKey.uri()) .append("\n\tServer Key Thumbprint: ").append(serverKey.thumbprint()) .append("\n\tServer Key Creation Date: ").append(serverKey.creationDate() != null ? serverKey.creationDate().toString() : ""); System.out.println(builder.toString()); } /** * Prints information of the elastic pool passed in. * * @param elasticPool elastic pool to be printed */ public static void print(SqlElasticPool elasticPool) { StringBuilder builder = new StringBuilder().append("Sql elastic pool: ").append(elasticPool.id()) .append("Name: ").append(elasticPool.name()) .append("\n\tResource group: ").append(elasticPool.resourceGroupName()) .append("\n\tRegion: ").append(elasticPool.region()) .append("\n\tSqlServer Name: ").append(elasticPool.sqlServerName()) .append("\n\tEdition of elastic pool: ").append(elasticPool.edition()) .append("\n\tTotal number of DTUs in the elastic pool: ").append(elasticPool.dtu()) .append("\n\tMaximum DTUs a database can get in elastic pool: ").append(elasticPool.databaseDtuMax()) .append("\n\tMinimum DTUs a database is guaranteed in elastic pool: ").append(elasticPool.databaseDtuMin()) .append("\n\tCreation date for the elastic pool: ").append(elasticPool.creationDate()) .append("\n\tState of the elastic pool: ").append(elasticPool.state()) .append("\n\tStorage capacity in MBs for the elastic pool: ").append(elasticPool.storageCapacity()); System.out.println(builder.toString()); } /** * Prints information of the elastic pool activity. * * @param elasticPoolActivity elastic pool activity to be printed */ public static void print(ElasticPoolActivity elasticPoolActivity) { StringBuilder builder = new StringBuilder().append("Sql elastic pool activity: ").append(elasticPoolActivity.id()) .append("Name: ").append(elasticPoolActivity.name()) .append("\n\tResource group: ").append(elasticPoolActivity.resourceGroupName()) .append("\n\tState: ").append(elasticPoolActivity.state()) .append("\n\tElastic pool name: ").append(elasticPoolActivity.elasticPoolName()) .append("\n\tStart time of activity: ").append(elasticPoolActivity.startTime()) .append("\n\tEnd time of activity: ").append(elasticPoolActivity.endTime()) .append("\n\tError code of activity: ").append(elasticPoolActivity.errorCode()) .append("\n\tError message of activity: ").append(elasticPoolActivity.errorMessage()) .append("\n\tError severity of activity: ").append(elasticPoolActivity.errorSeverity()) .append("\n\tOperation: ").append(elasticPoolActivity.operation()) .append("\n\tCompleted percentage of activity: ").append(elasticPoolActivity.percentComplete()) .append("\n\tRequested DTU max limit in activity: ").append(elasticPoolActivity.requestedDatabaseDtuMax()) .append("\n\tRequested DTU min limit in activity: ").append(elasticPoolActivity.requestedDatabaseDtuMin()) .append("\n\tRequested DTU limit in activity: ").append(elasticPoolActivity.requestedDtu()); System.out.println(builder.toString()); } /** * Prints information of the database activity. * * @param databaseActivity database activity to be printed */ public static void print(ElasticPoolDatabaseActivity databaseActivity) { StringBuilder builder = new StringBuilder().append("Sql elastic pool database activity: ").append(databaseActivity.id()) .append("Name: ").append(databaseActivity.name()) .append("\n\tResource group: ").append(databaseActivity.resourceGroupName()) .append("\n\tSQL Server Name: ").append(databaseActivity.serverName()) .append("\n\tDatabase name name: ").append(databaseActivity.databaseName()) .append("\n\tCurrent elastic pool name of the database: ").append(databaseActivity.currentElasticPoolName()) .append("\n\tState: ").append(databaseActivity.state()) .append("\n\tStart time of activity: ").append(databaseActivity.startTime()) .append("\n\tEnd time of activity: ").append(databaseActivity.endTime()) .append("\n\tCompleted percentage: ").append(databaseActivity.percentComplete()) .append("\n\tError code of activity: ").append(databaseActivity.errorCode()) .append("\n\tError message of activity: ").append(databaseActivity.errorMessage()) .append("\n\tError severity of activity: ").append(databaseActivity.errorSeverity()); System.out.println(builder.toString()); } /** * Print an application gateway. * * @param resource an application gateway */ public static void print(ApplicationGateway resource) { StringBuilder info = new StringBuilder(); info.append("Application gateway: ").append(resource.id()) .append("Name: ").append(resource.name()) .append("\n\tResource group: ").append(resource.resourceGroupName()) .append("\n\tRegion: ").append(resource.region()) .append("\n\tTags: ").append(resource.tags()) .append("\n\tSKU: ").append(resource.sku().toString()) .append("\n\tOperational state: ").append(resource.operationalState()) .append("\n\tInternet-facing? ").append(resource.isPublic()) .append("\n\tInternal? ").append(resource.isPrivate()) .append("\n\tDefault private IP address: ").append(resource.privateIpAddress()) .append("\n\tPrivate IP address allocation method: ").append(resource.privateIpAllocationMethod()) .append("\n\tDisabled SSL protocols: ").append(resource.disabledSslProtocols().toString()); Map<String, ApplicationGatewayIpConfiguration> ipConfigs = resource.ipConfigurations(); info.append("\n\tIP configurations: ").append(ipConfigs.size()); for (ApplicationGatewayIpConfiguration ipConfig : ipConfigs.values()) { info.append("\n\t\tName: ").append(ipConfig.name()) .append("\n\t\t\tNetwork id: ").append(ipConfig.networkId()) .append("\n\t\t\tSubnet name: ").append(ipConfig.subnetName()); } Map<String, ApplicationGatewayFrontend> frontends = resource.frontends(); info.append("\n\tFrontends: ").append(frontends.size()); for (ApplicationGatewayFrontend frontend : frontends.values()) { info.append("\n\t\tName: ").append(frontend.name()) .append("\n\t\t\tPublic? ").append(frontend.isPublic()); if (frontend.isPublic()) { info.append("\n\t\t\tPublic IP address ID: ").append(frontend.publicIpAddressId()); } if (frontend.isPrivate()) { info.append("\n\t\t\tPrivate IP address: ").append(frontend.privateIpAddress()) .append("\n\t\t\tPrivate IP allocation method: ").append(frontend.privateIpAllocationMethod()) .append("\n\t\t\tSubnet name: ").append(frontend.subnetName()) .append("\n\t\t\tVirtual network ID: ").append(frontend.networkId()); } } Map<String, ApplicationGatewayBackend> backends = resource.backends(); info.append("\n\tBackends: ").append(backends.size()); for (ApplicationGatewayBackend backend : backends.values()) { info.append("\n\t\tName: ").append(backend.name()) .append("\n\t\t\tAssociated NIC IP configuration IDs: ").append(backend.backendNicIPConfigurationNames().keySet()); Collection<ApplicationGatewayBackendAddress> addresses = backend.addresses(); info.append("\n\t\t\tAddresses: ").append(addresses.size()); for (ApplicationGatewayBackendAddress address : addresses) { info.append("\n\t\t\t\tFQDN: ").append(address.fqdn()) .append("\n\t\t\t\tIP: ").append(address.ipAddress()); } } Map<String, ApplicationGatewayBackendHttpConfiguration> httpConfigs = resource.backendHttpConfigurations(); info.append("\n\tHTTP Configurations: ").append(httpConfigs.size()); for (ApplicationGatewayBackendHttpConfiguration httpConfig : httpConfigs.values()) { info.append("\n\t\tName: ").append(httpConfig.name()) .append("\n\t\t\tCookie based affinity: ").append(httpConfig.cookieBasedAffinity()) .append("\n\t\t\tPort: ").append(httpConfig.port()) .append("\n\t\t\tRequest timeout in seconds: ").append(httpConfig.requestTimeout()) .append("\n\t\t\tProtocol: ").append(httpConfig.protocol()) .append("\n\t\tHost header: ").append(httpConfig.hostHeader()) .append("\n\t\tHost header comes from backend? ").append(httpConfig.isHostHeaderFromBackend()) .append("\n\t\tConnection draining timeout in seconds: ").append(httpConfig.connectionDrainingTimeoutInSeconds()) .append("\n\t\tAffinity cookie name: ").append(httpConfig.affinityCookieName()) .append("\n\t\tPath: ").append(httpConfig.path()); ApplicationGatewayProbe probe = httpConfig.probe(); if (probe != null) { info.append("\n\t\tProbe: " + probe.name()); } info.append("\n\t\tIs probe enabled? ").append(httpConfig.isProbeEnabled()); } Map<String, ApplicationGatewaySslCertificate> sslCerts = resource.sslCertificates(); info.append("\n\tSSL certificates: ").append(sslCerts.size()); for (ApplicationGatewaySslCertificate cert : sslCerts.values()) { info.append("\n\t\tName: ").append(cert.name()) .append("\n\t\t\tCert data: ").append(cert.publicData()); } Map<String, ApplicationGatewayRedirectConfiguration> redirects = resource.redirectConfigurations(); info.append("\n\tRedirect configurations: ").append(redirects.size()); for (ApplicationGatewayRedirectConfiguration redirect : redirects.values()) { info.append("\n\t\tName: ").append(redirect.name()) .append("\n\t\tTarget URL: ").append(redirect.type()) .append("\n\t\tTarget URL: ").append(redirect.targetUrl()) .append("\n\t\tTarget listener: ").append(redirect.targetListener() != null ? redirect.targetListener().name() : null) .append("\n\t\tIs path included? ").append(redirect.isPathIncluded()) .append("\n\t\tIs query string included? ").append(redirect.isQueryStringIncluded()) .append("\n\t\tReferencing request routing rules: ").append(redirect.requestRoutingRules().values()); } Map<String, ApplicationGatewayListener> listeners = resource.listeners(); info.append("\n\tHTTP listeners: ").append(listeners.size()); for (ApplicationGatewayListener listener : listeners.values()) { info.append("\n\t\tName: ").append(listener.name()) .append("\n\t\t\tHost name: ").append(listener.hostname()) .append("\n\t\t\tServer name indication required? ").append(listener.requiresServerNameIndication()) .append("\n\t\t\tAssociated frontend name: ").append(listener.frontend().name()) .append("\n\t\t\tFrontend port name: ").append(listener.frontendPortName()) .append("\n\t\t\tFrontend port number: ").append(listener.frontendPortNumber()) .append("\n\t\t\tProtocol: ").append(listener.protocol().toString()); if (listener.sslCertificate() != null) { info.append("\n\t\t\tAssociated SSL certificate: ").append(listener.sslCertificate().name()); } } Map<String, ApplicationGatewayProbe> probes = resource.probes(); info.append("\n\tProbes: ").append(probes.size()); for (ApplicationGatewayProbe probe : probes.values()) { info.append("\n\t\tName: ").append(probe.name()) .append("\n\t\tProtocol:").append(probe.protocol().toString()) .append("\n\t\tInterval in seconds: ").append(probe.timeBetweenProbesInSeconds()) .append("\n\t\tRetries: ").append(probe.retriesBeforeUnhealthy()) .append("\n\t\tTimeout: ").append(probe.timeoutInSeconds()) .append("\n\t\tHost: ").append(probe.host()) .append("\n\t\tHealthy HTTP response status code ranges: ").append(probe.healthyHttpResponseStatusCodeRanges()) .append("\n\t\tHealthy HTTP response body contents: ").append(probe.healthyHttpResponseBodyContents()); } Map<String, ApplicationGatewayRequestRoutingRule> rules = resource.requestRoutingRules(); info.append("\n\tRequest routing rules: ").append(rules.size()); for (ApplicationGatewayRequestRoutingRule rule : rules.values()) { info.append("\n\t\tName: ").append(rule.name()) .append("\n\t\tType: ").append(rule.ruleType()) .append("\n\t\tPublic IP address ID: ").append(rule.publicIpAddressId()) .append("\n\t\tHost name: ").append(rule.hostname()) .append("\n\t\tServer name indication required? ").append(rule.requiresServerNameIndication()) .append("\n\t\tFrontend port: ").append(rule.frontendPort()) .append("\n\t\tFrontend protocol: ").append(rule.frontendProtocol().toString()) .append("\n\t\tBackend port: ").append(rule.backendPort()) .append("\n\t\tCookie based affinity enabled? ").append(rule.cookieBasedAffinity()) .append("\n\t\tRedirect configuration: ").append(rule.redirectConfiguration() != null ? rule.redirectConfiguration().name() : "(none)"); Collection<ApplicationGatewayBackendAddress> addresses = rule.backendAddresses(); info.append("\n\t\t\tBackend addresses: ").append(addresses.size()); for (ApplicationGatewayBackendAddress address : addresses) { info.append("\n\t\t\t\t") .append(address.fqdn()) .append(" [").append(address.ipAddress()).append("]"); } info.append("\n\t\t\tSSL certificate name: "); ApplicationGatewaySslCertificate cert = rule.sslCertificate(); if (cert == null) { info.append("(None)"); } else { info.append(cert.name()); } info.append("\n\t\t\tAssociated backend address pool: "); ApplicationGatewayBackend backend = rule.backend(); if (backend == null) { info.append("(None)"); } else { info.append(backend.name()); } info.append("\n\t\t\tAssociated backend HTTP settings configuration: "); ApplicationGatewayBackendHttpConfiguration config = rule.backendHttpConfiguration(); if (config == null) { info.append("(None)"); } else { info.append(config.name()); } info.append("\n\t\t\tAssociated frontend listener: "); ApplicationGatewayListener listener = rule.listener(); if (listener == null) { info.append("(None)"); } else { info.append(config.name()); } } System.out.println(info.toString()); } /** * Prints information of a virtual machine custom image. * * @param image the image */ public static void print(VirtualMachineCustomImage image) { StringBuilder builder = new StringBuilder().append("Virtual machine custom image: ").append(image.id()) .append("Name: ").append(image.name()) .append("\n\tResource group: ").append(image.resourceGroupName()) .append("\n\tCreated from virtual machine: ").append(image.sourceVirtualMachineId()); builder.append("\n\tOS disk image: ") .append("\n\t\tOperating system: ").append(image.osDiskImage().osType()) .append("\n\t\tOperating system state: ").append(image.osDiskImage().osState()) .append("\n\t\tCaching: ").append(image.osDiskImage().caching()) .append("\n\t\tSize (GB): ").append(image.osDiskImage().diskSizeGB()); if (image.isCreatedFromVirtualMachine()) { builder.append("\n\t\tSource virtual machine: ").append(image.sourceVirtualMachineId()); } if (image.osDiskImage().managedDisk() != null) { builder.append("\n\t\tSource managed disk: ").append(image.osDiskImage().managedDisk().id()); } if (image.osDiskImage().snapshot() != null) { builder.append("\n\t\tSource snapshot: ").append(image.osDiskImage().snapshot().id()); } if (image.osDiskImage().blobUri() != null) { builder.append("\n\t\tSource un-managed vhd: ").append(image.osDiskImage().blobUri()); } if (image.dataDiskImages() != null) { for (ImageDataDisk diskImage : image.dataDiskImages().values()) { builder.append("\n\tDisk Image (Lun) .append("\n\t\tCaching: ").append(diskImage.caching()) .append("\n\t\tSize (GB): ").append(diskImage.diskSizeGB()); if (image.isCreatedFromVirtualMachine()) { builder.append("\n\t\tSource virtual machine: ").append(image.sourceVirtualMachineId()); } if (diskImage.managedDisk() != null) { builder.append("\n\t\tSource managed disk: ").append(diskImage.managedDisk().id()); } if (diskImage.snapshot() != null) { builder.append("\n\t\tSource snapshot: ").append(diskImage.snapshot().id()); } if (diskImage.blobUri() != null) { builder.append("\n\t\tSource un-managed vhd: ").append(diskImage.blobUri()); } } } System.out.println(builder.toString()); } /** * Uploads a file to an Azure app service for Web App. * * @param profile the publishing profile for the app service. * @param fileName the name of the file on server * @param file the local file */ public static void uploadFileViaFtp(PublishingProfile profile, String fileName, InputStream file) { String path = "./site/wwwroot/webapps"; uploadFileViaFtp(profile, fileName, file, path); } /** * Uploads a file to an Azure app service for Function App. * * @param profile the publishing profile for the app service. * @param fileName the name of the file on server * @param file the local file */ public static void uploadFileForFunctionViaFtp(PublishingProfile profile, String fileName, InputStream file) { String path = "./site/wwwroot"; uploadFileViaFtp(profile, fileName, file, path); } private static void uploadFileViaFtp(PublishingProfile profile, String fileName, InputStream file, String path) { FTPClient ftpClient = new FTPClient(); String[] ftpUrlSegments = profile.ftpUrl().split("/", 2); String server = ftpUrlSegments[0]; if (fileName.contains("/")) { int lastslash = fileName.lastIndexOf('/'); path = path + "/" + fileName.substring(0, lastslash); fileName = fileName.substring(lastslash + 1); } try { ftpClient.connect(server); ftpClient.enterLocalPassiveMode(); ftpClient.login(profile.ftpUsername(), profile.ftpPassword()); ftpClient.setFileType(FTP.BINARY_FILE_TYPE); for (String segment : path.split("/")) { if (!ftpClient.changeWorkingDirectory(segment)) { ftpClient.makeDirectory(segment); ftpClient.changeWorkingDirectory(segment); } } ftpClient.storeFile(fileName, file); ftpClient.disconnect(); } catch (IOException e) { e.printStackTrace(); } } /** * Print service bus namespace info. * * @param serviceBusNamespace a service bus namespace */ public static void print(ServiceBusNamespace serviceBusNamespace) { StringBuilder builder = new StringBuilder() .append("Service bus Namespace: ").append(serviceBusNamespace.id()) .append("\n\tName: ").append(serviceBusNamespace.name()) .append("\n\tRegion: ").append(serviceBusNamespace.regionName()) .append("\n\tResourceGroupName: ").append(serviceBusNamespace.resourceGroupName()) .append("\n\tCreatedAt: ").append(serviceBusNamespace.createdAt()) .append("\n\tUpdatedAt: ").append(serviceBusNamespace.updatedAt()) .append("\n\tDnsLabel: ").append(serviceBusNamespace.dnsLabel()) .append("\n\tFQDN: ").append(serviceBusNamespace.fqdn()) .append("\n\tSku: ") .append("\n\t\tCapacity: ").append(serviceBusNamespace.sku().capacity()) .append("\n\t\tSkuName: ").append(serviceBusNamespace.sku().name()) .append("\n\t\tTier: ").append(serviceBusNamespace.sku().tier()); System.out.println(builder.toString()); } /** * Print service bus queue info. * * @param queue a service bus queue */ public static void print(Queue queue) { StringBuilder builder = new StringBuilder() .append("Service bus Queue: ").append(queue.id()) .append("\n\tName: ").append(queue.name()) .append("\n\tResourceGroupName: ").append(queue.resourceGroupName()) .append("\n\tCreatedAt: ").append(queue.createdAt()) .append("\n\tUpdatedAt: ").append(queue.updatedAt()) .append("\n\tAccessedAt: ").append(queue.accessedAt()) .append("\n\tActiveMessageCount: ").append(queue.activeMessageCount()) .append("\n\tCurrentSizeInBytes: ").append(queue.currentSizeInBytes()) .append("\n\tDeadLetterMessageCount: ").append(queue.deadLetterMessageCount()) .append("\n\tDefaultMessageTtlDuration: ").append(queue.defaultMessageTtlDuration()) .append("\n\tDuplicateMessageDetectionHistoryDuration: ").append(queue.duplicateMessageDetectionHistoryDuration()) .append("\n\tIsBatchedOperationsEnabled: ").append(queue.isBatchedOperationsEnabled()) .append("\n\tIsDeadLetteringEnabledForExpiredMessages: ").append(queue.isDeadLetteringEnabledForExpiredMessages()) .append("\n\tIsDuplicateDetectionEnabled: ").append(queue.isDuplicateDetectionEnabled()) .append("\n\tIsExpressEnabled: ").append(queue.isExpressEnabled()) .append("\n\tIsPartitioningEnabled: ").append(queue.isPartitioningEnabled()) .append("\n\tIsSessionEnabled: ").append(queue.isSessionEnabled()) .append("\n\tDeleteOnIdleDurationInMinutes: ").append(queue.deleteOnIdleDurationInMinutes()) .append("\n\tMaxDeliveryCountBeforeDeadLetteringMessage: ").append(queue.maxDeliveryCountBeforeDeadLetteringMessage()) .append("\n\tMaxSizeInMB: ").append(queue.maxSizeInMB()) .append("\n\tMessageCount: ").append(queue.messageCount()) .append("\n\tScheduledMessageCount: ").append(queue.scheduledMessageCount()) .append("\n\tStatus: ").append(queue.status()) .append("\n\tTransferMessageCount: ").append(queue.transferMessageCount()) .append("\n\tLockDurationInSeconds: ").append(queue.lockDurationInSeconds()) .append("\n\tTransferDeadLetterMessageCount: ").append(queue.transferDeadLetterMessageCount()); System.out.println(builder.toString()); } /** * Print service bus queue authorization keys info. * * @param queueAuthorizationRule a service bus queue authorization keys */ public static void print(QueueAuthorizationRule queueAuthorizationRule) { StringBuilder builder = new StringBuilder() .append("Service bus queue authorization rule: ").append(queueAuthorizationRule.id()) .append("\n\tName: ").append(queueAuthorizationRule.name()) .append("\n\tResourceGroupName: ").append(queueAuthorizationRule.resourceGroupName()) .append("\n\tNamespace Name: ").append(queueAuthorizationRule.namespaceName()) .append("\n\tQueue Name: ").append(queueAuthorizationRule.queueName()); List<com.azure.resourcemanager.servicebus.models.AccessRights> rights = queueAuthorizationRule.rights(); builder.append("\n\tNumber of access rights in queue: ").append(rights.size()); for (com.azure.resourcemanager.servicebus.models.AccessRights right : rights) { builder.append("\n\t\tAccessRight: ") .append("\n\t\t\tName :").append(right.name()); } System.out.println(builder.toString()); } /** * Print service bus namespace authorization keys info. * * @param keys a service bus namespace authorization keys */ public static void print(AuthorizationKeys keys) { StringBuilder builder = new StringBuilder() .append("Authorization keys: ") .append("\n\tPrimaryKey: ").append(keys.primaryKey()) .append("\n\tPrimaryConnectionString: ").append(keys.primaryConnectionString()) .append("\n\tSecondaryKey: ").append(keys.secondaryKey()) .append("\n\tSecondaryConnectionString: ").append(keys.secondaryConnectionString()); System.out.println(builder.toString()); } /** * Print service bus namespace authorization rule info. * * @param namespaceAuthorizationRule a service bus namespace authorization rule */ public static void print(NamespaceAuthorizationRule namespaceAuthorizationRule) { StringBuilder builder = new StringBuilder() .append("Service bus queue authorization rule: ").append(namespaceAuthorizationRule.id()) .append("\n\tName: ").append(namespaceAuthorizationRule.name()) .append("\n\tResourceGroupName: ").append(namespaceAuthorizationRule.resourceGroupName()) .append("\n\tNamespace Name: ").append(namespaceAuthorizationRule.namespaceName()); List<com.azure.resourcemanager.servicebus.models.AccessRights> rights = namespaceAuthorizationRule.rights(); builder.append("\n\tNumber of access rights in queue: ").append(rights.size()); for (com.azure.resourcemanager.servicebus.models.AccessRights right : rights) { builder.append("\n\t\tAccessRight: ") .append("\n\t\t\tName :").append(right.name()); } System.out.println(builder.toString()); } /** * Print service bus topic info. * * @param topic a service bus topic */ public static void print(Topic topic) { StringBuilder builder = new StringBuilder() .append("Service bus topic: ").append(topic.id()) .append("\n\tName: ").append(topic.name()) .append("\n\tResourceGroupName: ").append(topic.resourceGroupName()) .append("\n\tCreatedAt: ").append(topic.createdAt()) .append("\n\tUpdatedAt: ").append(topic.updatedAt()) .append("\n\tAccessedAt: ").append(topic.accessedAt()) .append("\n\tActiveMessageCount: ").append(topic.activeMessageCount()) .append("\n\tCurrentSizeInBytes: ").append(topic.currentSizeInBytes()) .append("\n\tDeadLetterMessageCount: ").append(topic.deadLetterMessageCount()) .append("\n\tDefaultMessageTtlDuration: ").append(topic.defaultMessageTtlDuration()) .append("\n\tDuplicateMessageDetectionHistoryDuration: ").append(topic.duplicateMessageDetectionHistoryDuration()) .append("\n\tIsBatchedOperationsEnabled: ").append(topic.isBatchedOperationsEnabled()) .append("\n\tIsDuplicateDetectionEnabled: ").append(topic.isDuplicateDetectionEnabled()) .append("\n\tIsExpressEnabled: ").append(topic.isExpressEnabled()) .append("\n\tIsPartitioningEnabled: ").append(topic.isPartitioningEnabled()) .append("\n\tDeleteOnIdleDurationInMinutes: ").append(topic.deleteOnIdleDurationInMinutes()) .append("\n\tMaxSizeInMB: ").append(topic.maxSizeInMB()) .append("\n\tScheduledMessageCount: ").append(topic.scheduledMessageCount()) .append("\n\tStatus: ").append(topic.status()) .append("\n\tTransferMessageCount: ").append(topic.transferMessageCount()) .append("\n\tSubscriptionCount: ").append(topic.subscriptionCount()) .append("\n\tTransferDeadLetterMessageCount: ").append(topic.transferDeadLetterMessageCount()); System.out.println(builder.toString()); } /** * Print service bus subscription info. * * @param serviceBusSubscription a service bus subscription */ public static void print(ServiceBusSubscription serviceBusSubscription) { StringBuilder builder = new StringBuilder() .append("Service bus subscription: ").append(serviceBusSubscription.id()) .append("\n\tName: ").append(serviceBusSubscription.name()) .append("\n\tResourceGroupName: ").append(serviceBusSubscription.resourceGroupName()) .append("\n\tCreatedAt: ").append(serviceBusSubscription.createdAt()) .append("\n\tUpdatedAt: ").append(serviceBusSubscription.updatedAt()) .append("\n\tAccessedAt: ").append(serviceBusSubscription.accessedAt()) .append("\n\tActiveMessageCount: ").append(serviceBusSubscription.activeMessageCount()) .append("\n\tDeadLetterMessageCount: ").append(serviceBusSubscription.deadLetterMessageCount()) .append("\n\tDefaultMessageTtlDuration: ").append(serviceBusSubscription.defaultMessageTtlDuration()) .append("\n\tIsBatchedOperationsEnabled: ").append(serviceBusSubscription.isBatchedOperationsEnabled()) .append("\n\tDeleteOnIdleDurationInMinutes: ").append(serviceBusSubscription.deleteOnIdleDurationInMinutes()) .append("\n\tScheduledMessageCount: ").append(serviceBusSubscription.scheduledMessageCount()) .append("\n\tStatus: ").append(serviceBusSubscription.status()) .append("\n\tTransferMessageCount: ").append(serviceBusSubscription.transferMessageCount()) .append("\n\tIsDeadLetteringEnabledForExpiredMessages: ").append(serviceBusSubscription.isDeadLetteringEnabledForExpiredMessages()) .append("\n\tIsSessionEnabled: ").append(serviceBusSubscription.isSessionEnabled()) .append("\n\tLockDurationInSeconds: ").append(serviceBusSubscription.lockDurationInSeconds()) .append("\n\tMaxDeliveryCountBeforeDeadLetteringMessage: ").append(serviceBusSubscription.maxDeliveryCountBeforeDeadLetteringMessage()) .append("\n\tIsDeadLetteringEnabledForFilterEvaluationFailedMessages: ").append(serviceBusSubscription.isDeadLetteringEnabledForFilterEvaluationFailedMessages()) .append("\n\tTransferMessageCount: ").append(serviceBusSubscription.transferMessageCount()) .append("\n\tTransferDeadLetterMessageCount: ").append(serviceBusSubscription.transferDeadLetterMessageCount()); System.out.println(builder.toString()); } /** * Print topic Authorization Rule info. * * @param topicAuthorizationRule a topic Authorization Rule */ public static void print(TopicAuthorizationRule topicAuthorizationRule) { StringBuilder builder = new StringBuilder() .append("Service bus topic authorization rule: ").append(topicAuthorizationRule.id()) .append("\n\tName: ").append(topicAuthorizationRule.name()) .append("\n\tResourceGroupName: ").append(topicAuthorizationRule.resourceGroupName()) .append("\n\tNamespace Name: ").append(topicAuthorizationRule.namespaceName()) .append("\n\tTopic Name: ").append(topicAuthorizationRule.topicName()); List<com.azure.resourcemanager.servicebus.models.AccessRights> rights = topicAuthorizationRule.rights(); builder.append("\n\tNumber of access rights in queue: ").append(rights.size()); for (com.azure.resourcemanager.servicebus.models.AccessRights right : rights) { builder.append("\n\t\tAccessRight: ") .append("\n\t\t\tName :").append(right.name()); } System.out.println(builder.toString()); } /** * Print CosmosDB info. * * @param cosmosDBAccount a CosmosDB */ public static void print(CosmosDBAccount cosmosDBAccount) { StringBuilder builder = new StringBuilder() .append("CosmosDB: ").append(cosmosDBAccount.id()) .append("\n\tName: ").append(cosmosDBAccount.name()) .append("\n\tResourceGroupName: ").append(cosmosDBAccount.resourceGroupName()) .append("\n\tKind: ").append(cosmosDBAccount.kind().toString()) .append("\n\tDefault consistency level: ").append(cosmosDBAccount.consistencyPolicy().defaultConsistencyLevel()) .append("\n\tIP range filter: ").append(cosmosDBAccount.ipRangeFilter()); DatabaseAccountListKeysResult keys = cosmosDBAccount.listKeys(); DatabaseAccountListReadOnlyKeysResult readOnlyKeys = cosmosDBAccount.listReadOnlyKeys(); builder .append("\n\tPrimary Master Key: ").append(keys.primaryMasterKey()) .append("\n\tSecondary Master Key: ").append(keys.secondaryMasterKey()) .append("\n\tPrimary Read-Only Key: ").append(readOnlyKeys.primaryReadonlyMasterKey()) .append("\n\tSecondary Read-Only Key: ").append(readOnlyKeys.secondaryReadonlyMasterKey()); for (Location writeReplica : cosmosDBAccount.writableReplications()) { builder.append("\n\t\tWrite replication: ") .append("\n\t\t\tName :").append(writeReplica.locationName()); } builder.append("\n\tNumber of read replications: ").append(cosmosDBAccount.readableReplications().size()); for (Location readReplica : cosmosDBAccount.readableReplications()) { builder.append("\n\t\tRead replication: ") .append("\n\t\t\tName :").append(readReplica.locationName()); } } /** * Print Active Directory User info. * * @param user active directory user */ public static void print(ActiveDirectoryUser user) { StringBuilder builder = new StringBuilder() .append("Active Directory User: ").append(user.id()) .append("\n\tName: ").append(user.name()) .append("\n\tMail: ").append(user.mail()) .append("\n\tMail Nickname: ").append(user.mailNickname()) .append("\n\tSign In Name: ").append(user.signInName()) .append("\n\tUser Principal Name: ").append(user.userPrincipalName()); System.out.println(builder.toString()); } /** * Print Active Directory User info. * * @param role role definition */ public static void print(RoleDefinition role) { StringBuilder builder = new StringBuilder() .append("Role Definition: ").append(role.id()) .append("\n\tName: ").append(role.name()) .append("\n\tRole Name: ").append(role.roleName()) .append("\n\tType: ").append(role.type()) .append("\n\tDescription: ").append(role.description()) .append("\n\tType: ").append(role.type()); Set<Permission> permissions = role.permissions(); builder.append("\n\tPermissions: ").append(permissions.size()); for (Permission permission : permissions) { builder.append("\n\t\tPermission Actions: " + permission.actions().size()); for (String action : permission.actions()) { builder.append("\n\t\t\tName :").append(action); } builder.append("\n\t\tPermission Not Actions: " + permission.notActions().size()); for (String notAction : permission.notActions()) { builder.append("\n\t\t\tName :").append(notAction); } } Set<String> assignableScopes = role.assignableScopes(); builder.append("\n\tAssignable scopes: ").append(assignableScopes.size()); for (String scope : assignableScopes) { builder.append("\n\t\tAssignable Scope: ") .append("\n\t\t\tName :").append(scope); } System.out.println(builder.toString()); } /** * Print Role Assignment info. * * @param roleAssignment role assignment */ public static void print(RoleAssignment roleAssignment) { StringBuilder builder = new StringBuilder() .append("Role Assignment: ") .append("\n\tScope: ").append(roleAssignment.scope()) .append("\n\tPrincipal Id: ").append(roleAssignment.principalId()) .append("\n\tRole Definition Id: ").append(roleAssignment.roleDefinitionId()); System.out.println(builder.toString()); } /** * Print Active Directory Group info. * * @param group active directory group */ public static void print(ActiveDirectoryGroup group) { StringBuilder builder = new StringBuilder() .append("Active Directory Group: ").append(group.id()) .append("\n\tName: ").append(group.name()) .append("\n\tMail: ").append(group.mail()) .append("\n\tSecurity Enabled: ").append(group.securityEnabled()) .append("\n\tGroup members:"); for (ActiveDirectoryObject object : group.listMembers()) { builder.append("\n\t\tType: ").append(object.getClass().getSimpleName()) .append("\tName: ").append(object.name()); } System.out.println(builder.toString()); } /** * Print Active Directory Application info. * * @param application active directory application */ public static void print(ActiveDirectoryApplication application) { StringBuilder builder = new StringBuilder() .append("Active Directory Application: ").append(application.id()) .append("\n\tName: ").append(application.name()) .append("\n\tSign on URL: ").append(application.signOnUrl()) .append("\n\tReply URLs:"); for (String replyUrl : application.replyUrls()) { builder.append("\n\t\t").append(replyUrl); } System.out.println(builder.toString()); } /** * Print Service Principal info. * * @param servicePrincipal service principal */ public static void print(ServicePrincipal servicePrincipal) { StringBuilder builder = new StringBuilder() .append("Service Principal: ").append(servicePrincipal.id()) .append("\n\tName: ").append(servicePrincipal.name()) .append("\n\tApplication Id: ").append(servicePrincipal.applicationId()); List<String> names = servicePrincipal.servicePrincipalNames(); builder.append("\n\tNames: ").append(names.size()); for (String name : names) { builder.append("\n\t\tName: ").append(name); } System.out.println(builder.toString()); } /** * Print Network Watcher info. * * @param nw network watcher */ public static void print(NetworkWatcher nw) { StringBuilder builder = new StringBuilder() .append("Network Watcher: ").append(nw.id()) .append("\n\tName: ").append(nw.name()) .append("\n\tResource group name: ").append(nw.resourceGroupName()) .append("\n\tRegion name: ").append(nw.regionName()); System.out.println(builder.toString()); } /** * Print packet capture info. * * @param resource packet capture */ public static void print(PacketCapture resource) { StringBuilder sb = new StringBuilder().append("Packet Capture: ").append(resource.id()) .append("\n\tName: ").append(resource.name()) .append("\n\tTarget id: ").append(resource.targetId()) .append("\n\tTime limit in seconds: ").append(resource.timeLimitInSeconds()) .append("\n\tBytes to capture per packet: ").append(resource.bytesToCapturePerPacket()) .append("\n\tProvisioning state: ").append(resource.provisioningState()) .append("\n\tStorage location:") .append("\n\tStorage account id: ").append(resource.storageLocation().storageId()) .append("\n\tStorage account path: ").append(resource.storageLocation().storagePath()) .append("\n\tFile path: ").append(resource.storageLocation().filePath()) .append("\n\t Packet capture filters: ").append(resource.filters().size()); for (PacketCaptureFilter filter : resource.filters()) { sb.append("\n\t\tProtocol: ").append(filter.protocol()); sb.append("\n\t\tLocal IP address: ").append(filter.localIpAddress()); sb.append("\n\t\tRemote IP address: ").append(filter.remoteIpAddress()); sb.append("\n\t\tLocal port: ").append(filter.localPort()); sb.append("\n\t\tRemote port: ").append(filter.remotePort()); } System.out.println(sb.toString()); } /** * Print verification IP flow info. * * @param resource IP flow verification info */ public static void print(VerificationIPFlow resource) { System.out.println(new StringBuilder("IP flow verification: ") .append("\n\tAccess: ").append(resource.access()) .append("\n\tRule name: ").append(resource.ruleName()) .toString()); } /** * Print topology info. * * @param resource topology */ public static void print(Topology resource) { StringBuilder sb = new StringBuilder().append("Topology: ").append(resource.id()) .append("\n\tTopology parameters: ") .append("\n\t\tResource group: ").append(resource.topologyParameters().targetResourceGroupName()) .append("\n\t\tVirtual network: ").append(resource.topologyParameters().targetVirtualNetwork() == null ? "" : resource.topologyParameters().targetVirtualNetwork().id()) .append("\n\t\tSubnet id: ").append(resource.topologyParameters().targetSubnet() == null ? "" : resource.topologyParameters().targetSubnet().id()) .append("\n\tCreated time: ").append(resource.createdTime()) .append("\n\tLast modified time: ").append(resource.lastModifiedTime()); for (TopologyResource tr : resource.resources().values()) { sb.append("\n\tTopology resource: ").append(tr.id()) .append("\n\t\tName: ").append(tr.name()) .append("\n\t\tLocation: ").append(tr.location()) .append("\n\t\tAssociations:"); for (TopologyAssociation association : tr.associations()) { sb.append("\n\t\t\tName:").append(association.name()) .append("\n\t\t\tResource id:").append(association.resourceId()) .append("\n\t\t\tAssociation type:").append(association.associationType()); } } System.out.println(sb.toString()); } /** * Print flow log settings info. * * @param resource flow log settings */ public static void print(FlowLogSettings resource) { System.out.println(new StringBuilder().append("Flow log settings: ") .append("Target resource id: ").append(resource.targetResourceId()) .append("\n\tFlow log enabled: ").append(resource.enabled()) .append("\n\tStorage account id: ").append(resource.storageId()) .append("\n\tRetention policy enabled: ").append(resource.isRetentionEnabled()) .append("\n\tRetention policy days: ").append(resource.retentionDays()) .toString()); } /** * Print availability set info. * * @param resource an availability set */ public static void print(SecurityGroupView resource) { StringBuilder sb = new StringBuilder().append("Security group view: ") .append("\n\tVirtual machine id: ").append(resource.vmId()); for (SecurityGroupNetworkInterface sgni : resource.networkInterfaces().values()) { sb.append("\n\tSecurity group network interface:").append(sgni.id()) .append("\n\t\tSecurity group network interface:") .append("\n\t\tEffective security rules:"); for (EffectiveNetworkSecurityRule rule : sgni.securityRuleAssociations().effectiveSecurityRules()) { sb.append("\n\t\t\tName: ").append(rule.name()) .append("\n\t\t\tDirection: ").append(rule.direction()) .append("\n\t\t\tAccess: ").append(rule.access()) .append("\n\t\t\tPriority: ").append(rule.priority()) .append("\n\t\t\tSource address prefix: ").append(rule.sourceAddressPrefix()) .append("\n\t\t\tSource port range: ").append(rule.sourcePortRange()) .append("\n\t\t\tDestination address prefix: ").append(rule.destinationAddressPrefix()) .append("\n\t\t\tDestination port range: ").append(rule.destinationPortRange()) .append("\n\t\t\tProtocol: ").append(rule.protocol()); } sb.append("\n\t\tSubnet:").append(sgni.securityRuleAssociations().subnetAssociation().id()); printSecurityRule(sb, sgni.securityRuleAssociations().subnetAssociation().securityRules()); if (sgni.securityRuleAssociations().networkInterfaceAssociation() != null) { sb.append("\n\t\tNetwork interface:").append(sgni.securityRuleAssociations().networkInterfaceAssociation().id()); printSecurityRule(sb, sgni.securityRuleAssociations().networkInterfaceAssociation().securityRules()); } sb.append("\n\t\tDefault security rules:"); printSecurityRule(sb, sgni.securityRuleAssociations().defaultSecurityRules()); } System.out.println(sb.toString()); } private static void printSecurityRule(StringBuilder sb, List<SecurityRuleInner> rules) { for (SecurityRuleInner rule : rules) { sb.append("\n\t\t\tName: ").append(rule.name()) .append("\n\t\t\tDirection: ").append(rule.direction()) .append("\n\t\t\tAccess: ").append(rule.access()) .append("\n\t\t\tPriority: ").append(rule.priority()) .append("\n\t\t\tSource address prefix: ").append(rule.sourceAddressPrefix()) .append("\n\t\t\tSource port range: ").append(rule.sourcePortRange()) .append("\n\t\t\tDestination address prefix: ").append(rule.destinationAddressPrefix()) .append("\n\t\t\tDestination port range: ").append(rule.destinationPortRange()) .append("\n\t\t\tProtocol: ").append(rule.protocol()) .append("\n\t\t\tDescription: ").append(rule.description()) .append("\n\t\t\tProvisioning state: ").append(rule.provisioningState()); } } /** * Print next hop info. * * @param resource an availability set */ public static void print(NextHop resource) { System.out.println(new StringBuilder("Next hop: ") .append("Next hop type: ").append(resource.nextHopType()) .append("\n\tNext hop ip address: ").append(resource.nextHopIpAddress()) .append("\n\tRoute table id: ").append(resource.routeTableId()) .toString()); } /** * Print container group info. * * @param resource a container group */ public static void print(ContainerGroup resource) { StringBuilder info = new StringBuilder().append("Container Group: ").append(resource.id()) .append("Name: ").append(resource.name()) .append("\n\tResource group: ").append(resource.resourceGroupName()) .append("\n\tRegion: ").append(resource.region()) .append("\n\tTags: ").append(resource.tags()) .append("\n\tOS type: ").append(resource.osType()); if (resource.ipAddress() != null) { info.append("\n\tPublic IP address: ").append(resource.ipAddress()); } if (resource.externalTcpPorts() != null) { info.append("\n\tExternal TCP ports:"); for (int port : resource.externalTcpPorts()) { info.append(" ").append(port); } } if (resource.externalUdpPorts() != null) { info.append("\n\tExternal UDP ports:"); for (int port : resource.externalUdpPorts()) { info.append(" ").append(port); } } if (resource.imageRegistryServers() != null) { info.append("\n\tPrivate Docker image registries:"); for (String server : resource.imageRegistryServers()) { info.append(" ").append(server); } } if (resource.volumes() != null) { info.append("\n\tVolume mapping: "); for (Map.Entry<String, Volume> entry : resource.volumes().entrySet()) { info.append("\n\t\tName: ").append(entry.getKey()).append(" -> ") .append(entry.getValue().azureFile() != null ? entry.getValue().azureFile().shareName() : "empty direcory volume"); } } if (resource.containers() != null) { info.append("\n\tContainer instances: "); for (Map.Entry<String, Container> entry : resource.containers().entrySet()) { Container container = entry.getValue(); info.append("\n\t\tName: ").append(entry.getKey()).append(" -> ").append(container.image()); info.append("\n\t\t\tResources: "); info.append(container.resources().requests().cpu()).append("CPUs "); info.append(container.resources().requests().memoryInGB()).append("GB"); info.append("\n\t\t\tPorts:"); for (ContainerPort port : container.ports()) { info.append(" ").append(port.port()); } if (container.volumeMounts() != null) { info.append("\n\t\t\tVolume mounts:"); for (VolumeMount volumeMount : container.volumeMounts()) { info.append(" ").append(volumeMount.name()).append("->").append(volumeMount.mountPath()); } } if (container.command() != null) { info.append("\n\t\t\tStart commands:"); for (String command : container.command()) { info.append("\n\t\t\t\t").append(command); } } if (container.environmentVariables() != null) { info.append("\n\t\t\tENV vars:"); for (EnvironmentVariable envVar : container.environmentVariables()) { info.append("\n\t\t\t\t").append(envVar.name()).append("=").append(envVar.value()); } } } } System.out.println(info.toString()); } /** * Print event hub namespace. * * @param resource a virtual machine */ public static void print(EventHubNamespace resource) { StringBuilder info = new StringBuilder(); info.append("Eventhub Namespace: ").append(resource.id()) .append("\n\tName: ").append(resource.name()) .append("\n\tRegion: ").append(resource.region()) .append("\n\tTags: ").append(resource.tags()) .append("\n\tAzureInsightMetricId: ").append(resource.azureInsightMetricId()) .append("\n\tIsAutoScale enabled: ").append(resource.isAutoScaleEnabled()) .append("\n\tServiceBus endpoint: ").append(resource.serviceBusEndpoint()) .append("\n\tThroughPut upper limit: ").append(resource.throughputUnitsUpperLimit()) .append("\n\tCurrent ThroughPut: ").append(resource.currentThroughputUnits()) .append("\n\tCreated time: ").append(resource.createdAt()) .append("\n\tUpdated time: ").append(resource.updatedAt()); System.out.println(info.toString()); } /** * Print event hub. * * @param resource event hub */ public static void print(EventHub resource) { StringBuilder info = new StringBuilder(); info.append("Eventhub: ").append(resource.id()) .append("\n\tName: ").append(resource.name()) .append("\n\tNamespace resource group: ").append(resource.namespaceResourceGroupName()) .append("\n\tNamespace: ").append(resource.namespaceName()) .append("\n\tIs data capture enabled: ").append(resource.isDataCaptureEnabled()) .append("\n\tPartition ids: ").append(resource.partitionIds()); if (resource.isDataCaptureEnabled()) { info.append("\n\t\t\tData capture window size in MB: ").append(resource.dataCaptureWindowSizeInMB()); info.append("\n\t\t\tData capture window size in seconds: ").append(resource.dataCaptureWindowSizeInSeconds()); if (resource.captureDestination() != null) { info.append("\n\t\t\tData capture storage account: ").append(resource.captureDestination().storageAccountResourceId()); info.append("\n\t\t\tData capture storage container: ").append(resource.captureDestination().blobContainer()); } } System.out.println(info.toString()); } /** * Print event hub namespace recovery pairing. * * @param resource event hub namespace disaster recovery pairing */ public static void print(EventHubDisasterRecoveryPairing resource) { StringBuilder info = new StringBuilder(); info.append("DisasterRecoveryPairing: ").append(resource.id()) .append("\n\tName: ").append(resource.name()) .append("\n\tPrimary namespace resource group name: ").append(resource.primaryNamespaceResourceGroupName()) .append("\n\tPrimary namespace name: ").append(resource.primaryNamespaceName()) .append("\n\tSecondary namespace: ").append(resource.secondaryNamespaceId()) .append("\n\tNamespace role: ").append(resource.namespaceRole()); System.out.println(info.toString()); } /** * Print event hub namespace recovery pairing auth rules. * * @param resource event hub namespace disaster recovery pairing auth rule */ public static void print(DisasterRecoveryPairingAuthorizationRule resource) { StringBuilder info = new StringBuilder(); info.append("DisasterRecoveryPairing auth rule: ").append(resource.name()); List<String> rightsStr = new ArrayList<>(); for (AccessRights rights : resource.rights()) { rightsStr.add(rights.toString()); } info.append("\n\tRights: ").append(rightsStr); System.out.println(info.toString()); } /** * Print event hub namespace recovery pairing auth rule key. * * @param resource event hub namespace disaster recovery pairing auth rule key */ public static void print(DisasterRecoveryPairingAuthorizationKey resource) { StringBuilder info = new StringBuilder(); info.append("DisasterRecoveryPairing auth key: ") .append("\n\t Alias primary connection string: ").append(resource.aliasPrimaryConnectionString()) .append("\n\t Alias secondary connection string: ").append(resource.aliasSecondaryConnectionString()) .append("\n\t Primary key: ").append(resource.primaryKey()) .append("\n\t Secondary key: ").append(resource.secondaryKey()) .append("\n\t Primary connection string: ").append(resource.primaryConnectionString()) .append("\n\t Secondary connection string: ").append(resource.secondaryConnectionString()); System.out.println(info.toString()); } /** * Print event hub consumer group. * * @param resource event hub consumer group */ public static void print(EventHubConsumerGroup resource) { StringBuilder info = new StringBuilder(); info.append("Event hub consumer group: ").append(resource.id()) .append("\n\tName: ").append(resource.name()) .append("\n\tNamespace resource group: ").append(resource.namespaceResourceGroupName()) .append("\n\tNamespace: ").append(resource.namespaceName()) .append("\n\tEvent hub name: ").append(resource.eventHubName()) .append("\n\tUser metadata: ").append(resource.userMetadata()); System.out.println(info.toString()); } /** * Print Diagnostic Setting. * * @param resource Diagnostic Setting instance */ public static void print(DiagnosticSetting resource) { StringBuilder info = new StringBuilder("Diagnostic Setting: ") .append("\n\tId: ").append(resource.id()) .append("\n\tAssociated resource Id: ").append(resource.resourceId()) .append("\n\tName: ").append(resource.name()) .append("\n\tStorage Account Id: ").append(resource.storageAccountId()) .append("\n\tEventHub Namespace Autorization Rule Id: ").append(resource.eventHubAuthorizationRuleId()) .append("\n\tEventHub name: ").append(resource.eventHubName()) .append("\n\tLog Analytics workspace Id: ").append(resource.workspaceId()); if (resource.logs() != null && !resource.logs().isEmpty()) { info.append("\n\tLog Settings: "); for (LogSettings ls : resource.logs()) { info.append("\n\t\tCategory: ").append(ls.category()); info.append("\n\t\tRetention policy: "); if (ls.retentionPolicy() != null) { info.append(ls.retentionPolicy().days() + " days"); } else { info.append("NONE"); } } } if (resource.metrics() != null && !resource.metrics().isEmpty()) { info.append("\n\tMetric Settings: "); for (MetricSettings ls : resource.metrics()) { info.append("\n\t\tCategory: ").append(ls.category()); info.append("\n\t\tTimegrain: ").append(ls.timeGrain()); info.append("\n\t\tRetention policy: "); if (ls.retentionPolicy() != null) { info.append(ls.retentionPolicy().days() + " days"); } else { info.append("NONE"); } } } System.out.println(info.toString()); } /** * Print Action group settings. * * @param actionGroup action group instance */ public static void print(ActionGroup actionGroup) { StringBuilder info = new StringBuilder("Action Group: ") .append("\n\tId: ").append(actionGroup.id()) .append("\n\tName: ").append(actionGroup.name()) .append("\n\tShort Name: ").append(actionGroup.shortName()); if (actionGroup.emailReceivers() != null && !actionGroup.emailReceivers().isEmpty()) { info.append("\n\tEmail receivers: "); for (EmailReceiver er : actionGroup.emailReceivers()) { info.append("\n\t\tName: ").append(er.name()); info.append("\n\t\tEMail: ").append(er.emailAddress()); info.append("\n\t\tStatus: ").append(er.status()); info.append("\n\t\t==="); } } if (actionGroup.smsReceivers() != null && !actionGroup.smsReceivers().isEmpty()) { info.append("\n\tSMS text message receivers: "); for (SmsReceiver er : actionGroup.smsReceivers()) { info.append("\n\t\tName: ").append(er.name()); info.append("\n\t\tPhone: ").append(er.countryCode() + er.phoneNumber()); info.append("\n\t\tStatus: ").append(er.status()); info.append("\n\t\t==="); } } if (actionGroup.webhookReceivers() != null && !actionGroup.webhookReceivers().isEmpty()) { info.append("\n\tWebhook receivers: "); for (WebhookReceiver er : actionGroup.webhookReceivers()) { info.append("\n\t\tName: ").append(er.name()); info.append("\n\t\tURI: ").append(er.serviceUri()); info.append("\n\t\t==="); } } if (actionGroup.pushNotificationReceivers() != null && !actionGroup.pushNotificationReceivers().isEmpty()) { info.append("\n\tApp Push Notification receivers: "); for (AzureAppPushReceiver er : actionGroup.pushNotificationReceivers()) { info.append("\n\t\tName: ").append(er.name()); info.append("\n\t\tEmail: ").append(er.emailAddress()); info.append("\n\t\t==="); } } if (actionGroup.voiceReceivers() != null && !actionGroup.voiceReceivers().isEmpty()) { info.append("\n\tVoice Message receivers: "); for (VoiceReceiver er : actionGroup.voiceReceivers()) { info.append("\n\t\tName: ").append(er.name()); info.append("\n\t\tPhone: ").append(er.countryCode() + er.phoneNumber()); info.append("\n\t\t==="); } } if (actionGroup.automationRunbookReceivers() != null && !actionGroup.automationRunbookReceivers().isEmpty()) { info.append("\n\tAutomation Runbook receivers: "); for (AutomationRunbookReceiver er : actionGroup.automationRunbookReceivers()) { info.append("\n\t\tName: ").append(er.name()); info.append("\n\t\tRunbook Name: ").append(er.runbookName()); info.append("\n\t\tAccount Id: ").append(er.automationAccountId()); info.append("\n\t\tIs Global: ").append(er.isGlobalRunbook()); info.append("\n\t\tService URI: ").append(er.serviceUri()); info.append("\n\t\tWebhook resource Id: ").append(er.webhookResourceId()); info.append("\n\t\t==="); } } if (actionGroup.azureFunctionReceivers() != null && !actionGroup.azureFunctionReceivers().isEmpty()) { info.append("\n\tAzure Functions receivers: "); for (AzureFunctionReceiver er : actionGroup.azureFunctionReceivers()) { info.append("\n\t\tName: ").append(er.name()); info.append("\n\t\tFunction Name: ").append(er.functionName()); info.append("\n\t\tFunction App Resource Id: ").append(er.functionAppResourceId()); info.append("\n\t\tFunction Trigger URI: ").append(er.httpTriggerUrl()); info.append("\n\t\t==="); } } if (actionGroup.logicAppReceivers() != null && !actionGroup.logicAppReceivers().isEmpty()) { info.append("\n\tLogic App receivers: "); for (LogicAppReceiver er : actionGroup.logicAppReceivers()) { info.append("\n\t\tName: ").append(er.name()); info.append("\n\t\tResource Id: ").append(er.resourceId()); info.append("\n\t\tCallback URL: ").append(er.callbackUrl()); info.append("\n\t\t==="); } } if (actionGroup.itsmReceivers() != null && !actionGroup.itsmReceivers().isEmpty()) { info.append("\n\tITSM receivers: "); for (ItsmReceiver er : actionGroup.itsmReceivers()) { info.append("\n\t\tName: ").append(er.name()); info.append("\n\t\tWorkspace Id: ").append(er.workspaceId()); info.append("\n\t\tConnection Id: ").append(er.connectionId()); info.append("\n\t\tRegion: ").append(er.region()); info.append("\n\t\tTicket Configuration: ").append(er.ticketConfiguration()); info.append("\n\t\t==="); } } System.out.println(info.toString()); } /** * Print activity log alert settings. * * @param activityLogAlert activity log instance */ public static void print(ActivityLogAlert activityLogAlert) { StringBuilder info = new StringBuilder("Activity Log Alert: ") .append("\n\tId: ").append(activityLogAlert.id()) .append("\n\tName: ").append(activityLogAlert.name()) .append("\n\tDescription: ").append(activityLogAlert.description()) .append("\n\tIs Enabled: ").append(activityLogAlert.enabled()); if (activityLogAlert.scopes() != null && !activityLogAlert.scopes().isEmpty()) { info.append("\n\tScopes: "); for (String er : activityLogAlert.scopes()) { info.append("\n\t\tId: ").append(er); } } if (activityLogAlert.actionGroupIds() != null && !activityLogAlert.actionGroupIds().isEmpty()) { info.append("\n\tAction Groups: "); for (String er : activityLogAlert.actionGroupIds()) { info.append("\n\t\tAction Group Id: ").append(er); } } if (activityLogAlert.equalsConditions() != null && !activityLogAlert.equalsConditions().isEmpty()) { info.append("\n\tAlert conditions (when all of is true): "); for (Map.Entry<String, String> er : activityLogAlert.equalsConditions().entrySet()) { info.append("\n\t\t'").append(er.getKey()).append("' equals '").append(er.getValue()).append("'"); } } System.out.println(info.toString()); } /** * Print metric alert settings. * * @param metricAlert metric alert instance */ public static void print(MetricAlert metricAlert) { StringBuilder info = new StringBuilder("Metric Alert: ") .append("\n\tId: ").append(metricAlert.id()) .append("\n\tName: ").append(metricAlert.name()) .append("\n\tDescription: ").append(metricAlert.description()) .append("\n\tIs Enabled: ").append(metricAlert.enabled()) .append("\n\tIs Auto Mitigated: ").append(metricAlert.autoMitigate()) .append("\n\tSeverity: ").append(metricAlert.severity()) .append("\n\tWindow Size: ").append(metricAlert.windowSize()) .append("\n\tEvaluation Frequency: ").append(metricAlert.evaluationFrequency()); if (metricAlert.scopes() != null && !metricAlert.scopes().isEmpty()) { info.append("\n\tScopes: "); for (String er : metricAlert.scopes()) { info.append("\n\t\tId: ").append(er); } } if (metricAlert.actionGroupIds() != null && !metricAlert.actionGroupIds().isEmpty()) { info.append("\n\tAction Groups: "); for (String er : metricAlert.actionGroupIds()) { info.append("\n\t\tAction Group Id: ").append(er); } } if (metricAlert.alertCriterias() != null && !metricAlert.alertCriterias().isEmpty()) { info.append("\n\tAlert conditions (when all of is true): "); for (Map.Entry<String, MetricAlertCondition> er : metricAlert.alertCriterias().entrySet()) { MetricAlertCondition alertCondition = er.getValue(); info.append("\n\t\tCondition name: ").append(er.getKey()) .append("\n\t\tSignal name: ").append(alertCondition.metricName()) .append("\n\t\tMetric Namespace: ").append(alertCondition.metricNamespace()) .append("\n\t\tOperator: ").append(alertCondition.condition()) .append("\n\t\tThreshold: ").append(alertCondition.threshold()) .append("\n\t\tTime Aggregation: ").append(alertCondition.timeAggregation()); if (alertCondition.dimensions() != null && !alertCondition.dimensions().isEmpty()) { for (MetricDimension dimon : alertCondition.dimensions()) { info.append("\n\t\tDimension Filter: ").append("Name [").append(dimon.name()).append("] operator [Include] values["); for (String vals : dimon.values()) { info.append(vals).append(", "); } info.append("]"); } } } } System.out.println(info.toString()); } /** * Print spring service settings. * * @param springService spring service instance */ public static void print(SpringService springService) { StringBuilder info = new StringBuilder("Spring Service: ") .append("\n\tId: ").append(springService.id()) .append("\n\tName: ").append(springService.name()) .append("\n\tResource Group: ").append(springService.resourceGroupName()) .append("\n\tRegion: ").append(springService.region()) .append("\n\tTags: ").append(springService.tags()); ConfigServerProperties serverProperties = springService.getServerProperties(); if (serverProperties != null && serverProperties.provisioningState() != null && serverProperties.provisioningState().equals(ConfigServerState.SUCCEEDED) && serverProperties.configServer() != null) { info.append("\n\tProperties: "); if (serverProperties.configServer().gitProperty() != null) { info.append("\n\t\tGit: ").append(serverProperties.configServer().gitProperty().uri()); } } if (springService.sku() != null) { info.append("\n\tSku: ") .append("\n\t\tName: ").append(springService.sku().name()) .append("\n\t\tTier: ").append(springService.sku().tier()) .append("\n\t\tCapacity: ").append(springService.sku().capacity()); } MonitoringSettingProperties monitoringSettingProperties = springService.getMonitoringSetting(); if (monitoringSettingProperties != null && monitoringSettingProperties.provisioningState() != null && monitoringSettingProperties.provisioningState().equals(MonitoringSettingState.SUCCEEDED)) { info.append("\n\tTrace: ") .append("\n\t\tEnabled: ").append(monitoringSettingProperties.traceEnabled()) .append("\n\t\tApp Insight Instrumentation Key: ").append(monitoringSettingProperties.appInsightsInstrumentationKey()); } System.out.println(info.toString()); } /** * Print spring app settings. * * @param springApp spring app instance */ public static void print(SpringApp springApp) { StringBuilder info = new StringBuilder("Spring Service: ") .append("\n\tId: ").append(springApp.id()) .append("\n\tName: ").append(springApp.name()) .append("\n\tCreated Time: ").append(springApp.createdTime()) .append("\n\tPublic Endpoint: ").append(springApp.isPublic()) .append("\n\tUrl: ").append(springApp.url()) .append("\n\tHttps Only: ").append(springApp.isHttpsOnly()) .append("\n\tFully Qualified Domain Name: ").append(springApp.fqdn()) .append("\n\tActive Deployment Name: ").append(springApp.activeDeploymentName()); if (springApp.temporaryDisk() != null) { info.append("\n\tTemporary Disk:") .append("\n\t\tSize In GB: ").append(springApp.temporaryDisk().sizeInGB()) .append("\n\t\tMount Path: ").append(springApp.temporaryDisk().mountPath()); } if (springApp.persistentDisk() != null) { info.append("\n\tPersistent Disk:") .append("\n\t\tSize In GB: ").append(springApp.persistentDisk().sizeInGB()) .append("\n\t\tMount Path: ").append(springApp.persistentDisk().mountPath()); } if (springApp.identity() != null) { info.append("\n\tIdentity:") .append("\n\t\tType: ").append(springApp.identity().type()) .append("\n\t\tPrincipal Id: ").append(springApp.identity().principalId()) .append("\n\t\tTenant Id: ").append(springApp.identity().tenantId()); } System.out.println(info.toString()); } /** * Sends a GET request to target URL. * <p> * Retry logic tuned for AppService. * The method does not handle 301 redirect. * * @param urlString the target URL. * @return Content of the HTTP response. */ public static String sendGetRequest(String urlString) { ClientLogger logger = new ClientLogger(Utils.class); try { Mono<Response<Flux<ByteBuffer>>> response = HTTP_CLIENT.getString(getHost(urlString), getPathAndQuery(urlString)) .retryWhen(Retry .fixedDelay(5, Duration.ofSeconds(30)) .filter(t -> { boolean retry = false; if (t instanceof TimeoutException) { retry = true; } else if (t instanceof HttpResponseException && ((HttpResponseException) t).getResponse().getStatusCode() == 503) { retry = true; } if (retry) { logger.info("retry GET request to {}", urlString); } return retry; })); Response<String> ret = stringResponse(response).block(); return ret == null ? null : ret.getValue(); } catch (MalformedURLException e) { logger.logThrowableAsError(e); return null; } } /** * Sends a POST request to target URL. * <p> * Retry logic tuned for AppService. * * @param urlString the target URL. * @param body the request body. * @return Content of the HTTP response. * */ public static String sendPostRequest(String urlString, String body) { ClientLogger logger = new ClientLogger(Utils.class); try { Mono<Response<String>> response = stringResponse(HTTP_CLIENT.postString(getHost(urlString), getPathAndQuery(urlString), body)) .retryWhen(Retry .fixedDelay(5, Duration.ofSeconds(30)) .filter(t -> { boolean retry = false; if (t instanceof TimeoutException) { retry = true; } if (retry) { logger.info("retry POST request to {}", urlString); } return retry; })); Response<String> ret = response.block(); return ret == null ? null : ret.getValue(); } catch (Exception e) { logger.logThrowableAsError(e); return null; } } private static Mono<Response<String>> stringResponse(Mono<Response<Flux<ByteBuffer>>> responseMono) { return responseMono.flatMap(response -> FluxUtil.collectBytesInByteBufferStream(response.getValue()) .map(bytes -> new String(bytes, StandardCharsets.UTF_8)) .map(str -> new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), str))); } private static String getHost(String urlString) throws MalformedURLException { URL url = new URL(urlString); String protocol = url.getProtocol(); String host = url.getAuthority(); return protocol + ": } private static String getPathAndQuery(String urlString) throws MalformedURLException { URL url = new URL(urlString); String path = url.getPath(); String query = url.getQuery(); if (query != null && !query.isEmpty()) { path = path + "?" + query; } return path; } private static final WebAppTestClient HTTP_CLIENT = RestProxy.create( WebAppTestClient.class, new HttpPipelineBuilder() .policies( new HttpLoggingPolicy(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BASIC)), new RetryPolicy("Retry-After", ChronoUnit.SECONDS)) .build()); @Host("{$host}") @ServiceInterface(name = "WebAppTestClient") private interface WebAppTestClient { @Get("{path}") @ExpectedResponses({200, 400, 404}) Mono<Response<Flux<ByteBuffer>>> getString(@HostParam("$host") String host, @PathParam(value = "path", encoded = true) String path); @Post("{path}") @ExpectedResponses({200, 400, 404}) Mono<Response<Flux<ByteBuffer>>> postString(@HostParam("$host") String host, @PathParam(value = "path", encoded = true) String path, @BodyParam("text/plain") String body); } public static <T> int getSize(Iterable<T> iterable) { int res = 0; Iterator<T> iterator = iterable.iterator(); while (iterator.hasNext()) { iterator.next(); } return res; } }
class Utils { /** @return a generated password */ public static String password() { String password = new ResourceManagerUtils.InternalRuntimeContext().randomResourceName("Pa5$", 12); System.out.printf("Password: %s%n", password); return password; } /** * Creates a randomized resource name. * Please provider your own implementation, or avoid using the method, if code is to be used in production. * * @param azure the AzureResourceManager instance. * @param prefix the prefix to the name. * @param maxLen the max length of the name. * @return the randomized resource name. */ public static String randomResourceName(AzureResourceManager azure, String prefix, int maxLen) { return azure.resourceGroups().manager().internalContext().randomResourceName(prefix, maxLen); } /** * Generates the specified number of random resource names with the same prefix. * Please provider your own implementation, or avoid using the method, if code is to be used in production. * * @param azure the AzureResourceManager instance. * @param prefix the prefix to be used if possible * @param maxLen the maximum length for the random generated name * @param count the number of names to generate * @return the randomized resource names. */ public static String[] randomResourceNames(AzureResourceManager azure, String prefix, int maxLen, int count) { String[] names = new String[count]; for (int i = 0; i < count; i++) { names[i] = randomResourceName(azure, prefix, maxLen); } return names; } /** * Creates a random UUID. * Please provider your own implementation, or avoid using the method, if code is to be used in production. * * @param azure the AzureResourceManager instance. * @return the random UUID. */ public static String randomUuid(AzureResourceManager azure) { return azure.resourceGroups().manager().internalContext().randomUuid(); } /** * Print resource group info. * * @param resource a resource group */ public static void print(ResourceGroup resource) { StringBuilder info = new StringBuilder(); info.append("Resource Group: ").append(resource.id()) .append("\n\tName: ").append(resource.name()) .append("\n\tRegion: ").append(resource.region()) .append("\n\tTags: ").append(resource.tags()); System.out.println(info.toString()); } /** * Print User Assigned MSI info. * * @param resource a User Assigned MSI */ public static void print(Identity resource) { StringBuilder info = new StringBuilder(); info.append("Resource Group: ").append(resource.id()) .append("\n\tName: ").append(resource.name()) .append("\n\tRegion: ").append(resource.region()) .append("\n\tTags: ").append(resource.tags()) .append("\n\tService Principal Id: ").append(resource.principalId()) .append("\n\tClient Id: ").append(resource.clientId()) .append("\n\tTenant Id: ").append(resource.tenantId()); System.out.println(info.toString()); } /** * Print virtual machine info. * * @param resource a virtual machine */ public static void print(VirtualMachine resource) { StringBuilder storageProfile = new StringBuilder().append("\n\tStorageProfile: "); if (resource.storageProfile().imageReference() != null) { storageProfile.append("\n\t\tImageReference:"); storageProfile.append("\n\t\t\tPublisher: ").append(resource.storageProfile().imageReference().publisher()); storageProfile.append("\n\t\t\tOffer: ").append(resource.storageProfile().imageReference().offer()); storageProfile.append("\n\t\t\tSKU: ").append(resource.storageProfile().imageReference().sku()); storageProfile.append("\n\t\t\tVersion: ").append(resource.storageProfile().imageReference().version()); } if (resource.storageProfile().osDisk() != null) { storageProfile.append("\n\t\tOSDisk:"); storageProfile.append("\n\t\t\tOSType: ").append(resource.storageProfile().osDisk().osType()); storageProfile.append("\n\t\t\tName: ").append(resource.storageProfile().osDisk().name()); storageProfile.append("\n\t\t\tCaching: ").append(resource.storageProfile().osDisk().caching()); storageProfile.append("\n\t\t\tCreateOption: ").append(resource.storageProfile().osDisk().createOption()); storageProfile.append("\n\t\t\tDiskSizeGB: ").append(resource.storageProfile().osDisk().diskSizeGB()); if (resource.storageProfile().osDisk().image() != null) { storageProfile.append("\n\t\t\tImage Uri: ").append(resource.storageProfile().osDisk().image().uri()); } if (resource.storageProfile().osDisk().vhd() != null) { storageProfile.append("\n\t\t\tVhd Uri: ").append(resource.storageProfile().osDisk().vhd().uri()); } if (resource.storageProfile().osDisk().encryptionSettings() != null) { storageProfile.append("\n\t\t\tEncryptionSettings: "); storageProfile.append("\n\t\t\t\tEnabled: ").append(resource.storageProfile().osDisk().encryptionSettings().enabled()); storageProfile.append("\n\t\t\t\tDiskEncryptionKey Uri: ").append(resource .storageProfile() .osDisk() .encryptionSettings() .diskEncryptionKey().secretUrl()); storageProfile.append("\n\t\t\t\tKeyEncryptionKey Uri: ").append(resource .storageProfile() .osDisk() .encryptionSettings() .keyEncryptionKey().keyUrl()); } } if (resource.storageProfile().dataDisks() != null) { int i = 0; for (DataDisk disk : resource.storageProfile().dataDisks()) { storageProfile.append("\n\t\tDataDisk: storageProfile.append("\n\t\t\tName: ").append(disk.name()); storageProfile.append("\n\t\t\tCaching: ").append(disk.caching()); storageProfile.append("\n\t\t\tCreateOption: ").append(disk.createOption()); storageProfile.append("\n\t\t\tDiskSizeGB: ").append(disk.diskSizeGB()); storageProfile.append("\n\t\t\tLun: ").append(disk.lun()); if (resource.isManagedDiskEnabled()) { if (disk.managedDisk() != null) { storageProfile.append("\n\t\t\tManaged Disk Id: ").append(disk.managedDisk().id()); } } else { if (disk.vhd().uri() != null) { storageProfile.append("\n\t\t\tVhd Uri: ").append(disk.vhd().uri()); } } if (disk.image() != null) { storageProfile.append("\n\t\t\tImage Uri: ").append(disk.image().uri()); } } } StringBuilder osProfile = new StringBuilder().append("\n\tOSProfile: "); if (resource.osProfile() != null) { osProfile.append("\n\t\tComputerName:").append(resource.osProfile().computerName()); if (resource.osProfile().windowsConfiguration() != null) { osProfile.append("\n\t\t\tWindowsConfiguration: "); osProfile.append("\n\t\t\t\tProvisionVMAgent: ") .append(resource.osProfile().windowsConfiguration().provisionVMAgent()); osProfile.append("\n\t\t\t\tEnableAutomaticUpdates: ") .append(resource.osProfile().windowsConfiguration().enableAutomaticUpdates()); osProfile.append("\n\t\t\t\tTimeZone: ") .append(resource.osProfile().windowsConfiguration().timeZone()); } if (resource.osProfile().linuxConfiguration() != null) { osProfile.append("\n\t\t\tLinuxConfiguration: "); osProfile.append("\n\t\t\t\tDisablePasswordAuthentication: ") .append(resource.osProfile().linuxConfiguration().disablePasswordAuthentication()); } } else { osProfile.append("null"); } StringBuilder networkProfile = new StringBuilder().append("\n\tNetworkProfile: "); for (String networkInterfaceId : resource.networkInterfaceIds()) { networkProfile.append("\n\t\tId:").append(networkInterfaceId); } StringBuilder extensions = new StringBuilder().append("\n\tExtensions: "); for (Map.Entry<String, VirtualMachineExtension> extensionEntry : resource.listExtensions().entrySet()) { VirtualMachineExtension extension = extensionEntry.getValue(); extensions.append("\n\t\tExtension: ").append(extension.id()) .append("\n\t\t\tName: ").append(extension.name()) .append("\n\t\t\tTags: ").append(extension.tags()) .append("\n\t\t\tProvisioningState: ").append(extension.provisioningState()) .append("\n\t\t\tAuto upgrade minor version enabled: ").append(extension.autoUpgradeMinorVersionEnabled()) .append("\n\t\t\tPublisher: ").append(extension.publisherName()) .append("\n\t\t\tType: ").append(extension.typeName()) .append("\n\t\t\tVersion: ").append(extension.versionName()) .append("\n\t\t\tPublic Settings: ").append(extension.publicSettingsAsJsonString()); } StringBuilder msi = new StringBuilder().append("\n\tMSI: "); msi.append("\n\t\t\tMSI enabled:").append(resource.isManagedServiceIdentityEnabled()); msi.append("\n\t\t\tSystem Assigned MSI Active Directory Service Principal Id:").append(resource.systemAssignedManagedServiceIdentityPrincipalId()); msi.append("\n\t\t\tSystem Assigned MSI Active Directory Tenant Id:").append(resource.systemAssignedManagedServiceIdentityTenantId()); StringBuilder zones = new StringBuilder().append("\n\tZones: "); zones.append(resource.availabilityZones()); System.out.println(new StringBuilder().append("Virtual Machine: ").append(resource.id()) .append("Name: ").append(resource.name()) .append("\n\tResource group: ").append(resource.resourceGroupName()) .append("\n\tRegion: ").append(resource.region()) .append("\n\tTags: ").append(resource.tags()) .append("\n\tHardwareProfile: ") .append("\n\t\tSize: ").append(resource.size()) .append(storageProfile) .append(osProfile) .append(networkProfile) .append(extensions) .append(msi) .append(zones) .toString()); } /** * Print availability set info. * * @param resource an availability set */ public static void print(AvailabilitySet resource) { System.out.println(new StringBuilder().append("Availability Set: ").append(resource.id()) .append("Name: ").append(resource.name()) .append("\n\tResource group: ").append(resource.resourceGroupName()) .append("\n\tRegion: ").append(resource.region()) .append("\n\tTags: ").append(resource.tags()) .append("\n\tFault domain count: ").append(resource.faultDomainCount()) .append("\n\tUpdate domain count: ").append(resource.updateDomainCount()) .toString()); } /** * Print network info. * * @param resource a network * @throws ManagementException Cloud errors */ public static void print(Network resource) { StringBuilder info = new StringBuilder(); info.append("Network: ").append(resource.id()) .append("Name: ").append(resource.name()) .append("\n\tResource group: ").append(resource.resourceGroupName()) .append("\n\tRegion: ").append(resource.region()) .append("\n\tTags: ").append(resource.tags()) .append("\n\tAddress spaces: ").append(resource.addressSpaces()) .append("\n\tDNS server IPs: ").append(resource.dnsServerIPs()); for (Subnet subnet : resource.subnets().values()) { info.append("\n\tSubnet: ").append(subnet.name()) .append("\n\t\tAddress prefix: ").append(subnet.addressPrefix()); NetworkSecurityGroup subnetNsg = subnet.getNetworkSecurityGroup(); if (subnetNsg != null) { info.append("\n\t\tNetwork security group ID: ").append(subnetNsg.id()); } RouteTable routeTable = subnet.getRouteTable(); if (routeTable != null) { info.append("\n\tRoute table ID: ").append(routeTable.id()); } Map<ServiceEndpointType, List<Region>> services = subnet.servicesWithAccess(); if (services.size() > 0) { info.append("\n\tServices with access"); for (Map.Entry<ServiceEndpointType, List<Region>> service : services.entrySet()) { info.append("\n\t\tService: ") .append(service.getKey()) .append(" Regions: " + service.getValue() + ""); } } } for (NetworkPeering peering : resource.peerings().list()) { info.append("\n\tPeering: ").append(peering.name()) .append("\n\t\tRemote network ID: ").append(peering.remoteNetworkId()) .append("\n\t\tPeering state: ").append(peering.state()) .append("\n\t\tIs traffic forwarded from remote network allowed? ").append(peering.isTrafficForwardingFromRemoteNetworkAllowed()) .append("\n\t\tGateway use: ").append(peering.gatewayUse()); } System.out.println(info.toString()); } /** * Print network interface. * * @param resource a network interface */ public static void print(NetworkInterface resource) { StringBuilder info = new StringBuilder(); info.append("NetworkInterface: ").append(resource.id()) .append("Name: ").append(resource.name()) .append("\n\tResource group: ").append(resource.resourceGroupName()) .append("\n\tRegion: ").append(resource.region()) .append("\n\tTags: ").append(resource.tags()) .append("\n\tInternal DNS name label: ").append(resource.internalDnsNameLabel()) .append("\n\tInternal FQDN: ").append(resource.internalFqdn()) .append("\n\tInternal domain name suffix: ").append(resource.internalDomainNameSuffix()) .append("\n\tNetwork security group: ").append(resource.networkSecurityGroupId()) .append("\n\tApplied DNS servers: ").append(resource.appliedDnsServers().toString()) .append("\n\tDNS server IPs: "); for (String dnsServerIp : resource.dnsServers()) { info.append("\n\t\t").append(dnsServerIp); } info.append("\n\tIP forwarding enabled? ").append(resource.isIPForwardingEnabled()) .append("\n\tAccelerated networking enabled? ").append(resource.isAcceleratedNetworkingEnabled()) .append("\n\tMAC Address:").append(resource.macAddress()) .append("\n\tPrivate IP:").append(resource.primaryPrivateIP()) .append("\n\tPrivate allocation method:").append(resource.primaryPrivateIpAllocationMethod()) .append("\n\tPrimary virtual network ID: ").append(resource.primaryIPConfiguration().networkId()) .append("\n\tPrimary subnet name:").append(resource.primaryIPConfiguration().subnetName()); System.out.println(info.toString()); } /** * Print network security group. * * @param resource a network security group */ public static void print(NetworkSecurityGroup resource) { StringBuilder info = new StringBuilder(); info.append("NSG: ").append(resource.id()) .append("Name: ").append(resource.name()) .append("\n\tResource group: ").append(resource.resourceGroupName()) .append("\n\tRegion: ").append(resource.region()) .append("\n\tTags: ").append(resource.tags()); for (NetworkSecurityRule rule : resource.securityRules().values()) { info.append("\n\tRule: ").append(rule.name()) .append("\n\t\tAccess: ").append(rule.access()) .append("\n\t\tDirection: ").append(rule.direction()) .append("\n\t\tFrom address: ").append(rule.sourceAddressPrefix()) .append("\n\t\tFrom port range: ").append(rule.sourcePortRange()) .append("\n\t\tTo address: ").append(rule.destinationAddressPrefix()) .append("\n\t\tTo port: ").append(rule.destinationPortRange()) .append("\n\t\tProtocol: ").append(rule.protocol()) .append("\n\t\tPriority: ").append(rule.priority()); } System.out.println(info.toString()); } /** * Print public IP address. * * @param resource a public IP address */ public static void print(PublicIpAddress resource) { System.out.println(new StringBuilder().append("Public IP Address: ").append(resource.id()) .append("Name: ").append(resource.name()) .append("\n\tResource group: ").append(resource.resourceGroupName()) .append("\n\tRegion: ").append(resource.region()) .append("\n\tTags: ").append(resource.tags()) .append("\n\tIP Address: ").append(resource.ipAddress()) .append("\n\tLeaf domain label: ").append(resource.leafDomainLabel()) .append("\n\tFQDN: ").append(resource.fqdn()) .append("\n\tReverse FQDN: ").append(resource.reverseFqdn()) .append("\n\tIdle timeout (minutes): ").append(resource.idleTimeoutInMinutes()) .append("\n\tIP allocation method: ").append(resource.ipAllocationMethod()) .append("\n\tZones: ").append(resource.availabilityZones()) .toString()); } /** * Print a key vault. * * @param vault the key vault resource */ public static void print(Vault vault) { StringBuilder info = new StringBuilder().append("Key Vault: ").append(vault.id()) .append("Name: ").append(vault.name()) .append("\n\tResource group: ").append(vault.resourceGroupName()) .append("\n\tRegion: ").append(vault.region()) .append("\n\tSku: ").append(vault.sku().name()).append(" - ").append(vault.sku().family()) .append("\n\tVault URI: ").append(vault.vaultUri()) .append("\n\tAccess policies: "); for (AccessPolicy accessPolicy : vault.accessPolicies()) { info.append("\n\t\tIdentity:").append(accessPolicy.objectId()); if (accessPolicy.permissions() != null) { if (accessPolicy.permissions().keys() != null) { info.append("\n\t\tKey permissions: ").append(accessPolicy.permissions().keys().stream().map(KeyPermissions::toString).collect(Collectors.joining(", "))); } if (accessPolicy.permissions().secrets() != null) { info.append("\n\t\tSecret permissions: ").append(accessPolicy.permissions().secrets().stream().map(SecretPermissions::toString).collect(Collectors.joining(", "))); } if (accessPolicy.permissions().certificates() != null) { info.append("\n\t\tCertificate permissions: ").append(accessPolicy.permissions().certificates().stream().map(CertificatePermissions::toString).collect(Collectors.joining(", "))); } } } System.out.println(info.toString()); } /** * Print storage account. * * @param storageAccount a storage account */ public static void print(StorageAccount storageAccount) { System.out.println(storageAccount.name() + " created @ " + storageAccount.creationTime()); StringBuilder info = new StringBuilder().append("Storage Account: ").append(storageAccount.id()) .append("Name: ").append(storageAccount.name()) .append("\n\tResource group: ").append(storageAccount.resourceGroupName()) .append("\n\tRegion: ").append(storageAccount.region()) .append("\n\tSKU: ").append(storageAccount.skuType().name().toString()) .append("\n\tAccessTier: ").append(storageAccount.accessTier()) .append("\n\tKind: ").append(storageAccount.kind()); info.append("\n\tNetwork Rule Configuration: ") .append("\n\t\tAllow reading logs from any network: ").append(storageAccount.canReadLogEntriesFromAnyNetwork()) .append("\n\t\tAllow reading metrics from any network: ").append(storageAccount.canReadMetricsFromAnyNetwork()) .append("\n\t\tAllow access from all azure services: ").append(storageAccount.canAccessFromAzureServices()); if (storageAccount.networkSubnetsWithAccess().size() > 0) { info.append("\n\t\tNetwork subnets with access: "); for (String subnetId : storageAccount.networkSubnetsWithAccess()) { info.append("\n\t\t\t").append(subnetId); } } if (storageAccount.ipAddressesWithAccess().size() > 0) { info.append("\n\t\tIP addresses with access: "); for (String ipAddress : storageAccount.ipAddressesWithAccess()) { info.append("\n\t\t\t").append(ipAddress); } } if (storageAccount.ipAddressRangesWithAccess().size() > 0) { info.append("\n\t\tIP address-ranges with access: "); for (String ipAddressRange : storageAccount.ipAddressRangesWithAccess()) { info.append("\n\t\t\t").append(ipAddressRange); } } info.append("\n\t\tTraffic allowed from only HTTPS: ").append(storageAccount.innerModel().enableHttpsTrafficOnly()); info.append("\n\tEncryption status: "); for (Map.Entry<StorageService, StorageAccountEncryptionStatus> eStatus : storageAccount.encryptionStatuses().entrySet()) { info.append("\n\t\t").append(eStatus.getValue().storageService()).append(": ").append(eStatus.getValue().isEnabled() ? "Enabled" : "Disabled"); } System.out.println(info.toString()); } /** * Print storage account keys. * * @param storageAccountKeys a list of storage account keys */ public static void print(List<StorageAccountKey> storageAccountKeys) { for (int i = 0; i < storageAccountKeys.size(); i++) { StorageAccountKey storageAccountKey = storageAccountKeys.get(i); System.out.println("Key (" + i + ") " + storageAccountKey.keyName() + "=" + storageAccountKey.value()); } } /** * Print Redis Cache. * * @param redisCache a Redis cache. */ public static void print(RedisCache redisCache) { StringBuilder redisInfo = new StringBuilder() .append("Redis Cache Name: ").append(redisCache.name()) .append("\n\tResource group: ").append(redisCache.resourceGroupName()) .append("\n\tRegion: ").append(redisCache.region()) .append("\n\tSKU Name: ").append(redisCache.sku().name()) .append("\n\tSKU Family: ").append(redisCache.sku().family()) .append("\n\tHostname: ").append(redisCache.hostname()) .append("\n\tSSL port: ").append(redisCache.sslPort()) .append("\n\tNon-SSL port (6379) enabled: ").append(redisCache.nonSslPort()); if (redisCache.redisConfiguration() != null && !redisCache.redisConfiguration().isEmpty()) { redisInfo.append("\n\tRedis Configuration:"); for (Map.Entry<String, String> redisConfiguration : redisCache.redisConfiguration().entrySet()) { redisInfo.append("\n\t '").append(redisConfiguration.getKey()) .append("' : '").append(redisConfiguration.getValue()).append("'"); } } if (redisCache.isPremium()) { RedisCachePremium premium = redisCache.asPremium(); List<ScheduleEntry> scheduleEntries = premium.listPatchSchedules(); if (scheduleEntries != null && !scheduleEntries.isEmpty()) { redisInfo.append("\n\tRedis Patch Schedule:"); for (ScheduleEntry schedule : scheduleEntries) { redisInfo.append("\n\t\tDay: '").append(schedule.dayOfWeek()) .append("', start at: '").append(schedule.startHourUtc()) .append("', maintenance window: '").append(schedule.maintenanceWindow()) .append("'"); } } } System.out.println(redisInfo.toString()); } /** * Print Redis Cache access keys. * * @param redisAccessKeys a keys for Redis Cache */ public static void print(RedisAccessKeys redisAccessKeys) { StringBuilder redisKeys = new StringBuilder() .append("Redis Access Keys: ") .append("\n\tPrimary Key: '").append(redisAccessKeys.primaryKey()).append("', ") .append("\n\tSecondary Key: '").append(redisAccessKeys.secondaryKey()).append("', "); System.out.println(redisKeys.toString()); } /** * Print load balancer. * * @param resource a load balancer */ public static void print(LoadBalancer resource) { StringBuilder info = new StringBuilder(); info.append("Load balancer: ").append(resource.id()) .append("Name: ").append(resource.name()) .append("\n\tResource group: ").append(resource.resourceGroupName()) .append("\n\tRegion: ").append(resource.region()) .append("\n\tTags: ").append(resource.tags()) .append("\n\tBackends: ").append(resource.backends().keySet().toString()); info.append("\n\tPublic IP address IDs: ") .append(resource.publicIpAddressIds().size()); for (String pipId : resource.publicIpAddressIds()) { info.append("\n\t\tPIP id: ").append(pipId); } info.append("\n\tTCP probes: ") .append(resource.tcpProbes().size()); for (LoadBalancerTcpProbe probe : resource.tcpProbes().values()) { info.append("\n\t\tProbe name: ").append(probe.name()) .append("\n\t\t\tPort: ").append(probe.port()) .append("\n\t\t\tInterval in seconds: ").append(probe.intervalInSeconds()) .append("\n\t\t\tRetries before unhealthy: ").append(probe.numberOfProbes()); info.append("\n\t\t\tReferenced from load balancing rules: ") .append(probe.loadBalancingRules().size()); for (LoadBalancingRule rule : probe.loadBalancingRules().values()) { info.append("\n\t\t\t\tName: ").append(rule.name()); } } info.append("\n\tHTTP probes: ") .append(resource.httpProbes().size()); for (LoadBalancerHttpProbe probe : resource.httpProbes().values()) { info.append("\n\t\tProbe name: ").append(probe.name()) .append("\n\t\t\tPort: ").append(probe.port()) .append("\n\t\t\tInterval in seconds: ").append(probe.intervalInSeconds()) .append("\n\t\t\tRetries before unhealthy: ").append(probe.numberOfProbes()) .append("\n\t\t\tHTTP request path: ").append(probe.requestPath()); info.append("\n\t\t\tReferenced from load balancing rules: ") .append(probe.loadBalancingRules().size()); for (LoadBalancingRule rule : probe.loadBalancingRules().values()) { info.append("\n\t\t\t\tName: ").append(rule.name()); } } info.append("\n\tHTTPS probes: ") .append(resource.httpsProbes().size()); for (LoadBalancerHttpProbe probe : resource.httpsProbes().values()) { info.append("\n\t\tProbe name: ").append(probe.name()) .append("\n\t\t\tPort: ").append(probe.port()) .append("\n\t\t\tInterval in seconds: ").append(probe.intervalInSeconds()) .append("\n\t\t\tRetries before unhealthy: ").append(probe.numberOfProbes()) .append("\n\t\t\tHTTPS request path: ").append(probe.requestPath()); info.append("\n\t\t\tReferenced from load balancing rules: ") .append(probe.loadBalancingRules().size()); for (LoadBalancingRule rule : probe.loadBalancingRules().values()) { info.append("\n\t\t\t\tName: ").append(rule.name()); } } info.append("\n\tLoad balancing rules: ") .append(resource.loadBalancingRules().size()); for (LoadBalancingRule rule : resource.loadBalancingRules().values()) { info.append("\n\t\tLB rule name: ").append(rule.name()) .append("\n\t\t\tProtocol: ").append(rule.protocol()) .append("\n\t\t\tFloating IP enabled? ").append(rule.floatingIPEnabled()) .append("\n\t\t\tIdle timeout in minutes: ").append(rule.idleTimeoutInMinutes()) .append("\n\t\t\tLoad distribution method: ").append(rule.loadDistribution().toString()); LoadBalancerFrontend frontend = rule.frontend(); info.append("\n\t\t\tFrontend: "); if (frontend != null) { info.append(frontend.name()); } else { info.append("(None)"); } info.append("\n\t\t\tFrontend port: ").append(rule.frontendPort()); LoadBalancerBackend backend = rule.backend(); info.append("\n\t\t\tBackend: "); if (backend != null) { info.append(backend.name()); } else { info.append("(None)"); } info.append("\n\t\t\tBackend port: ").append(rule.backendPort()); LoadBalancerProbe probe = rule.probe(); info.append("\n\t\t\tProbe: "); if (probe == null) { info.append("(None)"); } else { info.append(probe.name()).append(" [").append(probe.protocol().toString()).append("]"); } } info.append("\n\tFrontends: ") .append(resource.frontends().size()); for (LoadBalancerFrontend frontend : resource.frontends().values()) { info.append("\n\t\tFrontend name: ").append(frontend.name()) .append("\n\t\t\tInternet facing: ").append(frontend.isPublic()); if (frontend.isPublic()) { info.append("\n\t\t\tPublic IP Address ID: ").append(((LoadBalancerPublicFrontend) frontend).publicIpAddressId()); } else { info.append("\n\t\t\tVirtual network ID: ").append(((LoadBalancerPrivateFrontend) frontend).networkId()) .append("\n\t\t\tSubnet name: ").append(((LoadBalancerPrivateFrontend) frontend).subnetName()) .append("\n\t\t\tPrivate IP address: ").append(((LoadBalancerPrivateFrontend) frontend).privateIpAddress()) .append("\n\t\t\tPrivate IP allocation method: ").append(((LoadBalancerPrivateFrontend) frontend).privateIpAllocationMethod()); } info.append("\n\t\t\tReferenced inbound NAT pools: ") .append(frontend.inboundNatPools().size()); for (LoadBalancerInboundNatPool pool : frontend.inboundNatPools().values()) { info.append("\n\t\t\t\tName: ").append(pool.name()); } info.append("\n\t\t\tReferenced inbound NAT rules: ") .append(frontend.inboundNatRules().size()); for (LoadBalancerInboundNatRule rule : frontend.inboundNatRules().values()) { info.append("\n\t\t\t\tName: ").append(rule.name()); } info.append("\n\t\t\tReferenced load balancing rules: ") .append(frontend.loadBalancingRules().size()); for (LoadBalancingRule rule : frontend.loadBalancingRules().values()) { info.append("\n\t\t\t\tName: ").append(rule.name()); } } info.append("\n\tInbound NAT rules: ") .append(resource.inboundNatRules().size()); for (LoadBalancerInboundNatRule natRule : resource.inboundNatRules().values()) { info.append("\n\t\tInbound NAT rule name: ").append(natRule.name()) .append("\n\t\t\tProtocol: ").append(natRule.protocol().toString()) .append("\n\t\t\tFrontend: ").append(natRule.frontend().name()) .append("\n\t\t\tFrontend port: ").append(natRule.frontendPort()) .append("\n\t\t\tBackend port: ").append(natRule.backendPort()) .append("\n\t\t\tBackend NIC ID: ").append(natRule.backendNetworkInterfaceId()) .append("\n\t\t\tBackend NIC IP config name: ").append(natRule.backendNicIpConfigurationName()) .append("\n\t\t\tFloating IP? ").append(natRule.floatingIPEnabled()) .append("\n\t\t\tIdle timeout in minutes: ").append(natRule.idleTimeoutInMinutes()); } info.append("\n\tInbound NAT pools: ") .append(resource.inboundNatPools().size()); for (LoadBalancerInboundNatPool natPool : resource.inboundNatPools().values()) { info.append("\n\t\tInbound NAT pool name: ").append(natPool.name()) .append("\n\t\t\tProtocol: ").append(natPool.protocol().toString()) .append("\n\t\t\tFrontend: ").append(natPool.frontend().name()) .append("\n\t\t\tFrontend port range: ") .append(natPool.frontendPortRangeStart()) .append("-") .append(natPool.frontendPortRangeEnd()) .append("\n\t\t\tBackend port: ").append(natPool.backendPort()); } info.append("\n\tBackends: ") .append(resource.backends().size()); for (LoadBalancerBackend backend : resource.backends().values()) { info.append("\n\t\tBackend name: ").append(backend.name()); info.append("\n\t\t\tReferenced NICs: ") .append(backend.backendNicIPConfigurationNames().entrySet().size()); for (Map.Entry<String, String> entry : backend.backendNicIPConfigurationNames().entrySet()) { info.append("\n\t\t\t\tNIC ID: ").append(entry.getKey()) .append(" - IP Config: ").append(entry.getValue()); } Set<String> vmIds = backend.getVirtualMachineIds(); info.append("\n\t\t\tReferenced virtual machine ids: ") .append(vmIds.size()); for (String vmId : vmIds) { info.append("\n\t\t\t\tVM ID: ").append(vmId); } info.append("\n\t\t\tReferenced load balancing rules: ") .append(new ArrayList<String>(backend.loadBalancingRules().keySet())); } System.out.println(info.toString()); } /** * Print app service domain. * * @param resource an app service domain */ public static void print(AppServiceDomain resource) { StringBuilder builder = new StringBuilder().append("Domain: ").append(resource.id()) .append("Name: ").append(resource.name()) .append("\n\tResource group: ").append(resource.resourceGroupName()) .append("\n\tRegion: ").append(resource.region()) .append("\n\tCreated time: ").append(resource.createdTime()) .append("\n\tExpiration time: ").append(resource.expirationTime()) .append("\n\tContact: "); Contact contact = resource.registrantContact(); if (contact == null) { builder = builder.append("Private"); } else { builder = builder.append("\n\t\tName: ").append(contact.nameFirst() + " " + contact.nameLast()); } builder = builder.append("\n\tName servers: "); for (String nameServer : resource.nameServers()) { builder = builder.append("\n\t\t" + nameServer); } System.out.println(builder.toString()); } /** * Print app service certificate order. * * @param resource an app service certificate order */ public static void print(AppServiceCertificateOrder resource) { StringBuilder builder = new StringBuilder().append("App service certificate order: ").append(resource.id()) .append("Name: ").append(resource.name()) .append("\n\tResource group: ").append(resource.resourceGroupName()) .append("\n\tRegion: ").append(resource.region()) .append("\n\tDistinguished name: ").append(resource.distinguishedName()) .append("\n\tProduct type: ").append(resource.productType()) .append("\n\tValid years: ").append(resource.validityInYears()) .append("\n\tStatus: ").append(resource.status()) .append("\n\tIssuance time: ").append(resource.lastCertificateIssuanceTime()) .append("\n\tSigned certificate: ").append(resource.signedCertificate() == null ? null : resource.signedCertificate().thumbprint()); System.out.println(builder.toString()); } /** * Print app service plan. * * @param resource an app service plan */ public static void print(AppServicePlan resource) { StringBuilder builder = new StringBuilder().append("App service certificate order: ").append(resource.id()) .append("Name: ").append(resource.name()) .append("\n\tResource group: ").append(resource.resourceGroupName()) .append("\n\tRegion: ").append(resource.region()) .append("\n\tPricing tier: ").append(resource.pricingTier()); System.out.println(builder.toString()); } /** * Print a web app. * * @param resource a web app */ public static void print(WebAppBase resource) { StringBuilder builder = new StringBuilder().append("Web app: ").append(resource.id()) .append("\n\tName: ").append(resource.name()) .append("\n\tState: ").append(resource.state()) .append("\n\tResource group: ").append(resource.resourceGroupName()) .append("\n\tRegion: ").append(resource.region()) .append("\n\tDefault hostname: ").append(resource.defaultHostname()) .append("\n\tApp service plan: ").append(resource.appServicePlanId()) .append("\n\tHost name bindings: "); for (HostnameBinding binding : resource.getHostnameBindings().values()) { builder = builder.append("\n\t\t" + binding.toString()); } builder = builder.append("\n\tSSL bindings: "); for (HostnameSslState binding : resource.hostnameSslStates().values()) { builder = builder.append("\n\t\t" + binding.name() + ": " + binding.sslState()); if (binding.sslState() != null && binding.sslState() != SslState.DISABLED) { builder = builder.append(" - " + binding.thumbprint()); } } builder = builder.append("\n\tApp settings: "); for (AppSetting setting : resource.getAppSettings().values()) { builder = builder.append("\n\t\t" + setting.key() + ": " + setting.value() + (setting.sticky() ? " - slot setting" : "")); } builder = builder.append("\n\tConnection strings: "); for (ConnectionString conn : resource.getConnectionStrings().values()) { builder = builder.append("\n\t\t" + conn.name() + ": " + conn.value() + " - " + conn.type() + (conn.sticky() ? " - slot setting" : "")); } System.out.println(builder.toString()); } /** * Print a web site. * * @param resource a web site */ public static void print(WebSiteBase resource) { StringBuilder builder = new StringBuilder().append("Web app: ").append(resource.id()) .append("\n\tName: ").append(resource.name()) .append("\n\tState: ").append(resource.state()) .append("\n\tResource group: ").append(resource.resourceGroupName()) .append("\n\tRegion: ").append(resource.region()) .append("\n\tDefault hostname: ").append(resource.defaultHostname()) .append("\n\tApp service plan: ").append(resource.appServicePlanId()); builder = builder.append("\n\tSSL bindings: "); for (HostnameSslState binding : resource.hostnameSslStates().values()) { builder = builder.append("\n\t\t" + binding.name() + ": " + binding.sslState()); if (binding.sslState() != null && binding.sslState() != SslState.DISABLED) { builder = builder.append(" - " + binding.thumbprint()); } } System.out.println(builder.toString()); } /** * Print a traffic manager profile. * * @param profile a traffic manager profile */ public static void print(TrafficManagerProfile profile) { StringBuilder info = new StringBuilder(); info.append("Traffic Manager Profile: ").append(profile.id()) .append("\n\tName: ").append(profile.name()) .append("\n\tResource group: ").append(profile.resourceGroupName()) .append("\n\tRegion: ").append(profile.regionName()) .append("\n\tTags: ").append(profile.tags()) .append("\n\tDNSLabel: ").append(profile.dnsLabel()) .append("\n\tFQDN: ").append(profile.fqdn()) .append("\n\tTTL: ").append(profile.timeToLive()) .append("\n\tEnabled: ").append(profile.isEnabled()) .append("\n\tRoutingMethod: ").append(profile.trafficRoutingMethod()) .append("\n\tMonitor status: ").append(profile.monitorStatus()) .append("\n\tMonitoring port: ").append(profile.monitoringPort()) .append("\n\tMonitoring path: ").append(profile.monitoringPath()); Map<String, TrafficManagerAzureEndpoint> azureEndpoints = profile.azureEndpoints(); if (!azureEndpoints.isEmpty()) { info.append("\n\tAzure endpoints:"); int idx = 1; for (TrafficManagerAzureEndpoint endpoint : azureEndpoints.values()) { info.append("\n\t\tAzure endpoint: .append("\n\t\t\tId: ").append(endpoint.id()) .append("\n\t\t\tType: ").append(endpoint.endpointType()) .append("\n\t\t\tTarget resourceId: ").append(endpoint.targetAzureResourceId()) .append("\n\t\t\tTarget resourceType: ").append(endpoint.targetResourceType()) .append("\n\t\t\tMonitor status: ").append(endpoint.monitorStatus()) .append("\n\t\t\tEnabled: ").append(endpoint.isEnabled()) .append("\n\t\t\tRouting priority: ").append(endpoint.routingPriority()) .append("\n\t\t\tRouting weight: ").append(endpoint.routingWeight()); } } Map<String, TrafficManagerExternalEndpoint> externalEndpoints = profile.externalEndpoints(); if (!externalEndpoints.isEmpty()) { info.append("\n\tExternal endpoints:"); int idx = 1; for (TrafficManagerExternalEndpoint endpoint : externalEndpoints.values()) { info.append("\n\t\tExternal endpoint: .append("\n\t\t\tId: ").append(endpoint.id()) .append("\n\t\t\tType: ").append(endpoint.endpointType()) .append("\n\t\t\tFQDN: ").append(endpoint.fqdn()) .append("\n\t\t\tSource Traffic Location: ").append(endpoint.sourceTrafficLocation()) .append("\n\t\t\tMonitor status: ").append(endpoint.monitorStatus()) .append("\n\t\t\tEnabled: ").append(endpoint.isEnabled()) .append("\n\t\t\tRouting priority: ").append(endpoint.routingPriority()) .append("\n\t\t\tRouting weight: ").append(endpoint.routingWeight()); } } Map<String, TrafficManagerNestedProfileEndpoint> nestedProfileEndpoints = profile.nestedProfileEndpoints(); if (!nestedProfileEndpoints.isEmpty()) { info.append("\n\tNested profile endpoints:"); int idx = 1; for (TrafficManagerNestedProfileEndpoint endpoint : nestedProfileEndpoints.values()) { info.append("\n\t\tNested profile endpoint: .append("\n\t\t\tId: ").append(endpoint.id()) .append("\n\t\t\tType: ").append(endpoint.endpointType()) .append("\n\t\t\tNested profileId: ").append(endpoint.nestedProfileId()) .append("\n\t\t\tMinimum child threshold: ").append(endpoint.minimumChildEndpointCount()) .append("\n\t\t\tSource Traffic Location: ").append(endpoint.sourceTrafficLocation()) .append("\n\t\t\tMonitor status: ").append(endpoint.monitorStatus()) .append("\n\t\t\tEnabled: ").append(endpoint.isEnabled()) .append("\n\t\t\tRouting priority: ").append(endpoint.routingPriority()) .append("\n\t\t\tRouting weight: ").append(endpoint.routingWeight()); } } System.out.println(info.toString()); } /** * Print a dns zone. * * @param dnsZone a dns zone */ public static void print(DnsZone dnsZone) { StringBuilder info = new StringBuilder(); info.append("DNS Zone: ").append(dnsZone.id()) .append("\n\tName (Top level domain): ").append(dnsZone.name()) .append("\n\tResource group: ").append(dnsZone.resourceGroupName()) .append("\n\tRegion: ").append(dnsZone.regionName()) .append("\n\tTags: ").append(dnsZone.tags()) .append("\n\tName servers:"); for (String nameServer : dnsZone.nameServers()) { info.append("\n\t\t").append(nameServer); } SoaRecordSet soaRecordSet = dnsZone.getSoaRecordSet(); SoaRecord soaRecord = soaRecordSet.record(); info.append("\n\tSOA Record:") .append("\n\t\tHost:").append(soaRecord.host()) .append("\n\t\tEmail:").append(soaRecord.email()) .append("\n\t\tExpire time (seconds):").append(soaRecord.expireTime()) .append("\n\t\tRefresh time (seconds):").append(soaRecord.refreshTime()) .append("\n\t\tRetry time (seconds):").append(soaRecord.retryTime()) .append("\n\t\tNegative response cache ttl (seconds):").append(soaRecord.minimumTtl()) .append("\n\t\tTTL (seconds):").append(soaRecordSet.timeToLive()); PagedIterable<ARecordSet> aRecordSets = dnsZone.aRecordSets().list(); info.append("\n\tA Record sets:"); for (ARecordSet aRecordSet : aRecordSets) { info.append("\n\t\tId: ").append(aRecordSet.id()) .append("\n\t\tName: ").append(aRecordSet.name()) .append("\n\t\tTTL (seconds): ").append(aRecordSet.timeToLive()) .append("\n\t\tIP v4 addresses: "); for (String ipAddress : aRecordSet.ipv4Addresses()) { info.append("\n\t\t\t").append(ipAddress); } } PagedIterable<AaaaRecordSet> aaaaRecordSets = dnsZone.aaaaRecordSets().list(); info.append("\n\tAAAA Record sets:"); for (AaaaRecordSet aaaaRecordSet : aaaaRecordSets) { info.append("\n\t\tId: ").append(aaaaRecordSet.id()) .append("\n\t\tName: ").append(aaaaRecordSet.name()) .append("\n\t\tTTL (seconds): ").append(aaaaRecordSet.timeToLive()) .append("\n\t\tIP v6 addresses: "); for (String ipAddress : aaaaRecordSet.ipv6Addresses()) { info.append("\n\t\t\t").append(ipAddress); } } PagedIterable<CnameRecordSet> cnameRecordSets = dnsZone.cNameRecordSets().list(); info.append("\n\tCNAME Record sets:"); for (CnameRecordSet cnameRecordSet : cnameRecordSets) { info.append("\n\t\tId: ").append(cnameRecordSet.id()) .append("\n\t\tName: ").append(cnameRecordSet.name()) .append("\n\t\tTTL (seconds): ").append(cnameRecordSet.timeToLive()) .append("\n\t\tCanonical name: ").append(cnameRecordSet.canonicalName()); } PagedIterable<MxRecordSet> mxRecordSets = dnsZone.mxRecordSets().list(); info.append("\n\tMX Record sets:"); for (MxRecordSet mxRecordSet : mxRecordSets) { info.append("\n\t\tId: ").append(mxRecordSet.id()) .append("\n\t\tName: ").append(mxRecordSet.name()) .append("\n\t\tTTL (seconds): ").append(mxRecordSet.timeToLive()) .append("\n\t\tRecords: "); for (MxRecord mxRecord : mxRecordSet.records()) { info.append("\n\t\t\tExchange server, Preference: ") .append(mxRecord.exchange()) .append(" ") .append(mxRecord.preference()); } } PagedIterable<NsRecordSet> nsRecordSets = dnsZone.nsRecordSets().list(); info.append("\n\tNS Record sets:"); for (NsRecordSet nsRecordSet : nsRecordSets) { info.append("\n\t\tId: ").append(nsRecordSet.id()) .append("\n\t\tName: ").append(nsRecordSet.name()) .append("\n\t\tTTL (seconds): ").append(nsRecordSet.timeToLive()) .append("\n\t\tName servers: "); for (String nameServer : nsRecordSet.nameServers()) { info.append("\n\t\t\t").append(nameServer); } } PagedIterable<PtrRecordSet> ptrRecordSets = dnsZone.ptrRecordSets().list(); info.append("\n\tPTR Record sets:"); for (PtrRecordSet ptrRecordSet : ptrRecordSets) { info.append("\n\t\tId: ").append(ptrRecordSet.id()) .append("\n\t\tName: ").append(ptrRecordSet.name()) .append("\n\t\tTTL (seconds): ").append(ptrRecordSet.timeToLive()) .append("\n\t\tTarget domain names: "); for (String domainNames : ptrRecordSet.targetDomainNames()) { info.append("\n\t\t\t").append(domainNames); } } PagedIterable<SrvRecordSet> srvRecordSets = dnsZone.srvRecordSets().list(); info.append("\n\tSRV Record sets:"); for (SrvRecordSet srvRecordSet : srvRecordSets) { info.append("\n\t\tId: ").append(srvRecordSet.id()) .append("\n\t\tName: ").append(srvRecordSet.name()) .append("\n\t\tTTL (seconds): ").append(srvRecordSet.timeToLive()) .append("\n\t\tRecords: "); for (SrvRecord srvRecord : srvRecordSet.records()) { info.append("\n\t\t\tTarget, Port, Priority, Weight: ") .append(srvRecord.target()) .append(", ") .append(srvRecord.port()) .append(", ") .append(srvRecord.priority()) .append(", ") .append(srvRecord.weight()); } } PagedIterable<TxtRecordSet> txtRecordSets = dnsZone.txtRecordSets().list(); info.append("\n\tTXT Record sets:"); for (TxtRecordSet txtRecordSet : txtRecordSets) { info.append("\n\t\tId: ").append(txtRecordSet.id()) .append("\n\t\tName: ").append(txtRecordSet.name()) .append("\n\t\tTTL (seconds): ").append(txtRecordSet.timeToLive()) .append("\n\t\tRecords: "); for (TxtRecord txtRecord : txtRecordSet.records()) { if (txtRecord.value().size() > 0) { info.append("\n\t\t\tValue: ").append(txtRecord.value().get(0)); } } } System.out.println(info.toString()); } /** * Print a private dns zone. * * @param privateDnsZone a private dns zone */ public static void print(PrivateDnsZone privateDnsZone) { StringBuilder info = new StringBuilder(); info.append("Private DNS Zone: ").append(privateDnsZone.id()) .append("\n\tName (Top level domain): ").append(privateDnsZone.name()) .append("\n\tResource group: ").append(privateDnsZone.resourceGroupName()) .append("\n\tRegion: ").append(privateDnsZone.regionName()) .append("\n\tTags: ").append(privateDnsZone.tags()) .append("\n\tName servers:"); com.azure.resourcemanager.privatedns.models.SoaRecordSet soaRecordSet = privateDnsZone.getSoaRecordSet(); com.azure.resourcemanager.privatedns.models.SoaRecord soaRecord = soaRecordSet.record(); info.append("\n\tSOA Record:") .append("\n\t\tHost:").append(soaRecord.host()) .append("\n\t\tEmail:").append(soaRecord.email()) .append("\n\t\tExpire time (seconds):").append(soaRecord.expireTime()) .append("\n\t\tRefresh time (seconds):").append(soaRecord.refreshTime()) .append("\n\t\tRetry time (seconds):").append(soaRecord.retryTime()) .append("\n\t\tNegative response cache ttl (seconds):").append(soaRecord.minimumTtl()) .append("\n\t\tTTL (seconds):").append(soaRecordSet.timeToLive()); PagedIterable<com.azure.resourcemanager.privatedns.models.ARecordSet> aRecordSets = privateDnsZone .aRecordSets().list(); info.append("\n\tA Record sets:"); for (com.azure.resourcemanager.privatedns.models.ARecordSet aRecordSet : aRecordSets) { info.append("\n\t\tId: ").append(aRecordSet.id()) .append("\n\t\tName: ").append(aRecordSet.name()) .append("\n\t\tTTL (seconds): ").append(aRecordSet.timeToLive()) .append("\n\t\tIP v4 addresses: "); for (String ipAddress : aRecordSet.ipv4Addresses()) { info.append("\n\t\t\t").append(ipAddress); } } PagedIterable<com.azure.resourcemanager.privatedns.models.AaaaRecordSet> aaaaRecordSets = privateDnsZone .aaaaRecordSets().list(); info.append("\n\tAAAA Record sets:"); for (com.azure.resourcemanager.privatedns.models.AaaaRecordSet aaaaRecordSet : aaaaRecordSets) { info.append("\n\t\tId: ").append(aaaaRecordSet.id()) .append("\n\t\tName: ").append(aaaaRecordSet.name()) .append("\n\t\tTTL (seconds): ").append(aaaaRecordSet.timeToLive()) .append("\n\t\tIP v6 addresses: "); for (String ipAddress : aaaaRecordSet.ipv6Addresses()) { info.append("\n\t\t\t").append(ipAddress); } } PagedIterable<com.azure.resourcemanager.privatedns.models.CnameRecordSet> cnameRecordSets = privateDnsZone.cnameRecordSets().list(); info.append("\n\tCNAME Record sets:"); for (com.azure.resourcemanager.privatedns.models.CnameRecordSet cnameRecordSet : cnameRecordSets) { info.append("\n\t\tId: ").append(cnameRecordSet.id()) .append("\n\t\tName: ").append(cnameRecordSet.name()) .append("\n\t\tTTL (seconds): ").append(cnameRecordSet.timeToLive()) .append("\n\t\tCanonical name: ").append(cnameRecordSet.canonicalName()); } PagedIterable<com.azure.resourcemanager.privatedns.models.MxRecordSet> mxRecordSets = privateDnsZone.mxRecordSets().list(); info.append("\n\tMX Record sets:"); for (com.azure.resourcemanager.privatedns.models.MxRecordSet mxRecordSet : mxRecordSets) { info.append("\n\t\tId: ").append(mxRecordSet.id()) .append("\n\t\tName: ").append(mxRecordSet.name()) .append("\n\t\tTTL (seconds): ").append(mxRecordSet.timeToLive()) .append("\n\t\tRecords: "); for (com.azure.resourcemanager.privatedns.models.MxRecord mxRecord : mxRecordSet.records()) { info.append("\n\t\t\tExchange server, Preference: ") .append(mxRecord.exchange()) .append(" ") .append(mxRecord.preference()); } } PagedIterable<com.azure.resourcemanager.privatedns.models.PtrRecordSet> ptrRecordSets = privateDnsZone .ptrRecordSets().list(); info.append("\n\tPTR Record sets:"); for (com.azure.resourcemanager.privatedns.models.PtrRecordSet ptrRecordSet : ptrRecordSets) { info.append("\n\t\tId: ").append(ptrRecordSet.id()) .append("\n\t\tName: ").append(ptrRecordSet.name()) .append("\n\t\tTTL (seconds): ").append(ptrRecordSet.timeToLive()) .append("\n\t\tTarget domain names: "); for (String domainNames : ptrRecordSet.targetDomainNames()) { info.append("\n\t\t\t").append(domainNames); } } PagedIterable<com.azure.resourcemanager.privatedns.models.SrvRecordSet> srvRecordSets = privateDnsZone .srvRecordSets().list(); info.append("\n\tSRV Record sets:"); for (com.azure.resourcemanager.privatedns.models.SrvRecordSet srvRecordSet : srvRecordSets) { info.append("\n\t\tId: ").append(srvRecordSet.id()) .append("\n\t\tName: ").append(srvRecordSet.name()) .append("\n\t\tTTL (seconds): ").append(srvRecordSet.timeToLive()) .append("\n\t\tRecords: "); for (com.azure.resourcemanager.privatedns.models.SrvRecord srvRecord : srvRecordSet.records()) { info.append("\n\t\t\tTarget, Port, Priority, Weight: ") .append(srvRecord.target()) .append(", ") .append(srvRecord.port()) .append(", ") .append(srvRecord.priority()) .append(", ") .append(srvRecord.weight()); } } PagedIterable<com.azure.resourcemanager.privatedns.models.TxtRecordSet> txtRecordSets = privateDnsZone .txtRecordSets().list(); info.append("\n\tTXT Record sets:"); for (com.azure.resourcemanager.privatedns.models.TxtRecordSet txtRecordSet : txtRecordSets) { info.append("\n\t\tId: ").append(txtRecordSet.id()) .append("\n\t\tName: ").append(txtRecordSet.name()) .append("\n\t\tTTL (seconds): ").append(txtRecordSet.timeToLive()) .append("\n\t\tRecords: "); for (com.azure.resourcemanager.privatedns.models.TxtRecord txtRecord : txtRecordSet.records()) { if (txtRecord.value().size() > 0) { info.append("\n\t\t\tValue: ").append(txtRecord.value().get(0)); } } } PagedIterable<VirtualNetworkLink> virtualNetworkLinks = privateDnsZone.virtualNetworkLinks().list(); info.append("\n\tVirtual Network Links:"); for (VirtualNetworkLink virtualNetworkLink : virtualNetworkLinks) { info.append("\n\tId: ").append(virtualNetworkLink.id()) .append("\n\tName: ").append(virtualNetworkLink.name()) .append("\n\tReference of Virtual Network: ").append(virtualNetworkLink.referencedVirtualNetworkId()) .append("\n\tRegistration enabled: ").append(virtualNetworkLink.isAutoRegistrationEnabled()); } System.out.println(info.toString()); } /** * Print an Azure Container Registry. * * @param azureRegistry an Azure Container Registry */ public static void print(Registry azureRegistry) { StringBuilder info = new StringBuilder(); RegistryCredentials acrCredentials = azureRegistry.getCredentials(); info.append("Azure Container Registry: ").append(azureRegistry.id()) .append("\n\tName: ").append(azureRegistry.name()) .append("\n\tServer Url: ").append(azureRegistry.loginServerUrl()) .append("\n\tUser: ").append(acrCredentials.username()) .append("\n\tFirst Password: ").append(acrCredentials.accessKeys().get(AccessKeyType.PRIMARY)) .append("\n\tSecond Password: ").append(acrCredentials.accessKeys().get(AccessKeyType.SECONDARY)); System.out.println(info.toString()); } /** * Print an Azure Container Service (AKS). * * @param kubernetesCluster a managed container service */ public static void print(KubernetesCluster kubernetesCluster) { StringBuilder info = new StringBuilder(); info.append("Azure Container Service: ").append(kubernetesCluster.id()) .append("\n\tName: ").append(kubernetesCluster.name()) .append("\n\tFQDN: ").append(kubernetesCluster.fqdn()) .append("\n\tDNS prefix label: ").append(kubernetesCluster.dnsPrefix()) .append("\n\t\tWith Agent pool name: ").append(new ArrayList<>(kubernetesCluster.agentPools().keySet()).get(0)) .append("\n\t\tAgent pool count: ").append(new ArrayList<>(kubernetesCluster.agentPools().values()).get(0).count()) .append("\n\t\tAgent pool VM size: ").append(new ArrayList<>(kubernetesCluster.agentPools().values()).get(0).vmSize().toString()) .append("\n\tLinux user name: ").append(kubernetesCluster.linuxRootUsername()) .append("\n\tSSH key: ").append(kubernetesCluster.sshKey()) .append("\n\tService principal client ID: ").append(kubernetesCluster.servicePrincipalClientId()); System.out.println(info.toString()); } /** * Retrieve the secondary service principal client ID. * * @param envSecondaryServicePrincipal an Azure Container Registry * @return a service principal client ID * @throws Exception exception */
class Utils { private Utils() { } /** @return a generated password */ public static String password() { String password = new ResourceManagerUtils.InternalRuntimeContext().randomResourceName("Pa5$", 12); System.out.printf("Password: %s%n", password); return password; } /** * Creates a randomized resource name. * Please provider your own implementation, or avoid using the method, if code is to be used in production. * * @param azure the AzureResourceManager instance. * @param prefix the prefix to the name. * @param maxLen the max length of the name. * @return the randomized resource name. */ public static String randomResourceName(AzureResourceManager azure, String prefix, int maxLen) { return azure.resourceGroups().manager().internalContext().randomResourceName(prefix, maxLen); } /** * Generates the specified number of random resource names with the same prefix. * Please provider your own implementation, or avoid using the method, if code is to be used in production. * * @param azure the AzureResourceManager instance. * @param prefix the prefix to be used if possible * @param maxLen the maximum length for the random generated name * @param count the number of names to generate * @return the randomized resource names. */ public static String[] randomResourceNames(AzureResourceManager azure, String prefix, int maxLen, int count) { String[] names = new String[count]; for (int i = 0; i < count; i++) { names[i] = randomResourceName(azure, prefix, maxLen); } return names; } /** * Creates a random UUID. * Please provider your own implementation, or avoid using the method, if code is to be used in production. * * @param azure the AzureResourceManager instance. * @return the random UUID. */ public static String randomUuid(AzureResourceManager azure) { return azure.resourceGroups().manager().internalContext().randomUuid(); } /** * Creates a randomized resource name. * Please provider your own implementation, or avoid using the method, if code is to be used in production. * * @param authenticated the AzureResourceManager.Authenticated instance. * @param prefix the prefix to the name. * @param maxLen the max length of the name. * @return the randomized resource name. */ public static String randomResourceName(AzureResourceManager.Authenticated authenticated, String prefix, int maxLen) { return authenticated.roleAssignments().manager().internalContext().randomResourceName(prefix, maxLen); } /** * Creates a random UUID. * Please provider your own implementation, or avoid using the method, if code is to be used in production. * * @param authenticated the AzureResourceManager.Authenticated instance. * @return the random UUID. */ public static String randomUuid(AzureResourceManager.Authenticated authenticated) { return authenticated.roleAssignments().manager().internalContext().randomUuid(); } /** * Print resource group info. * * @param resource a resource group */ public static void print(ResourceGroup resource) { StringBuilder info = new StringBuilder(); info.append("Resource Group: ").append(resource.id()) .append("\n\tName: ").append(resource.name()) .append("\n\tRegion: ").append(resource.region()) .append("\n\tTags: ").append(resource.tags()); System.out.println(info.toString()); } /** * Print User Assigned MSI info. * * @param resource a User Assigned MSI */ public static void print(Identity resource) { StringBuilder info = new StringBuilder(); info.append("Resource Group: ").append(resource.id()) .append("\n\tName: ").append(resource.name()) .append("\n\tRegion: ").append(resource.region()) .append("\n\tTags: ").append(resource.tags()) .append("\n\tService Principal Id: ").append(resource.principalId()) .append("\n\tClient Id: ").append(resource.clientId()) .append("\n\tTenant Id: ").append(resource.tenantId()); System.out.println(info.toString()); } /** * Print virtual machine info. * * @param resource a virtual machine */ public static void print(VirtualMachine resource) { StringBuilder storageProfile = new StringBuilder().append("\n\tStorageProfile: "); if (resource.storageProfile().imageReference() != null) { storageProfile.append("\n\t\tImageReference:"); storageProfile.append("\n\t\t\tPublisher: ").append(resource.storageProfile().imageReference().publisher()); storageProfile.append("\n\t\t\tOffer: ").append(resource.storageProfile().imageReference().offer()); storageProfile.append("\n\t\t\tSKU: ").append(resource.storageProfile().imageReference().sku()); storageProfile.append("\n\t\t\tVersion: ").append(resource.storageProfile().imageReference().version()); } if (resource.storageProfile().osDisk() != null) { storageProfile.append("\n\t\tOSDisk:"); storageProfile.append("\n\t\t\tOSType: ").append(resource.storageProfile().osDisk().osType()); storageProfile.append("\n\t\t\tName: ").append(resource.storageProfile().osDisk().name()); storageProfile.append("\n\t\t\tCaching: ").append(resource.storageProfile().osDisk().caching()); storageProfile.append("\n\t\t\tCreateOption: ").append(resource.storageProfile().osDisk().createOption()); storageProfile.append("\n\t\t\tDiskSizeGB: ").append(resource.storageProfile().osDisk().diskSizeGB()); if (resource.storageProfile().osDisk().image() != null) { storageProfile.append("\n\t\t\tImage Uri: ").append(resource.storageProfile().osDisk().image().uri()); } if (resource.storageProfile().osDisk().vhd() != null) { storageProfile.append("\n\t\t\tVhd Uri: ").append(resource.storageProfile().osDisk().vhd().uri()); } if (resource.storageProfile().osDisk().encryptionSettings() != null) { storageProfile.append("\n\t\t\tEncryptionSettings: "); storageProfile.append("\n\t\t\t\tEnabled: ").append(resource.storageProfile().osDisk().encryptionSettings().enabled()); storageProfile.append("\n\t\t\t\tDiskEncryptionKey Uri: ").append(resource .storageProfile() .osDisk() .encryptionSettings() .diskEncryptionKey().secretUrl()); storageProfile.append("\n\t\t\t\tKeyEncryptionKey Uri: ").append(resource .storageProfile() .osDisk() .encryptionSettings() .keyEncryptionKey().keyUrl()); } } if (resource.storageProfile().dataDisks() != null) { int i = 0; for (DataDisk disk : resource.storageProfile().dataDisks()) { storageProfile.append("\n\t\tDataDisk: storageProfile.append("\n\t\t\tName: ").append(disk.name()); storageProfile.append("\n\t\t\tCaching: ").append(disk.caching()); storageProfile.append("\n\t\t\tCreateOption: ").append(disk.createOption()); storageProfile.append("\n\t\t\tDiskSizeGB: ").append(disk.diskSizeGB()); storageProfile.append("\n\t\t\tLun: ").append(disk.lun()); if (resource.isManagedDiskEnabled()) { if (disk.managedDisk() != null) { storageProfile.append("\n\t\t\tManaged Disk Id: ").append(disk.managedDisk().id()); } } else { if (disk.vhd().uri() != null) { storageProfile.append("\n\t\t\tVhd Uri: ").append(disk.vhd().uri()); } } if (disk.image() != null) { storageProfile.append("\n\t\t\tImage Uri: ").append(disk.image().uri()); } } } StringBuilder osProfile = new StringBuilder().append("\n\tOSProfile: "); if (resource.osProfile() != null) { osProfile.append("\n\t\tComputerName:").append(resource.osProfile().computerName()); if (resource.osProfile().windowsConfiguration() != null) { osProfile.append("\n\t\t\tWindowsConfiguration: "); osProfile.append("\n\t\t\t\tProvisionVMAgent: ") .append(resource.osProfile().windowsConfiguration().provisionVMAgent()); osProfile.append("\n\t\t\t\tEnableAutomaticUpdates: ") .append(resource.osProfile().windowsConfiguration().enableAutomaticUpdates()); osProfile.append("\n\t\t\t\tTimeZone: ") .append(resource.osProfile().windowsConfiguration().timeZone()); } if (resource.osProfile().linuxConfiguration() != null) { osProfile.append("\n\t\t\tLinuxConfiguration: "); osProfile.append("\n\t\t\t\tDisablePasswordAuthentication: ") .append(resource.osProfile().linuxConfiguration().disablePasswordAuthentication()); } } else { osProfile.append("null"); } StringBuilder networkProfile = new StringBuilder().append("\n\tNetworkProfile: "); for (String networkInterfaceId : resource.networkInterfaceIds()) { networkProfile.append("\n\t\tId:").append(networkInterfaceId); } StringBuilder extensions = new StringBuilder().append("\n\tExtensions: "); for (Map.Entry<String, VirtualMachineExtension> extensionEntry : resource.listExtensions().entrySet()) { VirtualMachineExtension extension = extensionEntry.getValue(); extensions.append("\n\t\tExtension: ").append(extension.id()) .append("\n\t\t\tName: ").append(extension.name()) .append("\n\t\t\tTags: ").append(extension.tags()) .append("\n\t\t\tProvisioningState: ").append(extension.provisioningState()) .append("\n\t\t\tAuto upgrade minor version enabled: ").append(extension.autoUpgradeMinorVersionEnabled()) .append("\n\t\t\tPublisher: ").append(extension.publisherName()) .append("\n\t\t\tType: ").append(extension.typeName()) .append("\n\t\t\tVersion: ").append(extension.versionName()) .append("\n\t\t\tPublic Settings: ").append(extension.publicSettingsAsJsonString()); } StringBuilder msi = new StringBuilder().append("\n\tMSI: "); msi.append("\n\t\t\tMSI enabled:").append(resource.isManagedServiceIdentityEnabled()); msi.append("\n\t\t\tSystem Assigned MSI Active Directory Service Principal Id:").append(resource.systemAssignedManagedServiceIdentityPrincipalId()); msi.append("\n\t\t\tSystem Assigned MSI Active Directory Tenant Id:").append(resource.systemAssignedManagedServiceIdentityTenantId()); StringBuilder zones = new StringBuilder().append("\n\tZones: "); zones.append(resource.availabilityZones()); System.out.println(new StringBuilder().append("Virtual Machine: ").append(resource.id()) .append("Name: ").append(resource.name()) .append("\n\tResource group: ").append(resource.resourceGroupName()) .append("\n\tRegion: ").append(resource.region()) .append("\n\tTags: ").append(resource.tags()) .append("\n\tHardwareProfile: ") .append("\n\t\tSize: ").append(resource.size()) .append(storageProfile) .append(osProfile) .append(networkProfile) .append(extensions) .append(msi) .append(zones) .toString()); } /** * Print availability set info. * * @param resource an availability set */ public static void print(AvailabilitySet resource) { System.out.println(new StringBuilder().append("Availability Set: ").append(resource.id()) .append("Name: ").append(resource.name()) .append("\n\tResource group: ").append(resource.resourceGroupName()) .append("\n\tRegion: ").append(resource.region()) .append("\n\tTags: ").append(resource.tags()) .append("\n\tFault domain count: ").append(resource.faultDomainCount()) .append("\n\tUpdate domain count: ").append(resource.updateDomainCount()) .toString()); } /** * Print network info. * * @param resource a network * @throws ManagementException Cloud errors */ public static void print(Network resource) { StringBuilder info = new StringBuilder(); info.append("Network: ").append(resource.id()) .append("Name: ").append(resource.name()) .append("\n\tResource group: ").append(resource.resourceGroupName()) .append("\n\tRegion: ").append(resource.region()) .append("\n\tTags: ").append(resource.tags()) .append("\n\tAddress spaces: ").append(resource.addressSpaces()) .append("\n\tDNS server IPs: ").append(resource.dnsServerIPs()); for (Subnet subnet : resource.subnets().values()) { info.append("\n\tSubnet: ").append(subnet.name()) .append("\n\t\tAddress prefix: ").append(subnet.addressPrefix()); NetworkSecurityGroup subnetNsg = subnet.getNetworkSecurityGroup(); if (subnetNsg != null) { info.append("\n\t\tNetwork security group ID: ").append(subnetNsg.id()); } RouteTable routeTable = subnet.getRouteTable(); if (routeTable != null) { info.append("\n\tRoute table ID: ").append(routeTable.id()); } Map<ServiceEndpointType, List<Region>> services = subnet.servicesWithAccess(); if (services.size() > 0) { info.append("\n\tServices with access"); for (Map.Entry<ServiceEndpointType, List<Region>> service : services.entrySet()) { info.append("\n\t\tService: ") .append(service.getKey()) .append(" Regions: " + service.getValue() + ""); } } } for (NetworkPeering peering : resource.peerings().list()) { info.append("\n\tPeering: ").append(peering.name()) .append("\n\t\tRemote network ID: ").append(peering.remoteNetworkId()) .append("\n\t\tPeering state: ").append(peering.state()) .append("\n\t\tIs traffic forwarded from remote network allowed? ").append(peering.isTrafficForwardingFromRemoteNetworkAllowed()) .append("\n\t\tGateway use: ").append(peering.gatewayUse()); } System.out.println(info.toString()); } /** * Print network interface. * * @param resource a network interface */ public static void print(NetworkInterface resource) { StringBuilder info = new StringBuilder(); info.append("NetworkInterface: ").append(resource.id()) .append("Name: ").append(resource.name()) .append("\n\tResource group: ").append(resource.resourceGroupName()) .append("\n\tRegion: ").append(resource.region()) .append("\n\tTags: ").append(resource.tags()) .append("\n\tInternal DNS name label: ").append(resource.internalDnsNameLabel()) .append("\n\tInternal FQDN: ").append(resource.internalFqdn()) .append("\n\tInternal domain name suffix: ").append(resource.internalDomainNameSuffix()) .append("\n\tNetwork security group: ").append(resource.networkSecurityGroupId()) .append("\n\tApplied DNS servers: ").append(resource.appliedDnsServers().toString()) .append("\n\tDNS server IPs: "); for (String dnsServerIp : resource.dnsServers()) { info.append("\n\t\t").append(dnsServerIp); } info.append("\n\tIP forwarding enabled? ").append(resource.isIPForwardingEnabled()) .append("\n\tAccelerated networking enabled? ").append(resource.isAcceleratedNetworkingEnabled()) .append("\n\tMAC Address:").append(resource.macAddress()) .append("\n\tPrivate IP:").append(resource.primaryPrivateIP()) .append("\n\tPrivate allocation method:").append(resource.primaryPrivateIpAllocationMethod()) .append("\n\tPrimary virtual network ID: ").append(resource.primaryIPConfiguration().networkId()) .append("\n\tPrimary subnet name:").append(resource.primaryIPConfiguration().subnetName()); System.out.println(info.toString()); } /** * Print network security group. * * @param resource a network security group */ public static void print(NetworkSecurityGroup resource) { StringBuilder info = new StringBuilder(); info.append("NSG: ").append(resource.id()) .append("Name: ").append(resource.name()) .append("\n\tResource group: ").append(resource.resourceGroupName()) .append("\n\tRegion: ").append(resource.region()) .append("\n\tTags: ").append(resource.tags()); for (NetworkSecurityRule rule : resource.securityRules().values()) { info.append("\n\tRule: ").append(rule.name()) .append("\n\t\tAccess: ").append(rule.access()) .append("\n\t\tDirection: ").append(rule.direction()) .append("\n\t\tFrom address: ").append(rule.sourceAddressPrefix()) .append("\n\t\tFrom port range: ").append(rule.sourcePortRange()) .append("\n\t\tTo address: ").append(rule.destinationAddressPrefix()) .append("\n\t\tTo port: ").append(rule.destinationPortRange()) .append("\n\t\tProtocol: ").append(rule.protocol()) .append("\n\t\tPriority: ").append(rule.priority()); } System.out.println(info.toString()); } /** * Print public IP address. * * @param resource a public IP address */ public static void print(PublicIpAddress resource) { System.out.println(new StringBuilder().append("Public IP Address: ").append(resource.id()) .append("Name: ").append(resource.name()) .append("\n\tResource group: ").append(resource.resourceGroupName()) .append("\n\tRegion: ").append(resource.region()) .append("\n\tTags: ").append(resource.tags()) .append("\n\tIP Address: ").append(resource.ipAddress()) .append("\n\tLeaf domain label: ").append(resource.leafDomainLabel()) .append("\n\tFQDN: ").append(resource.fqdn()) .append("\n\tReverse FQDN: ").append(resource.reverseFqdn()) .append("\n\tIdle timeout (minutes): ").append(resource.idleTimeoutInMinutes()) .append("\n\tIP allocation method: ").append(resource.ipAllocationMethod()) .append("\n\tZones: ").append(resource.availabilityZones()) .toString()); } /** * Print a key vault. * * @param vault the key vault resource */ public static void print(Vault vault) { StringBuilder info = new StringBuilder().append("Key Vault: ").append(vault.id()) .append("Name: ").append(vault.name()) .append("\n\tResource group: ").append(vault.resourceGroupName()) .append("\n\tRegion: ").append(vault.region()) .append("\n\tSku: ").append(vault.sku().name()).append(" - ").append(vault.sku().family()) .append("\n\tVault URI: ").append(vault.vaultUri()) .append("\n\tAccess policies: "); for (AccessPolicy accessPolicy : vault.accessPolicies()) { info.append("\n\t\tIdentity:").append(accessPolicy.objectId()); if (accessPolicy.permissions() != null) { if (accessPolicy.permissions().keys() != null) { info.append("\n\t\tKey permissions: ").append(accessPolicy.permissions().keys().stream().map(KeyPermissions::toString).collect(Collectors.joining(", "))); } if (accessPolicy.permissions().secrets() != null) { info.append("\n\t\tSecret permissions: ").append(accessPolicy.permissions().secrets().stream().map(SecretPermissions::toString).collect(Collectors.joining(", "))); } if (accessPolicy.permissions().certificates() != null) { info.append("\n\t\tCertificate permissions: ").append(accessPolicy.permissions().certificates().stream().map(CertificatePermissions::toString).collect(Collectors.joining(", "))); } } } System.out.println(info.toString()); } /** * Print storage account. * * @param storageAccount a storage account */ public static void print(StorageAccount storageAccount) { System.out.println(storageAccount.name() + " created @ " + storageAccount.creationTime()); StringBuilder info = new StringBuilder().append("Storage Account: ").append(storageAccount.id()) .append("Name: ").append(storageAccount.name()) .append("\n\tResource group: ").append(storageAccount.resourceGroupName()) .append("\n\tRegion: ").append(storageAccount.region()) .append("\n\tSKU: ").append(storageAccount.skuType().name().toString()) .append("\n\tAccessTier: ").append(storageAccount.accessTier()) .append("\n\tKind: ").append(storageAccount.kind()); info.append("\n\tNetwork Rule Configuration: ") .append("\n\t\tAllow reading logs from any network: ").append(storageAccount.canReadLogEntriesFromAnyNetwork()) .append("\n\t\tAllow reading metrics from any network: ").append(storageAccount.canReadMetricsFromAnyNetwork()) .append("\n\t\tAllow access from all azure services: ").append(storageAccount.canAccessFromAzureServices()); if (storageAccount.networkSubnetsWithAccess().size() > 0) { info.append("\n\t\tNetwork subnets with access: "); for (String subnetId : storageAccount.networkSubnetsWithAccess()) { info.append("\n\t\t\t").append(subnetId); } } if (storageAccount.ipAddressesWithAccess().size() > 0) { info.append("\n\t\tIP addresses with access: "); for (String ipAddress : storageAccount.ipAddressesWithAccess()) { info.append("\n\t\t\t").append(ipAddress); } } if (storageAccount.ipAddressRangesWithAccess().size() > 0) { info.append("\n\t\tIP address-ranges with access: "); for (String ipAddressRange : storageAccount.ipAddressRangesWithAccess()) { info.append("\n\t\t\t").append(ipAddressRange); } } info.append("\n\t\tTraffic allowed from only HTTPS: ").append(storageAccount.innerModel().enableHttpsTrafficOnly()); info.append("\n\tEncryption status: "); for (Map.Entry<StorageService, StorageAccountEncryptionStatus> eStatus : storageAccount.encryptionStatuses().entrySet()) { info.append("\n\t\t").append(eStatus.getValue().storageService()).append(": ").append(eStatus.getValue().isEnabled() ? "Enabled" : "Disabled"); } System.out.println(info.toString()); } /** * Print storage account keys. * * @param storageAccountKeys a list of storage account keys */ public static void print(List<StorageAccountKey> storageAccountKeys) { for (int i = 0; i < storageAccountKeys.size(); i++) { StorageAccountKey storageAccountKey = storageAccountKeys.get(i); System.out.println("Key (" + i + ") " + storageAccountKey.keyName() + "=" + storageAccountKey.value()); } } /** * Print Redis Cache. * * @param redisCache a Redis cache. */ public static void print(RedisCache redisCache) { StringBuilder redisInfo = new StringBuilder() .append("Redis Cache Name: ").append(redisCache.name()) .append("\n\tResource group: ").append(redisCache.resourceGroupName()) .append("\n\tRegion: ").append(redisCache.region()) .append("\n\tSKU Name: ").append(redisCache.sku().name()) .append("\n\tSKU Family: ").append(redisCache.sku().family()) .append("\n\tHostname: ").append(redisCache.hostname()) .append("\n\tSSL port: ").append(redisCache.sslPort()) .append("\n\tNon-SSL port (6379) enabled: ").append(redisCache.nonSslPort()); if (redisCache.redisConfiguration() != null && !redisCache.redisConfiguration().isEmpty()) { redisInfo.append("\n\tRedis Configuration:"); for (Map.Entry<String, String> redisConfiguration : redisCache.redisConfiguration().entrySet()) { redisInfo.append("\n\t '").append(redisConfiguration.getKey()) .append("' : '").append(redisConfiguration.getValue()).append("'"); } } if (redisCache.isPremium()) { RedisCachePremium premium = redisCache.asPremium(); List<ScheduleEntry> scheduleEntries = premium.listPatchSchedules(); if (scheduleEntries != null && !scheduleEntries.isEmpty()) { redisInfo.append("\n\tRedis Patch Schedule:"); for (ScheduleEntry schedule : scheduleEntries) { redisInfo.append("\n\t\tDay: '").append(schedule.dayOfWeek()) .append("', start at: '").append(schedule.startHourUtc()) .append("', maintenance window: '").append(schedule.maintenanceWindow()) .append("'"); } } } System.out.println(redisInfo.toString()); } /** * Print Redis Cache access keys. * * @param redisAccessKeys a keys for Redis Cache */ public static void print(RedisAccessKeys redisAccessKeys) { StringBuilder redisKeys = new StringBuilder() .append("Redis Access Keys: ") .append("\n\tPrimary Key: '").append(redisAccessKeys.primaryKey()).append("', ") .append("\n\tSecondary Key: '").append(redisAccessKeys.secondaryKey()).append("', "); System.out.println(redisKeys.toString()); } /** * Print load balancer. * * @param resource a load balancer */ public static void print(LoadBalancer resource) { StringBuilder info = new StringBuilder(); info.append("Load balancer: ").append(resource.id()) .append("Name: ").append(resource.name()) .append("\n\tResource group: ").append(resource.resourceGroupName()) .append("\n\tRegion: ").append(resource.region()) .append("\n\tTags: ").append(resource.tags()) .append("\n\tBackends: ").append(resource.backends().keySet().toString()); info.append("\n\tPublic IP address IDs: ") .append(resource.publicIpAddressIds().size()); for (String pipId : resource.publicIpAddressIds()) { info.append("\n\t\tPIP id: ").append(pipId); } info.append("\n\tTCP probes: ") .append(resource.tcpProbes().size()); for (LoadBalancerTcpProbe probe : resource.tcpProbes().values()) { info.append("\n\t\tProbe name: ").append(probe.name()) .append("\n\t\t\tPort: ").append(probe.port()) .append("\n\t\t\tInterval in seconds: ").append(probe.intervalInSeconds()) .append("\n\t\t\tRetries before unhealthy: ").append(probe.numberOfProbes()); info.append("\n\t\t\tReferenced from load balancing rules: ") .append(probe.loadBalancingRules().size()); for (LoadBalancingRule rule : probe.loadBalancingRules().values()) { info.append("\n\t\t\t\tName: ").append(rule.name()); } } info.append("\n\tHTTP probes: ") .append(resource.httpProbes().size()); for (LoadBalancerHttpProbe probe : resource.httpProbes().values()) { info.append("\n\t\tProbe name: ").append(probe.name()) .append("\n\t\t\tPort: ").append(probe.port()) .append("\n\t\t\tInterval in seconds: ").append(probe.intervalInSeconds()) .append("\n\t\t\tRetries before unhealthy: ").append(probe.numberOfProbes()) .append("\n\t\t\tHTTP request path: ").append(probe.requestPath()); info.append("\n\t\t\tReferenced from load balancing rules: ") .append(probe.loadBalancingRules().size()); for (LoadBalancingRule rule : probe.loadBalancingRules().values()) { info.append("\n\t\t\t\tName: ").append(rule.name()); } } info.append("\n\tHTTPS probes: ") .append(resource.httpsProbes().size()); for (LoadBalancerHttpProbe probe : resource.httpsProbes().values()) { info.append("\n\t\tProbe name: ").append(probe.name()) .append("\n\t\t\tPort: ").append(probe.port()) .append("\n\t\t\tInterval in seconds: ").append(probe.intervalInSeconds()) .append("\n\t\t\tRetries before unhealthy: ").append(probe.numberOfProbes()) .append("\n\t\t\tHTTPS request path: ").append(probe.requestPath()); info.append("\n\t\t\tReferenced from load balancing rules: ") .append(probe.loadBalancingRules().size()); for (LoadBalancingRule rule : probe.loadBalancingRules().values()) { info.append("\n\t\t\t\tName: ").append(rule.name()); } } info.append("\n\tLoad balancing rules: ") .append(resource.loadBalancingRules().size()); for (LoadBalancingRule rule : resource.loadBalancingRules().values()) { info.append("\n\t\tLB rule name: ").append(rule.name()) .append("\n\t\t\tProtocol: ").append(rule.protocol()) .append("\n\t\t\tFloating IP enabled? ").append(rule.floatingIPEnabled()) .append("\n\t\t\tIdle timeout in minutes: ").append(rule.idleTimeoutInMinutes()) .append("\n\t\t\tLoad distribution method: ").append(rule.loadDistribution().toString()); LoadBalancerFrontend frontend = rule.frontend(); info.append("\n\t\t\tFrontend: "); if (frontend != null) { info.append(frontend.name()); } else { info.append("(None)"); } info.append("\n\t\t\tFrontend port: ").append(rule.frontendPort()); LoadBalancerBackend backend = rule.backend(); info.append("\n\t\t\tBackend: "); if (backend != null) { info.append(backend.name()); } else { info.append("(None)"); } info.append("\n\t\t\tBackend port: ").append(rule.backendPort()); LoadBalancerProbe probe = rule.probe(); info.append("\n\t\t\tProbe: "); if (probe == null) { info.append("(None)"); } else { info.append(probe.name()).append(" [").append(probe.protocol().toString()).append("]"); } } info.append("\n\tFrontends: ") .append(resource.frontends().size()); for (LoadBalancerFrontend frontend : resource.frontends().values()) { info.append("\n\t\tFrontend name: ").append(frontend.name()) .append("\n\t\t\tInternet facing: ").append(frontend.isPublic()); if (frontend.isPublic()) { info.append("\n\t\t\tPublic IP Address ID: ").append(((LoadBalancerPublicFrontend) frontend).publicIpAddressId()); } else { info.append("\n\t\t\tVirtual network ID: ").append(((LoadBalancerPrivateFrontend) frontend).networkId()) .append("\n\t\t\tSubnet name: ").append(((LoadBalancerPrivateFrontend) frontend).subnetName()) .append("\n\t\t\tPrivate IP address: ").append(((LoadBalancerPrivateFrontend) frontend).privateIpAddress()) .append("\n\t\t\tPrivate IP allocation method: ").append(((LoadBalancerPrivateFrontend) frontend).privateIpAllocationMethod()); } info.append("\n\t\t\tReferenced inbound NAT pools: ") .append(frontend.inboundNatPools().size()); for (LoadBalancerInboundNatPool pool : frontend.inboundNatPools().values()) { info.append("\n\t\t\t\tName: ").append(pool.name()); } info.append("\n\t\t\tReferenced inbound NAT rules: ") .append(frontend.inboundNatRules().size()); for (LoadBalancerInboundNatRule rule : frontend.inboundNatRules().values()) { info.append("\n\t\t\t\tName: ").append(rule.name()); } info.append("\n\t\t\tReferenced load balancing rules: ") .append(frontend.loadBalancingRules().size()); for (LoadBalancingRule rule : frontend.loadBalancingRules().values()) { info.append("\n\t\t\t\tName: ").append(rule.name()); } } info.append("\n\tInbound NAT rules: ") .append(resource.inboundNatRules().size()); for (LoadBalancerInboundNatRule natRule : resource.inboundNatRules().values()) { info.append("\n\t\tInbound NAT rule name: ").append(natRule.name()) .append("\n\t\t\tProtocol: ").append(natRule.protocol().toString()) .append("\n\t\t\tFrontend: ").append(natRule.frontend().name()) .append("\n\t\t\tFrontend port: ").append(natRule.frontendPort()) .append("\n\t\t\tBackend port: ").append(natRule.backendPort()) .append("\n\t\t\tBackend NIC ID: ").append(natRule.backendNetworkInterfaceId()) .append("\n\t\t\tBackend NIC IP config name: ").append(natRule.backendNicIpConfigurationName()) .append("\n\t\t\tFloating IP? ").append(natRule.floatingIPEnabled()) .append("\n\t\t\tIdle timeout in minutes: ").append(natRule.idleTimeoutInMinutes()); } info.append("\n\tInbound NAT pools: ") .append(resource.inboundNatPools().size()); for (LoadBalancerInboundNatPool natPool : resource.inboundNatPools().values()) { info.append("\n\t\tInbound NAT pool name: ").append(natPool.name()) .append("\n\t\t\tProtocol: ").append(natPool.protocol().toString()) .append("\n\t\t\tFrontend: ").append(natPool.frontend().name()) .append("\n\t\t\tFrontend port range: ") .append(natPool.frontendPortRangeStart()) .append("-") .append(natPool.frontendPortRangeEnd()) .append("\n\t\t\tBackend port: ").append(natPool.backendPort()); } info.append("\n\tBackends: ") .append(resource.backends().size()); for (LoadBalancerBackend backend : resource.backends().values()) { info.append("\n\t\tBackend name: ").append(backend.name()); info.append("\n\t\t\tReferenced NICs: ") .append(backend.backendNicIPConfigurationNames().entrySet().size()); for (Map.Entry<String, String> entry : backend.backendNicIPConfigurationNames().entrySet()) { info.append("\n\t\t\t\tNIC ID: ").append(entry.getKey()) .append(" - IP Config: ").append(entry.getValue()); } Set<String> vmIds = backend.getVirtualMachineIds(); info.append("\n\t\t\tReferenced virtual machine ids: ") .append(vmIds.size()); for (String vmId : vmIds) { info.append("\n\t\t\t\tVM ID: ").append(vmId); } info.append("\n\t\t\tReferenced load balancing rules: ") .append(new ArrayList<String>(backend.loadBalancingRules().keySet())); } System.out.println(info.toString()); } /** * Print app service domain. * * @param resource an app service domain */ public static void print(AppServiceDomain resource) { StringBuilder builder = new StringBuilder().append("Domain: ").append(resource.id()) .append("Name: ").append(resource.name()) .append("\n\tResource group: ").append(resource.resourceGroupName()) .append("\n\tRegion: ").append(resource.region()) .append("\n\tCreated time: ").append(resource.createdTime()) .append("\n\tExpiration time: ").append(resource.expirationTime()) .append("\n\tContact: "); Contact contact = resource.registrantContact(); if (contact == null) { builder = builder.append("Private"); } else { builder = builder.append("\n\t\tName: ").append(contact.nameFirst() + " " + contact.nameLast()); } builder = builder.append("\n\tName servers: "); for (String nameServer : resource.nameServers()) { builder = builder.append("\n\t\t" + nameServer); } System.out.println(builder.toString()); } /** * Print app service certificate order. * * @param resource an app service certificate order */ public static void print(AppServiceCertificateOrder resource) { StringBuilder builder = new StringBuilder().append("App service certificate order: ").append(resource.id()) .append("Name: ").append(resource.name()) .append("\n\tResource group: ").append(resource.resourceGroupName()) .append("\n\tRegion: ").append(resource.region()) .append("\n\tDistinguished name: ").append(resource.distinguishedName()) .append("\n\tProduct type: ").append(resource.productType()) .append("\n\tValid years: ").append(resource.validityInYears()) .append("\n\tStatus: ").append(resource.status()) .append("\n\tIssuance time: ").append(resource.lastCertificateIssuanceTime()) .append("\n\tSigned certificate: ").append(resource.signedCertificate() == null ? null : resource.signedCertificate().thumbprint()); System.out.println(builder.toString()); } /** * Print app service plan. * * @param resource an app service plan */ public static void print(AppServicePlan resource) { StringBuilder builder = new StringBuilder().append("App service certificate order: ").append(resource.id()) .append("Name: ").append(resource.name()) .append("\n\tResource group: ").append(resource.resourceGroupName()) .append("\n\tRegion: ").append(resource.region()) .append("\n\tPricing tier: ").append(resource.pricingTier()); System.out.println(builder.toString()); } /** * Print a web app. * * @param resource a web app */ public static void print(WebAppBase resource) { StringBuilder builder = new StringBuilder().append("Web app: ").append(resource.id()) .append("\n\tName: ").append(resource.name()) .append("\n\tState: ").append(resource.state()) .append("\n\tResource group: ").append(resource.resourceGroupName()) .append("\n\tRegion: ").append(resource.region()) .append("\n\tDefault hostname: ").append(resource.defaultHostname()) .append("\n\tApp service plan: ").append(resource.appServicePlanId()) .append("\n\tHost name bindings: "); for (HostnameBinding binding : resource.getHostnameBindings().values()) { builder = builder.append("\n\t\t" + binding.toString()); } builder = builder.append("\n\tSSL bindings: "); for (HostnameSslState binding : resource.hostnameSslStates().values()) { builder = builder.append("\n\t\t" + binding.name() + ": " + binding.sslState()); if (binding.sslState() != null && binding.sslState() != SslState.DISABLED) { builder = builder.append(" - " + binding.thumbprint()); } } builder = builder.append("\n\tApp settings: "); for (AppSetting setting : resource.getAppSettings().values()) { builder = builder.append("\n\t\t" + setting.key() + ": " + setting.value() + (setting.sticky() ? " - slot setting" : "")); } builder = builder.append("\n\tConnection strings: "); for (ConnectionString conn : resource.getConnectionStrings().values()) { builder = builder.append("\n\t\t" + conn.name() + ": " + conn.value() + " - " + conn.type() + (conn.sticky() ? " - slot setting" : "")); } System.out.println(builder.toString()); } /** * Print a web site. * * @param resource a web site */ public static void print(WebSiteBase resource) { StringBuilder builder = new StringBuilder().append("Web app: ").append(resource.id()) .append("\n\tName: ").append(resource.name()) .append("\n\tState: ").append(resource.state()) .append("\n\tResource group: ").append(resource.resourceGroupName()) .append("\n\tRegion: ").append(resource.region()) .append("\n\tDefault hostname: ").append(resource.defaultHostname()) .append("\n\tApp service plan: ").append(resource.appServicePlanId()); builder = builder.append("\n\tSSL bindings: "); for (HostnameSslState binding : resource.hostnameSslStates().values()) { builder = builder.append("\n\t\t" + binding.name() + ": " + binding.sslState()); if (binding.sslState() != null && binding.sslState() != SslState.DISABLED) { builder = builder.append(" - " + binding.thumbprint()); } } System.out.println(builder.toString()); } /** * Print a traffic manager profile. * * @param profile a traffic manager profile */ public static void print(TrafficManagerProfile profile) { StringBuilder info = new StringBuilder(); info.append("Traffic Manager Profile: ").append(profile.id()) .append("\n\tName: ").append(profile.name()) .append("\n\tResource group: ").append(profile.resourceGroupName()) .append("\n\tRegion: ").append(profile.regionName()) .append("\n\tTags: ").append(profile.tags()) .append("\n\tDNSLabel: ").append(profile.dnsLabel()) .append("\n\tFQDN: ").append(profile.fqdn()) .append("\n\tTTL: ").append(profile.timeToLive()) .append("\n\tEnabled: ").append(profile.isEnabled()) .append("\n\tRoutingMethod: ").append(profile.trafficRoutingMethod()) .append("\n\tMonitor status: ").append(profile.monitorStatus()) .append("\n\tMonitoring port: ").append(profile.monitoringPort()) .append("\n\tMonitoring path: ").append(profile.monitoringPath()); Map<String, TrafficManagerAzureEndpoint> azureEndpoints = profile.azureEndpoints(); if (!azureEndpoints.isEmpty()) { info.append("\n\tAzure endpoints:"); int idx = 1; for (TrafficManagerAzureEndpoint endpoint : azureEndpoints.values()) { info.append("\n\t\tAzure endpoint: .append("\n\t\t\tId: ").append(endpoint.id()) .append("\n\t\t\tType: ").append(endpoint.endpointType()) .append("\n\t\t\tTarget resourceId: ").append(endpoint.targetAzureResourceId()) .append("\n\t\t\tTarget resourceType: ").append(endpoint.targetResourceType()) .append("\n\t\t\tMonitor status: ").append(endpoint.monitorStatus()) .append("\n\t\t\tEnabled: ").append(endpoint.isEnabled()) .append("\n\t\t\tRouting priority: ").append(endpoint.routingPriority()) .append("\n\t\t\tRouting weight: ").append(endpoint.routingWeight()); } } Map<String, TrafficManagerExternalEndpoint> externalEndpoints = profile.externalEndpoints(); if (!externalEndpoints.isEmpty()) { info.append("\n\tExternal endpoints:"); int idx = 1; for (TrafficManagerExternalEndpoint endpoint : externalEndpoints.values()) { info.append("\n\t\tExternal endpoint: .append("\n\t\t\tId: ").append(endpoint.id()) .append("\n\t\t\tType: ").append(endpoint.endpointType()) .append("\n\t\t\tFQDN: ").append(endpoint.fqdn()) .append("\n\t\t\tSource Traffic Location: ").append(endpoint.sourceTrafficLocation()) .append("\n\t\t\tMonitor status: ").append(endpoint.monitorStatus()) .append("\n\t\t\tEnabled: ").append(endpoint.isEnabled()) .append("\n\t\t\tRouting priority: ").append(endpoint.routingPriority()) .append("\n\t\t\tRouting weight: ").append(endpoint.routingWeight()); } } Map<String, TrafficManagerNestedProfileEndpoint> nestedProfileEndpoints = profile.nestedProfileEndpoints(); if (!nestedProfileEndpoints.isEmpty()) { info.append("\n\tNested profile endpoints:"); int idx = 1; for (TrafficManagerNestedProfileEndpoint endpoint : nestedProfileEndpoints.values()) { info.append("\n\t\tNested profile endpoint: .append("\n\t\t\tId: ").append(endpoint.id()) .append("\n\t\t\tType: ").append(endpoint.endpointType()) .append("\n\t\t\tNested profileId: ").append(endpoint.nestedProfileId()) .append("\n\t\t\tMinimum child threshold: ").append(endpoint.minimumChildEndpointCount()) .append("\n\t\t\tSource Traffic Location: ").append(endpoint.sourceTrafficLocation()) .append("\n\t\t\tMonitor status: ").append(endpoint.monitorStatus()) .append("\n\t\t\tEnabled: ").append(endpoint.isEnabled()) .append("\n\t\t\tRouting priority: ").append(endpoint.routingPriority()) .append("\n\t\t\tRouting weight: ").append(endpoint.routingWeight()); } } System.out.println(info.toString()); } /** * Print a dns zone. * * @param dnsZone a dns zone */ public static void print(DnsZone dnsZone) { StringBuilder info = new StringBuilder(); info.append("DNS Zone: ").append(dnsZone.id()) .append("\n\tName (Top level domain): ").append(dnsZone.name()) .append("\n\tResource group: ").append(dnsZone.resourceGroupName()) .append("\n\tRegion: ").append(dnsZone.regionName()) .append("\n\tTags: ").append(dnsZone.tags()) .append("\n\tName servers:"); for (String nameServer : dnsZone.nameServers()) { info.append("\n\t\t").append(nameServer); } SoaRecordSet soaRecordSet = dnsZone.getSoaRecordSet(); SoaRecord soaRecord = soaRecordSet.record(); info.append("\n\tSOA Record:") .append("\n\t\tHost:").append(soaRecord.host()) .append("\n\t\tEmail:").append(soaRecord.email()) .append("\n\t\tExpire time (seconds):").append(soaRecord.expireTime()) .append("\n\t\tRefresh time (seconds):").append(soaRecord.refreshTime()) .append("\n\t\tRetry time (seconds):").append(soaRecord.retryTime()) .append("\n\t\tNegative response cache ttl (seconds):").append(soaRecord.minimumTtl()) .append("\n\t\tTTL (seconds):").append(soaRecordSet.timeToLive()); PagedIterable<ARecordSet> aRecordSets = dnsZone.aRecordSets().list(); info.append("\n\tA Record sets:"); for (ARecordSet aRecordSet : aRecordSets) { info.append("\n\t\tId: ").append(aRecordSet.id()) .append("\n\t\tName: ").append(aRecordSet.name()) .append("\n\t\tTTL (seconds): ").append(aRecordSet.timeToLive()) .append("\n\t\tIP v4 addresses: "); for (String ipAddress : aRecordSet.ipv4Addresses()) { info.append("\n\t\t\t").append(ipAddress); } } PagedIterable<AaaaRecordSet> aaaaRecordSets = dnsZone.aaaaRecordSets().list(); info.append("\n\tAAAA Record sets:"); for (AaaaRecordSet aaaaRecordSet : aaaaRecordSets) { info.append("\n\t\tId: ").append(aaaaRecordSet.id()) .append("\n\t\tName: ").append(aaaaRecordSet.name()) .append("\n\t\tTTL (seconds): ").append(aaaaRecordSet.timeToLive()) .append("\n\t\tIP v6 addresses: "); for (String ipAddress : aaaaRecordSet.ipv6Addresses()) { info.append("\n\t\t\t").append(ipAddress); } } PagedIterable<CnameRecordSet> cnameRecordSets = dnsZone.cNameRecordSets().list(); info.append("\n\tCNAME Record sets:"); for (CnameRecordSet cnameRecordSet : cnameRecordSets) { info.append("\n\t\tId: ").append(cnameRecordSet.id()) .append("\n\t\tName: ").append(cnameRecordSet.name()) .append("\n\t\tTTL (seconds): ").append(cnameRecordSet.timeToLive()) .append("\n\t\tCanonical name: ").append(cnameRecordSet.canonicalName()); } PagedIterable<MxRecordSet> mxRecordSets = dnsZone.mxRecordSets().list(); info.append("\n\tMX Record sets:"); for (MxRecordSet mxRecordSet : mxRecordSets) { info.append("\n\t\tId: ").append(mxRecordSet.id()) .append("\n\t\tName: ").append(mxRecordSet.name()) .append("\n\t\tTTL (seconds): ").append(mxRecordSet.timeToLive()) .append("\n\t\tRecords: "); for (MxRecord mxRecord : mxRecordSet.records()) { info.append("\n\t\t\tExchange server, Preference: ") .append(mxRecord.exchange()) .append(" ") .append(mxRecord.preference()); } } PagedIterable<NsRecordSet> nsRecordSets = dnsZone.nsRecordSets().list(); info.append("\n\tNS Record sets:"); for (NsRecordSet nsRecordSet : nsRecordSets) { info.append("\n\t\tId: ").append(nsRecordSet.id()) .append("\n\t\tName: ").append(nsRecordSet.name()) .append("\n\t\tTTL (seconds): ").append(nsRecordSet.timeToLive()) .append("\n\t\tName servers: "); for (String nameServer : nsRecordSet.nameServers()) { info.append("\n\t\t\t").append(nameServer); } } PagedIterable<PtrRecordSet> ptrRecordSets = dnsZone.ptrRecordSets().list(); info.append("\n\tPTR Record sets:"); for (PtrRecordSet ptrRecordSet : ptrRecordSets) { info.append("\n\t\tId: ").append(ptrRecordSet.id()) .append("\n\t\tName: ").append(ptrRecordSet.name()) .append("\n\t\tTTL (seconds): ").append(ptrRecordSet.timeToLive()) .append("\n\t\tTarget domain names: "); for (String domainNames : ptrRecordSet.targetDomainNames()) { info.append("\n\t\t\t").append(domainNames); } } PagedIterable<SrvRecordSet> srvRecordSets = dnsZone.srvRecordSets().list(); info.append("\n\tSRV Record sets:"); for (SrvRecordSet srvRecordSet : srvRecordSets) { info.append("\n\t\tId: ").append(srvRecordSet.id()) .append("\n\t\tName: ").append(srvRecordSet.name()) .append("\n\t\tTTL (seconds): ").append(srvRecordSet.timeToLive()) .append("\n\t\tRecords: "); for (SrvRecord srvRecord : srvRecordSet.records()) { info.append("\n\t\t\tTarget, Port, Priority, Weight: ") .append(srvRecord.target()) .append(", ") .append(srvRecord.port()) .append(", ") .append(srvRecord.priority()) .append(", ") .append(srvRecord.weight()); } } PagedIterable<TxtRecordSet> txtRecordSets = dnsZone.txtRecordSets().list(); info.append("\n\tTXT Record sets:"); for (TxtRecordSet txtRecordSet : txtRecordSets) { info.append("\n\t\tId: ").append(txtRecordSet.id()) .append("\n\t\tName: ").append(txtRecordSet.name()) .append("\n\t\tTTL (seconds): ").append(txtRecordSet.timeToLive()) .append("\n\t\tRecords: "); for (TxtRecord txtRecord : txtRecordSet.records()) { if (txtRecord.value().size() > 0) { info.append("\n\t\t\tValue: ").append(txtRecord.value().get(0)); } } } System.out.println(info.toString()); } /** * Print a private dns zone. * * @param privateDnsZone a private dns zone */ public static void print(PrivateDnsZone privateDnsZone) { StringBuilder info = new StringBuilder(); info.append("Private DNS Zone: ").append(privateDnsZone.id()) .append("\n\tName (Top level domain): ").append(privateDnsZone.name()) .append("\n\tResource group: ").append(privateDnsZone.resourceGroupName()) .append("\n\tRegion: ").append(privateDnsZone.regionName()) .append("\n\tTags: ").append(privateDnsZone.tags()) .append("\n\tName servers:"); com.azure.resourcemanager.privatedns.models.SoaRecordSet soaRecordSet = privateDnsZone.getSoaRecordSet(); com.azure.resourcemanager.privatedns.models.SoaRecord soaRecord = soaRecordSet.record(); info.append("\n\tSOA Record:") .append("\n\t\tHost:").append(soaRecord.host()) .append("\n\t\tEmail:").append(soaRecord.email()) .append("\n\t\tExpire time (seconds):").append(soaRecord.expireTime()) .append("\n\t\tRefresh time (seconds):").append(soaRecord.refreshTime()) .append("\n\t\tRetry time (seconds):").append(soaRecord.retryTime()) .append("\n\t\tNegative response cache ttl (seconds):").append(soaRecord.minimumTtl()) .append("\n\t\tTTL (seconds):").append(soaRecordSet.timeToLive()); PagedIterable<com.azure.resourcemanager.privatedns.models.ARecordSet> aRecordSets = privateDnsZone .aRecordSets().list(); info.append("\n\tA Record sets:"); for (com.azure.resourcemanager.privatedns.models.ARecordSet aRecordSet : aRecordSets) { info.append("\n\t\tId: ").append(aRecordSet.id()) .append("\n\t\tName: ").append(aRecordSet.name()) .append("\n\t\tTTL (seconds): ").append(aRecordSet.timeToLive()) .append("\n\t\tIP v4 addresses: "); for (String ipAddress : aRecordSet.ipv4Addresses()) { info.append("\n\t\t\t").append(ipAddress); } } PagedIterable<com.azure.resourcemanager.privatedns.models.AaaaRecordSet> aaaaRecordSets = privateDnsZone .aaaaRecordSets().list(); info.append("\n\tAAAA Record sets:"); for (com.azure.resourcemanager.privatedns.models.AaaaRecordSet aaaaRecordSet : aaaaRecordSets) { info.append("\n\t\tId: ").append(aaaaRecordSet.id()) .append("\n\t\tName: ").append(aaaaRecordSet.name()) .append("\n\t\tTTL (seconds): ").append(aaaaRecordSet.timeToLive()) .append("\n\t\tIP v6 addresses: "); for (String ipAddress : aaaaRecordSet.ipv6Addresses()) { info.append("\n\t\t\t").append(ipAddress); } } PagedIterable<com.azure.resourcemanager.privatedns.models.CnameRecordSet> cnameRecordSets = privateDnsZone.cnameRecordSets().list(); info.append("\n\tCNAME Record sets:"); for (com.azure.resourcemanager.privatedns.models.CnameRecordSet cnameRecordSet : cnameRecordSets) { info.append("\n\t\tId: ").append(cnameRecordSet.id()) .append("\n\t\tName: ").append(cnameRecordSet.name()) .append("\n\t\tTTL (seconds): ").append(cnameRecordSet.timeToLive()) .append("\n\t\tCanonical name: ").append(cnameRecordSet.canonicalName()); } PagedIterable<com.azure.resourcemanager.privatedns.models.MxRecordSet> mxRecordSets = privateDnsZone.mxRecordSets().list(); info.append("\n\tMX Record sets:"); for (com.azure.resourcemanager.privatedns.models.MxRecordSet mxRecordSet : mxRecordSets) { info.append("\n\t\tId: ").append(mxRecordSet.id()) .append("\n\t\tName: ").append(mxRecordSet.name()) .append("\n\t\tTTL (seconds): ").append(mxRecordSet.timeToLive()) .append("\n\t\tRecords: "); for (com.azure.resourcemanager.privatedns.models.MxRecord mxRecord : mxRecordSet.records()) { info.append("\n\t\t\tExchange server, Preference: ") .append(mxRecord.exchange()) .append(" ") .append(mxRecord.preference()); } } PagedIterable<com.azure.resourcemanager.privatedns.models.PtrRecordSet> ptrRecordSets = privateDnsZone .ptrRecordSets().list(); info.append("\n\tPTR Record sets:"); for (com.azure.resourcemanager.privatedns.models.PtrRecordSet ptrRecordSet : ptrRecordSets) { info.append("\n\t\tId: ").append(ptrRecordSet.id()) .append("\n\t\tName: ").append(ptrRecordSet.name()) .append("\n\t\tTTL (seconds): ").append(ptrRecordSet.timeToLive()) .append("\n\t\tTarget domain names: "); for (String domainNames : ptrRecordSet.targetDomainNames()) { info.append("\n\t\t\t").append(domainNames); } } PagedIterable<com.azure.resourcemanager.privatedns.models.SrvRecordSet> srvRecordSets = privateDnsZone .srvRecordSets().list(); info.append("\n\tSRV Record sets:"); for (com.azure.resourcemanager.privatedns.models.SrvRecordSet srvRecordSet : srvRecordSets) { info.append("\n\t\tId: ").append(srvRecordSet.id()) .append("\n\t\tName: ").append(srvRecordSet.name()) .append("\n\t\tTTL (seconds): ").append(srvRecordSet.timeToLive()) .append("\n\t\tRecords: "); for (com.azure.resourcemanager.privatedns.models.SrvRecord srvRecord : srvRecordSet.records()) { info.append("\n\t\t\tTarget, Port, Priority, Weight: ") .append(srvRecord.target()) .append(", ") .append(srvRecord.port()) .append(", ") .append(srvRecord.priority()) .append(", ") .append(srvRecord.weight()); } } PagedIterable<com.azure.resourcemanager.privatedns.models.TxtRecordSet> txtRecordSets = privateDnsZone .txtRecordSets().list(); info.append("\n\tTXT Record sets:"); for (com.azure.resourcemanager.privatedns.models.TxtRecordSet txtRecordSet : txtRecordSets) { info.append("\n\t\tId: ").append(txtRecordSet.id()) .append("\n\t\tName: ").append(txtRecordSet.name()) .append("\n\t\tTTL (seconds): ").append(txtRecordSet.timeToLive()) .append("\n\t\tRecords: "); for (com.azure.resourcemanager.privatedns.models.TxtRecord txtRecord : txtRecordSet.records()) { if (txtRecord.value().size() > 0) { info.append("\n\t\t\tValue: ").append(txtRecord.value().get(0)); } } } PagedIterable<VirtualNetworkLink> virtualNetworkLinks = privateDnsZone.virtualNetworkLinks().list(); info.append("\n\tVirtual Network Links:"); for (VirtualNetworkLink virtualNetworkLink : virtualNetworkLinks) { info.append("\n\tId: ").append(virtualNetworkLink.id()) .append("\n\tName: ").append(virtualNetworkLink.name()) .append("\n\tReference of Virtual Network: ").append(virtualNetworkLink.referencedVirtualNetworkId()) .append("\n\tRegistration enabled: ").append(virtualNetworkLink.isAutoRegistrationEnabled()); } System.out.println(info.toString()); } /** * Print an Azure Container Registry. * * @param azureRegistry an Azure Container Registry */ public static void print(Registry azureRegistry) { StringBuilder info = new StringBuilder(); RegistryCredentials acrCredentials = azureRegistry.getCredentials(); info.append("Azure Container Registry: ").append(azureRegistry.id()) .append("\n\tName: ").append(azureRegistry.name()) .append("\n\tServer Url: ").append(azureRegistry.loginServerUrl()) .append("\n\tUser: ").append(acrCredentials.username()) .append("\n\tFirst Password: ").append(acrCredentials.accessKeys().get(AccessKeyType.PRIMARY)) .append("\n\tSecond Password: ").append(acrCredentials.accessKeys().get(AccessKeyType.SECONDARY)); System.out.println(info.toString()); } /** * Print an Azure Container Service (AKS). * * @param kubernetesCluster a managed container service */ public static void print(KubernetesCluster kubernetesCluster) { StringBuilder info = new StringBuilder(); info.append("Azure Container Service: ").append(kubernetesCluster.id()) .append("\n\tName: ").append(kubernetesCluster.name()) .append("\n\tFQDN: ").append(kubernetesCluster.fqdn()) .append("\n\tDNS prefix label: ").append(kubernetesCluster.dnsPrefix()) .append("\n\t\tWith Agent pool name: ").append(new ArrayList<>(kubernetesCluster.agentPools().keySet()).get(0)) .append("\n\t\tAgent pool count: ").append(new ArrayList<>(kubernetesCluster.agentPools().values()).get(0).count()) .append("\n\t\tAgent pool VM size: ").append(new ArrayList<>(kubernetesCluster.agentPools().values()).get(0).vmSize().toString()) .append("\n\tLinux user name: ").append(kubernetesCluster.linuxRootUsername()) .append("\n\tSSH key: ").append(kubernetesCluster.sshKey()) .append("\n\tService principal client ID: ").append(kubernetesCluster.servicePrincipalClientId()); System.out.println(info.toString()); } /** * Retrieve the secondary service principal client ID. * * @param envSecondaryServicePrincipal an Azure Container Registry * @return a service principal client ID * @throws Exception exception */
Only create NetworkerWatcher if not there.
public static boolean runSample(AzureResourceManager azureResourceManager) { final Region region = Region.EUROPE_NORTH; final String resourceGroupName = Utils.randomResourceName(azureResourceManager, "rg", 15); final String vnetAName = Utils.randomResourceName(azureResourceManager, "net", 15); final String vnetBName = Utils.randomResourceName(azureResourceManager, "net", 15); final String[] vmNames = Utils.randomResourceNames(azureResourceManager, "vm", 15, 2); final String[] vmIPAddresses = new String[]{ /* within subnetA */ "10.0.0.8", /* within subnetB */ "10.1.0.8" }; final String peeringABName = Utils.randomResourceName(azureResourceManager, "peer", 15); final String rootname = "tirekicker"; final String password = Utils.password(); final String networkWatcherName = Utils.randomResourceName(azureResourceManager, "netwch", 20); try { List<Creatable<Network>> networkDefinitions = new ArrayList<>(); networkDefinitions.add(azureResourceManager.networks().define(vnetAName) .withRegion(region) .withNewResourceGroup(resourceGroupName) .withAddressSpace("10.0.0.0/27") .withSubnet("subnetA", "10.0.0.0/27")); networkDefinitions.add(azureResourceManager.networks().define(vnetBName) .withRegion(region) .withNewResourceGroup(resourceGroupName) .withAddressSpace("10.1.0.0/27") .withSubnet("subnetB", "10.1.0.0/27")); List<Creatable<VirtualMachine>> vmDefinitions = new ArrayList<>(); for (int i = 0; i < networkDefinitions.size(); i++) { vmDefinitions.add(azureResourceManager.virtualMachines().define(vmNames[i]) .withRegion(region) .withExistingResourceGroup(resourceGroupName) .withNewPrimaryNetwork(networkDefinitions.get(i)) .withPrimaryPrivateIPAddressStatic(vmIPAddresses[i]) .withoutPrimaryPublicIPAddress() .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) .withRootUsername(rootname) .withRootPassword(password) .defineNewExtension("packetCapture") .withPublisher("Microsoft.Azure.NetworkWatcher") .withType("NetworkWatcherAgentLinux") .withVersion("1.4") .attach()); } System.out.println("Creating virtual machines and virtual networks..."); CreatedResources<VirtualMachine> createdVMs = azureResourceManager.virtualMachines().create(vmDefinitions); VirtualMachine vmA = createdVMs.get(vmDefinitions.get(0).key()); VirtualMachine vmB = createdVMs.get(vmDefinitions.get(1).key()); System.out.println("Created the virtual machines and networks."); Network networkA = vmA.getPrimaryNetworkInterface().primaryIPConfiguration().getNetwork(); Network networkB = vmB.getPrimaryNetworkInterface().primaryIPConfiguration().getNetwork(); Utils.print(networkA); Utils.print(networkB); System.out.println( "Peering the networks using default settings...\n" + "- Network access enabled\n" + "- Traffic forwarding disabled\n" + "- Gateway use (transit) by the remote network disabled"); NetworkPeering peeringAB = networkA.peerings().define(peeringABName) .withRemoteNetwork(networkB) .create(); Utils.print(networkA); Utils.print(networkB); NetworkWatcher networkWatcher = azureResourceManager.networkWatchers().list().stream() .filter(nw -> nw.region() == region).findFirst() .orElseGet(() -> azureResourceManager .networkWatchers() .define(networkWatcherName) .withRegion(region) .withExistingResourceGroup(resourceGroupName) .create()); Executable<ConnectivityCheck> connectivityAtoB = networkWatcher.checkConnectivity() .toDestinationAddress(vmIPAddresses[1]) .toDestinationPort(22) .fromSourceVirtualMachine(vmA); System.out.println("Connectivity from A to B: " + connectivityAtoB.execute().connectionStatus()); Executable<ConnectivityCheck> connectivityBtoA = networkWatcher.checkConnectivity() .toDestinationAddress(vmIPAddresses[0]) .toDestinationPort(22) .fromSourceVirtualMachine(vmB); System.out.println("Connectivity from B to A: " + connectivityBtoA.execute().connectionStatus()); System.out.println("Changing the peering to disable access between A and B..."); peeringAB.update() .withoutAccessFromEitherNetwork() .apply(); Utils.print(networkA); Utils.print(networkB); System.out.println("Peering configuration changed.\nNow, A should be unreachable from B, and B should be unreachable from A..."); System.out.println("Connectivity from A to B: " + connectivityAtoB.execute().connectionStatus()); System.out.println("Connectivity from B to A: " + connectivityBtoA.execute().connectionStatus()); return true; } finally { try { System.out.println("Deleting Resource Group: " + resourceGroupName); azureResourceManager.resourceGroups().beginDeleteByName(resourceGroupName); } catch (NullPointerException npe) { System.out.println("Did not create any resources in Azure. No clean up is necessary"); } catch (Exception g) { g.printStackTrace(); } } }
.orElseGet(() -> azureResourceManager
public static boolean runSample(AzureResourceManager azureResourceManager) { final Region region = Region.EUROPE_NORTH; final String resourceGroupName = Utils.randomResourceName(azureResourceManager, "rg", 15); final String vnetAName = Utils.randomResourceName(azureResourceManager, "net", 15); final String vnetBName = Utils.randomResourceName(azureResourceManager, "net", 15); final String[] vmNames = Utils.randomResourceNames(azureResourceManager, "vm", 15, 2); final String[] vmIPAddresses = new String[]{ /* within subnetA */ "10.0.0.8", /* within subnetB */ "10.1.0.8" }; final String peeringABName = Utils.randomResourceName(azureResourceManager, "peer", 15); final String rootname = "tirekicker"; final String password = Utils.password(); final String networkWatcherName = Utils.randomResourceName(azureResourceManager, "netwch", 20); try { List<Creatable<Network>> networkDefinitions = new ArrayList<>(); networkDefinitions.add(azureResourceManager.networks().define(vnetAName) .withRegion(region) .withNewResourceGroup(resourceGroupName) .withAddressSpace("10.0.0.0/27") .withSubnet("subnetA", "10.0.0.0/27")); networkDefinitions.add(azureResourceManager.networks().define(vnetBName) .withRegion(region) .withNewResourceGroup(resourceGroupName) .withAddressSpace("10.1.0.0/27") .withSubnet("subnetB", "10.1.0.0/27")); List<Creatable<VirtualMachine>> vmDefinitions = new ArrayList<>(); for (int i = 0; i < networkDefinitions.size(); i++) { vmDefinitions.add(azureResourceManager.virtualMachines().define(vmNames[i]) .withRegion(region) .withExistingResourceGroup(resourceGroupName) .withNewPrimaryNetwork(networkDefinitions.get(i)) .withPrimaryPrivateIPAddressStatic(vmIPAddresses[i]) .withoutPrimaryPublicIPAddress() .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) .withRootUsername(rootname) .withRootPassword(password) .defineNewExtension("packetCapture") .withPublisher("Microsoft.Azure.NetworkWatcher") .withType("NetworkWatcherAgentLinux") .withVersion("1.4") .attach()); } System.out.println("Creating virtual machines and virtual networks..."); CreatedResources<VirtualMachine> createdVMs = azureResourceManager.virtualMachines().create(vmDefinitions); VirtualMachine vmA = createdVMs.get(vmDefinitions.get(0).key()); VirtualMachine vmB = createdVMs.get(vmDefinitions.get(1).key()); System.out.println("Created the virtual machines and networks."); Network networkA = vmA.getPrimaryNetworkInterface().primaryIPConfiguration().getNetwork(); Network networkB = vmB.getPrimaryNetworkInterface().primaryIPConfiguration().getNetwork(); Utils.print(networkA); Utils.print(networkB); System.out.println( "Peering the networks using default settings...\n" + "- Network access enabled\n" + "- Traffic forwarding disabled\n" + "- Gateway use (transit) by the remote network disabled"); NetworkPeering peeringAB = networkA.peerings().define(peeringABName) .withRemoteNetwork(networkB) .create(); Utils.print(networkA); Utils.print(networkB); NetworkWatcher networkWatcher = azureResourceManager.networkWatchers().list().stream() .filter(nw -> nw.region() == region).findFirst() .orElseGet(() -> azureResourceManager .networkWatchers() .define(networkWatcherName) .withRegion(region) .withExistingResourceGroup(resourceGroupName) .create()); Executable<ConnectivityCheck> connectivityAtoB = networkWatcher.checkConnectivity() .toDestinationAddress(vmIPAddresses[1]) .toDestinationPort(22) .fromSourceVirtualMachine(vmA); System.out.println("Connectivity from A to B: " + connectivityAtoB.execute().connectionStatus()); Executable<ConnectivityCheck> connectivityBtoA = networkWatcher.checkConnectivity() .toDestinationAddress(vmIPAddresses[0]) .toDestinationPort(22) .fromSourceVirtualMachine(vmB); System.out.println("Connectivity from B to A: " + connectivityBtoA.execute().connectionStatus()); System.out.println("Changing the peering to disable access between A and B..."); peeringAB.update() .withoutAccessFromEitherNetwork() .apply(); Utils.print(networkA); Utils.print(networkB); System.out.println("Peering configuration changed.\nNow, A should be unreachable from B, and B should be unreachable from A..."); System.out.println("Connectivity from A to B: " + connectivityAtoB.execute().connectionStatus()); System.out.println("Connectivity from B to A: " + connectivityBtoA.execute().connectionStatus()); return true; } finally { try { System.out.println("Deleting Resource Group: " + resourceGroupName); azureResourceManager.resourceGroups().beginDeleteByName(resourceGroupName); } catch (NullPointerException npe) { System.out.println("Did not create any resources in Azure. No clean up is necessary"); } catch (Exception g) { g.printStackTrace(); } } }
class VerifyNetworkPeeringWithNetworkWatcher { /** * Main function which runs the actual sample. * * @param azureResourceManager instance of the azure client * @return true if sample runs successfully */ /** * Main entry point. * * @param args parameters */ public static void main(String[] args) { try { final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); final TokenCredential credential = new DefaultAzureCredentialBuilder() .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); AzureResourceManager azureResourceManager = AzureResourceManager .configure() .withLogLevel(HttpLogDetailLevel.BASIC) .authenticate(credential, profile) .withDefaultSubscription(); System.out.println("Selected subscription: " + azureResourceManager.subscriptionId()); runSample(azureResourceManager); } catch (Exception e) { System.out.println(e.getMessage()); e.printStackTrace(); } } private VerifyNetworkPeeringWithNetworkWatcher() { } }
class VerifyNetworkPeeringWithNetworkWatcher { /** * Main function which runs the actual sample. * * @param azureResourceManager instance of the azure client * @return true if sample runs successfully */ /** * Main entry point. * * @param args parameters */ public static void main(String[] args) { try { final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); final TokenCredential credential = new DefaultAzureCredentialBuilder() .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); AzureResourceManager azureResourceManager = AzureResourceManager .configure() .withLogLevel(HttpLogDetailLevel.BASIC) .authenticate(credential, profile) .withDefaultSubscription(); System.out.println("Selected subscription: " + azureResourceManager.subscriptionId()); runSample(azureResourceManager); } catch (Exception e) { System.out.println(e.getMessage()); e.printStackTrace(); } } private VerifyNetworkPeeringWithNetworkWatcher() { } }
`container.createItem()` will always either succeed and returns a CosmosItemResponse or will throw on failure. however here it seems we are allowing returning a TransactionalBatchResponse even if the whole batch fails. this is not consistent with the above. any reason for the deviation? shouldn't we follow the same pattern here? /CC @FabianMeiswinkel @kirankumarkolli
public boolean isSuccessStatusCode() { return this.responseStatus >= 200 && this.responseStatus <= 299; }
return this.responseStatus >= 200 && this.responseStatus <= 299;
public boolean isSuccessStatusCode() { return this.statusCode >= 200 && this.statusCode <= 299; }
class type for which deserialization is needed. * * @return TransactionalBatchOperationResult containing the individual result of operation. */ public <T> TransactionalBatchOperationResult<T> getOperationResultAtIndex( final int index, final Class<T> type) { checkArgument(index >= 0, "expected non-negative index"); checkNotNull(type, "expected non-null type"); final TransactionalBatchOperationResult<?> result = this.results.get(index); T item = null; if (result.getResourceObject() != null) { item = new JsonSerializable(result.getResourceObject()).toObject(type); } return new TransactionalBatchOperationResult<T>(result, item); }
class TransactionalBatchResponse { private final Map<String, String> responseHeaders; private final int statusCode; private final String errorMessage; private final List<TransactionalBatchOperationResult> results; private final int subStatusCode; private final CosmosDiagnostics cosmosDiagnostics; /** * Initializes a new instance of the {@link TransactionalBatchResponse} class. * * @param statusCode the response status code. * @param subStatusCode the response sub-status code. * @param errorMessage an error message or {@code null}. * @param responseHeaders the response http headers * @param cosmosDiagnostics the diagnostic */ TransactionalBatchResponse( final int statusCode, final int subStatusCode, final String errorMessage, final Map<String, String> responseHeaders, final CosmosDiagnostics cosmosDiagnostics) { checkNotNull(statusCode, "expected non-null statusCode"); checkNotNull(responseHeaders, "expected non-null responseHeaders"); this.statusCode = statusCode; this.subStatusCode = subStatusCode; this.errorMessage = errorMessage; this.responseHeaders = responseHeaders; this.cosmosDiagnostics = cosmosDiagnostics; this.results = new ArrayList<>(); } /** * Gets the diagnostics information for the current request to Azure Cosmos DB service. * * @return diagnostics information for the current request to Azure Cosmos DB service. */ public CosmosDiagnostics getDiagnostics() { return cosmosDiagnostics; } /** * Gets the number of operation results. * * @return the number of operations results in this response. */ public int size() { return this.results == null ? 0 : this.results.size(); } /** * Returns a value indicating whether the batch was successfully processed. * * @return a value indicating whether the batch was successfully processed. */ /** * Gets the activity ID that identifies the server request made to execute the batch. * * @return the activity ID that identifies the server request made to execute the batch. */ public String getActivityId() { return BatchExecUtils.getActivityId(this.responseHeaders); } /** * Gets the reason for the failure of the batch request, if any, or {@code null}. * * @return the reason for the failure of the batch request, if any, or {@code null}. */ public String getErrorMessage() { return this.errorMessage; } /** * Gets the request charge as request units (RU) consumed by the batch operation. * <p> * For more information about the RU and factors that can impact the effective charges please visit * <a href="https: * * @return the request charge. */ public double getRequestCharge() { return BatchExecUtils.getRequestCharge(this.responseHeaders); } /** * Gets the HTTP status code associated with the response. * * @return the status code. */ public int getStatusCode() { return this.statusCode; } /** * Gets the token used for managing client's consistency requirements. * * @return the session token. */ public String getSessionToken() { return BatchExecUtils.getSessionToken(this.responseHeaders); } /** * Gets the headers associated with the response. * * @return the response headers. */ public Map<String, String> getResponseHeaders() { return this.responseHeaders; } /** * Gets the amount of time to wait before retrying this or any other request due to throttling. * * @return the amount of time to wait before retrying this or any other request due to throttling. */ public Duration getRetryAfterDuration() { return BatchExecUtils.getRetryAfterDuration(this.responseHeaders); } /** * Gets the HTTP sub status code associated with the response. * * @return the sub status code. */ public int getSubStatusCode() { return this.subStatusCode; } /** * Get all the results of the operations in a batch in an unmodifiable instance so no one can * change it in the down path. * * @return Results of operations in a batch. */ public List<TransactionalBatchOperationResult> getResults() { return Collections.unmodifiableList(this.results); } /** * Gets the end-to-end request latency for the current request to Azure Cosmos DB service. * * @return end-to-end request latency for the current request to Azure Cosmos DB service. */ public Duration getDuration() { if (cosmosDiagnostics == null) { return Duration.ZERO; } return this.cosmosDiagnostics.getDuration(); } void addAll(List<? extends TransactionalBatchOperationResult> collection) { this.results.addAll(collection); } }
As discussed, user failure will have no exception. So it make sense to keep a function for checking if it succeeded.
public boolean isSuccessStatusCode() { return this.responseStatus >= 200 && this.responseStatus <= 299; }
return this.responseStatus >= 200 && this.responseStatus <= 299;
public boolean isSuccessStatusCode() { return this.statusCode >= 200 && this.statusCode <= 299; }
class type for which deserialization is needed. * * @return TransactionalBatchOperationResult containing the individual result of operation. */ public <T> TransactionalBatchOperationResult<T> getOperationResultAtIndex( final int index, final Class<T> type) { checkArgument(index >= 0, "expected non-negative index"); checkNotNull(type, "expected non-null type"); final TransactionalBatchOperationResult<?> result = this.results.get(index); T item = null; if (result.getResourceObject() != null) { item = new JsonSerializable(result.getResourceObject()).toObject(type); } return new TransactionalBatchOperationResult<T>(result, item); }
class TransactionalBatchResponse { private final Map<String, String> responseHeaders; private final int statusCode; private final String errorMessage; private final List<TransactionalBatchOperationResult> results; private final int subStatusCode; private final CosmosDiagnostics cosmosDiagnostics; /** * Initializes a new instance of the {@link TransactionalBatchResponse} class. * * @param statusCode the response status code. * @param subStatusCode the response sub-status code. * @param errorMessage an error message or {@code null}. * @param responseHeaders the response http headers * @param cosmosDiagnostics the diagnostic */ TransactionalBatchResponse( final int statusCode, final int subStatusCode, final String errorMessage, final Map<String, String> responseHeaders, final CosmosDiagnostics cosmosDiagnostics) { checkNotNull(statusCode, "expected non-null statusCode"); checkNotNull(responseHeaders, "expected non-null responseHeaders"); this.statusCode = statusCode; this.subStatusCode = subStatusCode; this.errorMessage = errorMessage; this.responseHeaders = responseHeaders; this.cosmosDiagnostics = cosmosDiagnostics; this.results = new ArrayList<>(); } /** * Gets the diagnostics information for the current request to Azure Cosmos DB service. * * @return diagnostics information for the current request to Azure Cosmos DB service. */ public CosmosDiagnostics getDiagnostics() { return cosmosDiagnostics; } /** * Gets the number of operation results. * * @return the number of operations results in this response. */ public int size() { return this.results == null ? 0 : this.results.size(); } /** * Returns a value indicating whether the batch was successfully processed. * * @return a value indicating whether the batch was successfully processed. */ /** * Gets the activity ID that identifies the server request made to execute the batch. * * @return the activity ID that identifies the server request made to execute the batch. */ public String getActivityId() { return BatchExecUtils.getActivityId(this.responseHeaders); } /** * Gets the reason for the failure of the batch request, if any, or {@code null}. * * @return the reason for the failure of the batch request, if any, or {@code null}. */ public String getErrorMessage() { return this.errorMessage; } /** * Gets the request charge as request units (RU) consumed by the batch operation. * <p> * For more information about the RU and factors that can impact the effective charges please visit * <a href="https: * * @return the request charge. */ public double getRequestCharge() { return BatchExecUtils.getRequestCharge(this.responseHeaders); } /** * Gets the HTTP status code associated with the response. * * @return the status code. */ public int getStatusCode() { return this.statusCode; } /** * Gets the token used for managing client's consistency requirements. * * @return the session token. */ public String getSessionToken() { return BatchExecUtils.getSessionToken(this.responseHeaders); } /** * Gets the headers associated with the response. * * @return the response headers. */ public Map<String, String> getResponseHeaders() { return this.responseHeaders; } /** * Gets the amount of time to wait before retrying this or any other request due to throttling. * * @return the amount of time to wait before retrying this or any other request due to throttling. */ public Duration getRetryAfterDuration() { return BatchExecUtils.getRetryAfterDuration(this.responseHeaders); } /** * Gets the HTTP sub status code associated with the response. * * @return the sub status code. */ public int getSubStatusCode() { return this.subStatusCode; } /** * Get all the results of the operations in a batch in an unmodifiable instance so no one can * change it in the down path. * * @return Results of operations in a batch. */ public List<TransactionalBatchOperationResult> getResults() { return Collections.unmodifiableList(this.results); } /** * Gets the end-to-end request latency for the current request to Azure Cosmos DB service. * * @return end-to-end request latency for the current request to Azure Cosmos DB service. */ public Duration getDuration() { if (cosmosDiagnostics == null) { return Duration.ZERO; } return this.cosmosDiagnostics.getDuration(); } void addAll(List<? extends TransactionalBatchOperationResult> collection) { this.results.addAll(collection); } }
very good test :-) thanks.
public void batchInvalidSessionToken() throws Exception { CosmosAsyncContainer container = batchAsyncContainer; this.createJsonTestDocs(container); CosmosItemResponse<TestDoc> readResponse = container.readItem( this.TestDocPk1ExistingC.getId(), this.getPartitionKey(this.partitionKey1), TestDoc.class).block(); assertThat(readResponse.getStatusCode()).isEqualTo(HttpResponseStatus.OK.code()); String invalidSessionToken = this.getDifferentLSNToken(readResponse.getSessionToken(), 2000); { TestDoc testDocToCreate = this.populateTestDoc(this.partitionKey1); TestDoc testDocToReplace = this.getTestDocCopy(this.TestDocPk1ExistingA); testDocToReplace.setCost(testDocToReplace.getCost() + 1); TestDoc testDocToUpsert = this.populateTestDoc(this.partitionKey1); TransactionalBatchResponse batchResponse = container.executeTransactionalBatch( TransactionalBatch.createTransactionalBatch(this.getPartitionKey(this.partitionKey1)) .createItem(testDocToCreate) .replaceItem(testDocToReplace.getId(), testDocToReplace) .upsertItem(testDocToUpsert) .deleteItem(this.TestDocPk1ExistingC.getId()), new TransactionalBatchRequestOptions().setSessionToken(invalidSessionToken)).block(); this.verifyBatchProcessed(batchResponse, 4); assertThat(batchResponse.get(0).getStatusCode()).isEqualTo(HttpResponseStatus.CREATED.code()); assertThat(batchResponse.get(1).getStatusCode()).isEqualTo(HttpResponseStatus.OK.code()); assertThat(batchResponse.get(2).getStatusCode()).isEqualTo(HttpResponseStatus.CREATED.code()); assertThat(batchResponse.get(3).getStatusCode()).isEqualTo(HttpResponseStatus.NO_CONTENT.code()); } { TestDoc testDocToCreate = this.populateTestDoc(this.partitionKey1); TestDoc testDocToReplace = this.getTestDocCopy(this.TestDocPk1ExistingB); testDocToReplace.setCost(testDocToReplace.getCost() + 1); TestDoc testDocToUpsert = this.populateTestDoc(this.partitionKey1); try { container.executeTransactionalBatch( TransactionalBatch.createTransactionalBatch(this.getPartitionKey(this.partitionKey1)) .createItem(testDocToCreate) .replaceItem(testDocToReplace.getId(), testDocToReplace) .upsertItem(testDocToUpsert) .deleteItem(this.TestDocPk1ExistingD.getId()) .readItem(this.TestDocPk1ExistingA.getId()), new TransactionalBatchRequestOptions().setSessionToken(invalidSessionToken)).block(); Assertions.fail("Should throw NOT_FOUND/READ_SESSION_NOT_AVAILABLE exception"); } catch (CosmosException ex) { assertThat(ex.getStatusCode()).isEqualTo(HttpResponseStatus.NOT_FOUND.code()); assertThat(ex.getSubStatusCode()).isEqualTo(HttpConstants.SubStatusCodes.READ_SESSION_NOT_AVAILABLE); } } }
Assertions.fail("Should throw NOT_FOUND/READ_SESSION_NOT_AVAILABLE exception");
public void batchInvalidSessionToken() throws Exception { CosmosAsyncContainer container = batchAsyncContainer; this.createJsonTestDocs(container); CosmosItemResponse<TestDoc> readResponse = container.readItem( this.TestDocPk1ExistingC.getId(), this.getPartitionKey(this.partitionKey1), TestDoc.class).block(); assertThat(readResponse.getStatusCode()).isEqualTo(HttpResponseStatus.OK.code()); String invalidSessionToken = this.getDifferentLSNToken(readResponse.getSessionToken(), 2000); { TestDoc testDocToCreate = this.populateTestDoc(this.partitionKey1); TestDoc testDocToReplace = this.getTestDocCopy(this.TestDocPk1ExistingA); testDocToReplace.setCost(testDocToReplace.getCost() + 1); TestDoc testDocToUpsert = this.populateTestDoc(this.partitionKey1); TransactionalBatch batch = TransactionalBatch.createTransactionalBatch(this.getPartitionKey(this.partitionKey1)); batch.createItemOperation(testDocToCreate); batch.replaceItemOperation(testDocToReplace.getId(), testDocToReplace); batch.upsertItemOperation(testDocToUpsert); batch.deleteItemOperation(this.TestDocPk1ExistingC.getId()); TransactionalBatchResponse batchResponse = container.executeTransactionalBatch( batch, new TransactionalBatchRequestOptions().setSessionToken(invalidSessionToken)).block(); this.verifyBatchProcessed(batchResponse, 4); assertThat(batchResponse.getResults().get(0).getStatusCode()).isEqualTo(HttpResponseStatus.CREATED.code()); assertThat(batchResponse.getResults().get(1).getStatusCode()).isEqualTo(HttpResponseStatus.OK.code()); assertThat(batchResponse.getResults().get(2).getStatusCode()).isEqualTo(HttpResponseStatus.CREATED.code()); assertThat(batchResponse.getResults().get(3).getStatusCode()).isEqualTo(HttpResponseStatus.NO_CONTENT.code()); List<CosmosItemOperation> batchOperations = batch.getOperations(); for (int index = 0; index < batchOperations.size(); index++) { assertThat(batchResponse.getResults().get(index).getOperation()).isEqualTo(batchOperations.get(index)); } } { TestDoc testDocToCreate = this.populateTestDoc(this.partitionKey1); TestDoc testDocToReplace = this.getTestDocCopy(this.TestDocPk1ExistingB); testDocToReplace.setCost(testDocToReplace.getCost() + 1); TestDoc testDocToUpsert = this.populateTestDoc(this.partitionKey1); TransactionalBatch batch = TransactionalBatch.createTransactionalBatch(this.getPartitionKey(this.partitionKey1)); batch.createItemOperation(testDocToCreate); batch.replaceItemOperation(testDocToReplace.getId(), testDocToReplace); batch.upsertItemOperation(testDocToUpsert); batch.deleteItemOperation(this.TestDocPk1ExistingD.getId()); batch.readItemOperation(this.TestDocPk1ExistingA.getId()); try { container.executeTransactionalBatch( batch, new TransactionalBatchRequestOptions().setSessionToken(invalidSessionToken)).block(); Assertions.fail("Should throw NOT_FOUND/READ_SESSION_NOT_AVAILABLE exception"); } catch (CosmosException ex) { assertThat(ex.getStatusCode()).isEqualTo(HttpResponseStatus.NOT_FOUND.code()); assertThat(ex.getSubStatusCode()).isEqualTo(HttpConstants.SubStatusCodes.READ_SESSION_NOT_AVAILABLE); } } }
class TransactionalBatchAsyncContainerTest extends BatchTestBase { private CosmosAsyncClient batchClient; private CosmosAsyncContainer batchAsyncContainer; @Factory(dataProvider = "clientBuildersWithDirectSession") public TransactionalBatchAsyncContainerTest(CosmosClientBuilder clientBuilder) { super(clientBuilder); } @BeforeClass(groups = {"simple"}, timeOut = SETUP_TIMEOUT) public void before_TransactionalBatchAsyncContainerTest() { assertThat(this.batchClient).isNull(); this.batchClient = getClientBuilder().buildAsyncClient(); batchAsyncContainer = getSharedMultiPartitionCosmosContainer(this.batchClient); } @AfterClass(groups = {"simple"}, timeOut = SHUTDOWN_TIMEOUT, alwaysRun = true) public void afterClass() { safeCloseAsync(this.batchClient); } @Test(groups = {"simple"}, timeOut = TIMEOUT) public void batchExecutionRepeat() { CosmosAsyncContainer container = this.batchAsyncContainer; this.createJsonTestDocs(container); TestDoc firstDoc = this.populateTestDoc(this.partitionKey1); TestDoc replaceDoc = this.getTestDocCopy(firstDoc); replaceDoc.setCost(replaceDoc.getCost() + 1); Mono<TransactionalBatchResponse> batchResponseMono = batchAsyncContainer.executeTransactionalBatch( TransactionalBatch.createTransactionalBatch(this.getPartitionKey(this.partitionKey1)) .createItem(firstDoc) .replaceItem(replaceDoc.getId(), replaceDoc)); TransactionalBatchResponse batchResponse1 = batchResponseMono.block(); this.verifyBatchProcessed(batchResponse1, 2); assertThat(batchResponse1.get(0).getStatusCode()).isEqualTo(HttpResponseStatus.CREATED.code()); assertThat(batchResponse1.get(1).getStatusCode()).isEqualTo(HttpResponseStatus.OK.code()); TransactionalBatchResponse batchResponse2 = batchResponseMono.block(); assertThat(batchResponse2.getStatusCode()).isEqualTo(HttpResponseStatus.CONFLICT.code()); assertThat(batchResponse2.get(0).getStatusCode()).isEqualTo(HttpResponseStatus.CONFLICT.code()); assertThat(batchResponse2.get(1).getStatusCode()).isEqualTo(HttpResponseStatus.FAILED_DEPENDENCY.code()); } @Test(groups = {"simple"}, timeOut = TIMEOUT * 100) }
class TransactionalBatchAsyncContainerTest extends BatchTestBase { private CosmosAsyncClient batchClient; private CosmosAsyncContainer batchAsyncContainer; @Factory(dataProvider = "clientBuildersWithDirectSession") public TransactionalBatchAsyncContainerTest(CosmosClientBuilder clientBuilder) { super(clientBuilder); } @BeforeClass(groups = {"simple"}, timeOut = SETUP_TIMEOUT) public void before_TransactionalBatchAsyncContainerTest() { assertThat(this.batchClient).isNull(); this.batchClient = getClientBuilder().buildAsyncClient(); batchAsyncContainer = getSharedMultiPartitionCosmosContainer(this.batchClient); } @AfterClass(groups = {"simple"}, timeOut = SHUTDOWN_TIMEOUT, alwaysRun = true) public void afterClass() { safeCloseAsync(this.batchClient); } @Test(groups = {"simple"}, timeOut = TIMEOUT) public void batchExecutionRepeat() { TestDoc firstDoc = this.populateTestDoc(this.partitionKey1); TestDoc replaceDoc = this.getTestDocCopy(firstDoc); replaceDoc.setCost(replaceDoc.getCost() + 1); TransactionalBatch batch = TransactionalBatch.createTransactionalBatch(this.getPartitionKey(this.partitionKey1)); batch.createItemOperation(firstDoc); batch.replaceItemOperation(replaceDoc.getId(), replaceDoc); Mono<TransactionalBatchResponse> batchResponseMono = batchAsyncContainer.executeTransactionalBatch(batch); TransactionalBatchResponse batchResponse1 = batchResponseMono.block(); this.verifyBatchProcessed(batchResponse1, 2); assertThat(batchResponse1.getResults().get(0).getStatusCode()).isEqualTo(HttpResponseStatus.CREATED.code()); assertThat(batchResponse1.getResults().get(1).getStatusCode()).isEqualTo(HttpResponseStatus.OK.code()); TransactionalBatchResponse batchResponse2 = batchResponseMono.block(); assertThat(batchResponse2.getStatusCode()).isEqualTo(HttpResponseStatus.CONFLICT.code()); assertThat(batchResponse2.getResults().get(0).getStatusCode()).isEqualTo(HttpResponseStatus.CONFLICT.code()); assertThat(batchResponse2.getResults().get(1).getStatusCode()).isEqualTo(HttpResponseStatus.FAILED_DEPENDENCY.code()); } @Test(groups = {"simple"}, timeOut = TIMEOUT * 100) }
Will multi-tenant application still function with this change?
private ClientRegistration azureClientRegistration() { String tenantId = aadAuthenticationProperties.getTenantId().trim(); Assert.hasText(tenantId, "azure.activedirectory.tenant-id should have text."); Assert.doesNotContain(tenantId, " ", "azure.activedirectory.tenant-id should not contain ' '."); Assert.doesNotContain(tenantId, "/", "azure.activedirectory.tenant-id should not contain '/'."); return ClientRegistration.withRegistrationId("azure") .clientId(aadAuthenticationProperties.getClientId()) .clientSecret(aadAuthenticationProperties.getClientSecret()) .clientAuthenticationMethod(ClientAuthenticationMethod.POST) .authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE) .redirectUriTemplate("{baseUrl}/login/oauth2/code/{registrationId}") .scope("openid", "https: .authorizationUri( String.format( "https: tenantId ) ) .tokenUri( String.format( "https: tenantId ) ) .userInfoUri("https: .userNameAttributeName(AADAccessTokenClaim.NAME) .jwkSetUri( String.format( "https: tenantId ) ) .clientName("Azure") .build(); }
return ClientRegistration.withRegistrationId("azure")
private ClientRegistration azureClientRegistration() { String tenantId = aadAuthenticationProperties.getTenantId().trim(); Assert.hasText(tenantId, "azure.activedirectory.tenant-id should have text."); Assert.doesNotContain(tenantId, " ", "azure.activedirectory.tenant-id should not contain ' '."); Assert.doesNotContain(tenantId, "/", "azure.activedirectory.tenant-id should not contain '/'."); return ClientRegistration.withRegistrationId("azure") .clientId(aadAuthenticationProperties.getClientId()) .clientSecret(aadAuthenticationProperties.getClientSecret()) .clientAuthenticationMethod(ClientAuthenticationMethod.POST) .authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE) .redirectUriTemplate("{baseUrl}/login/oauth2/code/{registrationId}") .scope(aadAuthenticationProperties.getScope()) .authorizationUri( String.format( "https: tenantId ) ) .tokenUri( String.format( "https: tenantId ) ) .userInfoUri("https: .userNameAttributeName(AADAccessTokenClaim.NAME) .jwkSetUri( String.format( "https: tenantId ) ) .clientName("Azure") .build(); }
class AADOAuth2AutoConfiguration { private final AADAuthenticationProperties aadAuthenticationProperties; private final ServiceEndpointsProperties serviceEndpointsProperties; public AADOAuth2AutoConfiguration(AADAuthenticationProperties aadAuthProperties, ServiceEndpointsProperties serviceEndpointsProperties) { this.aadAuthenticationProperties = aadAuthProperties; this.serviceEndpointsProperties = serviceEndpointsProperties; } @Bean @ConditionalOnProperty(prefix = "azure.activedirectory.user-group", value = "allowed-groups") public OAuth2UserService<OidcUserRequest, OidcUser> oidcUserService() { return new AADOAuth2UserService(aadAuthenticationProperties, serviceEndpointsProperties); } @Bean public ClientRegistrationRepository clientRegistrationRepository() { return new InMemoryClientRegistrationRepository(azureClientRegistration()); } @PostConstruct private void sendTelemetry() { if (aadAuthenticationProperties.isAllowTelemetry()) { final Map<String, String> events = new HashMap<>(); final TelemetrySender sender = new TelemetrySender(); events.put(SERVICE_NAME, getClassPackageSimpleName(AADOAuth2AutoConfiguration.class)); sender.send(ClassUtils.getUserClass(getClass()).getSimpleName(), events); } } }
class AADOAuth2AutoConfiguration { private final AADAuthenticationProperties aadAuthenticationProperties; private final ServiceEndpointsProperties serviceEndpointsProperties; public AADOAuth2AutoConfiguration(AADAuthenticationProperties aadAuthProperties, ServiceEndpointsProperties serviceEndpointsProperties) { this.aadAuthenticationProperties = aadAuthProperties; this.serviceEndpointsProperties = serviceEndpointsProperties; } @Bean @ConditionalOnProperty(prefix = "azure.activedirectory.user-group", value = "allowed-groups") public OAuth2UserService<OidcUserRequest, OidcUser> oidcUserService() { return new AADOAuth2UserService(aadAuthenticationProperties, serviceEndpointsProperties); } @Bean public ClientRegistrationRepository clientRegistrationRepository() { return new InMemoryClientRegistrationRepository(azureClientRegistration()); } @PostConstruct private void sendTelemetry() { if (aadAuthenticationProperties.isAllowTelemetry()) { final Map<String, String> events = new HashMap<>(); final TelemetrySender sender = new TelemetrySender(); events.put(SERVICE_NAME, getClassPackageSimpleName(AADOAuth2AutoConfiguration.class)); sender.send(ClassUtils.getUserClass(getClass()).getSimpleName(), events); } } }
IMU, if we set `azure.activedirectory.tenant-id=common`, then multi-tenant application will function.
private ClientRegistration azureClientRegistration() { String tenantId = aadAuthenticationProperties.getTenantId().trim(); Assert.hasText(tenantId, "azure.activedirectory.tenant-id should have text."); Assert.doesNotContain(tenantId, " ", "azure.activedirectory.tenant-id should not contain ' '."); Assert.doesNotContain(tenantId, "/", "azure.activedirectory.tenant-id should not contain '/'."); return ClientRegistration.withRegistrationId("azure") .clientId(aadAuthenticationProperties.getClientId()) .clientSecret(aadAuthenticationProperties.getClientSecret()) .clientAuthenticationMethod(ClientAuthenticationMethod.POST) .authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE) .redirectUriTemplate("{baseUrl}/login/oauth2/code/{registrationId}") .scope("openid", "https: .authorizationUri( String.format( "https: tenantId ) ) .tokenUri( String.format( "https: tenantId ) ) .userInfoUri("https: .userNameAttributeName(AADAccessTokenClaim.NAME) .jwkSetUri( String.format( "https: tenantId ) ) .clientName("Azure") .build(); }
return ClientRegistration.withRegistrationId("azure")
private ClientRegistration azureClientRegistration() { String tenantId = aadAuthenticationProperties.getTenantId().trim(); Assert.hasText(tenantId, "azure.activedirectory.tenant-id should have text."); Assert.doesNotContain(tenantId, " ", "azure.activedirectory.tenant-id should not contain ' '."); Assert.doesNotContain(tenantId, "/", "azure.activedirectory.tenant-id should not contain '/'."); return ClientRegistration.withRegistrationId("azure") .clientId(aadAuthenticationProperties.getClientId()) .clientSecret(aadAuthenticationProperties.getClientSecret()) .clientAuthenticationMethod(ClientAuthenticationMethod.POST) .authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE) .redirectUriTemplate("{baseUrl}/login/oauth2/code/{registrationId}") .scope(aadAuthenticationProperties.getScope()) .authorizationUri( String.format( "https: tenantId ) ) .tokenUri( String.format( "https: tenantId ) ) .userInfoUri("https: .userNameAttributeName(AADAccessTokenClaim.NAME) .jwkSetUri( String.format( "https: tenantId ) ) .clientName("Azure") .build(); }
class AADOAuth2AutoConfiguration { private final AADAuthenticationProperties aadAuthenticationProperties; private final ServiceEndpointsProperties serviceEndpointsProperties; public AADOAuth2AutoConfiguration(AADAuthenticationProperties aadAuthProperties, ServiceEndpointsProperties serviceEndpointsProperties) { this.aadAuthenticationProperties = aadAuthProperties; this.serviceEndpointsProperties = serviceEndpointsProperties; } @Bean @ConditionalOnProperty(prefix = "azure.activedirectory.user-group", value = "allowed-groups") public OAuth2UserService<OidcUserRequest, OidcUser> oidcUserService() { return new AADOAuth2UserService(aadAuthenticationProperties, serviceEndpointsProperties); } @Bean public ClientRegistrationRepository clientRegistrationRepository() { return new InMemoryClientRegistrationRepository(azureClientRegistration()); } @PostConstruct private void sendTelemetry() { if (aadAuthenticationProperties.isAllowTelemetry()) { final Map<String, String> events = new HashMap<>(); final TelemetrySender sender = new TelemetrySender(); events.put(SERVICE_NAME, getClassPackageSimpleName(AADOAuth2AutoConfiguration.class)); sender.send(ClassUtils.getUserClass(getClass()).getSimpleName(), events); } } }
class AADOAuth2AutoConfiguration { private final AADAuthenticationProperties aadAuthenticationProperties; private final ServiceEndpointsProperties serviceEndpointsProperties; public AADOAuth2AutoConfiguration(AADAuthenticationProperties aadAuthProperties, ServiceEndpointsProperties serviceEndpointsProperties) { this.aadAuthenticationProperties = aadAuthProperties; this.serviceEndpointsProperties = serviceEndpointsProperties; } @Bean @ConditionalOnProperty(prefix = "azure.activedirectory.user-group", value = "allowed-groups") public OAuth2UserService<OidcUserRequest, OidcUser> oidcUserService() { return new AADOAuth2UserService(aadAuthenticationProperties, serviceEndpointsProperties); } @Bean public ClientRegistrationRepository clientRegistrationRepository() { return new InMemoryClientRegistrationRepository(azureClientRegistration()); } @PostConstruct private void sendTelemetry() { if (aadAuthenticationProperties.isAllowTelemetry()) { final Map<String, String> events = new HashMap<>(); final TelemetrySender sender = new TelemetrySender(); events.put(SERVICE_NAME, getClassPackageSimpleName(AADOAuth2AutoConfiguration.class)); sender.send(ClassUtils.getUserClass(getClass()).getSimpleName(), events); } } }
The error message from Validation Util, won't be clear for user. I think, we should custom handle this with the error message "A certificate source as input stream or file path should be configured on the builder." We should also throw an exception, if both path and inputstream are configured.
public ClientCertificateCredential build() { ValidationUtil.validate(getClass().getSimpleName(), new HashMap<String, Object>() {{ put("clientId", clientId); put("tenantId", tenantId); put("clientCertificate", clientCertificate == null ? clientCertificatePath : clientCertificate); }}); return new ClientCertificateCredential(tenantId, clientId, clientCertificatePath, clientCertificate, clientCertificatePassword, identityClientOptions); }
put("clientCertificate", clientCertificate == null ? clientCertificatePath : clientCertificate);
public ClientCertificateCredential build() { ValidationUtil.validate(getClass().getSimpleName(), new HashMap<String, Object>() {{ put("clientId", clientId); put("tenantId", tenantId); put("clientCertificate", clientCertificate == null ? clientCertificatePath : clientCertificate); }}); if (clientCertificate != null && clientCertificatePath != null) { throw logger.logExceptionAsWarning(new IllegalArgumentException("Both certificate input stream and " + "certificate path are provided in ClientCertificateCredentialBuilder. Only one of them should " + "be provided.")); } return new ClientCertificateCredential(tenantId, clientId, clientCertificatePath, clientCertificate, clientCertificatePassword, identityClientOptions); }
class ClientCertificateCredentialBuilder extends AadCredentialBuilderBase<ClientCertificateCredentialBuilder> { private String clientCertificatePath; private InputStream clientCertificate; private String clientCertificatePassword; /** * Sets the client certificate for authenticating to AAD. * * @param certificatePath the PEM file containing the certificate * @return An updated instance of this builder. */ public ClientCertificateCredentialBuilder pemCertificate(String certificatePath) { ValidationUtil.validateFilePath(getClass().getSimpleName(), certificatePath, "Pem Certificate Path"); this.clientCertificatePath = certificatePath; return this; } /** * Sets the client certificate for authenticating to AAD. * * @param certificate the input stream containing the PEM certificate * @return An updated instance of this builder. */ public ClientCertificateCredentialBuilder pemCertificate(InputStream certificate) { this.clientCertificate = certificate; return this; } /** * Sets the client certificate for authenticating to AAD. * * @param certificatePath the password protected PFX file containing the certificate * @param clientCertificatePassword the password protecting the PFX file * @return An updated instance of this builder. */ public ClientCertificateCredentialBuilder pfxCertificate(String certificatePath, String clientCertificatePassword) { ValidationUtil.validateFilePath(getClass().getSimpleName(), certificatePath, "Pfx Certificate Path"); this.clientCertificatePath = certificatePath; this.clientCertificatePassword = clientCertificatePassword; return this; } /** * Sets the client certificate for authenticating to AAD. * * @param certificate the input stream containing the password protected PFX certificate * @param clientCertificatePassword the password protecting the PFX file * @return An updated instance of this builder. */ public ClientCertificateCredentialBuilder pfxCertificate(InputStream certificate, String clientCertificatePassword) { this.clientCertificate = certificate; this.clientCertificatePassword = clientCertificatePassword; return this; } /** * Allows to use an unprotected file specified by <code>cacheFileLocation()</code> instead of * Gnome keyring on Linux. This is restricted by default. * * @return An updated instance of this builder. */ public ClientCertificateCredentialBuilder allowUnencryptedCache() { this.identityClientOptions.setAllowUnencryptedCache(true); return this; } /** * Enables the shared token cache which is disabled by default. If enabled, the credential will store tokens * in a cache persisted to the machine, protected to the current user, which can be shared by other credentials * and processes. * * @return An updated instance of this builder. */ public ClientCertificateCredentialBuilder enablePersistentCache() { this.identityClientOptions.enablePersistentCache(); return this; } /** * Creates a new {@link ClientCertificateCredential} with the current configurations. * * @return a {@link ClientCertificateCredential} with the current configurations. */ }
class ClientCertificateCredentialBuilder extends AadCredentialBuilderBase<ClientCertificateCredentialBuilder> { private String clientCertificatePath; private InputStream clientCertificate; private String clientCertificatePassword; private final ClientLogger logger = new ClientLogger(ClientCertificateCredentialBuilder.class); /** * Sets the path of the PEM certificate for authenticating to AAD. * * @param certificatePath the PEM file containing the certificate * @return An updated instance of this builder. */ public ClientCertificateCredentialBuilder pemCertificate(String certificatePath) { ValidationUtil.validateFilePath(getClass().getSimpleName(), certificatePath, "Pem Certificate Path"); this.clientCertificatePath = certificatePath; return this; } /** * Sets the input stream holding the PEM certificate for authenticating to AAD. * * @param certificate the input stream containing the PEM certificate * @return An updated instance of this builder. */ public ClientCertificateCredentialBuilder pemCertificate(InputStream certificate) { this.clientCertificate = certificate; return this; } /** * Sets the path and password of the PFX certificate for authenticating to AAD. * * @param certificatePath the password protected PFX file containing the certificate * @param clientCertificatePassword the password protecting the PFX file * @return An updated instance of this builder. */ public ClientCertificateCredentialBuilder pfxCertificate(String certificatePath, String clientCertificatePassword) { ValidationUtil.validateFilePath(getClass().getSimpleName(), certificatePath, "Pfx Certificate Path"); this.clientCertificatePath = certificatePath; this.clientCertificatePassword = clientCertificatePassword; return this; } /** * Sets the input stream holding the PFX certificate and its password for authenticating to AAD. * * @param certificate the input stream containing the password protected PFX certificate * @param clientCertificatePassword the password protecting the PFX file * @return An updated instance of this builder. */ public ClientCertificateCredentialBuilder pfxCertificate(InputStream certificate, String clientCertificatePassword) { this.clientCertificate = certificate; this.clientCertificatePassword = clientCertificatePassword; return this; } /** * Allows to use an unprotected file specified by <code>cacheFileLocation()</code> instead of * Gnome keyring on Linux. This is restricted by default. * * @return An updated instance of this builder. */ public ClientCertificateCredentialBuilder allowUnencryptedCache() { this.identityClientOptions.setAllowUnencryptedCache(true); return this; } /** * Enables the shared token cache which is disabled by default. If enabled, the credential will store tokens * in a cache persisted to the machine, protected to the current user, which can be shared by other credentials * and processes. * * @return An updated instance of this builder. */ public ClientCertificateCredentialBuilder enablePersistentCache() { this.identityClientOptions.enablePersistentCache(); return this; } /** * Specifies if the x5c claim (public key of the certificate) should be sent as part of the authentication request * and enable subject name / issuer based authentication. The default value is false. * * @param includeX5c the flag to indicate if x5c should be sent as part of authentication request. * @return An updated instance of this builder. */ public ClientCertificateCredentialBuilder includeX5c(boolean includeX5c) { this.identityClientOptions.setIncludeX5c(includeX5c); return this; } /** * Creates a new {@link ClientCertificateCredential} with the current configurations. * * @return a {@link ClientCertificateCredential} with the current configurations. */ }
Changing the error message will break the current certificate path scenario - people may be depending on the error message.
public ClientCertificateCredential build() { ValidationUtil.validate(getClass().getSimpleName(), new HashMap<String, Object>() {{ put("clientId", clientId); put("tenantId", tenantId); put("clientCertificate", clientCertificate == null ? clientCertificatePath : clientCertificate); }}); return new ClientCertificateCredential(tenantId, clientId, clientCertificatePath, clientCertificate, clientCertificatePassword, identityClientOptions); }
put("clientCertificate", clientCertificate == null ? clientCertificatePath : clientCertificate);
public ClientCertificateCredential build() { ValidationUtil.validate(getClass().getSimpleName(), new HashMap<String, Object>() {{ put("clientId", clientId); put("tenantId", tenantId); put("clientCertificate", clientCertificate == null ? clientCertificatePath : clientCertificate); }}); if (clientCertificate != null && clientCertificatePath != null) { throw logger.logExceptionAsWarning(new IllegalArgumentException("Both certificate input stream and " + "certificate path are provided in ClientCertificateCredentialBuilder. Only one of them should " + "be provided.")); } return new ClientCertificateCredential(tenantId, clientId, clientCertificatePath, clientCertificate, clientCertificatePassword, identityClientOptions); }
class ClientCertificateCredentialBuilder extends AadCredentialBuilderBase<ClientCertificateCredentialBuilder> { private String clientCertificatePath; private InputStream clientCertificate; private String clientCertificatePassword; /** * Sets the client certificate for authenticating to AAD. * * @param certificatePath the PEM file containing the certificate * @return An updated instance of this builder. */ public ClientCertificateCredentialBuilder pemCertificate(String certificatePath) { ValidationUtil.validateFilePath(getClass().getSimpleName(), certificatePath, "Pem Certificate Path"); this.clientCertificatePath = certificatePath; return this; } /** * Sets the client certificate for authenticating to AAD. * * @param certificate the input stream containing the PEM certificate * @return An updated instance of this builder. */ public ClientCertificateCredentialBuilder pemCertificate(InputStream certificate) { this.clientCertificate = certificate; return this; } /** * Sets the client certificate for authenticating to AAD. * * @param certificatePath the password protected PFX file containing the certificate * @param clientCertificatePassword the password protecting the PFX file * @return An updated instance of this builder. */ public ClientCertificateCredentialBuilder pfxCertificate(String certificatePath, String clientCertificatePassword) { ValidationUtil.validateFilePath(getClass().getSimpleName(), certificatePath, "Pfx Certificate Path"); this.clientCertificatePath = certificatePath; this.clientCertificatePassword = clientCertificatePassword; return this; } /** * Sets the client certificate for authenticating to AAD. * * @param certificate the input stream containing the password protected PFX certificate * @param clientCertificatePassword the password protecting the PFX file * @return An updated instance of this builder. */ public ClientCertificateCredentialBuilder pfxCertificate(InputStream certificate, String clientCertificatePassword) { this.clientCertificate = certificate; this.clientCertificatePassword = clientCertificatePassword; return this; } /** * Allows to use an unprotected file specified by <code>cacheFileLocation()</code> instead of * Gnome keyring on Linux. This is restricted by default. * * @return An updated instance of this builder. */ public ClientCertificateCredentialBuilder allowUnencryptedCache() { this.identityClientOptions.setAllowUnencryptedCache(true); return this; } /** * Enables the shared token cache which is disabled by default. If enabled, the credential will store tokens * in a cache persisted to the machine, protected to the current user, which can be shared by other credentials * and processes. * * @return An updated instance of this builder. */ public ClientCertificateCredentialBuilder enablePersistentCache() { this.identityClientOptions.enablePersistentCache(); return this; } /** * Creates a new {@link ClientCertificateCredential} with the current configurations. * * @return a {@link ClientCertificateCredential} with the current configurations. */ }
class ClientCertificateCredentialBuilder extends AadCredentialBuilderBase<ClientCertificateCredentialBuilder> { private String clientCertificatePath; private InputStream clientCertificate; private String clientCertificatePassword; private final ClientLogger logger = new ClientLogger(ClientCertificateCredentialBuilder.class); /** * Sets the path of the PEM certificate for authenticating to AAD. * * @param certificatePath the PEM file containing the certificate * @return An updated instance of this builder. */ public ClientCertificateCredentialBuilder pemCertificate(String certificatePath) { ValidationUtil.validateFilePath(getClass().getSimpleName(), certificatePath, "Pem Certificate Path"); this.clientCertificatePath = certificatePath; return this; } /** * Sets the input stream holding the PEM certificate for authenticating to AAD. * * @param certificate the input stream containing the PEM certificate * @return An updated instance of this builder. */ public ClientCertificateCredentialBuilder pemCertificate(InputStream certificate) { this.clientCertificate = certificate; return this; } /** * Sets the path and password of the PFX certificate for authenticating to AAD. * * @param certificatePath the password protected PFX file containing the certificate * @param clientCertificatePassword the password protecting the PFX file * @return An updated instance of this builder. */ public ClientCertificateCredentialBuilder pfxCertificate(String certificatePath, String clientCertificatePassword) { ValidationUtil.validateFilePath(getClass().getSimpleName(), certificatePath, "Pfx Certificate Path"); this.clientCertificatePath = certificatePath; this.clientCertificatePassword = clientCertificatePassword; return this; } /** * Sets the input stream holding the PFX certificate and its password for authenticating to AAD. * * @param certificate the input stream containing the password protected PFX certificate * @param clientCertificatePassword the password protecting the PFX file * @return An updated instance of this builder. */ public ClientCertificateCredentialBuilder pfxCertificate(InputStream certificate, String clientCertificatePassword) { this.clientCertificate = certificate; this.clientCertificatePassword = clientCertificatePassword; return this; } /** * Allows to use an unprotected file specified by <code>cacheFileLocation()</code> instead of * Gnome keyring on Linux. This is restricted by default. * * @return An updated instance of this builder. */ public ClientCertificateCredentialBuilder allowUnencryptedCache() { this.identityClientOptions.setAllowUnencryptedCache(true); return this; } /** * Enables the shared token cache which is disabled by default. If enabled, the credential will store tokens * in a cache persisted to the machine, protected to the current user, which can be shared by other credentials * and processes. * * @return An updated instance of this builder. */ public ClientCertificateCredentialBuilder enablePersistentCache() { this.identityClientOptions.enablePersistentCache(); return this; } /** * Specifies if the x5c claim (public key of the certificate) should be sent as part of the authentication request * and enable subject name / issuer based authentication. The default value is false. * * @param includeX5c the flag to indicate if x5c should be sent as part of authentication request. * @return An updated instance of this builder. */ public ClientCertificateCredentialBuilder includeX5c(boolean includeX5c) { this.identityClientOptions.setIncludeX5c(includeX5c); return this; } /** * Creates a new {@link ClientCertificateCredential} with the current configurations. * * @return a {@link ClientCertificateCredential} with the current configurations. */ }
okay, then we should atleast add an additive check for the scenario and throw an exception if both path and inputstream are configured.
public ClientCertificateCredential build() { ValidationUtil.validate(getClass().getSimpleName(), new HashMap<String, Object>() {{ put("clientId", clientId); put("tenantId", tenantId); put("clientCertificate", clientCertificate == null ? clientCertificatePath : clientCertificate); }}); return new ClientCertificateCredential(tenantId, clientId, clientCertificatePath, clientCertificate, clientCertificatePassword, identityClientOptions); }
put("clientCertificate", clientCertificate == null ? clientCertificatePath : clientCertificate);
public ClientCertificateCredential build() { ValidationUtil.validate(getClass().getSimpleName(), new HashMap<String, Object>() {{ put("clientId", clientId); put("tenantId", tenantId); put("clientCertificate", clientCertificate == null ? clientCertificatePath : clientCertificate); }}); if (clientCertificate != null && clientCertificatePath != null) { throw logger.logExceptionAsWarning(new IllegalArgumentException("Both certificate input stream and " + "certificate path are provided in ClientCertificateCredentialBuilder. Only one of them should " + "be provided.")); } return new ClientCertificateCredential(tenantId, clientId, clientCertificatePath, clientCertificate, clientCertificatePassword, identityClientOptions); }
class ClientCertificateCredentialBuilder extends AadCredentialBuilderBase<ClientCertificateCredentialBuilder> { private String clientCertificatePath; private InputStream clientCertificate; private String clientCertificatePassword; /** * Sets the client certificate for authenticating to AAD. * * @param certificatePath the PEM file containing the certificate * @return An updated instance of this builder. */ public ClientCertificateCredentialBuilder pemCertificate(String certificatePath) { ValidationUtil.validateFilePath(getClass().getSimpleName(), certificatePath, "Pem Certificate Path"); this.clientCertificatePath = certificatePath; return this; } /** * Sets the client certificate for authenticating to AAD. * * @param certificate the input stream containing the PEM certificate * @return An updated instance of this builder. */ public ClientCertificateCredentialBuilder pemCertificate(InputStream certificate) { this.clientCertificate = certificate; return this; } /** * Sets the client certificate for authenticating to AAD. * * @param certificatePath the password protected PFX file containing the certificate * @param clientCertificatePassword the password protecting the PFX file * @return An updated instance of this builder. */ public ClientCertificateCredentialBuilder pfxCertificate(String certificatePath, String clientCertificatePassword) { ValidationUtil.validateFilePath(getClass().getSimpleName(), certificatePath, "Pfx Certificate Path"); this.clientCertificatePath = certificatePath; this.clientCertificatePassword = clientCertificatePassword; return this; } /** * Sets the client certificate for authenticating to AAD. * * @param certificate the input stream containing the password protected PFX certificate * @param clientCertificatePassword the password protecting the PFX file * @return An updated instance of this builder. */ public ClientCertificateCredentialBuilder pfxCertificate(InputStream certificate, String clientCertificatePassword) { this.clientCertificate = certificate; this.clientCertificatePassword = clientCertificatePassword; return this; } /** * Allows to use an unprotected file specified by <code>cacheFileLocation()</code> instead of * Gnome keyring on Linux. This is restricted by default. * * @return An updated instance of this builder. */ public ClientCertificateCredentialBuilder allowUnencryptedCache() { this.identityClientOptions.setAllowUnencryptedCache(true); return this; } /** * Enables the shared token cache which is disabled by default. If enabled, the credential will store tokens * in a cache persisted to the machine, protected to the current user, which can be shared by other credentials * and processes. * * @return An updated instance of this builder. */ public ClientCertificateCredentialBuilder enablePersistentCache() { this.identityClientOptions.enablePersistentCache(); return this; } /** * Creates a new {@link ClientCertificateCredential} with the current configurations. * * @return a {@link ClientCertificateCredential} with the current configurations. */ }
class ClientCertificateCredentialBuilder extends AadCredentialBuilderBase<ClientCertificateCredentialBuilder> { private String clientCertificatePath; private InputStream clientCertificate; private String clientCertificatePassword; private final ClientLogger logger = new ClientLogger(ClientCertificateCredentialBuilder.class); /** * Sets the path of the PEM certificate for authenticating to AAD. * * @param certificatePath the PEM file containing the certificate * @return An updated instance of this builder. */ public ClientCertificateCredentialBuilder pemCertificate(String certificatePath) { ValidationUtil.validateFilePath(getClass().getSimpleName(), certificatePath, "Pem Certificate Path"); this.clientCertificatePath = certificatePath; return this; } /** * Sets the input stream holding the PEM certificate for authenticating to AAD. * * @param certificate the input stream containing the PEM certificate * @return An updated instance of this builder. */ public ClientCertificateCredentialBuilder pemCertificate(InputStream certificate) { this.clientCertificate = certificate; return this; } /** * Sets the path and password of the PFX certificate for authenticating to AAD. * * @param certificatePath the password protected PFX file containing the certificate * @param clientCertificatePassword the password protecting the PFX file * @return An updated instance of this builder. */ public ClientCertificateCredentialBuilder pfxCertificate(String certificatePath, String clientCertificatePassword) { ValidationUtil.validateFilePath(getClass().getSimpleName(), certificatePath, "Pfx Certificate Path"); this.clientCertificatePath = certificatePath; this.clientCertificatePassword = clientCertificatePassword; return this; } /** * Sets the input stream holding the PFX certificate and its password for authenticating to AAD. * * @param certificate the input stream containing the password protected PFX certificate * @param clientCertificatePassword the password protecting the PFX file * @return An updated instance of this builder. */ public ClientCertificateCredentialBuilder pfxCertificate(InputStream certificate, String clientCertificatePassword) { this.clientCertificate = certificate; this.clientCertificatePassword = clientCertificatePassword; return this; } /** * Allows to use an unprotected file specified by <code>cacheFileLocation()</code> instead of * Gnome keyring on Linux. This is restricted by default. * * @return An updated instance of this builder. */ public ClientCertificateCredentialBuilder allowUnencryptedCache() { this.identityClientOptions.setAllowUnencryptedCache(true); return this; } /** * Enables the shared token cache which is disabled by default. If enabled, the credential will store tokens * in a cache persisted to the machine, protected to the current user, which can be shared by other credentials * and processes. * * @return An updated instance of this builder. */ public ClientCertificateCredentialBuilder enablePersistentCache() { this.identityClientOptions.enablePersistentCache(); return this; } /** * Specifies if the x5c claim (public key of the certificate) should be sent as part of the authentication request * and enable subject name / issuer based authentication. The default value is false. * * @param includeX5c the flag to indicate if x5c should be sent as part of authentication request. * @return An updated instance of this builder. */ public ClientCertificateCredentialBuilder includeX5c(boolean includeX5c) { this.identityClientOptions.setIncludeX5c(includeX5c); return this; } /** * Creates a new {@link ClientCertificateCredential} with the current configurations. * * @return a {@link ClientCertificateCredential} with the current configurations. */ }
If we are doing this, then maybe the `ClientCertificateCredential` constructor should only have the input stream arg. If the path is given, the builder can wrap the path with `FileInputStream` and create the credential instance. This saves multiple `if-else` checks in `ClientCertificateCredential`.
public ClientCertificateCredential build() { ValidationUtil.validate(getClass().getSimpleName(), new HashMap<String, Object>() {{ put("clientId", clientId); put("tenantId", tenantId); put("clientCertificate", clientCertificate == null ? clientCertificatePath : clientCertificate); }}); if (clientCertificate != null && clientCertificatePath != null) { throw logger.logExceptionAsWarning(new IllegalArgumentException("Both certificate input stream and " + "certificate path are provided in ClientCertificateCredentialBuilder. Only one of them should " + "be provided.")); } return new ClientCertificateCredential(tenantId, clientId, clientCertificatePath, clientCertificate, clientCertificatePassword, identityClientOptions); }
}
public ClientCertificateCredential build() { ValidationUtil.validate(getClass().getSimpleName(), new HashMap<String, Object>() {{ put("clientId", clientId); put("tenantId", tenantId); put("clientCertificate", clientCertificate == null ? clientCertificatePath : clientCertificate); }}); if (clientCertificate != null && clientCertificatePath != null) { throw logger.logExceptionAsWarning(new IllegalArgumentException("Both certificate input stream and " + "certificate path are provided in ClientCertificateCredentialBuilder. Only one of them should " + "be provided.")); } return new ClientCertificateCredential(tenantId, clientId, clientCertificatePath, clientCertificate, clientCertificatePassword, identityClientOptions); }
class ClientCertificateCredentialBuilder extends AadCredentialBuilderBase<ClientCertificateCredentialBuilder> { private String clientCertificatePath; private InputStream clientCertificate; private String clientCertificatePassword; private final ClientLogger logger = new ClientLogger(ClientCertificateCredentialBuilder.class); /** * Sets the path of the PEM certificate for authenticating to AAD. * * @param certificatePath the PEM file containing the certificate * @return An updated instance of this builder. */ public ClientCertificateCredentialBuilder pemCertificate(String certificatePath) { ValidationUtil.validateFilePath(getClass().getSimpleName(), certificatePath, "Pem Certificate Path"); this.clientCertificatePath = certificatePath; return this; } /** * Sets the input stream holding the PEM certificate for authenticating to AAD. * * @param certificate the input stream containing the PEM certificate * @return An updated instance of this builder. */ public ClientCertificateCredentialBuilder pemCertificate(InputStream certificate) { this.clientCertificate = certificate; return this; } /** * Sets the path and password of the PFX certificate for authenticating to AAD. * * @param certificatePath the password protected PFX file containing the certificate * @param clientCertificatePassword the password protecting the PFX file * @return An updated instance of this builder. */ public ClientCertificateCredentialBuilder pfxCertificate(String certificatePath, String clientCertificatePassword) { ValidationUtil.validateFilePath(getClass().getSimpleName(), certificatePath, "Pfx Certificate Path"); this.clientCertificatePath = certificatePath; this.clientCertificatePassword = clientCertificatePassword; return this; } /** * Sets the input stream holding the PFX certificate and its password for authenticating to AAD. * * @param certificate the input stream containing the password protected PFX certificate * @param clientCertificatePassword the password protecting the PFX file * @return An updated instance of this builder. */ public ClientCertificateCredentialBuilder pfxCertificate(InputStream certificate, String clientCertificatePassword) { this.clientCertificate = certificate; this.clientCertificatePassword = clientCertificatePassword; return this; } /** * Allows to use an unprotected file specified by <code>cacheFileLocation()</code> instead of * Gnome keyring on Linux. This is restricted by default. * * @return An updated instance of this builder. */ public ClientCertificateCredentialBuilder allowUnencryptedCache() { this.identityClientOptions.setAllowUnencryptedCache(true); return this; } /** * Enables the shared token cache which is disabled by default. If enabled, the credential will store tokens * in a cache persisted to the machine, protected to the current user, which can be shared by other credentials * and processes. * * @return An updated instance of this builder. */ public ClientCertificateCredentialBuilder enablePersistentCache() { this.identityClientOptions.enablePersistentCache(); return this; } /** * Specifies if the x5c claim (public key of the certificate) should be sent as part of the authentication request * and enable subject name / issuer based authentication. The default value is false. * * @param includeX5c the flag to indicate if x5c should be sent as part of authentication request. * @return An updated instance of this builder. */ public ClientCertificateCredentialBuilder includeX5c(boolean includeX5c) { this.identityClientOptions.setIncludeX5c(includeX5c); return this; } /** * Creates a new {@link ClientCertificateCredential} with the current configurations. * * @return a {@link ClientCertificateCredential} with the current configurations. */ }
class ClientCertificateCredentialBuilder extends AadCredentialBuilderBase<ClientCertificateCredentialBuilder> { private String clientCertificatePath; private InputStream clientCertificate; private String clientCertificatePassword; private final ClientLogger logger = new ClientLogger(ClientCertificateCredentialBuilder.class); /** * Sets the path of the PEM certificate for authenticating to AAD. * * @param certificatePath the PEM file containing the certificate * @return An updated instance of this builder. */ public ClientCertificateCredentialBuilder pemCertificate(String certificatePath) { ValidationUtil.validateFilePath(getClass().getSimpleName(), certificatePath, "Pem Certificate Path"); this.clientCertificatePath = certificatePath; return this; } /** * Sets the input stream holding the PEM certificate for authenticating to AAD. * * @param certificate the input stream containing the PEM certificate * @return An updated instance of this builder. */ public ClientCertificateCredentialBuilder pemCertificate(InputStream certificate) { this.clientCertificate = certificate; return this; } /** * Sets the path and password of the PFX certificate for authenticating to AAD. * * @param certificatePath the password protected PFX file containing the certificate * @param clientCertificatePassword the password protecting the PFX file * @return An updated instance of this builder. */ public ClientCertificateCredentialBuilder pfxCertificate(String certificatePath, String clientCertificatePassword) { ValidationUtil.validateFilePath(getClass().getSimpleName(), certificatePath, "Pfx Certificate Path"); this.clientCertificatePath = certificatePath; this.clientCertificatePassword = clientCertificatePassword; return this; } /** * Sets the input stream holding the PFX certificate and its password for authenticating to AAD. * * @param certificate the input stream containing the password protected PFX certificate * @param clientCertificatePassword the password protecting the PFX file * @return An updated instance of this builder. */ public ClientCertificateCredentialBuilder pfxCertificate(InputStream certificate, String clientCertificatePassword) { this.clientCertificate = certificate; this.clientCertificatePassword = clientCertificatePassword; return this; } /** * Allows to use an unprotected file specified by <code>cacheFileLocation()</code> instead of * Gnome keyring on Linux. This is restricted by default. * * @return An updated instance of this builder. */ public ClientCertificateCredentialBuilder allowUnencryptedCache() { this.identityClientOptions.setAllowUnencryptedCache(true); return this; } /** * Enables the shared token cache which is disabled by default. If enabled, the credential will store tokens * in a cache persisted to the machine, protected to the current user, which can be shared by other credentials * and processes. * * @return An updated instance of this builder. */ public ClientCertificateCredentialBuilder enablePersistentCache() { this.identityClientOptions.enablePersistentCache(); return this; } /** * Specifies if the x5c claim (public key of the certificate) should be sent as part of the authentication request * and enable subject name / issuer based authentication. The default value is false. * * @param includeX5c the flag to indicate if x5c should be sent as part of authentication request. * @return An updated instance of this builder. */ public ClientCertificateCredentialBuilder includeX5c(boolean includeX5c) { this.identityClientOptions.setIncludeX5c(includeX5c); return this; } /** * Creates a new {@link ClientCertificateCredential} with the current configurations. * * @return a {@link ClientCertificateCredential} with the current configurations. */ }
Can we could add some documentation around this method. I get 3 is because it's get, but 2 because `is`?
static void setPropertiesFromGetters(TableEntity entity, ClientLogger logger) { Class<?> myClass = entity.getClass(); if (myClass == TableEntity.class) { return; } for (Method m : myClass.getMethods()) { if (m.getName().length() < 3 || TABLE_ENTITY_METHODS.contains(m.getName()) || (!m.getName().startsWith("get") && !m.getName().startsWith("is")) || m.getParameterTypes().length != 0 || void.class.equals(m.getReturnType())) { continue; } int prefixLength = m.getName().startsWith("get") ? 3 : 2; String propName = m.getName().substring(prefixLength); try { entity.getProperties().put(propName, m.invoke(entity)); } catch (ReflectiveOperationException | IllegalArgumentException e) { logger.logThrowableAsWarning(new ReflectiveOperationException(String.format( "Failed to get property '%s' on type '%s'", propName, myClass.getName()), e)); } } }
int prefixLength = m.getName().startsWith("get") ? 3 : 2;
static void setPropertiesFromGetters(TableEntity entity, ClientLogger logger) { Class<?> myClass = entity.getClass(); if (myClass == TableEntity.class) { return; } for (Method m : myClass.getMethods()) { if (m.getName().length() < 3 || TABLE_ENTITY_METHODS.contains(m.getName()) || (!m.getName().startsWith("get") && !m.getName().startsWith("is")) || m.getParameterTypes().length != 0 || void.class.equals(m.getReturnType())) { continue; } if (m.getName().startsWith("is") && m.getReturnType() != Boolean.class && m.getReturnType() != boolean.class) { continue; } int prefixLength = m.getName().startsWith("is") ? 2 : 3; String propName = m.getName().substring(prefixLength); try { entity.getProperties().put(propName, m.invoke(entity)); } catch (ReflectiveOperationException | IllegalArgumentException e) { logger.logThrowableAsWarning(new ReflectiveOperationException(String.format( "Failed to get property '%s' on type '%s'", propName, myClass.getName()), e)); } } }
class EntityHelper { private static final HashSet<String> TABLE_ENTITY_METHODS = Arrays.stream(TableEntity.class.getMethods()) .map(Method::getName).collect(Collectors.toCollection(HashSet::new)); private EntityHelper() { } @SuppressWarnings("unchecked") static <T extends TableEntity> T convertToSubclass(TableEntity entity, Class<T> clazz, ClientLogger logger) { if (TableEntity.class == clazz) { return (T) entity; } T result; try { result = clazz.getDeclaredConstructor(String.class, String.class).newInstance(entity.getPartitionKey(), entity.getRowKey()); } catch (ReflectiveOperationException | SecurityException e) { logger.logThrowableAsWarning(new ReflectiveOperationException(String.format( "Failed to instantiate type '%s'", clazz.getName()), e)); return null; } result.addProperties(entity.getProperties()); for (Method m : clazz.getMethods()) { if (m.getName().length() < 4 || !m.getName().startsWith("set") || m.getParameterTypes().length != 1 || !void.class.equals(m.getReturnType())) { continue; } String propName = m.getName().substring(3); Object value = result.getProperties().get(propName); if (value == null) { continue; } Class<?> paramType = m.getParameterTypes()[0]; if (paramType.isEnum() && value instanceof String) { try { value = Enum.valueOf(paramType.asSubclass(Enum.class), (String) value); } catch (IllegalArgumentException e) { logger.logThrowableAsWarning(new IllegalArgumentException(String.format( "Failed to convert '%s' to value of enum '%s'", propName, paramType.getName()), e)); } } try { m.invoke(result, value); } catch (ReflectiveOperationException | IllegalArgumentException e) { logger.logThrowableAsWarning(new ReflectiveOperationException(String.format( "Failed to set property '%s' on type '%s'", propName, clazz.getName()), e)); } } return result; } }
class of `TableEntity`, locate all getter methods (those that start with `get` or `is`, take no
assuming this is blocking, should we let the `backupStatusPoller` do the initial polling?
public void getBackupStatus(HttpClient httpClient) { if (getTestMode() != TestMode.PLAYBACK) { return; } client = getClientBuilder(httpClient, false).buildClient(); SyncPoller<KeyVaultBackupOperation, String> backupPoller = client.beginBackup(blobStorageUrl, sasToken); String jobId = backupPoller.poll().getValue().getJobId(); SyncPoller<KeyVaultBackupOperation, String> backupStatusPoller = client.getBackupOperation(jobId); KeyVaultBackupOperation backupOperation = backupPoller.waitForCompletion().getValue(); KeyVaultBackupOperation backupStatusOperation = backupStatusPoller.waitForCompletion().getValue(); String backupBlobUri = backupPoller.getFinalResult(); String backupStatusBlobUri = backupStatusPoller.getFinalResult(); assertEquals(backupBlobUri, backupStatusBlobUri); assertEquals(backupOperation.getStartTime(), backupStatusOperation.getStartTime()); assertEquals(backupOperation.getEndTime(), backupStatusOperation.getEndTime()); }
KeyVaultBackupOperation backupOperation = backupPoller.waitForCompletion().getValue();
public void getBackupStatus(HttpClient httpClient) { if (getTestMode() != TestMode.PLAYBACK) { return; } client = getClientBuilder(httpClient, false).buildClient(); SyncPoller<KeyVaultBackupOperation, String> backupPoller = client.beginBackup(blobStorageUrl, sasToken); String jobId = backupPoller.poll().getValue().getJobId(); SyncPoller<KeyVaultBackupOperation, String> backupStatusPoller = client.getBackupOperation(jobId); KeyVaultBackupOperation backupOperation = backupPoller.waitForCompletion().getValue(); KeyVaultBackupOperation backupStatusOperation = backupStatusPoller.waitForCompletion().getValue(); String backupBlobUri = backupPoller.getFinalResult(); String backupStatusBlobUri = backupStatusPoller.getFinalResult(); assertEquals(backupBlobUri, backupStatusBlobUri); assertEquals(backupOperation.getStartTime(), backupStatusOperation.getStartTime()); assertEquals(backupOperation.getEndTime(), backupStatusOperation.getEndTime()); }
class KeyVaultBackupClientTest extends KeyVaultBackupClientTestBase { private KeyVaultBackupClient client; private final String blobStorageUrl = "https: private final String sasToken = "someSasToken"; @Override protected void beforeTest() { beforeTestSetup(); } /** * Tests that a Key Vault can be backed up. */ @ParameterizedTest(name = DISPLAY_NAME) @MethodSource("com.azure.security.keyvault.administration.KeyVaultAdministrationClientTestBase public void beginBackup(HttpClient httpClient) { if (getTestMode() != TestMode.PLAYBACK) { return; } client = getClientBuilder(httpClient, false).buildClient(); SyncPoller<KeyVaultBackupOperation, String> backupPoller = client.beginBackup(blobStorageUrl, sasToken); backupPoller.waitForCompletion(); String backupBlobUri = backupPoller.getFinalResult(); assertNotNull(backupBlobUri); assertTrue(backupBlobUri.startsWith(blobStorageUrl)); } /** * Tests that a backup operation can be obtained by using its {@code jobId}. */ @ParameterizedTest(name = DISPLAY_NAME) @MethodSource("com.azure.security.keyvault.administration.KeyVaultAdministrationClientTestBase /** * Tests that a Key Vault can be restored from a backup. */ @ParameterizedTest(name = DISPLAY_NAME) @MethodSource("com.azure.security.keyvault.administration.KeyVaultAdministrationClientTestBase public void beginRestore(HttpClient httpClient) { if (getTestMode() != TestMode.PLAYBACK) { return; } client = getClientBuilder(httpClient, false).buildClient(); SyncPoller<KeyVaultBackupOperation, String> backupPoller = client.beginBackup(blobStorageUrl, sasToken); backupPoller.waitForCompletion(); String backupBlobUri = backupPoller.getFinalResult(); String[] segments = backupBlobUri.split("/"); String folderName = segments[segments.length - 1]; SyncPoller<KeyVaultRestoreOperation, Void> restorePoller = client.beginRestore(blobStorageUrl, sasToken, folderName); restorePoller.waitForCompletion(); PollResponse<KeyVaultRestoreOperation> restoreResponse = restorePoller.poll(); assertEquals(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, restoreResponse.getStatus()); } /** * Tests that a restore operation can be obtained by using its {@code jobId}. */ @ParameterizedTest(name = DISPLAY_NAME) @MethodSource("com.azure.security.keyvault.administration.KeyVaultAdministrationClientTestBase public void getRestoreStatus(HttpClient httpClient) { if (getTestMode() != TestMode.PLAYBACK) { return; } client = getClientBuilder(httpClient, false).buildClient(); SyncPoller<KeyVaultBackupOperation, String> backupPoller = client.beginBackup(blobStorageUrl, sasToken); backupPoller.waitForCompletion(); String backupBlobUri = backupPoller.getFinalResult(); String[] segments = backupBlobUri.split("/"); String folderName = segments[segments.length - 1]; SyncPoller<KeyVaultRestoreOperation, Void> restorePoller = client.beginRestore(blobStorageUrl, sasToken, folderName); String jobId = restorePoller.poll().getValue().getJobId(); SyncPoller<KeyVaultRestoreOperation, Void> restoreStatusPoller = client.getRestoreOperation(jobId); KeyVaultRestoreOperation restoreOperation = restorePoller.waitForCompletion().getValue(); KeyVaultRestoreOperation restoreStatusOperation = restoreStatusPoller.waitForCompletion().getValue(); assertEquals(restoreOperation.getStartTime(), restoreStatusOperation.getStartTime()); assertEquals(restoreOperation.getEndTime(), restoreStatusOperation.getEndTime()); } /** * Tests that a key can be restored from a backup. */ @ParameterizedTest(name = DISPLAY_NAME) @MethodSource("com.azure.security.keyvault.administration.KeyVaultAdministrationClientTestBase public void beginSelectiveRestore(HttpClient httpClient) { if (getTestMode() != TestMode.PLAYBACK) { return; } client = getClientBuilder(httpClient, false).buildClient(); SyncPoller<KeyVaultBackupOperation, String> backupPoller = client.beginBackup(blobStorageUrl, sasToken); backupPoller.waitForCompletion(); String backupBlobUri = backupPoller.getFinalResult(); String[] segments = backupBlobUri.split("/"); String folderName = segments[segments.length - 1]; SyncPoller<KeyVaultRestoreOperation, Void> selectiveRestorePoller = client.beginSelectiveRestore("testKey", blobStorageUrl, sasToken, folderName); PollResponse<KeyVaultRestoreOperation> response = selectiveRestorePoller.poll(); assertNotNull(response); assertEquals(LongRunningOperationStatus.IN_PROGRESS, response.getStatus()); assertNotNull(response.getValue()); selectiveRestorePoller.waitForCompletion(); response = selectiveRestorePoller.poll(); assertEquals(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, response.getStatus()); } }
class KeyVaultBackupClientTest extends KeyVaultBackupClientTestBase { private KeyVaultBackupClient client; private final String blobStorageUrl = "https: private final String sasToken = "someSasToken"; @Override protected void beforeTest() { beforeTestSetup(); } /** * Tests that a Key Vault can be backed up. */ @ParameterizedTest(name = DISPLAY_NAME) @MethodSource("com.azure.security.keyvault.administration.KeyVaultAdministrationClientTestBase public void beginBackup(HttpClient httpClient) { if (getTestMode() != TestMode.PLAYBACK) { return; } client = getClientBuilder(httpClient, false).buildClient(); SyncPoller<KeyVaultBackupOperation, String> backupPoller = client.beginBackup(blobStorageUrl, sasToken); backupPoller.waitForCompletion(); String backupBlobUri = backupPoller.getFinalResult(); assertNotNull(backupBlobUri); assertTrue(backupBlobUri.startsWith(blobStorageUrl)); } /** * Tests that a backup operation can be obtained by using its {@code jobId}. */ @ParameterizedTest(name = DISPLAY_NAME) @MethodSource("com.azure.security.keyvault.administration.KeyVaultAdministrationClientTestBase /** * Tests that a Key Vault can be restored from a backup. */ @ParameterizedTest(name = DISPLAY_NAME) @MethodSource("com.azure.security.keyvault.administration.KeyVaultAdministrationClientTestBase public void beginRestore(HttpClient httpClient) { if (getTestMode() != TestMode.PLAYBACK) { return; } client = getClientBuilder(httpClient, false).buildClient(); SyncPoller<KeyVaultBackupOperation, String> backupPoller = client.beginBackup(blobStorageUrl, sasToken); backupPoller.waitForCompletion(); String backupBlobUri = backupPoller.getFinalResult(); String[] segments = backupBlobUri.split("/"); String folderName = segments[segments.length - 1]; SyncPoller<KeyVaultRestoreOperation, Void> restorePoller = client.beginRestore(blobStorageUrl, sasToken, folderName); restorePoller.waitForCompletion(); PollResponse<KeyVaultRestoreOperation> restoreResponse = restorePoller.poll(); assertEquals(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, restoreResponse.getStatus()); } /** * Tests that a restore operation can be obtained by using its {@code jobId}. */ @ParameterizedTest(name = DISPLAY_NAME) @MethodSource("com.azure.security.keyvault.administration.KeyVaultAdministrationClientTestBase public void getRestoreStatus(HttpClient httpClient) { if (getTestMode() != TestMode.PLAYBACK) { return; } client = getClientBuilder(httpClient, false).buildClient(); SyncPoller<KeyVaultBackupOperation, String> backupPoller = client.beginBackup(blobStorageUrl, sasToken); backupPoller.waitForCompletion(); String backupBlobUri = backupPoller.getFinalResult(); String[] segments = backupBlobUri.split("/"); String folderName = segments[segments.length - 1]; SyncPoller<KeyVaultRestoreOperation, Void> restorePoller = client.beginRestore(blobStorageUrl, sasToken, folderName); String jobId = restorePoller.poll().getValue().getJobId(); SyncPoller<KeyVaultRestoreOperation, Void> restoreStatusPoller = client.getRestoreOperation(jobId); KeyVaultRestoreOperation restoreOperation = restorePoller.waitForCompletion().getValue(); KeyVaultRestoreOperation restoreStatusOperation = restoreStatusPoller.waitForCompletion().getValue(); assertEquals(restoreOperation.getStartTime(), restoreStatusOperation.getStartTime()); assertEquals(restoreOperation.getEndTime(), restoreStatusOperation.getEndTime()); } /** * Tests that a key can be restored from a backup. */ @ParameterizedTest(name = DISPLAY_NAME) @MethodSource("com.azure.security.keyvault.administration.KeyVaultAdministrationClientTestBase public void beginSelectiveRestore(HttpClient httpClient) { if (getTestMode() != TestMode.PLAYBACK) { return; } client = getClientBuilder(httpClient, false).buildClient(); SyncPoller<KeyVaultBackupOperation, String> backupPoller = client.beginBackup(blobStorageUrl, sasToken); backupPoller.waitForCompletion(); String backupBlobUri = backupPoller.getFinalResult(); String[] segments = backupBlobUri.split("/"); String folderName = segments[segments.length - 1]; SyncPoller<KeyVaultRestoreOperation, Void> selectiveRestorePoller = client.beginSelectiveRestore("testKey", blobStorageUrl, sasToken, folderName); PollResponse<KeyVaultRestoreOperation> response = selectiveRestorePoller.poll(); assertNotNull(response); assertEquals(LongRunningOperationStatus.IN_PROGRESS, response.getStatus()); assertNotNull(response.getValue()); selectiveRestorePoller.waitForCompletion(); response = selectiveRestorePoller.poll(); assertEquals(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, response.getStatus()); } }
I don't think it would change much since we need to get the final result from both pollers. Maybe I don't understand all the implications when it comes to the async aspect of things.
public void getBackupStatus(HttpClient httpClient) { if (getTestMode() != TestMode.PLAYBACK) { return; } client = getClientBuilder(httpClient, false).buildClient(); SyncPoller<KeyVaultBackupOperation, String> backupPoller = client.beginBackup(blobStorageUrl, sasToken); String jobId = backupPoller.poll().getValue().getJobId(); SyncPoller<KeyVaultBackupOperation, String> backupStatusPoller = client.getBackupOperation(jobId); KeyVaultBackupOperation backupOperation = backupPoller.waitForCompletion().getValue(); KeyVaultBackupOperation backupStatusOperation = backupStatusPoller.waitForCompletion().getValue(); String backupBlobUri = backupPoller.getFinalResult(); String backupStatusBlobUri = backupStatusPoller.getFinalResult(); assertEquals(backupBlobUri, backupStatusBlobUri); assertEquals(backupOperation.getStartTime(), backupStatusOperation.getStartTime()); assertEquals(backupOperation.getEndTime(), backupStatusOperation.getEndTime()); }
KeyVaultBackupOperation backupOperation = backupPoller.waitForCompletion().getValue();
public void getBackupStatus(HttpClient httpClient) { if (getTestMode() != TestMode.PLAYBACK) { return; } client = getClientBuilder(httpClient, false).buildClient(); SyncPoller<KeyVaultBackupOperation, String> backupPoller = client.beginBackup(blobStorageUrl, sasToken); String jobId = backupPoller.poll().getValue().getJobId(); SyncPoller<KeyVaultBackupOperation, String> backupStatusPoller = client.getBackupOperation(jobId); KeyVaultBackupOperation backupOperation = backupPoller.waitForCompletion().getValue(); KeyVaultBackupOperation backupStatusOperation = backupStatusPoller.waitForCompletion().getValue(); String backupBlobUri = backupPoller.getFinalResult(); String backupStatusBlobUri = backupStatusPoller.getFinalResult(); assertEquals(backupBlobUri, backupStatusBlobUri); assertEquals(backupOperation.getStartTime(), backupStatusOperation.getStartTime()); assertEquals(backupOperation.getEndTime(), backupStatusOperation.getEndTime()); }
class KeyVaultBackupClientTest extends KeyVaultBackupClientTestBase { private KeyVaultBackupClient client; private final String blobStorageUrl = "https: private final String sasToken = "someSasToken"; @Override protected void beforeTest() { beforeTestSetup(); } /** * Tests that a Key Vault can be backed up. */ @ParameterizedTest(name = DISPLAY_NAME) @MethodSource("com.azure.security.keyvault.administration.KeyVaultAdministrationClientTestBase public void beginBackup(HttpClient httpClient) { if (getTestMode() != TestMode.PLAYBACK) { return; } client = getClientBuilder(httpClient, false).buildClient(); SyncPoller<KeyVaultBackupOperation, String> backupPoller = client.beginBackup(blobStorageUrl, sasToken); backupPoller.waitForCompletion(); String backupBlobUri = backupPoller.getFinalResult(); assertNotNull(backupBlobUri); assertTrue(backupBlobUri.startsWith(blobStorageUrl)); } /** * Tests that a backup operation can be obtained by using its {@code jobId}. */ @ParameterizedTest(name = DISPLAY_NAME) @MethodSource("com.azure.security.keyvault.administration.KeyVaultAdministrationClientTestBase /** * Tests that a Key Vault can be restored from a backup. */ @ParameterizedTest(name = DISPLAY_NAME) @MethodSource("com.azure.security.keyvault.administration.KeyVaultAdministrationClientTestBase public void beginRestore(HttpClient httpClient) { if (getTestMode() != TestMode.PLAYBACK) { return; } client = getClientBuilder(httpClient, false).buildClient(); SyncPoller<KeyVaultBackupOperation, String> backupPoller = client.beginBackup(blobStorageUrl, sasToken); backupPoller.waitForCompletion(); String backupBlobUri = backupPoller.getFinalResult(); String[] segments = backupBlobUri.split("/"); String folderName = segments[segments.length - 1]; SyncPoller<KeyVaultRestoreOperation, Void> restorePoller = client.beginRestore(blobStorageUrl, sasToken, folderName); restorePoller.waitForCompletion(); PollResponse<KeyVaultRestoreOperation> restoreResponse = restorePoller.poll(); assertEquals(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, restoreResponse.getStatus()); } /** * Tests that a restore operation can be obtained by using its {@code jobId}. */ @ParameterizedTest(name = DISPLAY_NAME) @MethodSource("com.azure.security.keyvault.administration.KeyVaultAdministrationClientTestBase public void getRestoreStatus(HttpClient httpClient) { if (getTestMode() != TestMode.PLAYBACK) { return; } client = getClientBuilder(httpClient, false).buildClient(); SyncPoller<KeyVaultBackupOperation, String> backupPoller = client.beginBackup(blobStorageUrl, sasToken); backupPoller.waitForCompletion(); String backupBlobUri = backupPoller.getFinalResult(); String[] segments = backupBlobUri.split("/"); String folderName = segments[segments.length - 1]; SyncPoller<KeyVaultRestoreOperation, Void> restorePoller = client.beginRestore(blobStorageUrl, sasToken, folderName); String jobId = restorePoller.poll().getValue().getJobId(); SyncPoller<KeyVaultRestoreOperation, Void> restoreStatusPoller = client.getRestoreOperation(jobId); KeyVaultRestoreOperation restoreOperation = restorePoller.waitForCompletion().getValue(); KeyVaultRestoreOperation restoreStatusOperation = restoreStatusPoller.waitForCompletion().getValue(); assertEquals(restoreOperation.getStartTime(), restoreStatusOperation.getStartTime()); assertEquals(restoreOperation.getEndTime(), restoreStatusOperation.getEndTime()); } /** * Tests that a key can be restored from a backup. */ @ParameterizedTest(name = DISPLAY_NAME) @MethodSource("com.azure.security.keyvault.administration.KeyVaultAdministrationClientTestBase public void beginSelectiveRestore(HttpClient httpClient) { if (getTestMode() != TestMode.PLAYBACK) { return; } client = getClientBuilder(httpClient, false).buildClient(); SyncPoller<KeyVaultBackupOperation, String> backupPoller = client.beginBackup(blobStorageUrl, sasToken); backupPoller.waitForCompletion(); String backupBlobUri = backupPoller.getFinalResult(); String[] segments = backupBlobUri.split("/"); String folderName = segments[segments.length - 1]; SyncPoller<KeyVaultRestoreOperation, Void> selectiveRestorePoller = client.beginSelectiveRestore("testKey", blobStorageUrl, sasToken, folderName); PollResponse<KeyVaultRestoreOperation> response = selectiveRestorePoller.poll(); assertNotNull(response); assertEquals(LongRunningOperationStatus.IN_PROGRESS, response.getStatus()); assertNotNull(response.getValue()); selectiveRestorePoller.waitForCompletion(); response = selectiveRestorePoller.poll(); assertEquals(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, response.getStatus()); } }
class KeyVaultBackupClientTest extends KeyVaultBackupClientTestBase { private KeyVaultBackupClient client; private final String blobStorageUrl = "https: private final String sasToken = "someSasToken"; @Override protected void beforeTest() { beforeTestSetup(); } /** * Tests that a Key Vault can be backed up. */ @ParameterizedTest(name = DISPLAY_NAME) @MethodSource("com.azure.security.keyvault.administration.KeyVaultAdministrationClientTestBase public void beginBackup(HttpClient httpClient) { if (getTestMode() != TestMode.PLAYBACK) { return; } client = getClientBuilder(httpClient, false).buildClient(); SyncPoller<KeyVaultBackupOperation, String> backupPoller = client.beginBackup(blobStorageUrl, sasToken); backupPoller.waitForCompletion(); String backupBlobUri = backupPoller.getFinalResult(); assertNotNull(backupBlobUri); assertTrue(backupBlobUri.startsWith(blobStorageUrl)); } /** * Tests that a backup operation can be obtained by using its {@code jobId}. */ @ParameterizedTest(name = DISPLAY_NAME) @MethodSource("com.azure.security.keyvault.administration.KeyVaultAdministrationClientTestBase /** * Tests that a Key Vault can be restored from a backup. */ @ParameterizedTest(name = DISPLAY_NAME) @MethodSource("com.azure.security.keyvault.administration.KeyVaultAdministrationClientTestBase public void beginRestore(HttpClient httpClient) { if (getTestMode() != TestMode.PLAYBACK) { return; } client = getClientBuilder(httpClient, false).buildClient(); SyncPoller<KeyVaultBackupOperation, String> backupPoller = client.beginBackup(blobStorageUrl, sasToken); backupPoller.waitForCompletion(); String backupBlobUri = backupPoller.getFinalResult(); String[] segments = backupBlobUri.split("/"); String folderName = segments[segments.length - 1]; SyncPoller<KeyVaultRestoreOperation, Void> restorePoller = client.beginRestore(blobStorageUrl, sasToken, folderName); restorePoller.waitForCompletion(); PollResponse<KeyVaultRestoreOperation> restoreResponse = restorePoller.poll(); assertEquals(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, restoreResponse.getStatus()); } /** * Tests that a restore operation can be obtained by using its {@code jobId}. */ @ParameterizedTest(name = DISPLAY_NAME) @MethodSource("com.azure.security.keyvault.administration.KeyVaultAdministrationClientTestBase public void getRestoreStatus(HttpClient httpClient) { if (getTestMode() != TestMode.PLAYBACK) { return; } client = getClientBuilder(httpClient, false).buildClient(); SyncPoller<KeyVaultBackupOperation, String> backupPoller = client.beginBackup(blobStorageUrl, sasToken); backupPoller.waitForCompletion(); String backupBlobUri = backupPoller.getFinalResult(); String[] segments = backupBlobUri.split("/"); String folderName = segments[segments.length - 1]; SyncPoller<KeyVaultRestoreOperation, Void> restorePoller = client.beginRestore(blobStorageUrl, sasToken, folderName); String jobId = restorePoller.poll().getValue().getJobId(); SyncPoller<KeyVaultRestoreOperation, Void> restoreStatusPoller = client.getRestoreOperation(jobId); KeyVaultRestoreOperation restoreOperation = restorePoller.waitForCompletion().getValue(); KeyVaultRestoreOperation restoreStatusOperation = restoreStatusPoller.waitForCompletion().getValue(); assertEquals(restoreOperation.getStartTime(), restoreStatusOperation.getStartTime()); assertEquals(restoreOperation.getEndTime(), restoreStatusOperation.getEndTime()); } /** * Tests that a key can be restored from a backup. */ @ParameterizedTest(name = DISPLAY_NAME) @MethodSource("com.azure.security.keyvault.administration.KeyVaultAdministrationClientTestBase public void beginSelectiveRestore(HttpClient httpClient) { if (getTestMode() != TestMode.PLAYBACK) { return; } client = getClientBuilder(httpClient, false).buildClient(); SyncPoller<KeyVaultBackupOperation, String> backupPoller = client.beginBackup(blobStorageUrl, sasToken); backupPoller.waitForCompletion(); String backupBlobUri = backupPoller.getFinalResult(); String[] segments = backupBlobUri.split("/"); String folderName = segments[segments.length - 1]; SyncPoller<KeyVaultRestoreOperation, Void> selectiveRestorePoller = client.beginSelectiveRestore("testKey", blobStorageUrl, sasToken, folderName); PollResponse<KeyVaultRestoreOperation> response = selectiveRestorePoller.poll(); assertNotNull(response); assertEquals(LongRunningOperationStatus.IN_PROGRESS, response.getStatus()); assertNotNull(response.getValue()); selectiveRestorePoller.waitForCompletion(); response = selectiveRestorePoller.poll(); assertEquals(LongRunningOperationStatus.SUCCESSFULLY_COMPLETED, response.getStatus()); } }
I think documentation in general would be nice (even though this is package-private) to facilitate understanding the code base for future devs.
static void setPropertiesFromGetters(TableEntity entity, ClientLogger logger) { Class<?> myClass = entity.getClass(); if (myClass == TableEntity.class) { return; } for (Method m : myClass.getMethods()) { if (m.getName().length() < 3 || TABLE_ENTITY_METHODS.contains(m.getName()) || (!m.getName().startsWith("get") && !m.getName().startsWith("is")) || m.getParameterTypes().length != 0 || void.class.equals(m.getReturnType())) { continue; } int prefixLength = m.getName().startsWith("get") ? 3 : 2; String propName = m.getName().substring(prefixLength); try { entity.getProperties().put(propName, m.invoke(entity)); } catch (ReflectiveOperationException | IllegalArgumentException e) { logger.logThrowableAsWarning(new ReflectiveOperationException(String.format( "Failed to get property '%s' on type '%s'", propName, myClass.getName()), e)); } } }
int prefixLength = m.getName().startsWith("get") ? 3 : 2;
static void setPropertiesFromGetters(TableEntity entity, ClientLogger logger) { Class<?> myClass = entity.getClass(); if (myClass == TableEntity.class) { return; } for (Method m : myClass.getMethods()) { if (m.getName().length() < 3 || TABLE_ENTITY_METHODS.contains(m.getName()) || (!m.getName().startsWith("get") && !m.getName().startsWith("is")) || m.getParameterTypes().length != 0 || void.class.equals(m.getReturnType())) { continue; } if (m.getName().startsWith("is") && m.getReturnType() != Boolean.class && m.getReturnType() != boolean.class) { continue; } int prefixLength = m.getName().startsWith("is") ? 2 : 3; String propName = m.getName().substring(prefixLength); try { entity.getProperties().put(propName, m.invoke(entity)); } catch (ReflectiveOperationException | IllegalArgumentException e) { logger.logThrowableAsWarning(new ReflectiveOperationException(String.format( "Failed to get property '%s' on type '%s'", propName, myClass.getName()), e)); } } }
class EntityHelper { private static final HashSet<String> TABLE_ENTITY_METHODS = Arrays.stream(TableEntity.class.getMethods()) .map(Method::getName).collect(Collectors.toCollection(HashSet::new)); private EntityHelper() { } @SuppressWarnings("unchecked") static <T extends TableEntity> T convertToSubclass(TableEntity entity, Class<T> clazz, ClientLogger logger) { if (TableEntity.class == clazz) { return (T) entity; } T result; try { result = clazz.getDeclaredConstructor(String.class, String.class).newInstance(entity.getPartitionKey(), entity.getRowKey()); } catch (ReflectiveOperationException | SecurityException e) { logger.logThrowableAsWarning(new ReflectiveOperationException(String.format( "Failed to instantiate type '%s'", clazz.getName()), e)); return null; } result.addProperties(entity.getProperties()); for (Method m : clazz.getMethods()) { if (m.getName().length() < 4 || !m.getName().startsWith("set") || m.getParameterTypes().length != 1 || !void.class.equals(m.getReturnType())) { continue; } String propName = m.getName().substring(3); Object value = result.getProperties().get(propName); if (value == null) { continue; } Class<?> paramType = m.getParameterTypes()[0]; if (paramType.isEnum() && value instanceof String) { try { value = Enum.valueOf(paramType.asSubclass(Enum.class), (String) value); } catch (IllegalArgumentException e) { logger.logThrowableAsWarning(new IllegalArgumentException(String.format( "Failed to convert '%s' to value of enum '%s'", propName, paramType.getName()), e)); } } try { m.invoke(result, value); } catch (ReflectiveOperationException | IllegalArgumentException e) { logger.logThrowableAsWarning(new ReflectiveOperationException(String.format( "Failed to set property '%s' on type '%s'", propName, clazz.getName()), e)); } } return result; } }
class of `TableEntity`, locate all getter methods (those that start with `get` or `is`, take no
nit; consistent use of final.
void updateEntityWithResponseSubclassAsync() { final String partitionKeyValue = testResourceNamer.randomName("APartitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("ARowKey", 20); final int expectedStatusCode = 204; SingleFieldEntity tableEntity = new SingleFieldEntity(partitionKeyValue, rowKeyValue); tableEntity.setSubclassProperty("InitialValue"); tableClient.createEntity(tableEntity).block(TIMEOUT); tableEntity.setSubclassProperty("UpdatedValue"); StepVerifier.create(tableClient.updateEntityWithResponse(tableEntity, true, UpdateMode.MERGE)) .assertNext(response -> assertEquals(expectedStatusCode, response.getStatusCode())) .expectComplete() .verify(); StepVerifier.create(tableClient.getEntity(partitionKeyValue, rowKeyValue)) .assertNext(entity -> { final Map<String, Object> properties = entity.getProperties(); assertTrue(properties.containsKey("SubclassProperty")); assertEquals("UpdatedValue", properties.get("SubclassProperty")); }) .verifyComplete(); }
SingleFieldEntity tableEntity = new SingleFieldEntity(partitionKeyValue, rowKeyValue);
void updateEntityWithResponseSubclassAsync() { String partitionKeyValue = testResourceNamer.randomName("APartitionKey", 20); String rowKeyValue = testResourceNamer.randomName("ARowKey", 20); int expectedStatusCode = 204; SingleFieldEntity tableEntity = new SingleFieldEntity(partitionKeyValue, rowKeyValue); tableEntity.setSubclassProperty("InitialValue"); tableClient.createEntity(tableEntity).block(TIMEOUT); tableEntity.setSubclassProperty("UpdatedValue"); StepVerifier.create(tableClient.updateEntityWithResponse(tableEntity, true, UpdateMode.MERGE)) .assertNext(response -> assertEquals(expectedStatusCode, response.getStatusCode())) .expectComplete() .verify(); StepVerifier.create(tableClient.getEntity(partitionKeyValue, rowKeyValue)) .assertNext(entity -> { Map<String, Object> properties = entity.getProperties(); assertTrue(properties.containsKey("SubclassProperty")); assertEquals("UpdatedValue", properties.get("SubclassProperty")); }) .verifyComplete(); }
class TablesAsyncClientTest extends TestBase { private static final Duration TIMEOUT = Duration.ofSeconds(100); private TableAsyncClient tableClient; private HttpPipelinePolicy recordPolicy; private HttpClient playbackClient; @BeforeAll static void beforeAll() { StepVerifier.setDefaultTimeout(TIMEOUT); } @AfterAll static void afterAll() { StepVerifier.resetDefaultTimeout(); } @Override protected void beforeTest() { final String tableName = testResourceNamer.randomName("tableName", 20); final String connectionString = TestUtils.getConnectionString(interceptorManager.isPlaybackMode()); final TableClientBuilder builder = new TableClientBuilder() .connectionString(connectionString) .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)) .tableName(tableName); if (interceptorManager.isPlaybackMode()) { playbackClient = interceptorManager.getPlaybackClient(); builder.httpClient(playbackClient); } else { builder.httpClient(HttpClient.createDefault()); if (!interceptorManager.isLiveMode()) { recordPolicy = interceptorManager.getRecordPolicy(); builder.addPolicy(recordPolicy); } builder.addPolicy(new RetryPolicy(new ExponentialBackoff(6, Duration.ofMillis(1500), Duration.ofSeconds(100)))); } tableClient = builder.buildAsyncClient(); tableClient.create().block(TIMEOUT); } @Test void createTableAsync() { final String tableName2 = testResourceNamer.randomName("tableName", 20); final String connectionString = TestUtils.getConnectionString(interceptorManager.isPlaybackMode()); final TableClientBuilder builder = new TableClientBuilder() .connectionString(connectionString) .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)) .tableName(tableName2); if (interceptorManager.isPlaybackMode()) { builder.httpClient(playbackClient); } else { builder.httpClient(HttpClient.createDefault()); if (!interceptorManager.isLiveMode()) { builder.addPolicy(recordPolicy); } builder.addPolicy(new RetryPolicy(new ExponentialBackoff(6, Duration.ofMillis(1500), Duration.ofSeconds(100)))); } final TableAsyncClient tableClient2 = builder.buildAsyncClient(); StepVerifier.create(tableClient2.create()) .expectComplete() .verify(); } @Test void createTableWithResponseAsync() { final String tableName2 = testResourceNamer.randomName("tableName", 20); final String connectionString = TestUtils.getConnectionString(interceptorManager.isPlaybackMode()); final TableClientBuilder builder = new TableClientBuilder() .connectionString(connectionString) .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)) .tableName(tableName2); if (interceptorManager.isPlaybackMode()) { builder.httpClient(playbackClient); } else { builder.httpClient(HttpClient.createDefault()); if (!interceptorManager.isLiveMode()) { builder.addPolicy(recordPolicy); } builder.addPolicy(new RetryPolicy(new ExponentialBackoff(6, Duration.ofMillis(1500), Duration.ofSeconds(100)))); } final TableAsyncClient tableClient2 = builder.buildAsyncClient(); final int expectedStatusCode = 204; StepVerifier.create(tableClient2.createWithResponse()) .assertNext(response -> { assertEquals(expectedStatusCode, response.getStatusCode()); }) .expectComplete() .verify(); } @Test void createEntityAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue); StepVerifier.create(tableClient.createEntity(tableEntity)) .expectComplete() .verify(); } @Test void createEntityWithResponseAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity entity = new TableEntity(partitionKeyValue, rowKeyValue); final int expectedStatusCode = 204; StepVerifier.create(tableClient.createEntityWithResponse(entity)) .assertNext(response -> { assertEquals(expectedStatusCode, response.getStatusCode()); }) .expectComplete() .verify(); } @Test void createEntityWithAllSupportedDataTypesAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue); final boolean booleanValue = true; final byte[] binaryValue = "Test value".getBytes(); final Date dateValue = new Date(); final OffsetDateTime offsetDateTimeValue = OffsetDateTime.now(); final double doubleValue = 2.0d; final UUID guidValue = UUID.randomUUID(); final int int32Value = 1337; final long int64Value = 1337L; final String stringValue = "This is table entity"; tableEntity.addProperty("BinaryTypeProperty", binaryValue); tableEntity.addProperty("BooleanTypeProperty", booleanValue); tableEntity.addProperty("DateTypeProperty", dateValue); tableEntity.addProperty("OffsetDateTimeTypeProperty", offsetDateTimeValue); tableEntity.addProperty("DoubleTypeProperty", doubleValue); tableEntity.addProperty("GuidTypeProperty", guidValue); tableEntity.addProperty("Int32TypeProperty", int32Value); tableEntity.addProperty("Int64TypeProperty", int64Value); tableEntity.addProperty("StringTypeProperty", stringValue); tableClient.createEntity(tableEntity).block(TIMEOUT); StepVerifier.create(tableClient.getEntityWithResponse(partitionKeyValue, rowKeyValue, null)) .assertNext(response -> { final TableEntity entity = response.getValue(); Map<String, Object> properties = entity.getProperties(); assertTrue(properties.get("BinaryTypeProperty") instanceof byte[]); assertTrue(properties.get("BooleanTypeProperty") instanceof Boolean); assertTrue(properties.get("DateTypeProperty") instanceof OffsetDateTime); assertTrue(properties.get("OffsetDateTimeTypeProperty") instanceof OffsetDateTime); assertTrue(properties.get("DoubleTypeProperty") instanceof Double); assertTrue(properties.get("GuidTypeProperty") instanceof UUID); assertTrue(properties.get("Int32TypeProperty") instanceof Integer); assertTrue(properties.get("Int64TypeProperty") instanceof Long); assertTrue(properties.get("StringTypeProperty") instanceof String); }) .expectComplete() .verify(); } @Test void createEntitySubclassAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); byte[] bytes = new byte[]{1, 2, 3}; boolean b = true; OffsetDateTime dateTime = OffsetDateTime.of(2020, 1, 1, 0, 0, 0, 0, ZoneOffset.UTC); double d = 1.23D; UUID uuid = UUID.fromString("11111111-2222-3333-4444-555555555555"); int i = 123; long l = 123L; String s = "Test"; SampleEntity.Color color = SampleEntity.Color.GREEN; SampleEntity tableEntity = new SampleEntity(partitionKeyValue, rowKeyValue); tableEntity.setByteField(bytes); tableEntity.setBooleanField(b); tableEntity.setDateTimeField(dateTime); tableEntity.setDoubleField(d); tableEntity.setUuidField(uuid); tableEntity.setIntField(i); tableEntity.setLongField(l); tableEntity.setStringField(s); tableEntity.setEnumField(color); tableClient.createEntity(tableEntity).block(TIMEOUT); StepVerifier.create(tableClient.getEntityWithResponse(partitionKeyValue, rowKeyValue, null)) .assertNext(response -> { final TableEntity entity = response.getValue(); assertArrayEquals((byte[]) entity.getProperties().get("ByteField"), bytes); assertEquals(entity.getProperties().get("BooleanField"), b); assertTrue(dateTime.isEqual((OffsetDateTime) entity.getProperties().get("DateTimeField"))); assertEquals(entity.getProperties().get("DoubleField"), d); assertEquals(0, uuid.compareTo((UUID) entity.getProperties().get("UuidField"))); assertEquals(entity.getProperties().get("IntField"), i); assertEquals(entity.getProperties().get("LongField"), l); assertEquals(entity.getProperties().get("StringField"), s); assertEquals(entity.getProperties().get("EnumField"), color.name()); }) .expectComplete() .verify(); } @Test void deleteTableAsync() { StepVerifier.create(tableClient.delete()) .expectComplete() .verify(); } @Test void deleteTableWithResponseAsync() { final int expectedStatusCode = 204; StepVerifier.create(tableClient.deleteWithResponse()) .assertNext(response -> { assertEquals(expectedStatusCode, response.getStatusCode()); }) .expectComplete() .verify(); } @Test void deleteEntityAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue); tableClient.createEntity(tableEntity).block(TIMEOUT); final TableEntity createdEntity = tableClient.getEntity(partitionKeyValue, rowKeyValue).block(TIMEOUT); assertNotNull(createdEntity, "'createdEntity' should not be null."); assertNotNull(createdEntity.getETag(), "'eTag' should not be null."); StepVerifier.create(tableClient.deleteEntity(partitionKeyValue, rowKeyValue)) .expectComplete() .verify(); } @Test void deleteEntityWithResponseAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue); final int expectedStatusCode = 204; tableClient.createEntity(tableEntity).block(TIMEOUT); final TableEntity createdEntity = tableClient.getEntity(partitionKeyValue, rowKeyValue).block(TIMEOUT); assertNotNull(createdEntity, "'createdEntity' should not be null."); assertNotNull(createdEntity.getETag(), "'eTag' should not be null."); StepVerifier.create(tableClient.deleteEntityWithResponse(partitionKeyValue, rowKeyValue, null)) .assertNext(response -> { assertEquals(expectedStatusCode, response.getStatusCode()); }) .expectComplete() .verify(); } @Test void deleteEntityWithResponseMatchETagAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue); final int expectedStatusCode = 204; tableClient.createEntity(tableEntity).block(TIMEOUT); final TableEntity createdEntity = tableClient.getEntity(partitionKeyValue, rowKeyValue).block(TIMEOUT); assertNotNull(createdEntity, "'createdEntity' should not be null."); assertNotNull(createdEntity.getETag(), "'eTag' should not be null."); StepVerifier.create(tableClient.deleteEntityWithResponse(partitionKeyValue, rowKeyValue, createdEntity.getETag())) .assertNext(response -> { assertEquals(expectedStatusCode, response.getStatusCode()); }) .expectComplete() .verify(); } @Test void getEntityWithResponseAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue); final int expectedStatusCode = 200; tableClient.createEntity(tableEntity).block(TIMEOUT); StepVerifier.create(tableClient.getEntityWithResponse(partitionKeyValue, rowKeyValue, null)) .assertNext(response -> { final TableEntity entity = response.getValue(); assertEquals(expectedStatusCode, response.getStatusCode()); assertNotNull(entity); assertEquals(tableEntity.getPartitionKey(), entity.getPartitionKey()); assertEquals(tableEntity.getRowKey(), entity.getRowKey()); assertNotNull(entity.getTimestamp()); assertNotNull(entity.getETag()); assertNotNull(entity.getProperties()); }) .expectComplete() .verify(); } @Test void getEntityWithResponseWithSelectAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue); tableEntity.addProperty("Test", "Value"); final int expectedStatusCode = 200; tableClient.createEntity(tableEntity).block(TIMEOUT); StepVerifier.create(tableClient.getEntityWithResponse(partitionKeyValue, rowKeyValue, "Test")) .assertNext(response -> { final TableEntity entity = response.getValue(); assertEquals(expectedStatusCode, response.getStatusCode()); assertNotNull(entity); assertNull(entity.getPartitionKey()); assertNull(entity.getRowKey()); assertNull(entity.getTimestamp()); assertNotNull(entity.getETag()); assertEquals(entity.getProperties().get("Test"), "Value"); }) .expectComplete() .verify(); } @Test void getEntityWithResponseSubclassAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue); byte[] bytes = new byte[]{1, 2, 3}; boolean b = true; OffsetDateTime dateTime = OffsetDateTime.of(2020, 1, 1, 0, 0, 0, 0, ZoneOffset.UTC); double d = 1.23D; UUID uuid = UUID.fromString("11111111-2222-3333-4444-555555555555"); int i = 123; long l = 123L; String s = "Test"; SampleEntity.Color color = SampleEntity.Color.GREEN; Map<String, Object> props = new HashMap<>(); props.put("ByteField", bytes); props.put("BooleanField", b); props.put("DateTimeField", dateTime); props.put("DoubleField", d); props.put("UuidField", uuid); props.put("IntField", i); props.put("LongField", l); props.put("StringField", s); props.put("EnumField", color); tableEntity.addProperties(props); final int expectedStatusCode = 200; tableClient.createEntity(tableEntity).block(TIMEOUT); StepVerifier.create(tableClient.getEntityWithResponse(partitionKeyValue, rowKeyValue, null, SampleEntity.class)) .assertNext(response -> { final SampleEntity entity = response.getValue(); assertEquals(expectedStatusCode, response.getStatusCode()); assertNotNull(entity); assertEquals(tableEntity.getPartitionKey(), entity.getPartitionKey()); assertEquals(tableEntity.getRowKey(), entity.getRowKey()); assertNotNull(entity.getTimestamp()); assertNotNull(entity.getETag()); assertArrayEquals(bytes, entity.getByteField()); assertEquals(b, entity.getBooleanField()); assertTrue(dateTime.isEqual(entity.getDateTimeField())); assertEquals(d, entity.getDoubleField()); assertEquals(0, uuid.compareTo(entity.getUuidField())); assertEquals(i, entity.getIntField()); assertEquals(l, entity.getLongField()); assertEquals(s, entity.getStringField()); assertEquals(color, entity.getEnumField()); }) .expectComplete() .verify(); } @Test void updateEntityWithResponseReplaceAsync() { updateEntityWithResponseAsync(UpdateMode.REPLACE); } @Test void updateEntityWithResponseMergeAsync() { updateEntityWithResponseAsync(UpdateMode.MERGE); } /** * In the case of {@link UpdateMode * In the case of {@link UpdateMode */ void updateEntityWithResponseAsync(UpdateMode mode) { final boolean expectOldProperty = mode == UpdateMode.MERGE; final String partitionKeyValue = testResourceNamer.randomName("APartitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("ARowKey", 20); final int expectedStatusCode = 204; final String oldPropertyKey = "propertyA"; final String newPropertyKey = "propertyB"; final TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue) .addProperty(oldPropertyKey, "valueA"); tableClient.createEntity(tableEntity).block(TIMEOUT); final TableEntity createdEntity = tableClient.getEntity(partitionKeyValue, rowKeyValue).block(TIMEOUT); assertNotNull(createdEntity, "'createdEntity' should not be null."); assertNotNull(createdEntity.getETag(), "'eTag' should not be null."); createdEntity.getProperties().remove(oldPropertyKey); createdEntity.addProperty(newPropertyKey, "valueB"); if (mode == UpdateMode.MERGE && tableClient.getTableUrl().contains("cosmos.azure.com")) { StepVerifier.create(tableClient.updateEntityWithResponse(createdEntity, true, mode)) .expectError(com.azure.data.tables.implementation.models.TableServiceErrorException.class) .verify(); } else { StepVerifier.create(tableClient.updateEntityWithResponse(createdEntity, true, mode)) .assertNext(response -> assertEquals(expectedStatusCode, response.getStatusCode())) .expectComplete() .verify(); StepVerifier.create(tableClient.getEntity(partitionKeyValue, rowKeyValue)) .assertNext(entity -> { final Map<String, Object> properties = entity.getProperties(); assertTrue(properties.containsKey(newPropertyKey)); assertEquals(expectOldProperty, properties.containsKey(oldPropertyKey)); }) .verifyComplete(); } } @Test @Test @Tag("ListEntities") void listEntitiesAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final String rowKeyValue2 = testResourceNamer.randomName("rowKey", 20); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue)).block(TIMEOUT); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue2)).block(TIMEOUT); StepVerifier.create(tableClient.listEntities()) .expectNextCount(2) .thenConsumeWhile(x -> true) .expectComplete() .verify(); } @Test @Tag("ListEntities") void listEntitiesWithFilterAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final String rowKeyValue2 = testResourceNamer.randomName("rowKey", 20); ListEntitiesOptions options = new ListEntitiesOptions().setFilter("RowKey eq '" + rowKeyValue + "'"); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue)).block(TIMEOUT); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue2)).block(TIMEOUT); StepVerifier.create(tableClient.listEntities(options)) .assertNext(returnEntity -> { assertEquals(partitionKeyValue, returnEntity.getPartitionKey()); assertEquals(rowKeyValue, returnEntity.getRowKey()); }) .expectNextCount(0) .thenConsumeWhile(x -> true) .expectComplete() .verify(); } @Test @Tag("ListEntities") void listEntitiesWithSelectAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity entity = new TableEntity(partitionKeyValue, rowKeyValue) .addProperty("propertyC", "valueC") .addProperty("propertyD", "valueD"); ListEntitiesOptions options = new ListEntitiesOptions() .setSelect("propertyC"); tableClient.createEntity(entity).block(TIMEOUT); StepVerifier.create(tableClient.listEntities(options)) .assertNext(returnEntity -> { assertNull(returnEntity.getRowKey()); assertNull(returnEntity.getPartitionKey()); assertEquals("valueC", returnEntity.getProperties().get("propertyC")); assertNull(returnEntity.getProperties().get("propertyD")); }) .expectComplete() .verify(); } @Test @Tag("ListEntities") void listEntitiesWithTopAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final String rowKeyValue2 = testResourceNamer.randomName("rowKey", 20); final String rowKeyValue3 = testResourceNamer.randomName("rowKey", 20); ListEntitiesOptions options = new ListEntitiesOptions().setTop(2); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue)).block(TIMEOUT); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue2)).block(TIMEOUT); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue3)).block(TIMEOUT); StepVerifier.create(tableClient.listEntities(options)) .expectNextCount(2) .thenConsumeWhile(x -> true) .expectComplete() .verify(); } @Test @Tag("ListEntities") void listEntitiesSubclassAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final String rowKeyValue2 = testResourceNamer.randomName("rowKey", 20); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue)).block(TIMEOUT); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue2)).block(TIMEOUT); StepVerifier.create(tableClient.listEntities(SampleEntity.class)) .expectNextCount(2) .thenConsumeWhile(x -> true) .expectComplete() .verify(); } }
class TablesAsyncClientTest extends TestBase { private static final Duration TIMEOUT = Duration.ofSeconds(100); private TableAsyncClient tableClient; private HttpPipelinePolicy recordPolicy; private HttpClient playbackClient; @BeforeAll static void beforeAll() { StepVerifier.setDefaultTimeout(TIMEOUT); } @AfterAll static void afterAll() { StepVerifier.resetDefaultTimeout(); } @Override protected void beforeTest() { final String tableName = testResourceNamer.randomName("tableName", 20); final String connectionString = TestUtils.getConnectionString(interceptorManager.isPlaybackMode()); final TableClientBuilder builder = new TableClientBuilder() .connectionString(connectionString) .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)) .tableName(tableName); if (interceptorManager.isPlaybackMode()) { playbackClient = interceptorManager.getPlaybackClient(); builder.httpClient(playbackClient); } else { builder.httpClient(HttpClient.createDefault()); if (!interceptorManager.isLiveMode()) { recordPolicy = interceptorManager.getRecordPolicy(); builder.addPolicy(recordPolicy); } builder.addPolicy(new RetryPolicy(new ExponentialBackoff(6, Duration.ofMillis(1500), Duration.ofSeconds(100)))); } tableClient = builder.buildAsyncClient(); tableClient.create().block(TIMEOUT); } @Test void createTableAsync() { final String tableName2 = testResourceNamer.randomName("tableName", 20); final String connectionString = TestUtils.getConnectionString(interceptorManager.isPlaybackMode()); final TableClientBuilder builder = new TableClientBuilder() .connectionString(connectionString) .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)) .tableName(tableName2); if (interceptorManager.isPlaybackMode()) { builder.httpClient(playbackClient); } else { builder.httpClient(HttpClient.createDefault()); if (!interceptorManager.isLiveMode()) { builder.addPolicy(recordPolicy); } builder.addPolicy(new RetryPolicy(new ExponentialBackoff(6, Duration.ofMillis(1500), Duration.ofSeconds(100)))); } final TableAsyncClient tableClient2 = builder.buildAsyncClient(); StepVerifier.create(tableClient2.create()) .expectComplete() .verify(); } @Test void createTableWithResponseAsync() { final String tableName2 = testResourceNamer.randomName("tableName", 20); final String connectionString = TestUtils.getConnectionString(interceptorManager.isPlaybackMode()); final TableClientBuilder builder = new TableClientBuilder() .connectionString(connectionString) .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)) .tableName(tableName2); if (interceptorManager.isPlaybackMode()) { builder.httpClient(playbackClient); } else { builder.httpClient(HttpClient.createDefault()); if (!interceptorManager.isLiveMode()) { builder.addPolicy(recordPolicy); } builder.addPolicy(new RetryPolicy(new ExponentialBackoff(6, Duration.ofMillis(1500), Duration.ofSeconds(100)))); } final TableAsyncClient tableClient2 = builder.buildAsyncClient(); final int expectedStatusCode = 204; StepVerifier.create(tableClient2.createWithResponse()) .assertNext(response -> { assertEquals(expectedStatusCode, response.getStatusCode()); }) .expectComplete() .verify(); } @Test void createEntityAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue); StepVerifier.create(tableClient.createEntity(tableEntity)) .expectComplete() .verify(); } @Test void createEntityWithResponseAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity entity = new TableEntity(partitionKeyValue, rowKeyValue); final int expectedStatusCode = 204; StepVerifier.create(tableClient.createEntityWithResponse(entity)) .assertNext(response -> { assertEquals(expectedStatusCode, response.getStatusCode()); }) .expectComplete() .verify(); } @Test void createEntityWithAllSupportedDataTypesAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue); final boolean booleanValue = true; final byte[] binaryValue = "Test value".getBytes(); final Date dateValue = new Date(); final OffsetDateTime offsetDateTimeValue = OffsetDateTime.now(); final double doubleValue = 2.0d; final UUID guidValue = UUID.randomUUID(); final int int32Value = 1337; final long int64Value = 1337L; final String stringValue = "This is table entity"; tableEntity.addProperty("BinaryTypeProperty", binaryValue); tableEntity.addProperty("BooleanTypeProperty", booleanValue); tableEntity.addProperty("DateTypeProperty", dateValue); tableEntity.addProperty("OffsetDateTimeTypeProperty", offsetDateTimeValue); tableEntity.addProperty("DoubleTypeProperty", doubleValue); tableEntity.addProperty("GuidTypeProperty", guidValue); tableEntity.addProperty("Int32TypeProperty", int32Value); tableEntity.addProperty("Int64TypeProperty", int64Value); tableEntity.addProperty("StringTypeProperty", stringValue); tableClient.createEntity(tableEntity).block(TIMEOUT); StepVerifier.create(tableClient.getEntityWithResponse(partitionKeyValue, rowKeyValue, null)) .assertNext(response -> { final TableEntity entity = response.getValue(); Map<String, Object> properties = entity.getProperties(); assertTrue(properties.get("BinaryTypeProperty") instanceof byte[]); assertTrue(properties.get("BooleanTypeProperty") instanceof Boolean); assertTrue(properties.get("DateTypeProperty") instanceof OffsetDateTime); assertTrue(properties.get("OffsetDateTimeTypeProperty") instanceof OffsetDateTime); assertTrue(properties.get("DoubleTypeProperty") instanceof Double); assertTrue(properties.get("GuidTypeProperty") instanceof UUID); assertTrue(properties.get("Int32TypeProperty") instanceof Integer); assertTrue(properties.get("Int64TypeProperty") instanceof Long); assertTrue(properties.get("StringTypeProperty") instanceof String); }) .expectComplete() .verify(); } @Test void createEntitySubclassAsync() { String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); String rowKeyValue = testResourceNamer.randomName("rowKey", 20); byte[] bytes = new byte[]{1, 2, 3}; boolean b = true; OffsetDateTime dateTime = OffsetDateTime.of(2020, 1, 1, 0, 0, 0, 0, ZoneOffset.UTC); double d = 1.23D; UUID uuid = UUID.fromString("11111111-2222-3333-4444-555555555555"); int i = 123; long l = 123L; String s = "Test"; SampleEntity.Color color = SampleEntity.Color.GREEN; SampleEntity tableEntity = new SampleEntity(partitionKeyValue, rowKeyValue); tableEntity.setByteField(bytes); tableEntity.setBooleanField(b); tableEntity.setDateTimeField(dateTime); tableEntity.setDoubleField(d); tableEntity.setUuidField(uuid); tableEntity.setIntField(i); tableEntity.setLongField(l); tableEntity.setStringField(s); tableEntity.setEnumField(color); tableClient.createEntity(tableEntity).block(TIMEOUT); StepVerifier.create(tableClient.getEntityWithResponse(partitionKeyValue, rowKeyValue, null)) .assertNext(response -> { TableEntity entity = response.getValue(); assertArrayEquals((byte[]) entity.getProperties().get("ByteField"), bytes); assertEquals(entity.getProperties().get("BooleanField"), b); assertTrue(dateTime.isEqual((OffsetDateTime) entity.getProperties().get("DateTimeField"))); assertEquals(entity.getProperties().get("DoubleField"), d); assertEquals(0, uuid.compareTo((UUID) entity.getProperties().get("UuidField"))); assertEquals(entity.getProperties().get("IntField"), i); assertEquals(entity.getProperties().get("LongField"), l); assertEquals(entity.getProperties().get("StringField"), s); assertEquals(entity.getProperties().get("EnumField"), color.name()); }) .expectComplete() .verify(); } @Test void deleteTableAsync() { StepVerifier.create(tableClient.delete()) .expectComplete() .verify(); } @Test void deleteTableWithResponseAsync() { final int expectedStatusCode = 204; StepVerifier.create(tableClient.deleteWithResponse()) .assertNext(response -> { assertEquals(expectedStatusCode, response.getStatusCode()); }) .expectComplete() .verify(); } @Test void deleteEntityAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue); tableClient.createEntity(tableEntity).block(TIMEOUT); final TableEntity createdEntity = tableClient.getEntity(partitionKeyValue, rowKeyValue).block(TIMEOUT); assertNotNull(createdEntity, "'createdEntity' should not be null."); assertNotNull(createdEntity.getETag(), "'eTag' should not be null."); StepVerifier.create(tableClient.deleteEntity(partitionKeyValue, rowKeyValue)) .expectComplete() .verify(); } @Test void deleteEntityWithResponseAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue); final int expectedStatusCode = 204; tableClient.createEntity(tableEntity).block(TIMEOUT); final TableEntity createdEntity = tableClient.getEntity(partitionKeyValue, rowKeyValue).block(TIMEOUT); assertNotNull(createdEntity, "'createdEntity' should not be null."); assertNotNull(createdEntity.getETag(), "'eTag' should not be null."); StepVerifier.create(tableClient.deleteEntityWithResponse(partitionKeyValue, rowKeyValue, null)) .assertNext(response -> { assertEquals(expectedStatusCode, response.getStatusCode()); }) .expectComplete() .verify(); } @Test void deleteEntityWithResponseMatchETagAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue); final int expectedStatusCode = 204; tableClient.createEntity(tableEntity).block(TIMEOUT); final TableEntity createdEntity = tableClient.getEntity(partitionKeyValue, rowKeyValue).block(TIMEOUT); assertNotNull(createdEntity, "'createdEntity' should not be null."); assertNotNull(createdEntity.getETag(), "'eTag' should not be null."); StepVerifier.create(tableClient.deleteEntityWithResponse(partitionKeyValue, rowKeyValue, createdEntity.getETag())) .assertNext(response -> { assertEquals(expectedStatusCode, response.getStatusCode()); }) .expectComplete() .verify(); } @Test void getEntityWithResponseAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue); final int expectedStatusCode = 200; tableClient.createEntity(tableEntity).block(TIMEOUT); StepVerifier.create(tableClient.getEntityWithResponse(partitionKeyValue, rowKeyValue, null)) .assertNext(response -> { final TableEntity entity = response.getValue(); assertEquals(expectedStatusCode, response.getStatusCode()); assertNotNull(entity); assertEquals(tableEntity.getPartitionKey(), entity.getPartitionKey()); assertEquals(tableEntity.getRowKey(), entity.getRowKey()); assertNotNull(entity.getTimestamp()); assertNotNull(entity.getETag()); assertNotNull(entity.getProperties()); }) .expectComplete() .verify(); } @Test void getEntityWithResponseWithSelectAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue); tableEntity.addProperty("Test", "Value"); final int expectedStatusCode = 200; tableClient.createEntity(tableEntity).block(TIMEOUT); StepVerifier.create(tableClient.getEntityWithResponse(partitionKeyValue, rowKeyValue, "Test")) .assertNext(response -> { final TableEntity entity = response.getValue(); assertEquals(expectedStatusCode, response.getStatusCode()); assertNotNull(entity); assertNull(entity.getPartitionKey()); assertNull(entity.getRowKey()); assertNull(entity.getTimestamp()); assertNotNull(entity.getETag()); assertEquals(entity.getProperties().get("Test"), "Value"); }) .expectComplete() .verify(); } @Test void getEntityWithResponseSubclassAsync() { String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); String rowKeyValue = testResourceNamer.randomName("rowKey", 20); byte[] bytes = new byte[]{1, 2, 3}; boolean b = true; OffsetDateTime dateTime = OffsetDateTime.of(2020, 1, 1, 0, 0, 0, 0, ZoneOffset.UTC); double d = 1.23D; UUID uuid = UUID.fromString("11111111-2222-3333-4444-555555555555"); int i = 123; long l = 123L; String s = "Test"; SampleEntity.Color color = SampleEntity.Color.GREEN; Map<String, Object> props = new HashMap<>(); props.put("ByteField", bytes); props.put("BooleanField", b); props.put("DateTimeField", dateTime); props.put("DoubleField", d); props.put("UuidField", uuid); props.put("IntField", i); props.put("LongField", l); props.put("StringField", s); props.put("EnumField", color); TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue); tableEntity.addProperties(props); int expectedStatusCode = 200; tableClient.createEntity(tableEntity).block(TIMEOUT); StepVerifier.create(tableClient.getEntityWithResponse(partitionKeyValue, rowKeyValue, null, SampleEntity.class)) .assertNext(response -> { SampleEntity entity = response.getValue(); assertEquals(expectedStatusCode, response.getStatusCode()); assertNotNull(entity); assertEquals(tableEntity.getPartitionKey(), entity.getPartitionKey()); assertEquals(tableEntity.getRowKey(), entity.getRowKey()); assertNotNull(entity.getTimestamp()); assertNotNull(entity.getETag()); assertArrayEquals(bytes, entity.getByteField()); assertEquals(b, entity.getBooleanField()); assertTrue(dateTime.isEqual(entity.getDateTimeField())); assertEquals(d, entity.getDoubleField()); assertEquals(0, uuid.compareTo(entity.getUuidField())); assertEquals(i, entity.getIntField()); assertEquals(l, entity.getLongField()); assertEquals(s, entity.getStringField()); assertEquals(color, entity.getEnumField()); }) .expectComplete() .verify(); } @Test void updateEntityWithResponseReplaceAsync() { updateEntityWithResponseAsync(UpdateMode.REPLACE); } @Test void updateEntityWithResponseMergeAsync() { updateEntityWithResponseAsync(UpdateMode.MERGE); } /** * In the case of {@link UpdateMode * In the case of {@link UpdateMode */ void updateEntityWithResponseAsync(UpdateMode mode) { final boolean expectOldProperty = mode == UpdateMode.MERGE; final String partitionKeyValue = testResourceNamer.randomName("APartitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("ARowKey", 20); final int expectedStatusCode = 204; final String oldPropertyKey = "propertyA"; final String newPropertyKey = "propertyB"; final TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue) .addProperty(oldPropertyKey, "valueA"); tableClient.createEntity(tableEntity).block(TIMEOUT); final TableEntity createdEntity = tableClient.getEntity(partitionKeyValue, rowKeyValue).block(TIMEOUT); assertNotNull(createdEntity, "'createdEntity' should not be null."); assertNotNull(createdEntity.getETag(), "'eTag' should not be null."); createdEntity.getProperties().remove(oldPropertyKey); createdEntity.addProperty(newPropertyKey, "valueB"); if (mode == UpdateMode.MERGE && tableClient.getTableUrl().contains("cosmos.azure.com")) { StepVerifier.create(tableClient.updateEntityWithResponse(createdEntity, true, mode)) .expectError(com.azure.data.tables.implementation.models.TableServiceErrorException.class) .verify(); } else { StepVerifier.create(tableClient.updateEntityWithResponse(createdEntity, true, mode)) .assertNext(response -> assertEquals(expectedStatusCode, response.getStatusCode())) .expectComplete() .verify(); StepVerifier.create(tableClient.getEntity(partitionKeyValue, rowKeyValue)) .assertNext(entity -> { final Map<String, Object> properties = entity.getProperties(); assertTrue(properties.containsKey(newPropertyKey)); assertEquals(expectOldProperty, properties.containsKey(oldPropertyKey)); }) .verifyComplete(); } } @Test @Test @Tag("ListEntities") void listEntitiesAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final String rowKeyValue2 = testResourceNamer.randomName("rowKey", 20); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue)).block(TIMEOUT); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue2)).block(TIMEOUT); StepVerifier.create(tableClient.listEntities()) .expectNextCount(2) .thenConsumeWhile(x -> true) .expectComplete() .verify(); } @Test @Tag("ListEntities") void listEntitiesWithFilterAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final String rowKeyValue2 = testResourceNamer.randomName("rowKey", 20); ListEntitiesOptions options = new ListEntitiesOptions().setFilter("RowKey eq '" + rowKeyValue + "'"); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue)).block(TIMEOUT); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue2)).block(TIMEOUT); StepVerifier.create(tableClient.listEntities(options)) .assertNext(returnEntity -> { assertEquals(partitionKeyValue, returnEntity.getPartitionKey()); assertEquals(rowKeyValue, returnEntity.getRowKey()); }) .expectNextCount(0) .thenConsumeWhile(x -> true) .expectComplete() .verify(); } @Test @Tag("ListEntities") void listEntitiesWithSelectAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity entity = new TableEntity(partitionKeyValue, rowKeyValue) .addProperty("propertyC", "valueC") .addProperty("propertyD", "valueD"); ListEntitiesOptions options = new ListEntitiesOptions() .setSelect("propertyC"); tableClient.createEntity(entity).block(TIMEOUT); StepVerifier.create(tableClient.listEntities(options)) .assertNext(returnEntity -> { assertNull(returnEntity.getRowKey()); assertNull(returnEntity.getPartitionKey()); assertEquals("valueC", returnEntity.getProperties().get("propertyC")); assertNull(returnEntity.getProperties().get("propertyD")); }) .expectComplete() .verify(); } @Test @Tag("ListEntities") void listEntitiesWithTopAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final String rowKeyValue2 = testResourceNamer.randomName("rowKey", 20); final String rowKeyValue3 = testResourceNamer.randomName("rowKey", 20); ListEntitiesOptions options = new ListEntitiesOptions().setTop(2); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue)).block(TIMEOUT); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue2)).block(TIMEOUT); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue3)).block(TIMEOUT); StepVerifier.create(tableClient.listEntities(options)) .expectNextCount(2) .thenConsumeWhile(x -> true) .expectComplete() .verify(); } @Test @Tag("ListEntities") void listEntitiesSubclassAsync() { String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); String rowKeyValue = testResourceNamer.randomName("rowKey", 20); String rowKeyValue2 = testResourceNamer.randomName("rowKey", 20); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue)).block(TIMEOUT); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue2)).block(TIMEOUT); StepVerifier.create(tableClient.listEntities(SampleEntity.class)) .expectNextCount(2) .thenConsumeWhile(x -> true) .expectComplete() .verify(); } }
nit: consistent use of final.
void getEntityWithResponseSubclassAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue); byte[] bytes = new byte[]{1, 2, 3}; boolean b = true; OffsetDateTime dateTime = OffsetDateTime.of(2020, 1, 1, 0, 0, 0, 0, ZoneOffset.UTC); double d = 1.23D; UUID uuid = UUID.fromString("11111111-2222-3333-4444-555555555555"); int i = 123; long l = 123L; String s = "Test"; SampleEntity.Color color = SampleEntity.Color.GREEN; Map<String, Object> props = new HashMap<>(); props.put("ByteField", bytes); props.put("BooleanField", b); props.put("DateTimeField", dateTime); props.put("DoubleField", d); props.put("UuidField", uuid); props.put("IntField", i); props.put("LongField", l); props.put("StringField", s); props.put("EnumField", color); tableEntity.addProperties(props); final int expectedStatusCode = 200; tableClient.createEntity(tableEntity).block(TIMEOUT); StepVerifier.create(tableClient.getEntityWithResponse(partitionKeyValue, rowKeyValue, null, SampleEntity.class)) .assertNext(response -> { final SampleEntity entity = response.getValue(); assertEquals(expectedStatusCode, response.getStatusCode()); assertNotNull(entity); assertEquals(tableEntity.getPartitionKey(), entity.getPartitionKey()); assertEquals(tableEntity.getRowKey(), entity.getRowKey()); assertNotNull(entity.getTimestamp()); assertNotNull(entity.getETag()); assertArrayEquals(bytes, entity.getByteField()); assertEquals(b, entity.getBooleanField()); assertTrue(dateTime.isEqual(entity.getDateTimeField())); assertEquals(d, entity.getDoubleField()); assertEquals(0, uuid.compareTo(entity.getUuidField())); assertEquals(i, entity.getIntField()); assertEquals(l, entity.getLongField()); assertEquals(s, entity.getStringField()); assertEquals(color, entity.getEnumField()); }) .expectComplete() .verify(); }
byte[] bytes = new byte[]{1, 2, 3};
void getEntityWithResponseSubclassAsync() { String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); String rowKeyValue = testResourceNamer.randomName("rowKey", 20); byte[] bytes = new byte[]{1, 2, 3}; boolean b = true; OffsetDateTime dateTime = OffsetDateTime.of(2020, 1, 1, 0, 0, 0, 0, ZoneOffset.UTC); double d = 1.23D; UUID uuid = UUID.fromString("11111111-2222-3333-4444-555555555555"); int i = 123; long l = 123L; String s = "Test"; SampleEntity.Color color = SampleEntity.Color.GREEN; Map<String, Object> props = new HashMap<>(); props.put("ByteField", bytes); props.put("BooleanField", b); props.put("DateTimeField", dateTime); props.put("DoubleField", d); props.put("UuidField", uuid); props.put("IntField", i); props.put("LongField", l); props.put("StringField", s); props.put("EnumField", color); TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue); tableEntity.addProperties(props); int expectedStatusCode = 200; tableClient.createEntity(tableEntity).block(TIMEOUT); StepVerifier.create(tableClient.getEntityWithResponse(partitionKeyValue, rowKeyValue, null, SampleEntity.class)) .assertNext(response -> { SampleEntity entity = response.getValue(); assertEquals(expectedStatusCode, response.getStatusCode()); assertNotNull(entity); assertEquals(tableEntity.getPartitionKey(), entity.getPartitionKey()); assertEquals(tableEntity.getRowKey(), entity.getRowKey()); assertNotNull(entity.getTimestamp()); assertNotNull(entity.getETag()); assertArrayEquals(bytes, entity.getByteField()); assertEquals(b, entity.getBooleanField()); assertTrue(dateTime.isEqual(entity.getDateTimeField())); assertEquals(d, entity.getDoubleField()); assertEquals(0, uuid.compareTo(entity.getUuidField())); assertEquals(i, entity.getIntField()); assertEquals(l, entity.getLongField()); assertEquals(s, entity.getStringField()); assertEquals(color, entity.getEnumField()); }) .expectComplete() .verify(); }
class TablesAsyncClientTest extends TestBase { private static final Duration TIMEOUT = Duration.ofSeconds(100); private TableAsyncClient tableClient; private HttpPipelinePolicy recordPolicy; private HttpClient playbackClient; @BeforeAll static void beforeAll() { StepVerifier.setDefaultTimeout(TIMEOUT); } @AfterAll static void afterAll() { StepVerifier.resetDefaultTimeout(); } @Override protected void beforeTest() { final String tableName = testResourceNamer.randomName("tableName", 20); final String connectionString = TestUtils.getConnectionString(interceptorManager.isPlaybackMode()); final TableClientBuilder builder = new TableClientBuilder() .connectionString(connectionString) .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)) .tableName(tableName); if (interceptorManager.isPlaybackMode()) { playbackClient = interceptorManager.getPlaybackClient(); builder.httpClient(playbackClient); } else { builder.httpClient(HttpClient.createDefault()); if (!interceptorManager.isLiveMode()) { recordPolicy = interceptorManager.getRecordPolicy(); builder.addPolicy(recordPolicy); } builder.addPolicy(new RetryPolicy(new ExponentialBackoff(6, Duration.ofMillis(1500), Duration.ofSeconds(100)))); } tableClient = builder.buildAsyncClient(); tableClient.create().block(TIMEOUT); } @Test void createTableAsync() { final String tableName2 = testResourceNamer.randomName("tableName", 20); final String connectionString = TestUtils.getConnectionString(interceptorManager.isPlaybackMode()); final TableClientBuilder builder = new TableClientBuilder() .connectionString(connectionString) .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)) .tableName(tableName2); if (interceptorManager.isPlaybackMode()) { builder.httpClient(playbackClient); } else { builder.httpClient(HttpClient.createDefault()); if (!interceptorManager.isLiveMode()) { builder.addPolicy(recordPolicy); } builder.addPolicy(new RetryPolicy(new ExponentialBackoff(6, Duration.ofMillis(1500), Duration.ofSeconds(100)))); } final TableAsyncClient tableClient2 = builder.buildAsyncClient(); StepVerifier.create(tableClient2.create()) .expectComplete() .verify(); } @Test void createTableWithResponseAsync() { final String tableName2 = testResourceNamer.randomName("tableName", 20); final String connectionString = TestUtils.getConnectionString(interceptorManager.isPlaybackMode()); final TableClientBuilder builder = new TableClientBuilder() .connectionString(connectionString) .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)) .tableName(tableName2); if (interceptorManager.isPlaybackMode()) { builder.httpClient(playbackClient); } else { builder.httpClient(HttpClient.createDefault()); if (!interceptorManager.isLiveMode()) { builder.addPolicy(recordPolicy); } builder.addPolicy(new RetryPolicy(new ExponentialBackoff(6, Duration.ofMillis(1500), Duration.ofSeconds(100)))); } final TableAsyncClient tableClient2 = builder.buildAsyncClient(); final int expectedStatusCode = 204; StepVerifier.create(tableClient2.createWithResponse()) .assertNext(response -> { assertEquals(expectedStatusCode, response.getStatusCode()); }) .expectComplete() .verify(); } @Test void createEntityAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue); StepVerifier.create(tableClient.createEntity(tableEntity)) .expectComplete() .verify(); } @Test void createEntityWithResponseAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity entity = new TableEntity(partitionKeyValue, rowKeyValue); final int expectedStatusCode = 204; StepVerifier.create(tableClient.createEntityWithResponse(entity)) .assertNext(response -> { assertEquals(expectedStatusCode, response.getStatusCode()); }) .expectComplete() .verify(); } @Test void createEntityWithAllSupportedDataTypesAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue); final boolean booleanValue = true; final byte[] binaryValue = "Test value".getBytes(); final Date dateValue = new Date(); final OffsetDateTime offsetDateTimeValue = OffsetDateTime.now(); final double doubleValue = 2.0d; final UUID guidValue = UUID.randomUUID(); final int int32Value = 1337; final long int64Value = 1337L; final String stringValue = "This is table entity"; tableEntity.addProperty("BinaryTypeProperty", binaryValue); tableEntity.addProperty("BooleanTypeProperty", booleanValue); tableEntity.addProperty("DateTypeProperty", dateValue); tableEntity.addProperty("OffsetDateTimeTypeProperty", offsetDateTimeValue); tableEntity.addProperty("DoubleTypeProperty", doubleValue); tableEntity.addProperty("GuidTypeProperty", guidValue); tableEntity.addProperty("Int32TypeProperty", int32Value); tableEntity.addProperty("Int64TypeProperty", int64Value); tableEntity.addProperty("StringTypeProperty", stringValue); tableClient.createEntity(tableEntity).block(TIMEOUT); StepVerifier.create(tableClient.getEntityWithResponse(partitionKeyValue, rowKeyValue, null)) .assertNext(response -> { final TableEntity entity = response.getValue(); Map<String, Object> properties = entity.getProperties(); assertTrue(properties.get("BinaryTypeProperty") instanceof byte[]); assertTrue(properties.get("BooleanTypeProperty") instanceof Boolean); assertTrue(properties.get("DateTypeProperty") instanceof OffsetDateTime); assertTrue(properties.get("OffsetDateTimeTypeProperty") instanceof OffsetDateTime); assertTrue(properties.get("DoubleTypeProperty") instanceof Double); assertTrue(properties.get("GuidTypeProperty") instanceof UUID); assertTrue(properties.get("Int32TypeProperty") instanceof Integer); assertTrue(properties.get("Int64TypeProperty") instanceof Long); assertTrue(properties.get("StringTypeProperty") instanceof String); }) .expectComplete() .verify(); } @Test void createEntitySubclassAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); byte[] bytes = new byte[]{1, 2, 3}; boolean b = true; OffsetDateTime dateTime = OffsetDateTime.of(2020, 1, 1, 0, 0, 0, 0, ZoneOffset.UTC); double d = 1.23D; UUID uuid = UUID.fromString("11111111-2222-3333-4444-555555555555"); int i = 123; long l = 123L; String s = "Test"; SampleEntity.Color color = SampleEntity.Color.GREEN; SampleEntity tableEntity = new SampleEntity(partitionKeyValue, rowKeyValue); tableEntity.setByteField(bytes); tableEntity.setBooleanField(b); tableEntity.setDateTimeField(dateTime); tableEntity.setDoubleField(d); tableEntity.setUuidField(uuid); tableEntity.setIntField(i); tableEntity.setLongField(l); tableEntity.setStringField(s); tableEntity.setEnumField(color); tableClient.createEntity(tableEntity).block(TIMEOUT); StepVerifier.create(tableClient.getEntityWithResponse(partitionKeyValue, rowKeyValue, null)) .assertNext(response -> { final TableEntity entity = response.getValue(); assertArrayEquals((byte[]) entity.getProperties().get("ByteField"), bytes); assertEquals(entity.getProperties().get("BooleanField"), b); assertTrue(dateTime.isEqual((OffsetDateTime) entity.getProperties().get("DateTimeField"))); assertEquals(entity.getProperties().get("DoubleField"), d); assertEquals(0, uuid.compareTo((UUID) entity.getProperties().get("UuidField"))); assertEquals(entity.getProperties().get("IntField"), i); assertEquals(entity.getProperties().get("LongField"), l); assertEquals(entity.getProperties().get("StringField"), s); assertEquals(entity.getProperties().get("EnumField"), color.name()); }) .expectComplete() .verify(); } @Test void deleteTableAsync() { StepVerifier.create(tableClient.delete()) .expectComplete() .verify(); } @Test void deleteTableWithResponseAsync() { final int expectedStatusCode = 204; StepVerifier.create(tableClient.deleteWithResponse()) .assertNext(response -> { assertEquals(expectedStatusCode, response.getStatusCode()); }) .expectComplete() .verify(); } @Test void deleteEntityAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue); tableClient.createEntity(tableEntity).block(TIMEOUT); final TableEntity createdEntity = tableClient.getEntity(partitionKeyValue, rowKeyValue).block(TIMEOUT); assertNotNull(createdEntity, "'createdEntity' should not be null."); assertNotNull(createdEntity.getETag(), "'eTag' should not be null."); StepVerifier.create(tableClient.deleteEntity(partitionKeyValue, rowKeyValue)) .expectComplete() .verify(); } @Test void deleteEntityWithResponseAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue); final int expectedStatusCode = 204; tableClient.createEntity(tableEntity).block(TIMEOUT); final TableEntity createdEntity = tableClient.getEntity(partitionKeyValue, rowKeyValue).block(TIMEOUT); assertNotNull(createdEntity, "'createdEntity' should not be null."); assertNotNull(createdEntity.getETag(), "'eTag' should not be null."); StepVerifier.create(tableClient.deleteEntityWithResponse(partitionKeyValue, rowKeyValue, null)) .assertNext(response -> { assertEquals(expectedStatusCode, response.getStatusCode()); }) .expectComplete() .verify(); } @Test void deleteEntityWithResponseMatchETagAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue); final int expectedStatusCode = 204; tableClient.createEntity(tableEntity).block(TIMEOUT); final TableEntity createdEntity = tableClient.getEntity(partitionKeyValue, rowKeyValue).block(TIMEOUT); assertNotNull(createdEntity, "'createdEntity' should not be null."); assertNotNull(createdEntity.getETag(), "'eTag' should not be null."); StepVerifier.create(tableClient.deleteEntityWithResponse(partitionKeyValue, rowKeyValue, createdEntity.getETag())) .assertNext(response -> { assertEquals(expectedStatusCode, response.getStatusCode()); }) .expectComplete() .verify(); } @Test void getEntityWithResponseAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue); final int expectedStatusCode = 200; tableClient.createEntity(tableEntity).block(TIMEOUT); StepVerifier.create(tableClient.getEntityWithResponse(partitionKeyValue, rowKeyValue, null)) .assertNext(response -> { final TableEntity entity = response.getValue(); assertEquals(expectedStatusCode, response.getStatusCode()); assertNotNull(entity); assertEquals(tableEntity.getPartitionKey(), entity.getPartitionKey()); assertEquals(tableEntity.getRowKey(), entity.getRowKey()); assertNotNull(entity.getTimestamp()); assertNotNull(entity.getETag()); assertNotNull(entity.getProperties()); }) .expectComplete() .verify(); } @Test void getEntityWithResponseWithSelectAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue); tableEntity.addProperty("Test", "Value"); final int expectedStatusCode = 200; tableClient.createEntity(tableEntity).block(TIMEOUT); StepVerifier.create(tableClient.getEntityWithResponse(partitionKeyValue, rowKeyValue, "Test")) .assertNext(response -> { final TableEntity entity = response.getValue(); assertEquals(expectedStatusCode, response.getStatusCode()); assertNotNull(entity); assertNull(entity.getPartitionKey()); assertNull(entity.getRowKey()); assertNull(entity.getTimestamp()); assertNotNull(entity.getETag()); assertEquals(entity.getProperties().get("Test"), "Value"); }) .expectComplete() .verify(); } @Test @Test void updateEntityWithResponseReplaceAsync() { updateEntityWithResponseAsync(UpdateMode.REPLACE); } @Test void updateEntityWithResponseMergeAsync() { updateEntityWithResponseAsync(UpdateMode.MERGE); } /** * In the case of {@link UpdateMode * In the case of {@link UpdateMode */ void updateEntityWithResponseAsync(UpdateMode mode) { final boolean expectOldProperty = mode == UpdateMode.MERGE; final String partitionKeyValue = testResourceNamer.randomName("APartitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("ARowKey", 20); final int expectedStatusCode = 204; final String oldPropertyKey = "propertyA"; final String newPropertyKey = "propertyB"; final TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue) .addProperty(oldPropertyKey, "valueA"); tableClient.createEntity(tableEntity).block(TIMEOUT); final TableEntity createdEntity = tableClient.getEntity(partitionKeyValue, rowKeyValue).block(TIMEOUT); assertNotNull(createdEntity, "'createdEntity' should not be null."); assertNotNull(createdEntity.getETag(), "'eTag' should not be null."); createdEntity.getProperties().remove(oldPropertyKey); createdEntity.addProperty(newPropertyKey, "valueB"); if (mode == UpdateMode.MERGE && tableClient.getTableUrl().contains("cosmos.azure.com")) { StepVerifier.create(tableClient.updateEntityWithResponse(createdEntity, true, mode)) .expectError(com.azure.data.tables.implementation.models.TableServiceErrorException.class) .verify(); } else { StepVerifier.create(tableClient.updateEntityWithResponse(createdEntity, true, mode)) .assertNext(response -> assertEquals(expectedStatusCode, response.getStatusCode())) .expectComplete() .verify(); StepVerifier.create(tableClient.getEntity(partitionKeyValue, rowKeyValue)) .assertNext(entity -> { final Map<String, Object> properties = entity.getProperties(); assertTrue(properties.containsKey(newPropertyKey)); assertEquals(expectOldProperty, properties.containsKey(oldPropertyKey)); }) .verifyComplete(); } } @Test void updateEntityWithResponseSubclassAsync() { final String partitionKeyValue = testResourceNamer.randomName("APartitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("ARowKey", 20); final int expectedStatusCode = 204; SingleFieldEntity tableEntity = new SingleFieldEntity(partitionKeyValue, rowKeyValue); tableEntity.setSubclassProperty("InitialValue"); tableClient.createEntity(tableEntity).block(TIMEOUT); tableEntity.setSubclassProperty("UpdatedValue"); StepVerifier.create(tableClient.updateEntityWithResponse(tableEntity, true, UpdateMode.MERGE)) .assertNext(response -> assertEquals(expectedStatusCode, response.getStatusCode())) .expectComplete() .verify(); StepVerifier.create(tableClient.getEntity(partitionKeyValue, rowKeyValue)) .assertNext(entity -> { final Map<String, Object> properties = entity.getProperties(); assertTrue(properties.containsKey("SubclassProperty")); assertEquals("UpdatedValue", properties.get("SubclassProperty")); }) .verifyComplete(); } @Test @Tag("ListEntities") void listEntitiesAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final String rowKeyValue2 = testResourceNamer.randomName("rowKey", 20); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue)).block(TIMEOUT); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue2)).block(TIMEOUT); StepVerifier.create(tableClient.listEntities()) .expectNextCount(2) .thenConsumeWhile(x -> true) .expectComplete() .verify(); } @Test @Tag("ListEntities") void listEntitiesWithFilterAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final String rowKeyValue2 = testResourceNamer.randomName("rowKey", 20); ListEntitiesOptions options = new ListEntitiesOptions().setFilter("RowKey eq '" + rowKeyValue + "'"); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue)).block(TIMEOUT); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue2)).block(TIMEOUT); StepVerifier.create(tableClient.listEntities(options)) .assertNext(returnEntity -> { assertEquals(partitionKeyValue, returnEntity.getPartitionKey()); assertEquals(rowKeyValue, returnEntity.getRowKey()); }) .expectNextCount(0) .thenConsumeWhile(x -> true) .expectComplete() .verify(); } @Test @Tag("ListEntities") void listEntitiesWithSelectAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity entity = new TableEntity(partitionKeyValue, rowKeyValue) .addProperty("propertyC", "valueC") .addProperty("propertyD", "valueD"); ListEntitiesOptions options = new ListEntitiesOptions() .setSelect("propertyC"); tableClient.createEntity(entity).block(TIMEOUT); StepVerifier.create(tableClient.listEntities(options)) .assertNext(returnEntity -> { assertNull(returnEntity.getRowKey()); assertNull(returnEntity.getPartitionKey()); assertEquals("valueC", returnEntity.getProperties().get("propertyC")); assertNull(returnEntity.getProperties().get("propertyD")); }) .expectComplete() .verify(); } @Test @Tag("ListEntities") void listEntitiesWithTopAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final String rowKeyValue2 = testResourceNamer.randomName("rowKey", 20); final String rowKeyValue3 = testResourceNamer.randomName("rowKey", 20); ListEntitiesOptions options = new ListEntitiesOptions().setTop(2); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue)).block(TIMEOUT); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue2)).block(TIMEOUT); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue3)).block(TIMEOUT); StepVerifier.create(tableClient.listEntities(options)) .expectNextCount(2) .thenConsumeWhile(x -> true) .expectComplete() .verify(); } @Test @Tag("ListEntities") void listEntitiesSubclassAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final String rowKeyValue2 = testResourceNamer.randomName("rowKey", 20); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue)).block(TIMEOUT); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue2)).block(TIMEOUT); StepVerifier.create(tableClient.listEntities(SampleEntity.class)) .expectNextCount(2) .thenConsumeWhile(x -> true) .expectComplete() .verify(); } }
class TablesAsyncClientTest extends TestBase { private static final Duration TIMEOUT = Duration.ofSeconds(100); private TableAsyncClient tableClient; private HttpPipelinePolicy recordPolicy; private HttpClient playbackClient; @BeforeAll static void beforeAll() { StepVerifier.setDefaultTimeout(TIMEOUT); } @AfterAll static void afterAll() { StepVerifier.resetDefaultTimeout(); } @Override protected void beforeTest() { final String tableName = testResourceNamer.randomName("tableName", 20); final String connectionString = TestUtils.getConnectionString(interceptorManager.isPlaybackMode()); final TableClientBuilder builder = new TableClientBuilder() .connectionString(connectionString) .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)) .tableName(tableName); if (interceptorManager.isPlaybackMode()) { playbackClient = interceptorManager.getPlaybackClient(); builder.httpClient(playbackClient); } else { builder.httpClient(HttpClient.createDefault()); if (!interceptorManager.isLiveMode()) { recordPolicy = interceptorManager.getRecordPolicy(); builder.addPolicy(recordPolicy); } builder.addPolicy(new RetryPolicy(new ExponentialBackoff(6, Duration.ofMillis(1500), Duration.ofSeconds(100)))); } tableClient = builder.buildAsyncClient(); tableClient.create().block(TIMEOUT); } @Test void createTableAsync() { final String tableName2 = testResourceNamer.randomName("tableName", 20); final String connectionString = TestUtils.getConnectionString(interceptorManager.isPlaybackMode()); final TableClientBuilder builder = new TableClientBuilder() .connectionString(connectionString) .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)) .tableName(tableName2); if (interceptorManager.isPlaybackMode()) { builder.httpClient(playbackClient); } else { builder.httpClient(HttpClient.createDefault()); if (!interceptorManager.isLiveMode()) { builder.addPolicy(recordPolicy); } builder.addPolicy(new RetryPolicy(new ExponentialBackoff(6, Duration.ofMillis(1500), Duration.ofSeconds(100)))); } final TableAsyncClient tableClient2 = builder.buildAsyncClient(); StepVerifier.create(tableClient2.create()) .expectComplete() .verify(); } @Test void createTableWithResponseAsync() { final String tableName2 = testResourceNamer.randomName("tableName", 20); final String connectionString = TestUtils.getConnectionString(interceptorManager.isPlaybackMode()); final TableClientBuilder builder = new TableClientBuilder() .connectionString(connectionString) .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)) .tableName(tableName2); if (interceptorManager.isPlaybackMode()) { builder.httpClient(playbackClient); } else { builder.httpClient(HttpClient.createDefault()); if (!interceptorManager.isLiveMode()) { builder.addPolicy(recordPolicy); } builder.addPolicy(new RetryPolicy(new ExponentialBackoff(6, Duration.ofMillis(1500), Duration.ofSeconds(100)))); } final TableAsyncClient tableClient2 = builder.buildAsyncClient(); final int expectedStatusCode = 204; StepVerifier.create(tableClient2.createWithResponse()) .assertNext(response -> { assertEquals(expectedStatusCode, response.getStatusCode()); }) .expectComplete() .verify(); } @Test void createEntityAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue); StepVerifier.create(tableClient.createEntity(tableEntity)) .expectComplete() .verify(); } @Test void createEntityWithResponseAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity entity = new TableEntity(partitionKeyValue, rowKeyValue); final int expectedStatusCode = 204; StepVerifier.create(tableClient.createEntityWithResponse(entity)) .assertNext(response -> { assertEquals(expectedStatusCode, response.getStatusCode()); }) .expectComplete() .verify(); } @Test void createEntityWithAllSupportedDataTypesAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue); final boolean booleanValue = true; final byte[] binaryValue = "Test value".getBytes(); final Date dateValue = new Date(); final OffsetDateTime offsetDateTimeValue = OffsetDateTime.now(); final double doubleValue = 2.0d; final UUID guidValue = UUID.randomUUID(); final int int32Value = 1337; final long int64Value = 1337L; final String stringValue = "This is table entity"; tableEntity.addProperty("BinaryTypeProperty", binaryValue); tableEntity.addProperty("BooleanTypeProperty", booleanValue); tableEntity.addProperty("DateTypeProperty", dateValue); tableEntity.addProperty("OffsetDateTimeTypeProperty", offsetDateTimeValue); tableEntity.addProperty("DoubleTypeProperty", doubleValue); tableEntity.addProperty("GuidTypeProperty", guidValue); tableEntity.addProperty("Int32TypeProperty", int32Value); tableEntity.addProperty("Int64TypeProperty", int64Value); tableEntity.addProperty("StringTypeProperty", stringValue); tableClient.createEntity(tableEntity).block(TIMEOUT); StepVerifier.create(tableClient.getEntityWithResponse(partitionKeyValue, rowKeyValue, null)) .assertNext(response -> { final TableEntity entity = response.getValue(); Map<String, Object> properties = entity.getProperties(); assertTrue(properties.get("BinaryTypeProperty") instanceof byte[]); assertTrue(properties.get("BooleanTypeProperty") instanceof Boolean); assertTrue(properties.get("DateTypeProperty") instanceof OffsetDateTime); assertTrue(properties.get("OffsetDateTimeTypeProperty") instanceof OffsetDateTime); assertTrue(properties.get("DoubleTypeProperty") instanceof Double); assertTrue(properties.get("GuidTypeProperty") instanceof UUID); assertTrue(properties.get("Int32TypeProperty") instanceof Integer); assertTrue(properties.get("Int64TypeProperty") instanceof Long); assertTrue(properties.get("StringTypeProperty") instanceof String); }) .expectComplete() .verify(); } @Test void createEntitySubclassAsync() { String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); String rowKeyValue = testResourceNamer.randomName("rowKey", 20); byte[] bytes = new byte[]{1, 2, 3}; boolean b = true; OffsetDateTime dateTime = OffsetDateTime.of(2020, 1, 1, 0, 0, 0, 0, ZoneOffset.UTC); double d = 1.23D; UUID uuid = UUID.fromString("11111111-2222-3333-4444-555555555555"); int i = 123; long l = 123L; String s = "Test"; SampleEntity.Color color = SampleEntity.Color.GREEN; SampleEntity tableEntity = new SampleEntity(partitionKeyValue, rowKeyValue); tableEntity.setByteField(bytes); tableEntity.setBooleanField(b); tableEntity.setDateTimeField(dateTime); tableEntity.setDoubleField(d); tableEntity.setUuidField(uuid); tableEntity.setIntField(i); tableEntity.setLongField(l); tableEntity.setStringField(s); tableEntity.setEnumField(color); tableClient.createEntity(tableEntity).block(TIMEOUT); StepVerifier.create(tableClient.getEntityWithResponse(partitionKeyValue, rowKeyValue, null)) .assertNext(response -> { TableEntity entity = response.getValue(); assertArrayEquals((byte[]) entity.getProperties().get("ByteField"), bytes); assertEquals(entity.getProperties().get("BooleanField"), b); assertTrue(dateTime.isEqual((OffsetDateTime) entity.getProperties().get("DateTimeField"))); assertEquals(entity.getProperties().get("DoubleField"), d); assertEquals(0, uuid.compareTo((UUID) entity.getProperties().get("UuidField"))); assertEquals(entity.getProperties().get("IntField"), i); assertEquals(entity.getProperties().get("LongField"), l); assertEquals(entity.getProperties().get("StringField"), s); assertEquals(entity.getProperties().get("EnumField"), color.name()); }) .expectComplete() .verify(); } @Test void deleteTableAsync() { StepVerifier.create(tableClient.delete()) .expectComplete() .verify(); } @Test void deleteTableWithResponseAsync() { final int expectedStatusCode = 204; StepVerifier.create(tableClient.deleteWithResponse()) .assertNext(response -> { assertEquals(expectedStatusCode, response.getStatusCode()); }) .expectComplete() .verify(); } @Test void deleteEntityAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue); tableClient.createEntity(tableEntity).block(TIMEOUT); final TableEntity createdEntity = tableClient.getEntity(partitionKeyValue, rowKeyValue).block(TIMEOUT); assertNotNull(createdEntity, "'createdEntity' should not be null."); assertNotNull(createdEntity.getETag(), "'eTag' should not be null."); StepVerifier.create(tableClient.deleteEntity(partitionKeyValue, rowKeyValue)) .expectComplete() .verify(); } @Test void deleteEntityWithResponseAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue); final int expectedStatusCode = 204; tableClient.createEntity(tableEntity).block(TIMEOUT); final TableEntity createdEntity = tableClient.getEntity(partitionKeyValue, rowKeyValue).block(TIMEOUT); assertNotNull(createdEntity, "'createdEntity' should not be null."); assertNotNull(createdEntity.getETag(), "'eTag' should not be null."); StepVerifier.create(tableClient.deleteEntityWithResponse(partitionKeyValue, rowKeyValue, null)) .assertNext(response -> { assertEquals(expectedStatusCode, response.getStatusCode()); }) .expectComplete() .verify(); } @Test void deleteEntityWithResponseMatchETagAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue); final int expectedStatusCode = 204; tableClient.createEntity(tableEntity).block(TIMEOUT); final TableEntity createdEntity = tableClient.getEntity(partitionKeyValue, rowKeyValue).block(TIMEOUT); assertNotNull(createdEntity, "'createdEntity' should not be null."); assertNotNull(createdEntity.getETag(), "'eTag' should not be null."); StepVerifier.create(tableClient.deleteEntityWithResponse(partitionKeyValue, rowKeyValue, createdEntity.getETag())) .assertNext(response -> { assertEquals(expectedStatusCode, response.getStatusCode()); }) .expectComplete() .verify(); } @Test void getEntityWithResponseAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue); final int expectedStatusCode = 200; tableClient.createEntity(tableEntity).block(TIMEOUT); StepVerifier.create(tableClient.getEntityWithResponse(partitionKeyValue, rowKeyValue, null)) .assertNext(response -> { final TableEntity entity = response.getValue(); assertEquals(expectedStatusCode, response.getStatusCode()); assertNotNull(entity); assertEquals(tableEntity.getPartitionKey(), entity.getPartitionKey()); assertEquals(tableEntity.getRowKey(), entity.getRowKey()); assertNotNull(entity.getTimestamp()); assertNotNull(entity.getETag()); assertNotNull(entity.getProperties()); }) .expectComplete() .verify(); } @Test void getEntityWithResponseWithSelectAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue); tableEntity.addProperty("Test", "Value"); final int expectedStatusCode = 200; tableClient.createEntity(tableEntity).block(TIMEOUT); StepVerifier.create(tableClient.getEntityWithResponse(partitionKeyValue, rowKeyValue, "Test")) .assertNext(response -> { final TableEntity entity = response.getValue(); assertEquals(expectedStatusCode, response.getStatusCode()); assertNotNull(entity); assertNull(entity.getPartitionKey()); assertNull(entity.getRowKey()); assertNull(entity.getTimestamp()); assertNotNull(entity.getETag()); assertEquals(entity.getProperties().get("Test"), "Value"); }) .expectComplete() .verify(); } @Test @Test void updateEntityWithResponseReplaceAsync() { updateEntityWithResponseAsync(UpdateMode.REPLACE); } @Test void updateEntityWithResponseMergeAsync() { updateEntityWithResponseAsync(UpdateMode.MERGE); } /** * In the case of {@link UpdateMode * In the case of {@link UpdateMode */ void updateEntityWithResponseAsync(UpdateMode mode) { final boolean expectOldProperty = mode == UpdateMode.MERGE; final String partitionKeyValue = testResourceNamer.randomName("APartitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("ARowKey", 20); final int expectedStatusCode = 204; final String oldPropertyKey = "propertyA"; final String newPropertyKey = "propertyB"; final TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue) .addProperty(oldPropertyKey, "valueA"); tableClient.createEntity(tableEntity).block(TIMEOUT); final TableEntity createdEntity = tableClient.getEntity(partitionKeyValue, rowKeyValue).block(TIMEOUT); assertNotNull(createdEntity, "'createdEntity' should not be null."); assertNotNull(createdEntity.getETag(), "'eTag' should not be null."); createdEntity.getProperties().remove(oldPropertyKey); createdEntity.addProperty(newPropertyKey, "valueB"); if (mode == UpdateMode.MERGE && tableClient.getTableUrl().contains("cosmos.azure.com")) { StepVerifier.create(tableClient.updateEntityWithResponse(createdEntity, true, mode)) .expectError(com.azure.data.tables.implementation.models.TableServiceErrorException.class) .verify(); } else { StepVerifier.create(tableClient.updateEntityWithResponse(createdEntity, true, mode)) .assertNext(response -> assertEquals(expectedStatusCode, response.getStatusCode())) .expectComplete() .verify(); StepVerifier.create(tableClient.getEntity(partitionKeyValue, rowKeyValue)) .assertNext(entity -> { final Map<String, Object> properties = entity.getProperties(); assertTrue(properties.containsKey(newPropertyKey)); assertEquals(expectOldProperty, properties.containsKey(oldPropertyKey)); }) .verifyComplete(); } } @Test void updateEntityWithResponseSubclassAsync() { String partitionKeyValue = testResourceNamer.randomName("APartitionKey", 20); String rowKeyValue = testResourceNamer.randomName("ARowKey", 20); int expectedStatusCode = 204; SingleFieldEntity tableEntity = new SingleFieldEntity(partitionKeyValue, rowKeyValue); tableEntity.setSubclassProperty("InitialValue"); tableClient.createEntity(tableEntity).block(TIMEOUT); tableEntity.setSubclassProperty("UpdatedValue"); StepVerifier.create(tableClient.updateEntityWithResponse(tableEntity, true, UpdateMode.MERGE)) .assertNext(response -> assertEquals(expectedStatusCode, response.getStatusCode())) .expectComplete() .verify(); StepVerifier.create(tableClient.getEntity(partitionKeyValue, rowKeyValue)) .assertNext(entity -> { Map<String, Object> properties = entity.getProperties(); assertTrue(properties.containsKey("SubclassProperty")); assertEquals("UpdatedValue", properties.get("SubclassProperty")); }) .verifyComplete(); } @Test @Tag("ListEntities") void listEntitiesAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final String rowKeyValue2 = testResourceNamer.randomName("rowKey", 20); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue)).block(TIMEOUT); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue2)).block(TIMEOUT); StepVerifier.create(tableClient.listEntities()) .expectNextCount(2) .thenConsumeWhile(x -> true) .expectComplete() .verify(); } @Test @Tag("ListEntities") void listEntitiesWithFilterAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final String rowKeyValue2 = testResourceNamer.randomName("rowKey", 20); ListEntitiesOptions options = new ListEntitiesOptions().setFilter("RowKey eq '" + rowKeyValue + "'"); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue)).block(TIMEOUT); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue2)).block(TIMEOUT); StepVerifier.create(tableClient.listEntities(options)) .assertNext(returnEntity -> { assertEquals(partitionKeyValue, returnEntity.getPartitionKey()); assertEquals(rowKeyValue, returnEntity.getRowKey()); }) .expectNextCount(0) .thenConsumeWhile(x -> true) .expectComplete() .verify(); } @Test @Tag("ListEntities") void listEntitiesWithSelectAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity entity = new TableEntity(partitionKeyValue, rowKeyValue) .addProperty("propertyC", "valueC") .addProperty("propertyD", "valueD"); ListEntitiesOptions options = new ListEntitiesOptions() .setSelect("propertyC"); tableClient.createEntity(entity).block(TIMEOUT); StepVerifier.create(tableClient.listEntities(options)) .assertNext(returnEntity -> { assertNull(returnEntity.getRowKey()); assertNull(returnEntity.getPartitionKey()); assertEquals("valueC", returnEntity.getProperties().get("propertyC")); assertNull(returnEntity.getProperties().get("propertyD")); }) .expectComplete() .verify(); } @Test @Tag("ListEntities") void listEntitiesWithTopAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final String rowKeyValue2 = testResourceNamer.randomName("rowKey", 20); final String rowKeyValue3 = testResourceNamer.randomName("rowKey", 20); ListEntitiesOptions options = new ListEntitiesOptions().setTop(2); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue)).block(TIMEOUT); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue2)).block(TIMEOUT); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue3)).block(TIMEOUT); StepVerifier.create(tableClient.listEntities(options)) .expectNextCount(2) .thenConsumeWhile(x -> true) .expectComplete() .verify(); } @Test @Tag("ListEntities") void listEntitiesSubclassAsync() { String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); String rowKeyValue = testResourceNamer.randomName("rowKey", 20); String rowKeyValue2 = testResourceNamer.randomName("rowKey", 20); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue)).block(TIMEOUT); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue2)).block(TIMEOUT); StepVerifier.create(tableClient.listEntities(SampleEntity.class)) .expectNextCount(2) .thenConsumeWhile(x -> true) .expectComplete() .verify(); } }
For a list the labelData is null
private static List<FormField> toFieldValueArray(List<FieldValue> valueArray, List<ReadResult> readResults) { return valueArray.stream() .map(fieldValue -> setFormField(fieldValue.getText(), null, fieldValue, readResults)) .collect(Collectors.toList()); }
.map(fieldValue -> setFormField(fieldValue.getText(), null, fieldValue, readResults))
private static List<FormField> toFieldValueArray(List<FieldValue> valueArray, List<ReadResult> readResults) { return valueArray.stream() .map(fieldValue -> { FieldData valueData = null; if (ARRAY != fieldValue.getType()) { valueData = new FieldData(fieldValue.getText(), toBoundingBox(fieldValue.getBoundingBox()), fieldValue.getPage() == null ? 1 : fieldValue.getPage(), setReferenceElements(fieldValue.getElements(), readResults)); } return setFormField(null, valueData, fieldValue, readResults); }) .collect(Collectors.toList()); }
class Transforms { private static final ClientLogger LOGGER = new ClientLogger(Transforms.class); private static final Pattern NON_DIGIT_PATTERN = Pattern.compile("[^0-9]+"); private static final float DEFAULT_CONFIDENCE_VALUE = 1.0f; private static final int DEFAULT_TABLE_SPAN = 1; private Transforms() { } /** * Helper method to transform the service returned {@link AnalyzeResult} to SDK model {@link RecognizedForm}. * * @param analyzeResult The service returned result for analyze custom forms. * @param includeFieldElements Boolean to indicate if to set reference elements data on fields. * * @return The List of {@code RecognizedForm}. */ static List<RecognizedForm> toRecognizedForm(AnalyzeResult analyzeResult, boolean includeFieldElements) { List<ReadResult> readResults = analyzeResult.getReadResults(); List<DocumentResult> documentResults = analyzeResult.getDocumentResults(); List<PageResult> pageResults = analyzeResult.getPageResults(); List<RecognizedForm> extractedFormList; List<FormPage> formPages = toRecognizedLayout(analyzeResult, includeFieldElements); if (!CoreUtils.isNullOrEmpty(documentResults)) { extractedFormList = new ArrayList<>(); for (DocumentResult documentResultItem : documentResults) { FormPageRange formPageRange; List<Integer> documentPageRange = documentResultItem.getPageRange(); if (documentPageRange.size() == 2) { formPageRange = new FormPageRange(documentPageRange.get(0), documentPageRange.get(1)); } else { formPageRange = new FormPageRange(1, 1); } Map<String, FormField> extractedFieldMap = getLabeledFieldMap(documentResultItem, readResults); extractedFormList.add(new RecognizedForm( extractedFieldMap, documentResultItem.getDocType(), formPageRange, formPages.subList(formPageRange.getFirstPageNumber() - 1, formPageRange.getLastPageNumber()))); } } else { extractedFormList = new ArrayList<>(); forEachWithIndex(pageResults, ((index, pageResultItem) -> { StringBuilder formType = new StringBuilder("form-"); int pageNumber = pageResultItem.getPage(); Integer clusterId = pageResultItem.getClusterId(); if (clusterId != null) { formType.append(clusterId); } Map<String, FormField> extractedFieldMap = getUnlabeledFieldMap(includeFieldElements, readResults, pageResultItem, pageNumber); extractedFormList.add(new RecognizedForm( extractedFieldMap, formType.toString(), new FormPageRange(pageNumber, pageNumber), Collections.singletonList(formPages.get(index)))); })); } return extractedFormList; } /** * Helper method to transform the service returned {@link AnalyzeResult} to SDK model {@link FormPage}. * * @param analyzeResult The service returned result for analyze layouts. * @param includeFieldElements Boolean to indicate if to set reference elements data on fields. * * @return The List of {@code FormPage}. */ static List<FormPage> toRecognizedLayout(AnalyzeResult analyzeResult, boolean includeFieldElements) { List<ReadResult> readResults = analyzeResult.getReadResults(); List<PageResult> pageResults = analyzeResult.getPageResults(); List<FormPage> formPages = new ArrayList<>(); boolean pageResultsIsNullOrEmpty = CoreUtils.isNullOrEmpty(pageResults); forEachWithIndex(readResults, ((index, readResultItem) -> { List<FormTable> perPageTableList = new ArrayList<>(); if (!pageResultsIsNullOrEmpty) { PageResult pageResultItem = pageResults.get(index); perPageTableList = getPageTables(pageResultItem, readResults, pageResultItem.getPage()); } List<FormLine> perPageFormLineList = new ArrayList<>(); if (includeFieldElements && !CoreUtils.isNullOrEmpty(readResultItem.getLines())) { perPageFormLineList = getReadResultFormLines(readResultItem); } formPages.add(getFormPage(readResultItem, perPageTableList, perPageFormLineList)); })); return formPages; } /** * Helper method to get per-page table information. * * @param pageResultItem The extracted page level information returned by the service. * @param readResults The text extraction result returned by the service. * @param pageNumber The 1 based page number on which these fields exist. * * @return The list of per page {@code FormTable}. */ static List<FormTable> getPageTables(PageResult pageResultItem, List<ReadResult> readResults, int pageNumber) { return pageResultItem.getTables().stream() .map(dataTable -> new FormTable(dataTable.getRows(), dataTable.getColumns(), dataTable.getCells() .stream() .map(dataTableCell -> new FormTableCell( dataTableCell.getRowIndex(), dataTableCell.getColumnIndex(), dataTableCell.getRowSpan() == null ? DEFAULT_TABLE_SPAN : dataTableCell.getRowSpan(), dataTableCell.getColumnSpan() == null ? DEFAULT_TABLE_SPAN : dataTableCell.getColumnSpan(), dataTableCell.getText(), toBoundingBox(dataTableCell.getBoundingBox()), dataTableCell.getConfidence(), dataTableCell.isHeader() == null ? false : dataTableCell.isHeader(), dataTableCell.isFooter() == null ? false : dataTableCell.isFooter(), pageNumber, setReferenceElements(dataTableCell.getElements(), readResults))) .collect(Collectors.toList()), pageNumber)) .collect(Collectors.toList()); } /** * Helper method to convert the per page {@link ReadResult} item to {@link FormLine}. * * @param readResultItem The per page text extraction item result returned by the service. * * @return The list of {@code FormLine}. */ static List<FormLine> getReadResultFormLines(ReadResult readResultItem) { return readResultItem.getLines().stream() .map(textLine -> new FormLine( textLine.getText(), toBoundingBox(textLine.getBoundingBox()), readResultItem.getPage(), toWords(textLine.getWords(), readResultItem.getPage()))) .collect(Collectors.toList()); } /** * The field map returned on analyze with an unlabeled model id. * * @param documentResultItem The extracted document level information. * @param readResults The text extraction result returned by the service. * @return The {@link RecognizedForm */ private static Map<String, FormField> getLabeledFieldMap(DocumentResult documentResultItem, List<ReadResult> readResults) { Map<String, FormField> recognizedFieldMap = new LinkedHashMap<>(); if (!CoreUtils.isNullOrEmpty(documentResultItem.getFields())) { documentResultItem.getFields().forEach((key, fieldValue) -> { if (fieldValue != null) { List<FormElement> formElementList = setReferenceElements(fieldValue.getElements(), readResults); FieldData valueData; if ("ReceiptType".equals(key) || com.azure.ai.formrecognizer.implementation.models.FieldValueType.ARRAY == fieldValue.getType()) { valueData = null; } else { valueData = new FieldData(fieldValue.getText(), toBoundingBox(fieldValue.getBoundingBox()), fieldValue.getPage(), formElementList); } recognizedFieldMap.put(key, setFormField(key, valueData, fieldValue, readResults)); } else { recognizedFieldMap.put(key, new FormField(key, null, null, null, DEFAULT_CONFIDENCE_VALUE)); } }); } return recognizedFieldMap; } /** * Helper method that converts the incoming service field value to one of the strongly typed SDK level * {@link FormField} with reference elements set when {@code includeFieldElements} is set to true. * * @param name The name of the field. * @param fieldValue The named field values returned by the service. * @param valueData The value text of the field. * @param readResults The text extraction result returned by the service. * * @return The strongly typed {@link FormField} for the field input. */ private static FormField setFormField(String name, FieldData valueData, FieldValue fieldValue, List<ReadResult> readResults) { com.azure.ai.formrecognizer.models.FieldValue value; switch (fieldValue.getType()) { case PHONE_NUMBER: value = new com.azure.ai.formrecognizer.models.FieldValue(fieldValue.getValuePhoneNumber(), FieldValueType.PHONE_NUMBER); break; case STRING: value = new com.azure.ai.formrecognizer.models.FieldValue(fieldValue.getValueString(), FieldValueType.STRING); break; case TIME: LocalTime fieldTime = fieldValue.getValueTime() == null ? null : LocalTime .parse(fieldValue.getValueTime(), DateTimeFormatter.ofPattern("HH:mm:ss")); value = new com.azure.ai.formrecognizer.models.FieldValue(fieldTime, FieldValueType.TIME); break; case DATE: value = new com.azure.ai.formrecognizer.models.FieldValue(fieldValue.getValueDate(), FieldValueType.DATE); break; case INTEGER: com.azure.ai.formrecognizer.models.FieldValue longFieldValue; if (fieldValue.getValueInteger() == null) { longFieldValue = new com.azure.ai.formrecognizer.models.FieldValue(null, FieldValueType.LONG); } else { longFieldValue = new com.azure.ai.formrecognizer.models.FieldValue(fieldValue.getValueInteger().longValue(), FieldValueType.LONG); } value = longFieldValue; break; case NUMBER: value = new com.azure.ai.formrecognizer.models.FieldValue(fieldValue.getValueNumber(), FieldValueType.FLOAT); break; case ARRAY: value = new com.azure.ai.formrecognizer.models.FieldValue( toFieldValueArray(fieldValue.getValueArray(), readResults), FieldValueType.LIST); break; case OBJECT: value = new com.azure.ai.formrecognizer.models.FieldValue( toFieldValueObject(fieldValue.getValueObject(), readResults), FieldValueType.MAP); break; default: throw LOGGER.logExceptionAsError(new RuntimeException("FieldValue Type not supported")); } FieldData labelData = null; if (name != null && name.equals(fieldValue.getText())) { valueData = new FieldData(name, toBoundingBox(fieldValue.getBoundingBox()), fieldValue.getPage() == null ? -1 : fieldValue.getPage(), setReferenceElements(fieldValue.getElements(), readResults)); } else { labelData = new FieldData(name, null, fieldValue.getPage() == null ? -1 : fieldValue.getPage(), setReferenceElements(fieldValue.getElements(), readResults)); } return new FormField(name, labelData, valueData, value, setDefaultConfidenceValue(fieldValue.getConfidence())); } /** * Helper method to set default confidence value if confidence returned by service is null. * * @param confidence the confidence returned by service. * * @return the field confidence value. */ private static float setDefaultConfidenceValue(Float confidence) { return confidence == null ? DEFAULT_CONFIDENCE_VALUE : confidence; } /** * Helper method to convert the service returned * {@link com.azure.ai.formrecognizer.implementation.models.FieldValue * to a SDK level map of {@link FormField}. * * @param valueObject The array of field values returned by the service in {@link FieldValue * * @return The Map of {@link FormField}. */ private static Map<String, FormField> toFieldValueObject(Map<String, FieldValue> valueObject, List<ReadResult> readResults) { Map<String, FormField> fieldValueObjectMap = new TreeMap<>(); valueObject.forEach((key, fieldValue) -> fieldValueObjectMap.put(key, setFormField(key, new FieldData(fieldValue.getText(), toBoundingBox(fieldValue.getBoundingBox()), fieldValue.getPage(), setReferenceElements(fieldValue.getElements(), readResults)), fieldValue, readResults) )); return fieldValueObjectMap; } /** * Helper method to convert the service returned * {@link com.azure.ai.formrecognizer.implementation.models.FieldValue * to a SDK level List of {@link FormField}. * * @param valueArray The array of field values returned by the service in {@link FieldValue * @param readResults The text extraction result returned by the service. * * @return The List of {@link FormField}. */ /** * Helper method to convert the page results to {@code FormPage form pages}. * * @param readResultItem The per page text extraction item result returned by the service. * @param perPageTableList The per page tables list. * @param perPageLineList The per page form lines. * * @return The per page {@code FormPage}. */ private static FormPage getFormPage(ReadResult readResultItem, List<FormTable> perPageTableList, List<FormLine> perPageLineList) { return new FormPage( readResultItem.getHeight(), readResultItem.getAngle(), LengthUnit.fromString(readResultItem.getUnit().toString()), readResultItem.getWidth(), perPageLineList, perPageTableList, readResultItem.getPage()); } /** * Helper method to set the {@link RecognizedForm * service. * * @param includeFieldElements Boolean to indicate if to set reference elements data on fields. * @param readResults The text extraction result returned by the service. * @param pageResultItem The extracted page level information returned by the service. * @param pageNumber The 1 based page number on which these fields exist. * * @return The fields populated on {@link RecognizedForm */ private static Map<String, FormField> getUnlabeledFieldMap(boolean includeFieldElements, List<ReadResult> readResults, PageResult pageResultItem, int pageNumber) { Map<String, FormField> formFieldMap = new LinkedHashMap<>(); List<KeyValuePair> keyValuePairs = pageResultItem.getKeyValuePairs(); forEachWithIndex(keyValuePairs, ((index, keyValuePair) -> { List<FormElement> formKeyContentList = null; List<FormElement> formValueContentList = null; if (includeFieldElements) { formKeyContentList = setReferenceElements(keyValuePair.getKey().getElements(), readResults); formValueContentList = setReferenceElements(keyValuePair.getValue().getElements(), readResults ); } FieldData labelData = new FieldData(keyValuePair.getKey().getText(), toBoundingBox(keyValuePair.getKey().getBoundingBox()), pageNumber, formKeyContentList); FieldData valueData = new FieldData(keyValuePair.getValue().getText(), toBoundingBox(keyValuePair.getValue().getBoundingBox()), pageNumber, formValueContentList); String fieldName = "field-" + index; FormField formField = new FormField(fieldName, labelData, valueData, new com.azure.ai.formrecognizer.models.FieldValue(keyValuePair.getValue().getText(), FieldValueType.STRING), setDefaultConfidenceValue(keyValuePair.getConfidence()) ); formFieldMap.put(fieldName, formField); })); return formFieldMap; } /** * Helper method to set the text reference elements on FieldValue/fields when {@code includeFieldElements} set to * true. * * @return The list if referenced elements. */ private static List<FormElement> setReferenceElements(List<String> elements, List<ReadResult> readResults) { if (CoreUtils.isNullOrEmpty(elements)) { return new ArrayList<>(); } List<FormElement> formElementList = new ArrayList<>(); elements.forEach(elementString -> { String[] indices = NON_DIGIT_PATTERN.matcher(elementString).replaceAll(" ").trim().split(" "); if (indices.length < 2) { throw LOGGER.logExceptionAsError(new RuntimeException("Cannot find corresponding reference elements " + "for the field value.")); } int readResultIndex = Integer.parseInt(indices[0]); int lineIndex = Integer.parseInt(indices[1]); if (indices.length == 3) { int wordIndex = Integer.parseInt(indices[2]); TextWord textWord = readResults.get(readResultIndex).getLines().get(lineIndex).getWords().get(wordIndex); FormWord wordElement = new FormWord(textWord.getText(), toBoundingBox(textWord.getBoundingBox()), readResultIndex + 1, setDefaultConfidenceValue(textWord.getConfidence())); formElementList.add(wordElement); } else { TextLine textLine = readResults.get(readResultIndex).getLines().get(lineIndex); FormLine lineElement = new FormLine(textLine.getText(), toBoundingBox(textLine.getBoundingBox()), readResultIndex + 1, toWords(textLine.getWords(), readResultIndex + 1)); formElementList.add(lineElement); } }); return formElementList; } /** * Helper method to convert the service level {@link TextWord} to list of SDK level model {@link FormWord}. * * @param words A list of word reference elements returned by the service. * @param pageNumber The 1 based page number on which this word element exists. * * @return The list of {@code FormWord words}. */ private static List<FormWord> toWords(List<TextWord> words, int pageNumber) { return words.stream() .map(textWord -> new FormWord( textWord.getText(), toBoundingBox(textWord.getBoundingBox()), pageNumber, setDefaultConfidenceValue(textWord.getConfidence())) ).collect(Collectors.toList()); } /** * Helper method to convert the service level modeled eight numbers representing the four points to SDK level * {@link FieldBoundingBox}. * * @param serviceBoundingBox A list of eight numbers representing the four points of a box. * * @return A {@link FieldBoundingBox}. */ private static FieldBoundingBox toBoundingBox(List<Float> serviceBoundingBox) { if (CoreUtils.isNullOrEmpty(serviceBoundingBox) || (serviceBoundingBox.size() % 2) != 0) { return null; } List<Point> pointList = new ArrayList<>(); for (int i = 0; i < serviceBoundingBox.size(); i++) { pointList.add(new Point(serviceBoundingBox.get(i), serviceBoundingBox.get(++i))); } return new FieldBoundingBox(pointList); } }
class Transforms { private static final ClientLogger LOGGER = new ClientLogger(Transforms.class); private static final Pattern NON_DIGIT_PATTERN = Pattern.compile("[^0-9]+"); private static final float DEFAULT_CONFIDENCE_VALUE = 1.0f; private static final int DEFAULT_TABLE_SPAN = 1; private Transforms() { } /** * Helper method to transform the service returned {@link AnalyzeResult} to SDK model {@link RecognizedForm}. * * @param analyzeResult The service returned result for analyze custom forms. * @param includeFieldElements Boolean to indicate if to set reference elements data on fields. * * @param modelId the unlabeled model Id used for recognition. * @return The List of {@code RecognizedForm}. */ static List<RecognizedForm> toRecognizedForm(AnalyzeResult analyzeResult, boolean includeFieldElements, String modelId) { List<ReadResult> readResults = analyzeResult.getReadResults(); List<DocumentResult> documentResults = analyzeResult.getDocumentResults(); List<PageResult> pageResults = analyzeResult.getPageResults(); List<RecognizedForm> extractedFormList; List<FormPage> formPages = toRecognizedLayout(analyzeResult, includeFieldElements); if (!CoreUtils.isNullOrEmpty(documentResults)) { extractedFormList = new ArrayList<>(); for (DocumentResult documentResultItem : documentResults) { FormPageRange formPageRange; List<Integer> documentPageRange = documentResultItem.getPageRange(); if (documentPageRange.size() == 2) { formPageRange = new FormPageRange(documentPageRange.get(0), documentPageRange.get(1)); } else { formPageRange = new FormPageRange(1, 1); } Map<String, FormField> extractedFieldMap = getLabeledFieldMap(documentResultItem, readResults); final RecognizedForm recognizedForm = new RecognizedForm( extractedFieldMap, documentResultItem.getDocType(), formPageRange, formPages.subList(formPageRange.getFirstPageNumber() - 1, formPageRange.getLastPageNumber())); PrivateFieldAccessHelper.set(recognizedForm, "formTypeConfidence", documentResultItem.getDocTypeConfidence()); if (documentResultItem.getModelId() != null) { PrivateFieldAccessHelper.set(recognizedForm, "modelId", documentResultItem.getModelId().toString()); } extractedFormList.add(recognizedForm); } } else { extractedFormList = new ArrayList<>(); forEachWithIndex(pageResults, ((index, pageResultItem) -> { StringBuilder formType = new StringBuilder("form-"); int pageNumber = pageResultItem.getPage(); Integer clusterId = pageResultItem.getClusterId(); if (clusterId != null) { formType.append(clusterId); } Map<String, FormField> extractedFieldMap = getUnlabeledFieldMap(includeFieldElements, readResults, pageResultItem, pageNumber); final RecognizedForm recognizedForm = new RecognizedForm( extractedFieldMap, formType.toString(), new FormPageRange(pageNumber, pageNumber), Collections.singletonList(formPages.get(index))); PrivateFieldAccessHelper.set(recognizedForm, "modelId", modelId); extractedFormList.add(recognizedForm); })); } return extractedFormList; } /** * Helper method to transform the service returned {@link AnalyzeResult} to SDK model {@link FormPage}. * * @param analyzeResult The service returned result for analyze layouts. * @param includeFieldElements Boolean to indicate if to set reference elements data on fields. * * @return The List of {@code FormPage}. */ static List<FormPage> toRecognizedLayout(AnalyzeResult analyzeResult, boolean includeFieldElements) { List<ReadResult> readResults = analyzeResult.getReadResults(); List<PageResult> pageResults = analyzeResult.getPageResults(); List<FormPage> formPages = new ArrayList<>(); boolean pageResultsIsNullOrEmpty = CoreUtils.isNullOrEmpty(pageResults); forEachWithIndex(readResults, ((index, readResultItem) -> { List<FormTable> perPageTableList = new ArrayList<>(); if (!pageResultsIsNullOrEmpty) { PageResult pageResultItem = pageResults.get(index); perPageTableList = getPageTables(pageResultItem, readResults, pageResultItem.getPage()); } List<FormLine> perPageFormLineList = new ArrayList<>(); if (includeFieldElements && !CoreUtils.isNullOrEmpty(readResultItem.getLines())) { perPageFormLineList = getReadResultFormLines(readResultItem); } formPages.add(getFormPage(readResultItem, perPageTableList, perPageFormLineList)); })); return formPages; } /** * Helper method to get per-page table information. * * @param pageResultItem The extracted page level information returned by the service. * @param readResults The text extraction result returned by the service. * @param pageNumber The 1 based page number on which these fields exist. * * @return The list of per page {@code FormTable}. */ static List<FormTable> getPageTables(PageResult pageResultItem, List<ReadResult> readResults, int pageNumber) { return pageResultItem.getTables().stream() .map(dataTable -> new FormTable(dataTable.getRows(), dataTable.getColumns(), dataTable.getCells() .stream() .map(dataTableCell -> new FormTableCell( dataTableCell.getRowIndex(), dataTableCell.getColumnIndex(), dataTableCell.getRowSpan() == null ? DEFAULT_TABLE_SPAN : dataTableCell.getRowSpan(), dataTableCell.getColumnSpan() == null ? DEFAULT_TABLE_SPAN : dataTableCell.getColumnSpan(), dataTableCell.getText(), toBoundingBox(dataTableCell.getBoundingBox()), dataTableCell.getConfidence(), dataTableCell.isHeader() == null ? false : dataTableCell.isHeader(), dataTableCell.isFooter() == null ? false : dataTableCell.isFooter(), pageNumber, setReferenceElements(dataTableCell.getElements(), readResults))) .collect(Collectors.toList()), pageNumber)) .collect(Collectors.toList()); } /** * Helper method to convert the per page {@link ReadResult} item to {@link FormLine}. * * @param readResultItem The per page text extraction item result returned by the service. * * @return The list of {@code FormLine}. */ static List<FormLine> getReadResultFormLines(ReadResult readResultItem) { return readResultItem.getLines().stream() .map(textLine -> new FormLine( textLine.getText(), toBoundingBox(textLine.getBoundingBox()), readResultItem.getPage(), toWords(textLine.getWords(), readResultItem.getPage()))) .collect(Collectors.toList()); } /** * The field map returned on analyze with an unlabeled model id. * * @param documentResultItem The extracted document level information. * @param readResults The text extraction result returned by the service. * @return The {@link RecognizedForm */ private static Map<String, FormField> getLabeledFieldMap(DocumentResult documentResultItem, List<ReadResult> readResults) { Map<String, FormField> recognizedFieldMap = new LinkedHashMap<>(); if (!CoreUtils.isNullOrEmpty(documentResultItem.getFields())) { documentResultItem.getFields().forEach((key, fieldValue) -> { if (fieldValue != null) { List<FormElement> formElementList = setReferenceElements(fieldValue.getElements(), readResults); FieldData valueData; if ("ReceiptType".equals(key) || ARRAY == fieldValue.getType()) { valueData = null; } else { valueData = new FieldData(fieldValue.getText(), toBoundingBox(fieldValue.getBoundingBox()), fieldValue.getPage(), formElementList); } recognizedFieldMap.put(key, setFormField(key, valueData, fieldValue, readResults)); } else { recognizedFieldMap.put(key, new FormField(key, null, null, null, DEFAULT_CONFIDENCE_VALUE)); } }); } return recognizedFieldMap; } /** * Helper method that converts the incoming service field value to one of the strongly typed SDK level * {@link FormField} with reference elements set when {@code includeFieldElements} is set to true. * * @param name The name of the field. * @param fieldValue The named field values returned by the service. * @param valueData The value text of the field. * @param readResults The text extraction result returned by the service. * * @return The strongly typed {@link FormField} for the field input. */ private static FormField setFormField(String name, FieldData valueData, FieldValue fieldValue, List<ReadResult> readResults) { com.azure.ai.formrecognizer.models.FieldValue value; switch (fieldValue.getType()) { case PHONE_NUMBER: value = new com.azure.ai.formrecognizer.models.FieldValue(fieldValue.getValuePhoneNumber(), FieldValueType.PHONE_NUMBER); break; case STRING: value = new com.azure.ai.formrecognizer.models.FieldValue(fieldValue.getValueString(), FieldValueType.STRING); break; case TIME: LocalTime fieldTime = fieldValue.getValueTime() == null ? null : LocalTime .parse(fieldValue.getValueTime(), DateTimeFormatter.ofPattern("HH:mm:ss")); value = new com.azure.ai.formrecognizer.models.FieldValue(fieldTime, FieldValueType.TIME); break; case DATE: value = new com.azure.ai.formrecognizer.models.FieldValue(fieldValue.getValueDate(), FieldValueType.DATE); break; case INTEGER: com.azure.ai.formrecognizer.models.FieldValue longFieldValue; if (fieldValue.getValueInteger() == null) { longFieldValue = new com.azure.ai.formrecognizer.models.FieldValue(null, FieldValueType.LONG); } else { longFieldValue = new com.azure.ai.formrecognizer.models.FieldValue(fieldValue.getValueInteger().longValue(), FieldValueType.LONG); } value = longFieldValue; break; case NUMBER: value = new com.azure.ai.formrecognizer.models.FieldValue(fieldValue.getValueNumber(), FieldValueType.FLOAT); break; case ARRAY: value = new com.azure.ai.formrecognizer.models.FieldValue( toFieldValueArray(fieldValue.getValueArray(), readResults), FieldValueType.LIST); break; case OBJECT: value = new com.azure.ai.formrecognizer.models.FieldValue( toFieldValueObject(fieldValue.getValueObject(), readResults), FieldValueType.MAP); break; default: throw LOGGER.logExceptionAsError(new RuntimeException("FieldValue Type not supported")); } return new FormField(name, null, valueData, value, setDefaultConfidenceValue(fieldValue.getConfidence())); } /** * Helper method to set default confidence value if confidence returned by service is null. * * @param confidence the confidence returned by service. * * @return the field confidence value. */ private static float setDefaultConfidenceValue(Float confidence) { return confidence == null ? DEFAULT_CONFIDENCE_VALUE : confidence; } /** * Helper method to convert the service returned * {@link com.azure.ai.formrecognizer.implementation.models.FieldValue * to a SDK level map of {@link FormField}. * * @param valueObject The array of field values returned by the service in {@link FieldValue * * @return The Map of {@link FormField}. */ private static Map<String, FormField> toFieldValueObject(Map<String, FieldValue> valueObject, List<ReadResult> readResults) { Map<String, FormField> fieldValueObjectMap = new TreeMap<>(); valueObject.forEach((key, fieldValue) -> fieldValueObjectMap.put(key, setFormField(key, new FieldData(fieldValue.getText(), toBoundingBox(fieldValue.getBoundingBox()), fieldValue.getPage(), setReferenceElements(fieldValue.getElements(), readResults)), fieldValue, readResults) )); return fieldValueObjectMap; } /** * Helper method to convert the service returned * {@link com.azure.ai.formrecognizer.implementation.models.FieldValue * to a SDK level List of {@link FormField}. * * @param valueArray The array of field values returned by the service in {@link FieldValue * @param readResults The text extraction result returned by the service. * * @return The List of {@link FormField}. */ /** * Helper method to convert the page results to {@code FormPage form pages}. * * @param readResultItem The per page text extraction item result returned by the service. * @param perPageTableList The per page tables list. * @param perPageLineList The per page form lines. * * @return The per page {@code FormPage}. */ private static FormPage getFormPage(ReadResult readResultItem, List<FormTable> perPageTableList, List<FormLine> perPageLineList) { return new FormPage( readResultItem.getHeight(), readResultItem.getAngle(), LengthUnit.fromString(readResultItem.getUnit().toString()), readResultItem.getWidth(), perPageLineList, perPageTableList, readResultItem.getPage()); } /** * Helper method to set the {@link RecognizedForm * service. * * @param includeFieldElements Boolean to indicate if to set reference elements data on fields. * @param readResults The text extraction result returned by the service. * @param pageResultItem The extracted page level information returned by the service. * @param pageNumber The 1 based page number on which these fields exist. * * @return The fields populated on {@link RecognizedForm */ private static Map<String, FormField> getUnlabeledFieldMap(boolean includeFieldElements, List<ReadResult> readResults, PageResult pageResultItem, int pageNumber) { Map<String, FormField> formFieldMap = new LinkedHashMap<>(); List<KeyValuePair> keyValuePairs = pageResultItem.getKeyValuePairs(); forEachWithIndex(keyValuePairs, ((index, keyValuePair) -> { List<FormElement> formKeyContentList = null; List<FormElement> formValueContentList = null; if (includeFieldElements) { formKeyContentList = setReferenceElements(keyValuePair.getKey().getElements(), readResults); formValueContentList = setReferenceElements(keyValuePair.getValue().getElements(), readResults ); } FieldData labelData = new FieldData(keyValuePair.getKey().getText(), toBoundingBox(keyValuePair.getKey().getBoundingBox()), pageNumber, formKeyContentList); FieldData valueData = new FieldData(keyValuePair.getValue().getText(), toBoundingBox(keyValuePair.getValue().getBoundingBox()), pageNumber, formValueContentList); String fieldName = "field-" + index; FormField formField = new FormField(fieldName, labelData, valueData, new com.azure.ai.formrecognizer.models.FieldValue(keyValuePair.getValue().getText(), FieldValueType.STRING), setDefaultConfidenceValue(keyValuePair.getConfidence()) ); formFieldMap.put(fieldName, formField); })); return formFieldMap; } /** * Helper method to set the text reference elements on FieldValue/fields when {@code includeFieldElements} set to * true. * * @return The list if referenced elements. */ private static List<FormElement> setReferenceElements(List<String> elements, List<ReadResult> readResults) { if (CoreUtils.isNullOrEmpty(elements)) { return new ArrayList<>(); } List<FormElement> formElementList = new ArrayList<>(); elements.forEach(elementString -> { String[] indices = NON_DIGIT_PATTERN.matcher(elementString).replaceAll(" ").trim().split(" "); if (indices.length < 2) { throw LOGGER.logExceptionAsError(new RuntimeException("Cannot find corresponding reference elements " + "for the field value.")); } int readResultIndex = Integer.parseInt(indices[0]); int lineIndex = Integer.parseInt(indices[1]); if (indices.length == 3) { int wordIndex = Integer.parseInt(indices[2]); TextWord textWord = readResults.get(readResultIndex).getLines().get(lineIndex).getWords().get(wordIndex); FormWord wordElement = new FormWord(textWord.getText(), toBoundingBox(textWord.getBoundingBox()), readResultIndex + 1, setDefaultConfidenceValue(textWord.getConfidence())); formElementList.add(wordElement); } else { TextLine textLine = readResults.get(readResultIndex).getLines().get(lineIndex); FormLine lineElement = new FormLine(textLine.getText(), toBoundingBox(textLine.getBoundingBox()), readResultIndex + 1, toWords(textLine.getWords(), readResultIndex + 1)); formElementList.add(lineElement); } }); return formElementList; } /** * Helper method to convert the service level {@link TextWord} to list of SDK level model {@link FormWord}. * * @param words A list of word reference elements returned by the service. * @param pageNumber The 1 based page number on which this word element exists. * * @return The list of {@code FormWord words}. */ private static List<FormWord> toWords(List<TextWord> words, int pageNumber) { return words.stream() .map(textWord -> new FormWord( textWord.getText(), toBoundingBox(textWord.getBoundingBox()), pageNumber, setDefaultConfidenceValue(textWord.getConfidence())) ).collect(Collectors.toList()); } /** * Helper method to convert the service level modeled eight numbers representing the four points to SDK level * {@link FieldBoundingBox}. * * @param serviceBoundingBox A list of eight numbers representing the four points of a box. * * @return A {@link FieldBoundingBox}. */ private static FieldBoundingBox toBoundingBox(List<Float> serviceBoundingBox) { if (CoreUtils.isNullOrEmpty(serviceBoundingBox) || (serviceBoundingBox.size() % 2) != 0) { return null; } List<Point> pointList = new ArrayList<>(); for (int i = 0; i < serviceBoundingBox.size(); i++) { pointList.add(new Point(serviceBoundingBox.get(i), serviceBoundingBox.get(++i))); } return new FieldBoundingBox(pointList); } }
Yep, correct. And I fully agree with that, I will add some docs. There is definitely some dark reflection magic here.
static void setPropertiesFromGetters(TableEntity entity, ClientLogger logger) { Class<?> myClass = entity.getClass(); if (myClass == TableEntity.class) { return; } for (Method m : myClass.getMethods()) { if (m.getName().length() < 3 || TABLE_ENTITY_METHODS.contains(m.getName()) || (!m.getName().startsWith("get") && !m.getName().startsWith("is")) || m.getParameterTypes().length != 0 || void.class.equals(m.getReturnType())) { continue; } int prefixLength = m.getName().startsWith("get") ? 3 : 2; String propName = m.getName().substring(prefixLength); try { entity.getProperties().put(propName, m.invoke(entity)); } catch (ReflectiveOperationException | IllegalArgumentException e) { logger.logThrowableAsWarning(new ReflectiveOperationException(String.format( "Failed to get property '%s' on type '%s'", propName, myClass.getName()), e)); } } }
int prefixLength = m.getName().startsWith("get") ? 3 : 2;
static void setPropertiesFromGetters(TableEntity entity, ClientLogger logger) { Class<?> myClass = entity.getClass(); if (myClass == TableEntity.class) { return; } for (Method m : myClass.getMethods()) { if (m.getName().length() < 3 || TABLE_ENTITY_METHODS.contains(m.getName()) || (!m.getName().startsWith("get") && !m.getName().startsWith("is")) || m.getParameterTypes().length != 0 || void.class.equals(m.getReturnType())) { continue; } if (m.getName().startsWith("is") && m.getReturnType() != Boolean.class && m.getReturnType() != boolean.class) { continue; } int prefixLength = m.getName().startsWith("is") ? 2 : 3; String propName = m.getName().substring(prefixLength); try { entity.getProperties().put(propName, m.invoke(entity)); } catch (ReflectiveOperationException | IllegalArgumentException e) { logger.logThrowableAsWarning(new ReflectiveOperationException(String.format( "Failed to get property '%s' on type '%s'", propName, myClass.getName()), e)); } } }
class EntityHelper { private static final HashSet<String> TABLE_ENTITY_METHODS = Arrays.stream(TableEntity.class.getMethods()) .map(Method::getName).collect(Collectors.toCollection(HashSet::new)); private EntityHelper() { } @SuppressWarnings("unchecked") static <T extends TableEntity> T convertToSubclass(TableEntity entity, Class<T> clazz, ClientLogger logger) { if (TableEntity.class == clazz) { return (T) entity; } T result; try { result = clazz.getDeclaredConstructor(String.class, String.class).newInstance(entity.getPartitionKey(), entity.getRowKey()); } catch (ReflectiveOperationException | SecurityException e) { logger.logThrowableAsWarning(new ReflectiveOperationException(String.format( "Failed to instantiate type '%s'", clazz.getName()), e)); return null; } result.addProperties(entity.getProperties()); for (Method m : clazz.getMethods()) { if (m.getName().length() < 4 || !m.getName().startsWith("set") || m.getParameterTypes().length != 1 || !void.class.equals(m.getReturnType())) { continue; } String propName = m.getName().substring(3); Object value = result.getProperties().get(propName); if (value == null) { continue; } Class<?> paramType = m.getParameterTypes()[0]; if (paramType.isEnum() && value instanceof String) { try { value = Enum.valueOf(paramType.asSubclass(Enum.class), (String) value); } catch (IllegalArgumentException e) { logger.logThrowableAsWarning(new IllegalArgumentException(String.format( "Failed to convert '%s' to value of enum '%s'", propName, paramType.getName()), e)); } } try { m.invoke(result, value); } catch (ReflectiveOperationException | IllegalArgumentException e) { logger.logThrowableAsWarning(new ReflectiveOperationException(String.format( "Failed to set property '%s' on type '%s'", propName, clazz.getName()), e)); } } return result; } }
class of `TableEntity`, locate all getter methods (those that start with `get` or `is`, take no
Resolved
void updateEntityWithResponseSubclassAsync() { final String partitionKeyValue = testResourceNamer.randomName("APartitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("ARowKey", 20); final int expectedStatusCode = 204; SingleFieldEntity tableEntity = new SingleFieldEntity(partitionKeyValue, rowKeyValue); tableEntity.setSubclassProperty("InitialValue"); tableClient.createEntity(tableEntity).block(TIMEOUT); tableEntity.setSubclassProperty("UpdatedValue"); StepVerifier.create(tableClient.updateEntityWithResponse(tableEntity, true, UpdateMode.MERGE)) .assertNext(response -> assertEquals(expectedStatusCode, response.getStatusCode())) .expectComplete() .verify(); StepVerifier.create(tableClient.getEntity(partitionKeyValue, rowKeyValue)) .assertNext(entity -> { final Map<String, Object> properties = entity.getProperties(); assertTrue(properties.containsKey("SubclassProperty")); assertEquals("UpdatedValue", properties.get("SubclassProperty")); }) .verifyComplete(); }
SingleFieldEntity tableEntity = new SingleFieldEntity(partitionKeyValue, rowKeyValue);
void updateEntityWithResponseSubclassAsync() { String partitionKeyValue = testResourceNamer.randomName("APartitionKey", 20); String rowKeyValue = testResourceNamer.randomName("ARowKey", 20); int expectedStatusCode = 204; SingleFieldEntity tableEntity = new SingleFieldEntity(partitionKeyValue, rowKeyValue); tableEntity.setSubclassProperty("InitialValue"); tableClient.createEntity(tableEntity).block(TIMEOUT); tableEntity.setSubclassProperty("UpdatedValue"); StepVerifier.create(tableClient.updateEntityWithResponse(tableEntity, true, UpdateMode.MERGE)) .assertNext(response -> assertEquals(expectedStatusCode, response.getStatusCode())) .expectComplete() .verify(); StepVerifier.create(tableClient.getEntity(partitionKeyValue, rowKeyValue)) .assertNext(entity -> { Map<String, Object> properties = entity.getProperties(); assertTrue(properties.containsKey("SubclassProperty")); assertEquals("UpdatedValue", properties.get("SubclassProperty")); }) .verifyComplete(); }
class TablesAsyncClientTest extends TestBase { private static final Duration TIMEOUT = Duration.ofSeconds(100); private TableAsyncClient tableClient; private HttpPipelinePolicy recordPolicy; private HttpClient playbackClient; @BeforeAll static void beforeAll() { StepVerifier.setDefaultTimeout(TIMEOUT); } @AfterAll static void afterAll() { StepVerifier.resetDefaultTimeout(); } @Override protected void beforeTest() { final String tableName = testResourceNamer.randomName("tableName", 20); final String connectionString = TestUtils.getConnectionString(interceptorManager.isPlaybackMode()); final TableClientBuilder builder = new TableClientBuilder() .connectionString(connectionString) .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)) .tableName(tableName); if (interceptorManager.isPlaybackMode()) { playbackClient = interceptorManager.getPlaybackClient(); builder.httpClient(playbackClient); } else { builder.httpClient(HttpClient.createDefault()); if (!interceptorManager.isLiveMode()) { recordPolicy = interceptorManager.getRecordPolicy(); builder.addPolicy(recordPolicy); } builder.addPolicy(new RetryPolicy(new ExponentialBackoff(6, Duration.ofMillis(1500), Duration.ofSeconds(100)))); } tableClient = builder.buildAsyncClient(); tableClient.create().block(TIMEOUT); } @Test void createTableAsync() { final String tableName2 = testResourceNamer.randomName("tableName", 20); final String connectionString = TestUtils.getConnectionString(interceptorManager.isPlaybackMode()); final TableClientBuilder builder = new TableClientBuilder() .connectionString(connectionString) .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)) .tableName(tableName2); if (interceptorManager.isPlaybackMode()) { builder.httpClient(playbackClient); } else { builder.httpClient(HttpClient.createDefault()); if (!interceptorManager.isLiveMode()) { builder.addPolicy(recordPolicy); } builder.addPolicy(new RetryPolicy(new ExponentialBackoff(6, Duration.ofMillis(1500), Duration.ofSeconds(100)))); } final TableAsyncClient tableClient2 = builder.buildAsyncClient(); StepVerifier.create(tableClient2.create()) .expectComplete() .verify(); } @Test void createTableWithResponseAsync() { final String tableName2 = testResourceNamer.randomName("tableName", 20); final String connectionString = TestUtils.getConnectionString(interceptorManager.isPlaybackMode()); final TableClientBuilder builder = new TableClientBuilder() .connectionString(connectionString) .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)) .tableName(tableName2); if (interceptorManager.isPlaybackMode()) { builder.httpClient(playbackClient); } else { builder.httpClient(HttpClient.createDefault()); if (!interceptorManager.isLiveMode()) { builder.addPolicy(recordPolicy); } builder.addPolicy(new RetryPolicy(new ExponentialBackoff(6, Duration.ofMillis(1500), Duration.ofSeconds(100)))); } final TableAsyncClient tableClient2 = builder.buildAsyncClient(); final int expectedStatusCode = 204; StepVerifier.create(tableClient2.createWithResponse()) .assertNext(response -> { assertEquals(expectedStatusCode, response.getStatusCode()); }) .expectComplete() .verify(); } @Test void createEntityAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue); StepVerifier.create(tableClient.createEntity(tableEntity)) .expectComplete() .verify(); } @Test void createEntityWithResponseAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity entity = new TableEntity(partitionKeyValue, rowKeyValue); final int expectedStatusCode = 204; StepVerifier.create(tableClient.createEntityWithResponse(entity)) .assertNext(response -> { assertEquals(expectedStatusCode, response.getStatusCode()); }) .expectComplete() .verify(); } @Test void createEntityWithAllSupportedDataTypesAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue); final boolean booleanValue = true; final byte[] binaryValue = "Test value".getBytes(); final Date dateValue = new Date(); final OffsetDateTime offsetDateTimeValue = OffsetDateTime.now(); final double doubleValue = 2.0d; final UUID guidValue = UUID.randomUUID(); final int int32Value = 1337; final long int64Value = 1337L; final String stringValue = "This is table entity"; tableEntity.addProperty("BinaryTypeProperty", binaryValue); tableEntity.addProperty("BooleanTypeProperty", booleanValue); tableEntity.addProperty("DateTypeProperty", dateValue); tableEntity.addProperty("OffsetDateTimeTypeProperty", offsetDateTimeValue); tableEntity.addProperty("DoubleTypeProperty", doubleValue); tableEntity.addProperty("GuidTypeProperty", guidValue); tableEntity.addProperty("Int32TypeProperty", int32Value); tableEntity.addProperty("Int64TypeProperty", int64Value); tableEntity.addProperty("StringTypeProperty", stringValue); tableClient.createEntity(tableEntity).block(TIMEOUT); StepVerifier.create(tableClient.getEntityWithResponse(partitionKeyValue, rowKeyValue, null)) .assertNext(response -> { final TableEntity entity = response.getValue(); Map<String, Object> properties = entity.getProperties(); assertTrue(properties.get("BinaryTypeProperty") instanceof byte[]); assertTrue(properties.get("BooleanTypeProperty") instanceof Boolean); assertTrue(properties.get("DateTypeProperty") instanceof OffsetDateTime); assertTrue(properties.get("OffsetDateTimeTypeProperty") instanceof OffsetDateTime); assertTrue(properties.get("DoubleTypeProperty") instanceof Double); assertTrue(properties.get("GuidTypeProperty") instanceof UUID); assertTrue(properties.get("Int32TypeProperty") instanceof Integer); assertTrue(properties.get("Int64TypeProperty") instanceof Long); assertTrue(properties.get("StringTypeProperty") instanceof String); }) .expectComplete() .verify(); } @Test void createEntitySubclassAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); byte[] bytes = new byte[]{1, 2, 3}; boolean b = true; OffsetDateTime dateTime = OffsetDateTime.of(2020, 1, 1, 0, 0, 0, 0, ZoneOffset.UTC); double d = 1.23D; UUID uuid = UUID.fromString("11111111-2222-3333-4444-555555555555"); int i = 123; long l = 123L; String s = "Test"; SampleEntity.Color color = SampleEntity.Color.GREEN; SampleEntity tableEntity = new SampleEntity(partitionKeyValue, rowKeyValue); tableEntity.setByteField(bytes); tableEntity.setBooleanField(b); tableEntity.setDateTimeField(dateTime); tableEntity.setDoubleField(d); tableEntity.setUuidField(uuid); tableEntity.setIntField(i); tableEntity.setLongField(l); tableEntity.setStringField(s); tableEntity.setEnumField(color); tableClient.createEntity(tableEntity).block(TIMEOUT); StepVerifier.create(tableClient.getEntityWithResponse(partitionKeyValue, rowKeyValue, null)) .assertNext(response -> { final TableEntity entity = response.getValue(); assertArrayEquals((byte[]) entity.getProperties().get("ByteField"), bytes); assertEquals(entity.getProperties().get("BooleanField"), b); assertTrue(dateTime.isEqual((OffsetDateTime) entity.getProperties().get("DateTimeField"))); assertEquals(entity.getProperties().get("DoubleField"), d); assertEquals(0, uuid.compareTo((UUID) entity.getProperties().get("UuidField"))); assertEquals(entity.getProperties().get("IntField"), i); assertEquals(entity.getProperties().get("LongField"), l); assertEquals(entity.getProperties().get("StringField"), s); assertEquals(entity.getProperties().get("EnumField"), color.name()); }) .expectComplete() .verify(); } @Test void deleteTableAsync() { StepVerifier.create(tableClient.delete()) .expectComplete() .verify(); } @Test void deleteTableWithResponseAsync() { final int expectedStatusCode = 204; StepVerifier.create(tableClient.deleteWithResponse()) .assertNext(response -> { assertEquals(expectedStatusCode, response.getStatusCode()); }) .expectComplete() .verify(); } @Test void deleteEntityAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue); tableClient.createEntity(tableEntity).block(TIMEOUT); final TableEntity createdEntity = tableClient.getEntity(partitionKeyValue, rowKeyValue).block(TIMEOUT); assertNotNull(createdEntity, "'createdEntity' should not be null."); assertNotNull(createdEntity.getETag(), "'eTag' should not be null."); StepVerifier.create(tableClient.deleteEntity(partitionKeyValue, rowKeyValue)) .expectComplete() .verify(); } @Test void deleteEntityWithResponseAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue); final int expectedStatusCode = 204; tableClient.createEntity(tableEntity).block(TIMEOUT); final TableEntity createdEntity = tableClient.getEntity(partitionKeyValue, rowKeyValue).block(TIMEOUT); assertNotNull(createdEntity, "'createdEntity' should not be null."); assertNotNull(createdEntity.getETag(), "'eTag' should not be null."); StepVerifier.create(tableClient.deleteEntityWithResponse(partitionKeyValue, rowKeyValue, null)) .assertNext(response -> { assertEquals(expectedStatusCode, response.getStatusCode()); }) .expectComplete() .verify(); } @Test void deleteEntityWithResponseMatchETagAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue); final int expectedStatusCode = 204; tableClient.createEntity(tableEntity).block(TIMEOUT); final TableEntity createdEntity = tableClient.getEntity(partitionKeyValue, rowKeyValue).block(TIMEOUT); assertNotNull(createdEntity, "'createdEntity' should not be null."); assertNotNull(createdEntity.getETag(), "'eTag' should not be null."); StepVerifier.create(tableClient.deleteEntityWithResponse(partitionKeyValue, rowKeyValue, createdEntity.getETag())) .assertNext(response -> { assertEquals(expectedStatusCode, response.getStatusCode()); }) .expectComplete() .verify(); } @Test void getEntityWithResponseAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue); final int expectedStatusCode = 200; tableClient.createEntity(tableEntity).block(TIMEOUT); StepVerifier.create(tableClient.getEntityWithResponse(partitionKeyValue, rowKeyValue, null)) .assertNext(response -> { final TableEntity entity = response.getValue(); assertEquals(expectedStatusCode, response.getStatusCode()); assertNotNull(entity); assertEquals(tableEntity.getPartitionKey(), entity.getPartitionKey()); assertEquals(tableEntity.getRowKey(), entity.getRowKey()); assertNotNull(entity.getTimestamp()); assertNotNull(entity.getETag()); assertNotNull(entity.getProperties()); }) .expectComplete() .verify(); } @Test void getEntityWithResponseWithSelectAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue); tableEntity.addProperty("Test", "Value"); final int expectedStatusCode = 200; tableClient.createEntity(tableEntity).block(TIMEOUT); StepVerifier.create(tableClient.getEntityWithResponse(partitionKeyValue, rowKeyValue, "Test")) .assertNext(response -> { final TableEntity entity = response.getValue(); assertEquals(expectedStatusCode, response.getStatusCode()); assertNotNull(entity); assertNull(entity.getPartitionKey()); assertNull(entity.getRowKey()); assertNull(entity.getTimestamp()); assertNotNull(entity.getETag()); assertEquals(entity.getProperties().get("Test"), "Value"); }) .expectComplete() .verify(); } @Test void getEntityWithResponseSubclassAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue); byte[] bytes = new byte[]{1, 2, 3}; boolean b = true; OffsetDateTime dateTime = OffsetDateTime.of(2020, 1, 1, 0, 0, 0, 0, ZoneOffset.UTC); double d = 1.23D; UUID uuid = UUID.fromString("11111111-2222-3333-4444-555555555555"); int i = 123; long l = 123L; String s = "Test"; SampleEntity.Color color = SampleEntity.Color.GREEN; Map<String, Object> props = new HashMap<>(); props.put("ByteField", bytes); props.put("BooleanField", b); props.put("DateTimeField", dateTime); props.put("DoubleField", d); props.put("UuidField", uuid); props.put("IntField", i); props.put("LongField", l); props.put("StringField", s); props.put("EnumField", color); tableEntity.addProperties(props); final int expectedStatusCode = 200; tableClient.createEntity(tableEntity).block(TIMEOUT); StepVerifier.create(tableClient.getEntityWithResponse(partitionKeyValue, rowKeyValue, null, SampleEntity.class)) .assertNext(response -> { final SampleEntity entity = response.getValue(); assertEquals(expectedStatusCode, response.getStatusCode()); assertNotNull(entity); assertEquals(tableEntity.getPartitionKey(), entity.getPartitionKey()); assertEquals(tableEntity.getRowKey(), entity.getRowKey()); assertNotNull(entity.getTimestamp()); assertNotNull(entity.getETag()); assertArrayEquals(bytes, entity.getByteField()); assertEquals(b, entity.getBooleanField()); assertTrue(dateTime.isEqual(entity.getDateTimeField())); assertEquals(d, entity.getDoubleField()); assertEquals(0, uuid.compareTo(entity.getUuidField())); assertEquals(i, entity.getIntField()); assertEquals(l, entity.getLongField()); assertEquals(s, entity.getStringField()); assertEquals(color, entity.getEnumField()); }) .expectComplete() .verify(); } @Test void updateEntityWithResponseReplaceAsync() { updateEntityWithResponseAsync(UpdateMode.REPLACE); } @Test void updateEntityWithResponseMergeAsync() { updateEntityWithResponseAsync(UpdateMode.MERGE); } /** * In the case of {@link UpdateMode * In the case of {@link UpdateMode */ void updateEntityWithResponseAsync(UpdateMode mode) { final boolean expectOldProperty = mode == UpdateMode.MERGE; final String partitionKeyValue = testResourceNamer.randomName("APartitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("ARowKey", 20); final int expectedStatusCode = 204; final String oldPropertyKey = "propertyA"; final String newPropertyKey = "propertyB"; final TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue) .addProperty(oldPropertyKey, "valueA"); tableClient.createEntity(tableEntity).block(TIMEOUT); final TableEntity createdEntity = tableClient.getEntity(partitionKeyValue, rowKeyValue).block(TIMEOUT); assertNotNull(createdEntity, "'createdEntity' should not be null."); assertNotNull(createdEntity.getETag(), "'eTag' should not be null."); createdEntity.getProperties().remove(oldPropertyKey); createdEntity.addProperty(newPropertyKey, "valueB"); if (mode == UpdateMode.MERGE && tableClient.getTableUrl().contains("cosmos.azure.com")) { StepVerifier.create(tableClient.updateEntityWithResponse(createdEntity, true, mode)) .expectError(com.azure.data.tables.implementation.models.TableServiceErrorException.class) .verify(); } else { StepVerifier.create(tableClient.updateEntityWithResponse(createdEntity, true, mode)) .assertNext(response -> assertEquals(expectedStatusCode, response.getStatusCode())) .expectComplete() .verify(); StepVerifier.create(tableClient.getEntity(partitionKeyValue, rowKeyValue)) .assertNext(entity -> { final Map<String, Object> properties = entity.getProperties(); assertTrue(properties.containsKey(newPropertyKey)); assertEquals(expectOldProperty, properties.containsKey(oldPropertyKey)); }) .verifyComplete(); } } @Test @Test @Tag("ListEntities") void listEntitiesAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final String rowKeyValue2 = testResourceNamer.randomName("rowKey", 20); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue)).block(TIMEOUT); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue2)).block(TIMEOUT); StepVerifier.create(tableClient.listEntities()) .expectNextCount(2) .thenConsumeWhile(x -> true) .expectComplete() .verify(); } @Test @Tag("ListEntities") void listEntitiesWithFilterAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final String rowKeyValue2 = testResourceNamer.randomName("rowKey", 20); ListEntitiesOptions options = new ListEntitiesOptions().setFilter("RowKey eq '" + rowKeyValue + "'"); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue)).block(TIMEOUT); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue2)).block(TIMEOUT); StepVerifier.create(tableClient.listEntities(options)) .assertNext(returnEntity -> { assertEquals(partitionKeyValue, returnEntity.getPartitionKey()); assertEquals(rowKeyValue, returnEntity.getRowKey()); }) .expectNextCount(0) .thenConsumeWhile(x -> true) .expectComplete() .verify(); } @Test @Tag("ListEntities") void listEntitiesWithSelectAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity entity = new TableEntity(partitionKeyValue, rowKeyValue) .addProperty("propertyC", "valueC") .addProperty("propertyD", "valueD"); ListEntitiesOptions options = new ListEntitiesOptions() .setSelect("propertyC"); tableClient.createEntity(entity).block(TIMEOUT); StepVerifier.create(tableClient.listEntities(options)) .assertNext(returnEntity -> { assertNull(returnEntity.getRowKey()); assertNull(returnEntity.getPartitionKey()); assertEquals("valueC", returnEntity.getProperties().get("propertyC")); assertNull(returnEntity.getProperties().get("propertyD")); }) .expectComplete() .verify(); } @Test @Tag("ListEntities") void listEntitiesWithTopAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final String rowKeyValue2 = testResourceNamer.randomName("rowKey", 20); final String rowKeyValue3 = testResourceNamer.randomName("rowKey", 20); ListEntitiesOptions options = new ListEntitiesOptions().setTop(2); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue)).block(TIMEOUT); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue2)).block(TIMEOUT); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue3)).block(TIMEOUT); StepVerifier.create(tableClient.listEntities(options)) .expectNextCount(2) .thenConsumeWhile(x -> true) .expectComplete() .verify(); } @Test @Tag("ListEntities") void listEntitiesSubclassAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final String rowKeyValue2 = testResourceNamer.randomName("rowKey", 20); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue)).block(TIMEOUT); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue2)).block(TIMEOUT); StepVerifier.create(tableClient.listEntities(SampleEntity.class)) .expectNextCount(2) .thenConsumeWhile(x -> true) .expectComplete() .verify(); } }
class TablesAsyncClientTest extends TestBase { private static final Duration TIMEOUT = Duration.ofSeconds(100); private TableAsyncClient tableClient; private HttpPipelinePolicy recordPolicy; private HttpClient playbackClient; @BeforeAll static void beforeAll() { StepVerifier.setDefaultTimeout(TIMEOUT); } @AfterAll static void afterAll() { StepVerifier.resetDefaultTimeout(); } @Override protected void beforeTest() { final String tableName = testResourceNamer.randomName("tableName", 20); final String connectionString = TestUtils.getConnectionString(interceptorManager.isPlaybackMode()); final TableClientBuilder builder = new TableClientBuilder() .connectionString(connectionString) .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)) .tableName(tableName); if (interceptorManager.isPlaybackMode()) { playbackClient = interceptorManager.getPlaybackClient(); builder.httpClient(playbackClient); } else { builder.httpClient(HttpClient.createDefault()); if (!interceptorManager.isLiveMode()) { recordPolicy = interceptorManager.getRecordPolicy(); builder.addPolicy(recordPolicy); } builder.addPolicy(new RetryPolicy(new ExponentialBackoff(6, Duration.ofMillis(1500), Duration.ofSeconds(100)))); } tableClient = builder.buildAsyncClient(); tableClient.create().block(TIMEOUT); } @Test void createTableAsync() { final String tableName2 = testResourceNamer.randomName("tableName", 20); final String connectionString = TestUtils.getConnectionString(interceptorManager.isPlaybackMode()); final TableClientBuilder builder = new TableClientBuilder() .connectionString(connectionString) .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)) .tableName(tableName2); if (interceptorManager.isPlaybackMode()) { builder.httpClient(playbackClient); } else { builder.httpClient(HttpClient.createDefault()); if (!interceptorManager.isLiveMode()) { builder.addPolicy(recordPolicy); } builder.addPolicy(new RetryPolicy(new ExponentialBackoff(6, Duration.ofMillis(1500), Duration.ofSeconds(100)))); } final TableAsyncClient tableClient2 = builder.buildAsyncClient(); StepVerifier.create(tableClient2.create()) .expectComplete() .verify(); } @Test void createTableWithResponseAsync() { final String tableName2 = testResourceNamer.randomName("tableName", 20); final String connectionString = TestUtils.getConnectionString(interceptorManager.isPlaybackMode()); final TableClientBuilder builder = new TableClientBuilder() .connectionString(connectionString) .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)) .tableName(tableName2); if (interceptorManager.isPlaybackMode()) { builder.httpClient(playbackClient); } else { builder.httpClient(HttpClient.createDefault()); if (!interceptorManager.isLiveMode()) { builder.addPolicy(recordPolicy); } builder.addPolicy(new RetryPolicy(new ExponentialBackoff(6, Duration.ofMillis(1500), Duration.ofSeconds(100)))); } final TableAsyncClient tableClient2 = builder.buildAsyncClient(); final int expectedStatusCode = 204; StepVerifier.create(tableClient2.createWithResponse()) .assertNext(response -> { assertEquals(expectedStatusCode, response.getStatusCode()); }) .expectComplete() .verify(); } @Test void createEntityAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue); StepVerifier.create(tableClient.createEntity(tableEntity)) .expectComplete() .verify(); } @Test void createEntityWithResponseAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity entity = new TableEntity(partitionKeyValue, rowKeyValue); final int expectedStatusCode = 204; StepVerifier.create(tableClient.createEntityWithResponse(entity)) .assertNext(response -> { assertEquals(expectedStatusCode, response.getStatusCode()); }) .expectComplete() .verify(); } @Test void createEntityWithAllSupportedDataTypesAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue); final boolean booleanValue = true; final byte[] binaryValue = "Test value".getBytes(); final Date dateValue = new Date(); final OffsetDateTime offsetDateTimeValue = OffsetDateTime.now(); final double doubleValue = 2.0d; final UUID guidValue = UUID.randomUUID(); final int int32Value = 1337; final long int64Value = 1337L; final String stringValue = "This is table entity"; tableEntity.addProperty("BinaryTypeProperty", binaryValue); tableEntity.addProperty("BooleanTypeProperty", booleanValue); tableEntity.addProperty("DateTypeProperty", dateValue); tableEntity.addProperty("OffsetDateTimeTypeProperty", offsetDateTimeValue); tableEntity.addProperty("DoubleTypeProperty", doubleValue); tableEntity.addProperty("GuidTypeProperty", guidValue); tableEntity.addProperty("Int32TypeProperty", int32Value); tableEntity.addProperty("Int64TypeProperty", int64Value); tableEntity.addProperty("StringTypeProperty", stringValue); tableClient.createEntity(tableEntity).block(TIMEOUT); StepVerifier.create(tableClient.getEntityWithResponse(partitionKeyValue, rowKeyValue, null)) .assertNext(response -> { final TableEntity entity = response.getValue(); Map<String, Object> properties = entity.getProperties(); assertTrue(properties.get("BinaryTypeProperty") instanceof byte[]); assertTrue(properties.get("BooleanTypeProperty") instanceof Boolean); assertTrue(properties.get("DateTypeProperty") instanceof OffsetDateTime); assertTrue(properties.get("OffsetDateTimeTypeProperty") instanceof OffsetDateTime); assertTrue(properties.get("DoubleTypeProperty") instanceof Double); assertTrue(properties.get("GuidTypeProperty") instanceof UUID); assertTrue(properties.get("Int32TypeProperty") instanceof Integer); assertTrue(properties.get("Int64TypeProperty") instanceof Long); assertTrue(properties.get("StringTypeProperty") instanceof String); }) .expectComplete() .verify(); } @Test void createEntitySubclassAsync() { String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); String rowKeyValue = testResourceNamer.randomName("rowKey", 20); byte[] bytes = new byte[]{1, 2, 3}; boolean b = true; OffsetDateTime dateTime = OffsetDateTime.of(2020, 1, 1, 0, 0, 0, 0, ZoneOffset.UTC); double d = 1.23D; UUID uuid = UUID.fromString("11111111-2222-3333-4444-555555555555"); int i = 123; long l = 123L; String s = "Test"; SampleEntity.Color color = SampleEntity.Color.GREEN; SampleEntity tableEntity = new SampleEntity(partitionKeyValue, rowKeyValue); tableEntity.setByteField(bytes); tableEntity.setBooleanField(b); tableEntity.setDateTimeField(dateTime); tableEntity.setDoubleField(d); tableEntity.setUuidField(uuid); tableEntity.setIntField(i); tableEntity.setLongField(l); tableEntity.setStringField(s); tableEntity.setEnumField(color); tableClient.createEntity(tableEntity).block(TIMEOUT); StepVerifier.create(tableClient.getEntityWithResponse(partitionKeyValue, rowKeyValue, null)) .assertNext(response -> { TableEntity entity = response.getValue(); assertArrayEquals((byte[]) entity.getProperties().get("ByteField"), bytes); assertEquals(entity.getProperties().get("BooleanField"), b); assertTrue(dateTime.isEqual((OffsetDateTime) entity.getProperties().get("DateTimeField"))); assertEquals(entity.getProperties().get("DoubleField"), d); assertEquals(0, uuid.compareTo((UUID) entity.getProperties().get("UuidField"))); assertEquals(entity.getProperties().get("IntField"), i); assertEquals(entity.getProperties().get("LongField"), l); assertEquals(entity.getProperties().get("StringField"), s); assertEquals(entity.getProperties().get("EnumField"), color.name()); }) .expectComplete() .verify(); } @Test void deleteTableAsync() { StepVerifier.create(tableClient.delete()) .expectComplete() .verify(); } @Test void deleteTableWithResponseAsync() { final int expectedStatusCode = 204; StepVerifier.create(tableClient.deleteWithResponse()) .assertNext(response -> { assertEquals(expectedStatusCode, response.getStatusCode()); }) .expectComplete() .verify(); } @Test void deleteEntityAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue); tableClient.createEntity(tableEntity).block(TIMEOUT); final TableEntity createdEntity = tableClient.getEntity(partitionKeyValue, rowKeyValue).block(TIMEOUT); assertNotNull(createdEntity, "'createdEntity' should not be null."); assertNotNull(createdEntity.getETag(), "'eTag' should not be null."); StepVerifier.create(tableClient.deleteEntity(partitionKeyValue, rowKeyValue)) .expectComplete() .verify(); } @Test void deleteEntityWithResponseAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue); final int expectedStatusCode = 204; tableClient.createEntity(tableEntity).block(TIMEOUT); final TableEntity createdEntity = tableClient.getEntity(partitionKeyValue, rowKeyValue).block(TIMEOUT); assertNotNull(createdEntity, "'createdEntity' should not be null."); assertNotNull(createdEntity.getETag(), "'eTag' should not be null."); StepVerifier.create(tableClient.deleteEntityWithResponse(partitionKeyValue, rowKeyValue, null)) .assertNext(response -> { assertEquals(expectedStatusCode, response.getStatusCode()); }) .expectComplete() .verify(); } @Test void deleteEntityWithResponseMatchETagAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue); final int expectedStatusCode = 204; tableClient.createEntity(tableEntity).block(TIMEOUT); final TableEntity createdEntity = tableClient.getEntity(partitionKeyValue, rowKeyValue).block(TIMEOUT); assertNotNull(createdEntity, "'createdEntity' should not be null."); assertNotNull(createdEntity.getETag(), "'eTag' should not be null."); StepVerifier.create(tableClient.deleteEntityWithResponse(partitionKeyValue, rowKeyValue, createdEntity.getETag())) .assertNext(response -> { assertEquals(expectedStatusCode, response.getStatusCode()); }) .expectComplete() .verify(); } @Test void getEntityWithResponseAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue); final int expectedStatusCode = 200; tableClient.createEntity(tableEntity).block(TIMEOUT); StepVerifier.create(tableClient.getEntityWithResponse(partitionKeyValue, rowKeyValue, null)) .assertNext(response -> { final TableEntity entity = response.getValue(); assertEquals(expectedStatusCode, response.getStatusCode()); assertNotNull(entity); assertEquals(tableEntity.getPartitionKey(), entity.getPartitionKey()); assertEquals(tableEntity.getRowKey(), entity.getRowKey()); assertNotNull(entity.getTimestamp()); assertNotNull(entity.getETag()); assertNotNull(entity.getProperties()); }) .expectComplete() .verify(); } @Test void getEntityWithResponseWithSelectAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue); tableEntity.addProperty("Test", "Value"); final int expectedStatusCode = 200; tableClient.createEntity(tableEntity).block(TIMEOUT); StepVerifier.create(tableClient.getEntityWithResponse(partitionKeyValue, rowKeyValue, "Test")) .assertNext(response -> { final TableEntity entity = response.getValue(); assertEquals(expectedStatusCode, response.getStatusCode()); assertNotNull(entity); assertNull(entity.getPartitionKey()); assertNull(entity.getRowKey()); assertNull(entity.getTimestamp()); assertNotNull(entity.getETag()); assertEquals(entity.getProperties().get("Test"), "Value"); }) .expectComplete() .verify(); } @Test void getEntityWithResponseSubclassAsync() { String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); String rowKeyValue = testResourceNamer.randomName("rowKey", 20); byte[] bytes = new byte[]{1, 2, 3}; boolean b = true; OffsetDateTime dateTime = OffsetDateTime.of(2020, 1, 1, 0, 0, 0, 0, ZoneOffset.UTC); double d = 1.23D; UUID uuid = UUID.fromString("11111111-2222-3333-4444-555555555555"); int i = 123; long l = 123L; String s = "Test"; SampleEntity.Color color = SampleEntity.Color.GREEN; Map<String, Object> props = new HashMap<>(); props.put("ByteField", bytes); props.put("BooleanField", b); props.put("DateTimeField", dateTime); props.put("DoubleField", d); props.put("UuidField", uuid); props.put("IntField", i); props.put("LongField", l); props.put("StringField", s); props.put("EnumField", color); TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue); tableEntity.addProperties(props); int expectedStatusCode = 200; tableClient.createEntity(tableEntity).block(TIMEOUT); StepVerifier.create(tableClient.getEntityWithResponse(partitionKeyValue, rowKeyValue, null, SampleEntity.class)) .assertNext(response -> { SampleEntity entity = response.getValue(); assertEquals(expectedStatusCode, response.getStatusCode()); assertNotNull(entity); assertEquals(tableEntity.getPartitionKey(), entity.getPartitionKey()); assertEquals(tableEntity.getRowKey(), entity.getRowKey()); assertNotNull(entity.getTimestamp()); assertNotNull(entity.getETag()); assertArrayEquals(bytes, entity.getByteField()); assertEquals(b, entity.getBooleanField()); assertTrue(dateTime.isEqual(entity.getDateTimeField())); assertEquals(d, entity.getDoubleField()); assertEquals(0, uuid.compareTo(entity.getUuidField())); assertEquals(i, entity.getIntField()); assertEquals(l, entity.getLongField()); assertEquals(s, entity.getStringField()); assertEquals(color, entity.getEnumField()); }) .expectComplete() .verify(); } @Test void updateEntityWithResponseReplaceAsync() { updateEntityWithResponseAsync(UpdateMode.REPLACE); } @Test void updateEntityWithResponseMergeAsync() { updateEntityWithResponseAsync(UpdateMode.MERGE); } /** * In the case of {@link UpdateMode * In the case of {@link UpdateMode */ void updateEntityWithResponseAsync(UpdateMode mode) { final boolean expectOldProperty = mode == UpdateMode.MERGE; final String partitionKeyValue = testResourceNamer.randomName("APartitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("ARowKey", 20); final int expectedStatusCode = 204; final String oldPropertyKey = "propertyA"; final String newPropertyKey = "propertyB"; final TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue) .addProperty(oldPropertyKey, "valueA"); tableClient.createEntity(tableEntity).block(TIMEOUT); final TableEntity createdEntity = tableClient.getEntity(partitionKeyValue, rowKeyValue).block(TIMEOUT); assertNotNull(createdEntity, "'createdEntity' should not be null."); assertNotNull(createdEntity.getETag(), "'eTag' should not be null."); createdEntity.getProperties().remove(oldPropertyKey); createdEntity.addProperty(newPropertyKey, "valueB"); if (mode == UpdateMode.MERGE && tableClient.getTableUrl().contains("cosmos.azure.com")) { StepVerifier.create(tableClient.updateEntityWithResponse(createdEntity, true, mode)) .expectError(com.azure.data.tables.implementation.models.TableServiceErrorException.class) .verify(); } else { StepVerifier.create(tableClient.updateEntityWithResponse(createdEntity, true, mode)) .assertNext(response -> assertEquals(expectedStatusCode, response.getStatusCode())) .expectComplete() .verify(); StepVerifier.create(tableClient.getEntity(partitionKeyValue, rowKeyValue)) .assertNext(entity -> { final Map<String, Object> properties = entity.getProperties(); assertTrue(properties.containsKey(newPropertyKey)); assertEquals(expectOldProperty, properties.containsKey(oldPropertyKey)); }) .verifyComplete(); } } @Test @Test @Tag("ListEntities") void listEntitiesAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final String rowKeyValue2 = testResourceNamer.randomName("rowKey", 20); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue)).block(TIMEOUT); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue2)).block(TIMEOUT); StepVerifier.create(tableClient.listEntities()) .expectNextCount(2) .thenConsumeWhile(x -> true) .expectComplete() .verify(); } @Test @Tag("ListEntities") void listEntitiesWithFilterAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final String rowKeyValue2 = testResourceNamer.randomName("rowKey", 20); ListEntitiesOptions options = new ListEntitiesOptions().setFilter("RowKey eq '" + rowKeyValue + "'"); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue)).block(TIMEOUT); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue2)).block(TIMEOUT); StepVerifier.create(tableClient.listEntities(options)) .assertNext(returnEntity -> { assertEquals(partitionKeyValue, returnEntity.getPartitionKey()); assertEquals(rowKeyValue, returnEntity.getRowKey()); }) .expectNextCount(0) .thenConsumeWhile(x -> true) .expectComplete() .verify(); } @Test @Tag("ListEntities") void listEntitiesWithSelectAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity entity = new TableEntity(partitionKeyValue, rowKeyValue) .addProperty("propertyC", "valueC") .addProperty("propertyD", "valueD"); ListEntitiesOptions options = new ListEntitiesOptions() .setSelect("propertyC"); tableClient.createEntity(entity).block(TIMEOUT); StepVerifier.create(tableClient.listEntities(options)) .assertNext(returnEntity -> { assertNull(returnEntity.getRowKey()); assertNull(returnEntity.getPartitionKey()); assertEquals("valueC", returnEntity.getProperties().get("propertyC")); assertNull(returnEntity.getProperties().get("propertyD")); }) .expectComplete() .verify(); } @Test @Tag("ListEntities") void listEntitiesWithTopAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final String rowKeyValue2 = testResourceNamer.randomName("rowKey", 20); final String rowKeyValue3 = testResourceNamer.randomName("rowKey", 20); ListEntitiesOptions options = new ListEntitiesOptions().setTop(2); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue)).block(TIMEOUT); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue2)).block(TIMEOUT); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue3)).block(TIMEOUT); StepVerifier.create(tableClient.listEntities(options)) .expectNextCount(2) .thenConsumeWhile(x -> true) .expectComplete() .verify(); } @Test @Tag("ListEntities") void listEntitiesSubclassAsync() { String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); String rowKeyValue = testResourceNamer.randomName("rowKey", 20); String rowKeyValue2 = testResourceNamer.randomName("rowKey", 20); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue)).block(TIMEOUT); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue2)).block(TIMEOUT); StepVerifier.create(tableClient.listEntities(SampleEntity.class)) .expectNextCount(2) .thenConsumeWhile(x -> true) .expectComplete() .verify(); } }
Resolved
void getEntityWithResponseSubclassAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue); byte[] bytes = new byte[]{1, 2, 3}; boolean b = true; OffsetDateTime dateTime = OffsetDateTime.of(2020, 1, 1, 0, 0, 0, 0, ZoneOffset.UTC); double d = 1.23D; UUID uuid = UUID.fromString("11111111-2222-3333-4444-555555555555"); int i = 123; long l = 123L; String s = "Test"; SampleEntity.Color color = SampleEntity.Color.GREEN; Map<String, Object> props = new HashMap<>(); props.put("ByteField", bytes); props.put("BooleanField", b); props.put("DateTimeField", dateTime); props.put("DoubleField", d); props.put("UuidField", uuid); props.put("IntField", i); props.put("LongField", l); props.put("StringField", s); props.put("EnumField", color); tableEntity.addProperties(props); final int expectedStatusCode = 200; tableClient.createEntity(tableEntity).block(TIMEOUT); StepVerifier.create(tableClient.getEntityWithResponse(partitionKeyValue, rowKeyValue, null, SampleEntity.class)) .assertNext(response -> { final SampleEntity entity = response.getValue(); assertEquals(expectedStatusCode, response.getStatusCode()); assertNotNull(entity); assertEquals(tableEntity.getPartitionKey(), entity.getPartitionKey()); assertEquals(tableEntity.getRowKey(), entity.getRowKey()); assertNotNull(entity.getTimestamp()); assertNotNull(entity.getETag()); assertArrayEquals(bytes, entity.getByteField()); assertEquals(b, entity.getBooleanField()); assertTrue(dateTime.isEqual(entity.getDateTimeField())); assertEquals(d, entity.getDoubleField()); assertEquals(0, uuid.compareTo(entity.getUuidField())); assertEquals(i, entity.getIntField()); assertEquals(l, entity.getLongField()); assertEquals(s, entity.getStringField()); assertEquals(color, entity.getEnumField()); }) .expectComplete() .verify(); }
byte[] bytes = new byte[]{1, 2, 3};
void getEntityWithResponseSubclassAsync() { String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); String rowKeyValue = testResourceNamer.randomName("rowKey", 20); byte[] bytes = new byte[]{1, 2, 3}; boolean b = true; OffsetDateTime dateTime = OffsetDateTime.of(2020, 1, 1, 0, 0, 0, 0, ZoneOffset.UTC); double d = 1.23D; UUID uuid = UUID.fromString("11111111-2222-3333-4444-555555555555"); int i = 123; long l = 123L; String s = "Test"; SampleEntity.Color color = SampleEntity.Color.GREEN; Map<String, Object> props = new HashMap<>(); props.put("ByteField", bytes); props.put("BooleanField", b); props.put("DateTimeField", dateTime); props.put("DoubleField", d); props.put("UuidField", uuid); props.put("IntField", i); props.put("LongField", l); props.put("StringField", s); props.put("EnumField", color); TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue); tableEntity.addProperties(props); int expectedStatusCode = 200; tableClient.createEntity(tableEntity).block(TIMEOUT); StepVerifier.create(tableClient.getEntityWithResponse(partitionKeyValue, rowKeyValue, null, SampleEntity.class)) .assertNext(response -> { SampleEntity entity = response.getValue(); assertEquals(expectedStatusCode, response.getStatusCode()); assertNotNull(entity); assertEquals(tableEntity.getPartitionKey(), entity.getPartitionKey()); assertEquals(tableEntity.getRowKey(), entity.getRowKey()); assertNotNull(entity.getTimestamp()); assertNotNull(entity.getETag()); assertArrayEquals(bytes, entity.getByteField()); assertEquals(b, entity.getBooleanField()); assertTrue(dateTime.isEqual(entity.getDateTimeField())); assertEquals(d, entity.getDoubleField()); assertEquals(0, uuid.compareTo(entity.getUuidField())); assertEquals(i, entity.getIntField()); assertEquals(l, entity.getLongField()); assertEquals(s, entity.getStringField()); assertEquals(color, entity.getEnumField()); }) .expectComplete() .verify(); }
class TablesAsyncClientTest extends TestBase { private static final Duration TIMEOUT = Duration.ofSeconds(100); private TableAsyncClient tableClient; private HttpPipelinePolicy recordPolicy; private HttpClient playbackClient; @BeforeAll static void beforeAll() { StepVerifier.setDefaultTimeout(TIMEOUT); } @AfterAll static void afterAll() { StepVerifier.resetDefaultTimeout(); } @Override protected void beforeTest() { final String tableName = testResourceNamer.randomName("tableName", 20); final String connectionString = TestUtils.getConnectionString(interceptorManager.isPlaybackMode()); final TableClientBuilder builder = new TableClientBuilder() .connectionString(connectionString) .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)) .tableName(tableName); if (interceptorManager.isPlaybackMode()) { playbackClient = interceptorManager.getPlaybackClient(); builder.httpClient(playbackClient); } else { builder.httpClient(HttpClient.createDefault()); if (!interceptorManager.isLiveMode()) { recordPolicy = interceptorManager.getRecordPolicy(); builder.addPolicy(recordPolicy); } builder.addPolicy(new RetryPolicy(new ExponentialBackoff(6, Duration.ofMillis(1500), Duration.ofSeconds(100)))); } tableClient = builder.buildAsyncClient(); tableClient.create().block(TIMEOUT); } @Test void createTableAsync() { final String tableName2 = testResourceNamer.randomName("tableName", 20); final String connectionString = TestUtils.getConnectionString(interceptorManager.isPlaybackMode()); final TableClientBuilder builder = new TableClientBuilder() .connectionString(connectionString) .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)) .tableName(tableName2); if (interceptorManager.isPlaybackMode()) { builder.httpClient(playbackClient); } else { builder.httpClient(HttpClient.createDefault()); if (!interceptorManager.isLiveMode()) { builder.addPolicy(recordPolicy); } builder.addPolicy(new RetryPolicy(new ExponentialBackoff(6, Duration.ofMillis(1500), Duration.ofSeconds(100)))); } final TableAsyncClient tableClient2 = builder.buildAsyncClient(); StepVerifier.create(tableClient2.create()) .expectComplete() .verify(); } @Test void createTableWithResponseAsync() { final String tableName2 = testResourceNamer.randomName("tableName", 20); final String connectionString = TestUtils.getConnectionString(interceptorManager.isPlaybackMode()); final TableClientBuilder builder = new TableClientBuilder() .connectionString(connectionString) .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)) .tableName(tableName2); if (interceptorManager.isPlaybackMode()) { builder.httpClient(playbackClient); } else { builder.httpClient(HttpClient.createDefault()); if (!interceptorManager.isLiveMode()) { builder.addPolicy(recordPolicy); } builder.addPolicy(new RetryPolicy(new ExponentialBackoff(6, Duration.ofMillis(1500), Duration.ofSeconds(100)))); } final TableAsyncClient tableClient2 = builder.buildAsyncClient(); final int expectedStatusCode = 204; StepVerifier.create(tableClient2.createWithResponse()) .assertNext(response -> { assertEquals(expectedStatusCode, response.getStatusCode()); }) .expectComplete() .verify(); } @Test void createEntityAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue); StepVerifier.create(tableClient.createEntity(tableEntity)) .expectComplete() .verify(); } @Test void createEntityWithResponseAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity entity = new TableEntity(partitionKeyValue, rowKeyValue); final int expectedStatusCode = 204; StepVerifier.create(tableClient.createEntityWithResponse(entity)) .assertNext(response -> { assertEquals(expectedStatusCode, response.getStatusCode()); }) .expectComplete() .verify(); } @Test void createEntityWithAllSupportedDataTypesAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue); final boolean booleanValue = true; final byte[] binaryValue = "Test value".getBytes(); final Date dateValue = new Date(); final OffsetDateTime offsetDateTimeValue = OffsetDateTime.now(); final double doubleValue = 2.0d; final UUID guidValue = UUID.randomUUID(); final int int32Value = 1337; final long int64Value = 1337L; final String stringValue = "This is table entity"; tableEntity.addProperty("BinaryTypeProperty", binaryValue); tableEntity.addProperty("BooleanTypeProperty", booleanValue); tableEntity.addProperty("DateTypeProperty", dateValue); tableEntity.addProperty("OffsetDateTimeTypeProperty", offsetDateTimeValue); tableEntity.addProperty("DoubleTypeProperty", doubleValue); tableEntity.addProperty("GuidTypeProperty", guidValue); tableEntity.addProperty("Int32TypeProperty", int32Value); tableEntity.addProperty("Int64TypeProperty", int64Value); tableEntity.addProperty("StringTypeProperty", stringValue); tableClient.createEntity(tableEntity).block(TIMEOUT); StepVerifier.create(tableClient.getEntityWithResponse(partitionKeyValue, rowKeyValue, null)) .assertNext(response -> { final TableEntity entity = response.getValue(); Map<String, Object> properties = entity.getProperties(); assertTrue(properties.get("BinaryTypeProperty") instanceof byte[]); assertTrue(properties.get("BooleanTypeProperty") instanceof Boolean); assertTrue(properties.get("DateTypeProperty") instanceof OffsetDateTime); assertTrue(properties.get("OffsetDateTimeTypeProperty") instanceof OffsetDateTime); assertTrue(properties.get("DoubleTypeProperty") instanceof Double); assertTrue(properties.get("GuidTypeProperty") instanceof UUID); assertTrue(properties.get("Int32TypeProperty") instanceof Integer); assertTrue(properties.get("Int64TypeProperty") instanceof Long); assertTrue(properties.get("StringTypeProperty") instanceof String); }) .expectComplete() .verify(); } @Test void createEntitySubclassAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); byte[] bytes = new byte[]{1, 2, 3}; boolean b = true; OffsetDateTime dateTime = OffsetDateTime.of(2020, 1, 1, 0, 0, 0, 0, ZoneOffset.UTC); double d = 1.23D; UUID uuid = UUID.fromString("11111111-2222-3333-4444-555555555555"); int i = 123; long l = 123L; String s = "Test"; SampleEntity.Color color = SampleEntity.Color.GREEN; SampleEntity tableEntity = new SampleEntity(partitionKeyValue, rowKeyValue); tableEntity.setByteField(bytes); tableEntity.setBooleanField(b); tableEntity.setDateTimeField(dateTime); tableEntity.setDoubleField(d); tableEntity.setUuidField(uuid); tableEntity.setIntField(i); tableEntity.setLongField(l); tableEntity.setStringField(s); tableEntity.setEnumField(color); tableClient.createEntity(tableEntity).block(TIMEOUT); StepVerifier.create(tableClient.getEntityWithResponse(partitionKeyValue, rowKeyValue, null)) .assertNext(response -> { final TableEntity entity = response.getValue(); assertArrayEquals((byte[]) entity.getProperties().get("ByteField"), bytes); assertEquals(entity.getProperties().get("BooleanField"), b); assertTrue(dateTime.isEqual((OffsetDateTime) entity.getProperties().get("DateTimeField"))); assertEquals(entity.getProperties().get("DoubleField"), d); assertEquals(0, uuid.compareTo((UUID) entity.getProperties().get("UuidField"))); assertEquals(entity.getProperties().get("IntField"), i); assertEquals(entity.getProperties().get("LongField"), l); assertEquals(entity.getProperties().get("StringField"), s); assertEquals(entity.getProperties().get("EnumField"), color.name()); }) .expectComplete() .verify(); } @Test void deleteTableAsync() { StepVerifier.create(tableClient.delete()) .expectComplete() .verify(); } @Test void deleteTableWithResponseAsync() { final int expectedStatusCode = 204; StepVerifier.create(tableClient.deleteWithResponse()) .assertNext(response -> { assertEquals(expectedStatusCode, response.getStatusCode()); }) .expectComplete() .verify(); } @Test void deleteEntityAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue); tableClient.createEntity(tableEntity).block(TIMEOUT); final TableEntity createdEntity = tableClient.getEntity(partitionKeyValue, rowKeyValue).block(TIMEOUT); assertNotNull(createdEntity, "'createdEntity' should not be null."); assertNotNull(createdEntity.getETag(), "'eTag' should not be null."); StepVerifier.create(tableClient.deleteEntity(partitionKeyValue, rowKeyValue)) .expectComplete() .verify(); } @Test void deleteEntityWithResponseAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue); final int expectedStatusCode = 204; tableClient.createEntity(tableEntity).block(TIMEOUT); final TableEntity createdEntity = tableClient.getEntity(partitionKeyValue, rowKeyValue).block(TIMEOUT); assertNotNull(createdEntity, "'createdEntity' should not be null."); assertNotNull(createdEntity.getETag(), "'eTag' should not be null."); StepVerifier.create(tableClient.deleteEntityWithResponse(partitionKeyValue, rowKeyValue, null)) .assertNext(response -> { assertEquals(expectedStatusCode, response.getStatusCode()); }) .expectComplete() .verify(); } @Test void deleteEntityWithResponseMatchETagAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue); final int expectedStatusCode = 204; tableClient.createEntity(tableEntity).block(TIMEOUT); final TableEntity createdEntity = tableClient.getEntity(partitionKeyValue, rowKeyValue).block(TIMEOUT); assertNotNull(createdEntity, "'createdEntity' should not be null."); assertNotNull(createdEntity.getETag(), "'eTag' should not be null."); StepVerifier.create(tableClient.deleteEntityWithResponse(partitionKeyValue, rowKeyValue, createdEntity.getETag())) .assertNext(response -> { assertEquals(expectedStatusCode, response.getStatusCode()); }) .expectComplete() .verify(); } @Test void getEntityWithResponseAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue); final int expectedStatusCode = 200; tableClient.createEntity(tableEntity).block(TIMEOUT); StepVerifier.create(tableClient.getEntityWithResponse(partitionKeyValue, rowKeyValue, null)) .assertNext(response -> { final TableEntity entity = response.getValue(); assertEquals(expectedStatusCode, response.getStatusCode()); assertNotNull(entity); assertEquals(tableEntity.getPartitionKey(), entity.getPartitionKey()); assertEquals(tableEntity.getRowKey(), entity.getRowKey()); assertNotNull(entity.getTimestamp()); assertNotNull(entity.getETag()); assertNotNull(entity.getProperties()); }) .expectComplete() .verify(); } @Test void getEntityWithResponseWithSelectAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue); tableEntity.addProperty("Test", "Value"); final int expectedStatusCode = 200; tableClient.createEntity(tableEntity).block(TIMEOUT); StepVerifier.create(tableClient.getEntityWithResponse(partitionKeyValue, rowKeyValue, "Test")) .assertNext(response -> { final TableEntity entity = response.getValue(); assertEquals(expectedStatusCode, response.getStatusCode()); assertNotNull(entity); assertNull(entity.getPartitionKey()); assertNull(entity.getRowKey()); assertNull(entity.getTimestamp()); assertNotNull(entity.getETag()); assertEquals(entity.getProperties().get("Test"), "Value"); }) .expectComplete() .verify(); } @Test @Test void updateEntityWithResponseReplaceAsync() { updateEntityWithResponseAsync(UpdateMode.REPLACE); } @Test void updateEntityWithResponseMergeAsync() { updateEntityWithResponseAsync(UpdateMode.MERGE); } /** * In the case of {@link UpdateMode * In the case of {@link UpdateMode */ void updateEntityWithResponseAsync(UpdateMode mode) { final boolean expectOldProperty = mode == UpdateMode.MERGE; final String partitionKeyValue = testResourceNamer.randomName("APartitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("ARowKey", 20); final int expectedStatusCode = 204; final String oldPropertyKey = "propertyA"; final String newPropertyKey = "propertyB"; final TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue) .addProperty(oldPropertyKey, "valueA"); tableClient.createEntity(tableEntity).block(TIMEOUT); final TableEntity createdEntity = tableClient.getEntity(partitionKeyValue, rowKeyValue).block(TIMEOUT); assertNotNull(createdEntity, "'createdEntity' should not be null."); assertNotNull(createdEntity.getETag(), "'eTag' should not be null."); createdEntity.getProperties().remove(oldPropertyKey); createdEntity.addProperty(newPropertyKey, "valueB"); if (mode == UpdateMode.MERGE && tableClient.getTableUrl().contains("cosmos.azure.com")) { StepVerifier.create(tableClient.updateEntityWithResponse(createdEntity, true, mode)) .expectError(com.azure.data.tables.implementation.models.TableServiceErrorException.class) .verify(); } else { StepVerifier.create(tableClient.updateEntityWithResponse(createdEntity, true, mode)) .assertNext(response -> assertEquals(expectedStatusCode, response.getStatusCode())) .expectComplete() .verify(); StepVerifier.create(tableClient.getEntity(partitionKeyValue, rowKeyValue)) .assertNext(entity -> { final Map<String, Object> properties = entity.getProperties(); assertTrue(properties.containsKey(newPropertyKey)); assertEquals(expectOldProperty, properties.containsKey(oldPropertyKey)); }) .verifyComplete(); } } @Test void updateEntityWithResponseSubclassAsync() { final String partitionKeyValue = testResourceNamer.randomName("APartitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("ARowKey", 20); final int expectedStatusCode = 204; SingleFieldEntity tableEntity = new SingleFieldEntity(partitionKeyValue, rowKeyValue); tableEntity.setSubclassProperty("InitialValue"); tableClient.createEntity(tableEntity).block(TIMEOUT); tableEntity.setSubclassProperty("UpdatedValue"); StepVerifier.create(tableClient.updateEntityWithResponse(tableEntity, true, UpdateMode.MERGE)) .assertNext(response -> assertEquals(expectedStatusCode, response.getStatusCode())) .expectComplete() .verify(); StepVerifier.create(tableClient.getEntity(partitionKeyValue, rowKeyValue)) .assertNext(entity -> { final Map<String, Object> properties = entity.getProperties(); assertTrue(properties.containsKey("SubclassProperty")); assertEquals("UpdatedValue", properties.get("SubclassProperty")); }) .verifyComplete(); } @Test @Tag("ListEntities") void listEntitiesAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final String rowKeyValue2 = testResourceNamer.randomName("rowKey", 20); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue)).block(TIMEOUT); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue2)).block(TIMEOUT); StepVerifier.create(tableClient.listEntities()) .expectNextCount(2) .thenConsumeWhile(x -> true) .expectComplete() .verify(); } @Test @Tag("ListEntities") void listEntitiesWithFilterAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final String rowKeyValue2 = testResourceNamer.randomName("rowKey", 20); ListEntitiesOptions options = new ListEntitiesOptions().setFilter("RowKey eq '" + rowKeyValue + "'"); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue)).block(TIMEOUT); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue2)).block(TIMEOUT); StepVerifier.create(tableClient.listEntities(options)) .assertNext(returnEntity -> { assertEquals(partitionKeyValue, returnEntity.getPartitionKey()); assertEquals(rowKeyValue, returnEntity.getRowKey()); }) .expectNextCount(0) .thenConsumeWhile(x -> true) .expectComplete() .verify(); } @Test @Tag("ListEntities") void listEntitiesWithSelectAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity entity = new TableEntity(partitionKeyValue, rowKeyValue) .addProperty("propertyC", "valueC") .addProperty("propertyD", "valueD"); ListEntitiesOptions options = new ListEntitiesOptions() .setSelect("propertyC"); tableClient.createEntity(entity).block(TIMEOUT); StepVerifier.create(tableClient.listEntities(options)) .assertNext(returnEntity -> { assertNull(returnEntity.getRowKey()); assertNull(returnEntity.getPartitionKey()); assertEquals("valueC", returnEntity.getProperties().get("propertyC")); assertNull(returnEntity.getProperties().get("propertyD")); }) .expectComplete() .verify(); } @Test @Tag("ListEntities") void listEntitiesWithTopAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final String rowKeyValue2 = testResourceNamer.randomName("rowKey", 20); final String rowKeyValue3 = testResourceNamer.randomName("rowKey", 20); ListEntitiesOptions options = new ListEntitiesOptions().setTop(2); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue)).block(TIMEOUT); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue2)).block(TIMEOUT); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue3)).block(TIMEOUT); StepVerifier.create(tableClient.listEntities(options)) .expectNextCount(2) .thenConsumeWhile(x -> true) .expectComplete() .verify(); } @Test @Tag("ListEntities") void listEntitiesSubclassAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final String rowKeyValue2 = testResourceNamer.randomName("rowKey", 20); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue)).block(TIMEOUT); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue2)).block(TIMEOUT); StepVerifier.create(tableClient.listEntities(SampleEntity.class)) .expectNextCount(2) .thenConsumeWhile(x -> true) .expectComplete() .verify(); } }
class TablesAsyncClientTest extends TestBase { private static final Duration TIMEOUT = Duration.ofSeconds(100); private TableAsyncClient tableClient; private HttpPipelinePolicy recordPolicy; private HttpClient playbackClient; @BeforeAll static void beforeAll() { StepVerifier.setDefaultTimeout(TIMEOUT); } @AfterAll static void afterAll() { StepVerifier.resetDefaultTimeout(); } @Override protected void beforeTest() { final String tableName = testResourceNamer.randomName("tableName", 20); final String connectionString = TestUtils.getConnectionString(interceptorManager.isPlaybackMode()); final TableClientBuilder builder = new TableClientBuilder() .connectionString(connectionString) .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)) .tableName(tableName); if (interceptorManager.isPlaybackMode()) { playbackClient = interceptorManager.getPlaybackClient(); builder.httpClient(playbackClient); } else { builder.httpClient(HttpClient.createDefault()); if (!interceptorManager.isLiveMode()) { recordPolicy = interceptorManager.getRecordPolicy(); builder.addPolicy(recordPolicy); } builder.addPolicy(new RetryPolicy(new ExponentialBackoff(6, Duration.ofMillis(1500), Duration.ofSeconds(100)))); } tableClient = builder.buildAsyncClient(); tableClient.create().block(TIMEOUT); } @Test void createTableAsync() { final String tableName2 = testResourceNamer.randomName("tableName", 20); final String connectionString = TestUtils.getConnectionString(interceptorManager.isPlaybackMode()); final TableClientBuilder builder = new TableClientBuilder() .connectionString(connectionString) .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)) .tableName(tableName2); if (interceptorManager.isPlaybackMode()) { builder.httpClient(playbackClient); } else { builder.httpClient(HttpClient.createDefault()); if (!interceptorManager.isLiveMode()) { builder.addPolicy(recordPolicy); } builder.addPolicy(new RetryPolicy(new ExponentialBackoff(6, Duration.ofMillis(1500), Duration.ofSeconds(100)))); } final TableAsyncClient tableClient2 = builder.buildAsyncClient(); StepVerifier.create(tableClient2.create()) .expectComplete() .verify(); } @Test void createTableWithResponseAsync() { final String tableName2 = testResourceNamer.randomName("tableName", 20); final String connectionString = TestUtils.getConnectionString(interceptorManager.isPlaybackMode()); final TableClientBuilder builder = new TableClientBuilder() .connectionString(connectionString) .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)) .tableName(tableName2); if (interceptorManager.isPlaybackMode()) { builder.httpClient(playbackClient); } else { builder.httpClient(HttpClient.createDefault()); if (!interceptorManager.isLiveMode()) { builder.addPolicy(recordPolicy); } builder.addPolicy(new RetryPolicy(new ExponentialBackoff(6, Duration.ofMillis(1500), Duration.ofSeconds(100)))); } final TableAsyncClient tableClient2 = builder.buildAsyncClient(); final int expectedStatusCode = 204; StepVerifier.create(tableClient2.createWithResponse()) .assertNext(response -> { assertEquals(expectedStatusCode, response.getStatusCode()); }) .expectComplete() .verify(); } @Test void createEntityAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue); StepVerifier.create(tableClient.createEntity(tableEntity)) .expectComplete() .verify(); } @Test void createEntityWithResponseAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity entity = new TableEntity(partitionKeyValue, rowKeyValue); final int expectedStatusCode = 204; StepVerifier.create(tableClient.createEntityWithResponse(entity)) .assertNext(response -> { assertEquals(expectedStatusCode, response.getStatusCode()); }) .expectComplete() .verify(); } @Test void createEntityWithAllSupportedDataTypesAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue); final boolean booleanValue = true; final byte[] binaryValue = "Test value".getBytes(); final Date dateValue = new Date(); final OffsetDateTime offsetDateTimeValue = OffsetDateTime.now(); final double doubleValue = 2.0d; final UUID guidValue = UUID.randomUUID(); final int int32Value = 1337; final long int64Value = 1337L; final String stringValue = "This is table entity"; tableEntity.addProperty("BinaryTypeProperty", binaryValue); tableEntity.addProperty("BooleanTypeProperty", booleanValue); tableEntity.addProperty("DateTypeProperty", dateValue); tableEntity.addProperty("OffsetDateTimeTypeProperty", offsetDateTimeValue); tableEntity.addProperty("DoubleTypeProperty", doubleValue); tableEntity.addProperty("GuidTypeProperty", guidValue); tableEntity.addProperty("Int32TypeProperty", int32Value); tableEntity.addProperty("Int64TypeProperty", int64Value); tableEntity.addProperty("StringTypeProperty", stringValue); tableClient.createEntity(tableEntity).block(TIMEOUT); StepVerifier.create(tableClient.getEntityWithResponse(partitionKeyValue, rowKeyValue, null)) .assertNext(response -> { final TableEntity entity = response.getValue(); Map<String, Object> properties = entity.getProperties(); assertTrue(properties.get("BinaryTypeProperty") instanceof byte[]); assertTrue(properties.get("BooleanTypeProperty") instanceof Boolean); assertTrue(properties.get("DateTypeProperty") instanceof OffsetDateTime); assertTrue(properties.get("OffsetDateTimeTypeProperty") instanceof OffsetDateTime); assertTrue(properties.get("DoubleTypeProperty") instanceof Double); assertTrue(properties.get("GuidTypeProperty") instanceof UUID); assertTrue(properties.get("Int32TypeProperty") instanceof Integer); assertTrue(properties.get("Int64TypeProperty") instanceof Long); assertTrue(properties.get("StringTypeProperty") instanceof String); }) .expectComplete() .verify(); } @Test void createEntitySubclassAsync() { String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); String rowKeyValue = testResourceNamer.randomName("rowKey", 20); byte[] bytes = new byte[]{1, 2, 3}; boolean b = true; OffsetDateTime dateTime = OffsetDateTime.of(2020, 1, 1, 0, 0, 0, 0, ZoneOffset.UTC); double d = 1.23D; UUID uuid = UUID.fromString("11111111-2222-3333-4444-555555555555"); int i = 123; long l = 123L; String s = "Test"; SampleEntity.Color color = SampleEntity.Color.GREEN; SampleEntity tableEntity = new SampleEntity(partitionKeyValue, rowKeyValue); tableEntity.setByteField(bytes); tableEntity.setBooleanField(b); tableEntity.setDateTimeField(dateTime); tableEntity.setDoubleField(d); tableEntity.setUuidField(uuid); tableEntity.setIntField(i); tableEntity.setLongField(l); tableEntity.setStringField(s); tableEntity.setEnumField(color); tableClient.createEntity(tableEntity).block(TIMEOUT); StepVerifier.create(tableClient.getEntityWithResponse(partitionKeyValue, rowKeyValue, null)) .assertNext(response -> { TableEntity entity = response.getValue(); assertArrayEquals((byte[]) entity.getProperties().get("ByteField"), bytes); assertEquals(entity.getProperties().get("BooleanField"), b); assertTrue(dateTime.isEqual((OffsetDateTime) entity.getProperties().get("DateTimeField"))); assertEquals(entity.getProperties().get("DoubleField"), d); assertEquals(0, uuid.compareTo((UUID) entity.getProperties().get("UuidField"))); assertEquals(entity.getProperties().get("IntField"), i); assertEquals(entity.getProperties().get("LongField"), l); assertEquals(entity.getProperties().get("StringField"), s); assertEquals(entity.getProperties().get("EnumField"), color.name()); }) .expectComplete() .verify(); } @Test void deleteTableAsync() { StepVerifier.create(tableClient.delete()) .expectComplete() .verify(); } @Test void deleteTableWithResponseAsync() { final int expectedStatusCode = 204; StepVerifier.create(tableClient.deleteWithResponse()) .assertNext(response -> { assertEquals(expectedStatusCode, response.getStatusCode()); }) .expectComplete() .verify(); } @Test void deleteEntityAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue); tableClient.createEntity(tableEntity).block(TIMEOUT); final TableEntity createdEntity = tableClient.getEntity(partitionKeyValue, rowKeyValue).block(TIMEOUT); assertNotNull(createdEntity, "'createdEntity' should not be null."); assertNotNull(createdEntity.getETag(), "'eTag' should not be null."); StepVerifier.create(tableClient.deleteEntity(partitionKeyValue, rowKeyValue)) .expectComplete() .verify(); } @Test void deleteEntityWithResponseAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue); final int expectedStatusCode = 204; tableClient.createEntity(tableEntity).block(TIMEOUT); final TableEntity createdEntity = tableClient.getEntity(partitionKeyValue, rowKeyValue).block(TIMEOUT); assertNotNull(createdEntity, "'createdEntity' should not be null."); assertNotNull(createdEntity.getETag(), "'eTag' should not be null."); StepVerifier.create(tableClient.deleteEntityWithResponse(partitionKeyValue, rowKeyValue, null)) .assertNext(response -> { assertEquals(expectedStatusCode, response.getStatusCode()); }) .expectComplete() .verify(); } @Test void deleteEntityWithResponseMatchETagAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue); final int expectedStatusCode = 204; tableClient.createEntity(tableEntity).block(TIMEOUT); final TableEntity createdEntity = tableClient.getEntity(partitionKeyValue, rowKeyValue).block(TIMEOUT); assertNotNull(createdEntity, "'createdEntity' should not be null."); assertNotNull(createdEntity.getETag(), "'eTag' should not be null."); StepVerifier.create(tableClient.deleteEntityWithResponse(partitionKeyValue, rowKeyValue, createdEntity.getETag())) .assertNext(response -> { assertEquals(expectedStatusCode, response.getStatusCode()); }) .expectComplete() .verify(); } @Test void getEntityWithResponseAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue); final int expectedStatusCode = 200; tableClient.createEntity(tableEntity).block(TIMEOUT); StepVerifier.create(tableClient.getEntityWithResponse(partitionKeyValue, rowKeyValue, null)) .assertNext(response -> { final TableEntity entity = response.getValue(); assertEquals(expectedStatusCode, response.getStatusCode()); assertNotNull(entity); assertEquals(tableEntity.getPartitionKey(), entity.getPartitionKey()); assertEquals(tableEntity.getRowKey(), entity.getRowKey()); assertNotNull(entity.getTimestamp()); assertNotNull(entity.getETag()); assertNotNull(entity.getProperties()); }) .expectComplete() .verify(); } @Test void getEntityWithResponseWithSelectAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue); tableEntity.addProperty("Test", "Value"); final int expectedStatusCode = 200; tableClient.createEntity(tableEntity).block(TIMEOUT); StepVerifier.create(tableClient.getEntityWithResponse(partitionKeyValue, rowKeyValue, "Test")) .assertNext(response -> { final TableEntity entity = response.getValue(); assertEquals(expectedStatusCode, response.getStatusCode()); assertNotNull(entity); assertNull(entity.getPartitionKey()); assertNull(entity.getRowKey()); assertNull(entity.getTimestamp()); assertNotNull(entity.getETag()); assertEquals(entity.getProperties().get("Test"), "Value"); }) .expectComplete() .verify(); } @Test @Test void updateEntityWithResponseReplaceAsync() { updateEntityWithResponseAsync(UpdateMode.REPLACE); } @Test void updateEntityWithResponseMergeAsync() { updateEntityWithResponseAsync(UpdateMode.MERGE); } /** * In the case of {@link UpdateMode * In the case of {@link UpdateMode */ void updateEntityWithResponseAsync(UpdateMode mode) { final boolean expectOldProperty = mode == UpdateMode.MERGE; final String partitionKeyValue = testResourceNamer.randomName("APartitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("ARowKey", 20); final int expectedStatusCode = 204; final String oldPropertyKey = "propertyA"; final String newPropertyKey = "propertyB"; final TableEntity tableEntity = new TableEntity(partitionKeyValue, rowKeyValue) .addProperty(oldPropertyKey, "valueA"); tableClient.createEntity(tableEntity).block(TIMEOUT); final TableEntity createdEntity = tableClient.getEntity(partitionKeyValue, rowKeyValue).block(TIMEOUT); assertNotNull(createdEntity, "'createdEntity' should not be null."); assertNotNull(createdEntity.getETag(), "'eTag' should not be null."); createdEntity.getProperties().remove(oldPropertyKey); createdEntity.addProperty(newPropertyKey, "valueB"); if (mode == UpdateMode.MERGE && tableClient.getTableUrl().contains("cosmos.azure.com")) { StepVerifier.create(tableClient.updateEntityWithResponse(createdEntity, true, mode)) .expectError(com.azure.data.tables.implementation.models.TableServiceErrorException.class) .verify(); } else { StepVerifier.create(tableClient.updateEntityWithResponse(createdEntity, true, mode)) .assertNext(response -> assertEquals(expectedStatusCode, response.getStatusCode())) .expectComplete() .verify(); StepVerifier.create(tableClient.getEntity(partitionKeyValue, rowKeyValue)) .assertNext(entity -> { final Map<String, Object> properties = entity.getProperties(); assertTrue(properties.containsKey(newPropertyKey)); assertEquals(expectOldProperty, properties.containsKey(oldPropertyKey)); }) .verifyComplete(); } } @Test void updateEntityWithResponseSubclassAsync() { String partitionKeyValue = testResourceNamer.randomName("APartitionKey", 20); String rowKeyValue = testResourceNamer.randomName("ARowKey", 20); int expectedStatusCode = 204; SingleFieldEntity tableEntity = new SingleFieldEntity(partitionKeyValue, rowKeyValue); tableEntity.setSubclassProperty("InitialValue"); tableClient.createEntity(tableEntity).block(TIMEOUT); tableEntity.setSubclassProperty("UpdatedValue"); StepVerifier.create(tableClient.updateEntityWithResponse(tableEntity, true, UpdateMode.MERGE)) .assertNext(response -> assertEquals(expectedStatusCode, response.getStatusCode())) .expectComplete() .verify(); StepVerifier.create(tableClient.getEntity(partitionKeyValue, rowKeyValue)) .assertNext(entity -> { Map<String, Object> properties = entity.getProperties(); assertTrue(properties.containsKey("SubclassProperty")); assertEquals("UpdatedValue", properties.get("SubclassProperty")); }) .verifyComplete(); } @Test @Tag("ListEntities") void listEntitiesAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final String rowKeyValue2 = testResourceNamer.randomName("rowKey", 20); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue)).block(TIMEOUT); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue2)).block(TIMEOUT); StepVerifier.create(tableClient.listEntities()) .expectNextCount(2) .thenConsumeWhile(x -> true) .expectComplete() .verify(); } @Test @Tag("ListEntities") void listEntitiesWithFilterAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final String rowKeyValue2 = testResourceNamer.randomName("rowKey", 20); ListEntitiesOptions options = new ListEntitiesOptions().setFilter("RowKey eq '" + rowKeyValue + "'"); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue)).block(TIMEOUT); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue2)).block(TIMEOUT); StepVerifier.create(tableClient.listEntities(options)) .assertNext(returnEntity -> { assertEquals(partitionKeyValue, returnEntity.getPartitionKey()); assertEquals(rowKeyValue, returnEntity.getRowKey()); }) .expectNextCount(0) .thenConsumeWhile(x -> true) .expectComplete() .verify(); } @Test @Tag("ListEntities") void listEntitiesWithSelectAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity entity = new TableEntity(partitionKeyValue, rowKeyValue) .addProperty("propertyC", "valueC") .addProperty("propertyD", "valueD"); ListEntitiesOptions options = new ListEntitiesOptions() .setSelect("propertyC"); tableClient.createEntity(entity).block(TIMEOUT); StepVerifier.create(tableClient.listEntities(options)) .assertNext(returnEntity -> { assertNull(returnEntity.getRowKey()); assertNull(returnEntity.getPartitionKey()); assertEquals("valueC", returnEntity.getProperties().get("propertyC")); assertNull(returnEntity.getProperties().get("propertyD")); }) .expectComplete() .verify(); } @Test @Tag("ListEntities") void listEntitiesWithTopAsync() { final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final String rowKeyValue2 = testResourceNamer.randomName("rowKey", 20); final String rowKeyValue3 = testResourceNamer.randomName("rowKey", 20); ListEntitiesOptions options = new ListEntitiesOptions().setTop(2); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue)).block(TIMEOUT); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue2)).block(TIMEOUT); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue3)).block(TIMEOUT); StepVerifier.create(tableClient.listEntities(options)) .expectNextCount(2) .thenConsumeWhile(x -> true) .expectComplete() .verify(); } @Test @Tag("ListEntities") void listEntitiesSubclassAsync() { String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); String rowKeyValue = testResourceNamer.randomName("rowKey", 20); String rowKeyValue2 = testResourceNamer.randomName("rowKey", 20); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue)).block(TIMEOUT); tableClient.createEntity(new TableEntity(partitionKeyValue, rowKeyValue2)).block(TIMEOUT); StepVerifier.create(tableClient.listEntities(SampleEntity.class)) .expectNextCount(2) .thenConsumeWhile(x -> true) .expectComplete() .verify(); } }
Resolved
static void setPropertiesFromGetters(TableEntity entity, ClientLogger logger) { Class<?> myClass = entity.getClass(); if (myClass == TableEntity.class) { return; } for (Method m : myClass.getMethods()) { if (m.getName().length() < 3 || TABLE_ENTITY_METHODS.contains(m.getName()) || (!m.getName().startsWith("get") && !m.getName().startsWith("is")) || m.getParameterTypes().length != 0 || void.class.equals(m.getReturnType())) { continue; } int prefixLength = m.getName().startsWith("get") ? 3 : 2; String propName = m.getName().substring(prefixLength); try { entity.getProperties().put(propName, m.invoke(entity)); } catch (ReflectiveOperationException | IllegalArgumentException e) { logger.logThrowableAsWarning(new ReflectiveOperationException(String.format( "Failed to get property '%s' on type '%s'", propName, myClass.getName()), e)); } } }
int prefixLength = m.getName().startsWith("get") ? 3 : 2;
static void setPropertiesFromGetters(TableEntity entity, ClientLogger logger) { Class<?> myClass = entity.getClass(); if (myClass == TableEntity.class) { return; } for (Method m : myClass.getMethods()) { if (m.getName().length() < 3 || TABLE_ENTITY_METHODS.contains(m.getName()) || (!m.getName().startsWith("get") && !m.getName().startsWith("is")) || m.getParameterTypes().length != 0 || void.class.equals(m.getReturnType())) { continue; } if (m.getName().startsWith("is") && m.getReturnType() != Boolean.class && m.getReturnType() != boolean.class) { continue; } int prefixLength = m.getName().startsWith("is") ? 2 : 3; String propName = m.getName().substring(prefixLength); try { entity.getProperties().put(propName, m.invoke(entity)); } catch (ReflectiveOperationException | IllegalArgumentException e) { logger.logThrowableAsWarning(new ReflectiveOperationException(String.format( "Failed to get property '%s' on type '%s'", propName, myClass.getName()), e)); } } }
class EntityHelper { private static final HashSet<String> TABLE_ENTITY_METHODS = Arrays.stream(TableEntity.class.getMethods()) .map(Method::getName).collect(Collectors.toCollection(HashSet::new)); private EntityHelper() { } @SuppressWarnings("unchecked") static <T extends TableEntity> T convertToSubclass(TableEntity entity, Class<T> clazz, ClientLogger logger) { if (TableEntity.class == clazz) { return (T) entity; } T result; try { result = clazz.getDeclaredConstructor(String.class, String.class).newInstance(entity.getPartitionKey(), entity.getRowKey()); } catch (ReflectiveOperationException | SecurityException e) { logger.logThrowableAsWarning(new ReflectiveOperationException(String.format( "Failed to instantiate type '%s'", clazz.getName()), e)); return null; } result.addProperties(entity.getProperties()); for (Method m : clazz.getMethods()) { if (m.getName().length() < 4 || !m.getName().startsWith("set") || m.getParameterTypes().length != 1 || !void.class.equals(m.getReturnType())) { continue; } String propName = m.getName().substring(3); Object value = result.getProperties().get(propName); if (value == null) { continue; } Class<?> paramType = m.getParameterTypes()[0]; if (paramType.isEnum() && value instanceof String) { try { value = Enum.valueOf(paramType.asSubclass(Enum.class), (String) value); } catch (IllegalArgumentException e) { logger.logThrowableAsWarning(new IllegalArgumentException(String.format( "Failed to convert '%s' to value of enum '%s'", propName, paramType.getName()), e)); } } try { m.invoke(result, value); } catch (ReflectiveOperationException | IllegalArgumentException e) { logger.logThrowableAsWarning(new ReflectiveOperationException(String.format( "Failed to set property '%s' on type '%s'", propName, clazz.getName()), e)); } } return result; } }
class of `TableEntity`, locate all getter methods (those that start with `get` or `is`, take no
Get the `version` param fixed.
protected Mono<SecretProperties> getInnerAsync() { return vault.secretClient().getSecret(name(), innerModel().getVersion()).map(secret -> { this.secretValue = secret.getValue(); return secret.getProperties(); }); }
return vault.secretClient().getSecret(name(), innerModel().getVersion()).map(secret -> {
protected Mono<SecretProperties> getInnerAsync() { return vault.secretClient().getSecret(name(), innerModel().getVersion()).map(secret -> { this.secretValue = secret.getValue(); return secret.getProperties(); }); }
class SecretImpl extends CreatableUpdatableImpl<Secret, SecretProperties, SecretImpl> implements Secret, Secret.Definition, Secret.Update { private final Vault vault; private String secretValueToSet; private String secretValue; SecretImpl(String name, SecretProperties innerObject, Vault vault) { super(name, innerObject); this.vault = vault; } SecretImpl(String name, KeyVaultSecret keyVaultSecret, Vault vault) { super(name, keyVaultSecret.getProperties()); this.secretValue = keyVaultSecret.getValue(); this.vault = vault; } private SecretImpl wrapModel(SecretProperties secret) { return new SecretImpl(secret.getName(), secret, vault); } @Override public String id() { return innerModel().getId(); } @Override public String getValue() { return getValueAsync().block(); } @Override public Mono<String> getValueAsync() { if (secretValue != null) { return Mono.just(secretValue); } else { return getInnerAsync().map(ignored -> secretValue); } } @Override public SecretProperties attributes() { return innerModel(); } @Override public Map<String, String> tags() { return innerModel().getTags(); } @Override public String contentType() { return innerModel().getContentType(); } @Override public String kid() { return innerModel().getKeyId(); } @Override public boolean managed() { return ResourceManagerUtils.toPrimitiveBoolean(innerModel().isManaged()); } @Override public boolean enabled() { return ResourceManagerUtils.toPrimitiveBoolean(innerModel().isEnabled()); } @Override public Iterable<Secret> listVersions() { return this.listVersionsAsync().toIterable(); } @Override public Flux<Secret> listVersionsAsync() { return vault .secretClient() .listPropertiesOfSecretVersions(name()) .map(this::wrapModel); } @Override @Override public SecretImpl withTags(Map<String, String> tags) { this.innerModel().setTags(tags); return this; } @Override public boolean isInCreateMode() { return id() == null; } @Override public Mono<Secret> createResourceAsync() { KeyVaultSecret newSecret = new KeyVaultSecret(this.name(), secretValueToSet); newSecret.setProperties(this.attributes()); return vault .secretClient() .setSecret(newSecret) .map( keyVaultSecret -> { this.setInner(keyVaultSecret.getProperties()); this.secretValue = keyVaultSecret.getValue(); secretValueToSet = null; return this; }); } @Override public Mono<Secret> updateResourceAsync() { if (secretValueToSet == null) { return vault .secretClient() .updateSecretProperties(this.innerModel()) .map( p -> { this.setInner(p); return this; }); } else { return this.createResourceAsync(); } } @Override public SecretImpl withAttributes(SecretProperties attributes) { this.setInner(attributes); return this; } @Override public SecretImpl withValue(String value) { Objects.requireNonNull(value); secretValueToSet = value; return this; } @Override public SecretImpl withContentType(String contentType) { this.innerModel().setContentType(contentType); return this; } }
class SecretImpl extends CreatableUpdatableImpl<Secret, SecretProperties, SecretImpl> implements Secret, Secret.Definition, Secret.Update { private final Vault vault; private String secretValueToSet; private String secretValue; SecretImpl(String name, SecretProperties innerObject, Vault vault) { super(name, innerObject); this.vault = vault; } SecretImpl(String name, KeyVaultSecret keyVaultSecret, Vault vault) { super(name, keyVaultSecret.getProperties()); this.secretValue = keyVaultSecret.getValue(); this.vault = vault; } private SecretImpl wrapModel(SecretProperties secret) { return new SecretImpl(secret.getName(), secret, vault); } @Override public String id() { return innerModel().getId(); } @Override public String getValue() { return getValueAsync().block(); } @Override public Mono<String> getValueAsync() { if (secretValue != null) { return Mono.just(secretValue); } else { return getInnerAsync().map(ignored -> secretValue); } } @Override public SecretProperties attributes() { return innerModel(); } @Override public Map<String, String> tags() { return innerModel().getTags(); } @Override public String contentType() { return innerModel().getContentType(); } @Override public String kid() { return innerModel().getKeyId(); } @Override public boolean managed() { return ResourceManagerUtils.toPrimitiveBoolean(innerModel().isManaged()); } @Override public boolean enabled() { return ResourceManagerUtils.toPrimitiveBoolean(innerModel().isEnabled()); } @Override public Iterable<Secret> listVersions() { return this.listVersionsAsync().toIterable(); } @Override public Flux<Secret> listVersionsAsync() { return vault .secretClient() .listPropertiesOfSecretVersions(name()) .map(this::wrapModel); } @Override @Override public SecretImpl withTags(Map<String, String> tags) { this.innerModel().setTags(tags); return this; } @Override public boolean isInCreateMode() { return id() == null; } @Override public Mono<Secret> createResourceAsync() { KeyVaultSecret newSecret = new KeyVaultSecret(this.name(), secretValueToSet); newSecret.setProperties(this.attributes()); return vault .secretClient() .setSecret(newSecret) .map( keyVaultSecret -> { this.setInner(keyVaultSecret.getProperties()); this.secretValue = keyVaultSecret.getValue(); secretValueToSet = null; return this; }); } @Override public Mono<Secret> updateResourceAsync() { if (secretValueToSet == null) { return vault .secretClient() .updateSecretProperties(this.innerModel()) .map( p -> { this.setInner(p); if (!p.isEnabled()) { secretValue = null; } return this; }); } else { return this.createResourceAsync(); } } @Override public SecretImpl withAttributes(SecretProperties attributes) { this.setInner(attributes); return this; } @Override public SecretImpl withValue(String value) { Objects.requireNonNull(value); secretValueToSet = value; return this; } @Override public SecretImpl withContentType(String contentType) { this.innerModel().setContentType(contentType); return this; } }
nit: business_card_url
public void beginRecognizeBusinessCardsFromUrl() { String businessCardUrl = "{file_source_url}"; formRecognizerAsyncClient.beginRecognizeBusinessCardsFromUrl(businessCardUrl) .flatMap(AsyncPollResponse::getFinalResult) .subscribe(recognizedBusinessCards -> { for (int i = 0; i < recognizedBusinessCards.size(); i++) { RecognizedForm recognizedForm = recognizedBusinessCards.get(i); Map<String, FormField> recognizedFields = recognizedForm.getFields(); System.out.printf("----------- Recognized Business Card page %d -----------%n", i); FormField contactNames = recognizedFields.get("ContactNames"); if (contactNames != null) { if (FieldValueType.LIST == contactNames.getValue().getValueType()) { List<FormField> businessCardItems = contactNames.getValue().asList(); businessCardItems.stream() .filter(businessCardItem -> FieldValueType.MAP == businessCardItem.getValue() .getValueType()) .map(formField -> formField.getValue().asMap()) .forEach(formFieldMap -> formFieldMap.forEach((key, formField) -> { if ("FirstName".equals(key)) { if (FieldValueType.STRING == formField.getValue().getValueType()) { String firstName = formField.getValue().asString(); System.out.printf("First Name: %s, confidence: %.2f%n", firstName, contactNames.getConfidence()); } } if ("LastName".equals(key)) { if (FieldValueType.STRING == formField.getValue().getValueType()) { String lastName = formField.getValue().asString(); System.out.printf("Last Name: %s, confidence: %.2f%n", lastName, contactNames.getConfidence()); } } })); } } FormField jobTitles = recognizedFields.get("JobTitles"); if (jobTitles != null) { if (FieldValueType.LIST == jobTitles.getValue().getValueType()) { List<FormField> jobTitlesItems = jobTitles.getValue().asList(); jobTitlesItems.stream().forEach(formField -> { if (FieldValueType.STRING == formField.getValue().getValueType()) { String jobTitle = formField.getValue().asString(); System.out.printf("Job Title: %s, confidence: %.2f%n", jobTitle, jobTitles.getConfidence()); } }); } } FormField addresses = recognizedFields.get("Addresses"); if (addresses != null) { if (FieldValueType.LIST == addresses.getValue().getValueType()) { List<FormField> addressesItems = addresses.getValue().asList(); addressesItems.stream().forEach(formField -> { if (FieldValueType.STRING == formField.getValue().getValueType()) { String address = formField.getValue().asString(); System.out.printf("Address: %s, confidence: %.2f%n", address, addresses.getConfidence()); } }); } } FormField companyName = recognizedFields.get("CompanyNames"); if (companyName != null) { if (FieldValueType.LIST == companyName.getValue().getValueType()) { List<FormField> companyNameItems = companyName.getValue().asList(); companyNameItems.stream().forEach(formField -> { if (FieldValueType.STRING == formField.getValue().getValueType()) { String companyNameValue = formField.getValue().asString(); System.out.printf("Company name: %s, confidence: %.2f%n", companyNameValue, companyName.getConfidence()); } }); } } } }); }
String businessCardUrl = "{file_source_url}";
public void beginRecognizeBusinessCardsFromUrl() { String businessCardUrl = "{business_card_url}"; formRecognizerAsyncClient.beginRecognizeBusinessCardsFromUrl(businessCardUrl) .flatMap(AsyncPollResponse::getFinalResult) .subscribe(recognizedBusinessCards -> { for (int i = 0; i < recognizedBusinessCards.size(); i++) { RecognizedForm recognizedForm = recognizedBusinessCards.get(i); Map<String, FormField> recognizedFields = recognizedForm.getFields(); System.out.printf("----------- Recognized Business Card page %d -----------%n", i); FormField contactNamesFormField = recognizedFields.get("ContactNames"); if (contactNamesFormField != null) { if (FieldValueType.LIST == contactNamesFormField.getValue().getValueType()) { List<FormField> contactNamesList = contactNamesFormField.getValue().asList(); contactNamesList.stream() .filter(contactName -> FieldValueType.MAP == contactName.getValue().getValueType()) .map(contactName -> { System.out.printf("Contact name: %s%n", contactName.getValueData().getText()); return contactName.getValue().asMap(); }) .forEach(contactNamesMap -> contactNamesMap.forEach((key, contactName) -> { if ("FirstName".equals(key)) { if (FieldValueType.STRING == contactName.getValue().getValueType()) { String firstName = contactName.getValue().asString(); System.out.printf("\tFirst Name: %s, confidence: %.2f%n", firstName, contactName.getConfidence()); } } if ("LastName".equals(key)) { if (FieldValueType.STRING == contactName.getValue().getValueType()) { String lastName = contactName.getValue().asString(); System.out.printf("\tLast Name: %s, confidence: %.2f%n", lastName, contactName.getConfidence()); } } })); } } FormField jobTitles = recognizedFields.get("JobTitles"); if (jobTitles != null) { if (FieldValueType.LIST == jobTitles.getValue().getValueType()) { List<FormField> jobTitlesItems = jobTitles.getValue().asList(); jobTitlesItems.stream().forEach(jobTitlesItem -> { if (FieldValueType.STRING == jobTitlesItem.getValue().getValueType()) { String jobTitle = jobTitlesItem.getValue().asString(); System.out.printf("Job Title: %s, confidence: %.2f%n", jobTitle, jobTitlesItem.getConfidence()); } }); } } } }); }
class FormRecognizerAsyncClientJavaDocCodeSnippets { FormRecognizerAsyncClient formRecognizerAsyncClient = new FormRecognizerClientBuilder().buildAsyncClient(); /** * Code snippet for creating a {@link FormRecognizerAsyncClient} */ public void createFormRecognizerAsyncClient() { FormRecognizerAsyncClient formRecognizerAsyncClient = new FormRecognizerClientBuilder() .credential(new AzureKeyCredential("{key}")) .endpoint("{endpoint}") .buildAsyncClient(); } /** * Code snippet for creating a {@link FormRecognizerAsyncClient} with pipeline */ public void createFormRecognizerAsyncClientWithPipeline() { HttpPipeline pipeline = new HttpPipelineBuilder() .policies(/* add policies */) .build(); FormRecognizerAsyncClient formRecognizerAsyncClient = new FormRecognizerClientBuilder() .credential(new AzureKeyCredential("{key}")) .endpoint("{endpoint}") .pipeline(pipeline) .buildAsyncClient(); } /** * Code snippet for {@link FormRecognizerAsyncClient */ public void beginRecognizeCustomFormsFromUrl() { String formUrl = "{form_url}"; String modelId = "{custom_trained_model_id}"; formRecognizerAsyncClient.beginRecognizeCustomFormsFromUrl(modelId, formUrl) .flatMap(AsyncPollResponse::getFinalResult) .flatMap(Flux::fromIterable) .subscribe(recognizedForm -> recognizedForm.getFields() .forEach((fieldText, formField) -> { System.out.printf("Field text: %s%n", fieldText); System.out.printf("Field value data text: %s%n", formField.getValueData().getText()); System.out.printf("Confidence score: %.2f%n", formField.getConfidence()); })); } /** * Code snippet for * {@link FormRecognizerAsyncClient */ public void beginRecognizeCustomFormsFromUrlWithOptions() { String formUrl = "{formUrl}"; String modelId = "{model_id}"; boolean includeFieldElements = true; formRecognizerAsyncClient.beginRecognizeCustomFormsFromUrl(modelId, formUrl, new RecognizeCustomFormsOptions() .setFieldElementsIncluded(includeFieldElements) .setPollInterval(Duration.ofSeconds(10))) .flatMap(AsyncPollResponse::getFinalResult) .flatMap(Flux::fromIterable) .subscribe(recognizedForm -> recognizedForm.getFields() .forEach((fieldText, formField) -> { System.out.printf("Field text: %s%n", fieldText); System.out.printf("Field value data text: %s%n", formField.getValueData().getText()); System.out.printf("Confidence score: %.2f%n", formField.getConfidence()); })); } /** * Code snippet for {@link FormRecognizerAsyncClient * * @throws IOException Exception thrown when there is an error in reading all the bytes from the File. */ public void beginRecognizeCustomForms() throws IOException { File form = new File("{local/file_path/fileName.jpg}"); String modelId = "{custom_trained_model_id}"; Flux<ByteBuffer> buffer = toFluxByteBuffer(new ByteArrayInputStream(Files.readAllBytes(form.toPath()))); formRecognizerAsyncClient.beginRecognizeCustomForms(modelId, buffer, form.length()) .flatMap(AsyncPollResponse::getFinalResult) .flatMap(Flux::fromIterable) .subscribe(recognizedForm -> recognizedForm.getFields() .forEach((fieldText, formField) -> { System.out.printf("Field text: %s%n", fieldText); System.out.printf("Field value data text: %s%n", formField.getValueData().getText()); System.out.printf("Confidence score: %.2f%n", formField.getConfidence()); })); } /** * Code snippet for * {@link FormRecognizerAsyncClient * with options * * @throws IOException Exception thrown when there is an error in reading all the bytes from the File. */ public void beginRecognizeCustomFormsWithOptions() throws IOException { File form = new File("{local/file_path/fileName.jpg}"); String modelId = "{custom_trained_model_id}"; boolean includeFieldElements = true; Flux<ByteBuffer> buffer = toFluxByteBuffer(new ByteArrayInputStream(Files.readAllBytes(form.toPath()))); formRecognizerAsyncClient.beginRecognizeCustomForms(modelId, buffer, form.length(), new RecognizeCustomFormsOptions() .setContentType(FormContentType.IMAGE_JPEG) .setFieldElementsIncluded(includeFieldElements) .setPollInterval(Duration.ofSeconds(5))) .flatMap(AsyncPollResponse::getFinalResult) .flatMap(Flux::fromIterable) .subscribe(recognizedForm -> recognizedForm.getFields() .forEach((fieldName, formField) -> { System.out.printf("Field text: %s%n", fieldName); System.out.printf("Field value data text: %s%n", formField.getValueData().getText()); System.out.printf("Confidence score: %.2f%n", formField.getConfidence()); })); } /** * Code snippet for {@link FormRecognizerAsyncClient */ public void beginRecognizeContentFromUrl() { String formUrl = "{formUrl}"; formRecognizerAsyncClient.beginRecognizeContentFromUrl(formUrl) .flatMap(AsyncPollResponse::getFinalResult) .flatMap(Flux::fromIterable) .subscribe(formPage -> { System.out.printf("Page Angle: %s%n", formPage.getTextAngle()); System.out.printf("Page Dimension unit: %s%n", formPage.getUnit()); System.out.println("Recognized Tables: "); formPage.getTables().forEach(formTable -> formTable.getCells().forEach(recognizedTableCell -> System.out.printf("%s ", recognizedTableCell.getText()))); }); } /** * Code snippet for {@link FormRecognizerAsyncClient * options */ public void beginRecognizeContentFromUrlWithOptions() { String formUrl = "{formUrl}"; formRecognizerAsyncClient.beginRecognizeContentFromUrl(formUrl, new RecognizeContentOptions().setPollInterval(Duration.ofSeconds(5))) .flatMap(AsyncPollResponse::getFinalResult) .flatMap(Flux::fromIterable) .subscribe(formPage -> { System.out.printf("Page Angle: %s%n", formPage.getTextAngle()); System.out.printf("Page Dimension unit: %s%n", formPage.getUnit()); System.out.println("Recognized Tables: "); formPage.getTables().forEach(formTable -> formTable.getCells().forEach(recognizedTableCell -> System.out.printf("%s ", recognizedTableCell.getText()))); }); } /** * Code snippet for {@link FormRecognizerAsyncClient * * @throws IOException Exception thrown when there is an error in reading all the bytes from the File. */ public void beginRecognizeContent() throws IOException { File form = new File("{local/file_path/fileName.jpg}"); Flux<ByteBuffer> buffer = toFluxByteBuffer(new ByteArrayInputStream(Files.readAllBytes(form.toPath()))); formRecognizerAsyncClient.beginRecognizeContent(buffer, form.length()) .flatMap(AsyncPollResponse::getFinalResult) .flatMap(Flux::fromIterable) .subscribe(formPage -> { System.out.printf("Page Angle: %s%n", formPage.getTextAngle()); System.out.printf("Page Dimension unit: %s%n", formPage.getUnit()); System.out.println("Recognized Tables: "); formPage.getTables().forEach(formTable -> formTable.getCells().forEach(recognizedTableCell -> System.out.printf("%s ", recognizedTableCell.getText()))); }); } /** * Code snippet for {@link FormRecognizerAsyncClient * options * * @throws IOException Exception thrown when there is an error in reading all the bytes from the File. */ public void beginRecognizeContentWithOptions() throws IOException { File form = new File("{local/file_path/fileName.jpg}"); Flux<ByteBuffer> buffer = toFluxByteBuffer(new ByteArrayInputStream(Files.readAllBytes(form.toPath()))); formRecognizerAsyncClient.beginRecognizeContent(buffer, form.length(), new RecognizeContentOptions() .setContentType(FormContentType.APPLICATION_PDF) .setPollInterval(Duration.ofSeconds(5))) .flatMap(AsyncPollResponse::getFinalResult) .flatMap(Flux::fromIterable) .subscribe(formPage -> { System.out.printf("Page Angle: %s%n", formPage.getTextAngle()); System.out.printf("Page Dimension unit: %s%n", formPage.getUnit()); System.out.println("Recognized Tables: "); formPage.getTables().forEach(formTable -> formTable.getCells().forEach(recognizedTableCell -> System.out.printf("%s ", recognizedTableCell.getText()))); }); } /** * Code snippet for {@link FormRecognizerAsyncClient */ public void beginRecognizeReceiptsFromUrl() { String receiptUrl = "{receiptUrl}"; formRecognizerAsyncClient.beginRecognizeReceiptsFromUrl(receiptUrl) .flatMap(AsyncPollResponse::getFinalResult) .subscribe(recognizedReceipts -> { for (int i = 0; i < recognizedReceipts.size(); i++) { RecognizedForm recognizedForm = recognizedReceipts.get(i); Map<String, FormField> recognizedFields = recognizedForm.getFields(); System.out.printf("----------- Recognized Receipt page %d -----------%n", i); FormField merchantNameField = recognizedFields.get("MerchantName"); if (merchantNameField != null) { if (FieldValueType.STRING == merchantNameField.getValue().getValueType()) { String merchantName = merchantNameField.getValue().asString(); System.out.printf("Merchant Name: %s, confidence: %.2f%n", merchantName, merchantNameField.getConfidence()); } } FormField merchantPhoneNumberField = recognizedFields.get("MerchantPhoneNumber"); if (merchantPhoneNumberField != null) { if (FieldValueType.PHONE_NUMBER == merchantPhoneNumberField.getValue().getValueType()) { String merchantAddress = merchantPhoneNumberField.getValue().asPhoneNumber(); System.out.printf("Merchant Phone number: %s, confidence: %.2f%n", merchantAddress, merchantPhoneNumberField.getConfidence()); } } FormField transactionDateField = recognizedFields.get("TransactionDate"); if (transactionDateField != null) { if (FieldValueType.DATE == transactionDateField.getValue().getValueType()) { LocalDate transactionDate = transactionDateField.getValue().asDate(); System.out.printf("Transaction Date: %s, confidence: %.2f%n", transactionDate, transactionDateField.getConfidence()); } } FormField receiptItemsField = recognizedFields.get("Items"); if (receiptItemsField != null) { System.out.printf("Receipt Items: %n"); if (FieldValueType.LIST == receiptItemsField.getValue().getValueType()) { List<FormField> receiptItems = receiptItemsField.getValue().asList(); receiptItems.stream() .filter(receiptItem -> FieldValueType.MAP == receiptItem.getValue().getValueType()) .map(formField -> formField.getValue().asMap()) .forEach(formFieldMap -> formFieldMap.forEach((key, formField) -> { if ("Quantity".equals(key)) { if (FieldValueType.FLOAT == formField.getValue().getValueType()) { Float quantity = formField.getValue().asFloat(); System.out.printf("Quantity: %f, confidence: %.2f%n", quantity, formField.getConfidence()); } } })); } } } }); } /** * Code snippet for {@link FormRecognizerAsyncClient */ public void beginRecognizeReceiptsFromUrlWithOptions() { String receiptUrl = "{receiptUrl}"; boolean includeFieldElements = true; formRecognizerAsyncClient.beginRecognizeReceiptsFromUrl(receiptUrl, new RecognizeReceiptsOptions() .setFieldElementsIncluded(includeFieldElements) .setPollInterval(Duration.ofSeconds(5))) .flatMap(AsyncPollResponse::getFinalResult) .subscribe(recognizedReceipts -> { for (int i = 0; i < recognizedReceipts.size(); i++) { RecognizedForm recognizedReceipt = recognizedReceipts.get(i); Map<String, FormField> recognizedFields = recognizedReceipt.getFields(); System.out.printf("----------- Recognized Receipt page %d -----------%n", i); FormField merchantNameField = recognizedFields.get("MerchantName"); if (merchantNameField != null) { if (FieldValueType.STRING == merchantNameField.getValue().getValueType()) { String merchantName = merchantNameField.getValue().asString(); System.out.printf("Merchant Name: %s, confidence: %.2f%n", merchantName, merchantNameField.getConfidence()); } } FormField merchantPhoneNumberField = recognizedFields.get("MerchantPhoneNumber"); if (merchantPhoneNumberField != null) { if (FieldValueType.PHONE_NUMBER == merchantPhoneNumberField.getValue().getValueType()) { String merchantAddress = merchantPhoneNumberField.getValue().asPhoneNumber(); System.out.printf("Merchant Phone number: %s, confidence: %.2f%n", merchantAddress, merchantPhoneNumberField.getConfidence()); } } FormField transactionDateField = recognizedFields.get("TransactionDate"); if (transactionDateField != null) { if (FieldValueType.DATE == transactionDateField.getValue().getValueType()) { LocalDate transactionDate = transactionDateField.getValue().asDate(); System.out.printf("Transaction Date: %s, confidence: %.2f%n", transactionDate, transactionDateField.getConfidence()); } } FormField receiptItemsField = recognizedFields.get("Items"); if (receiptItemsField != null) { System.out.printf("Receipt Items: %n"); if (FieldValueType.LIST == receiptItemsField.getValue().getValueType()) { List<FormField> receiptItems = receiptItemsField.getValue().asList(); receiptItems.stream() .filter(receiptItem -> FieldValueType.MAP == receiptItem.getValue().getValueType()) .map(formField -> formField.getValue().asMap()) .forEach(formFieldMap -> formFieldMap.forEach((key, formField) -> { if ("Quantity".equals(key)) { if (FieldValueType.FLOAT == formField.getValue().getValueType()) { Float quantity = formField.getValue().asFloat(); System.out.printf("Quantity: %f, confidence: %.2f%n", quantity, formField.getConfidence()); } } })); } } } }); } /** * Code snippet for {@link FormRecognizerAsyncClient * * @throws IOException Exception thrown when there is an error in reading all the bytes from the File. */ public void beginRecognizeReceipts() throws IOException { File receipt = new File("{file_source_url}"); Flux<ByteBuffer> buffer = toFluxByteBuffer(new ByteArrayInputStream(Files.readAllBytes(receipt.toPath()))); formRecognizerAsyncClient.beginRecognizeReceipts(buffer, receipt.length()) .flatMap(AsyncPollResponse::getFinalResult) .subscribe(recognizedReceipts -> { for (int i = 0; i < recognizedReceipts.size(); i++) { RecognizedForm recognizedForm = recognizedReceipts.get(i); Map<String, FormField> recognizedFields = recognizedForm.getFields(); System.out.printf("----------- Recognized Receipt page %d -----------%n", i); FormField merchantNameField = recognizedFields.get("MerchantName"); if (merchantNameField != null) { if (FieldValueType.STRING == merchantNameField.getValue().getValueType()) { String merchantName = merchantNameField.getValue().asString(); System.out.printf("Merchant Name: %s, confidence: %.2f%n", merchantName, merchantNameField.getConfidence()); } } FormField merchantPhoneNumberField = recognizedFields.get("MerchantPhoneNumber"); if (merchantPhoneNumberField != null) { if (FieldValueType.PHONE_NUMBER == merchantPhoneNumberField.getValue().getValueType()) { String merchantAddress = merchantPhoneNumberField.getValue().asPhoneNumber(); System.out.printf("Merchant Phone number: %s, confidence: %.2f%n", merchantAddress, merchantPhoneNumberField.getConfidence()); } } FormField transactionDateField = recognizedFields.get("TransactionDate"); if (transactionDateField != null) { if (FieldValueType.DATE == transactionDateField.getValue().getValueType()) { LocalDate transactionDate = transactionDateField.getValue().asDate(); System.out.printf("Transaction Date: %s, confidence: %.2f%n", transactionDate, transactionDateField.getConfidence()); } } FormField receiptItemsField = recognizedFields.get("Items"); if (receiptItemsField != null) { System.out.printf("Receipt Items: %n"); if (FieldValueType.LIST == receiptItemsField.getValue().getValueType()) { List<FormField> receiptItems = receiptItemsField.getValue().asList(); receiptItems.stream() .filter(receiptItem -> FieldValueType.MAP == receiptItem.getValue().getValueType()) .map(formField -> formField.getValue().asMap()) .forEach(formFieldMap -> formFieldMap.forEach((key, formField) -> { if ("Quantity".equals(key)) { if (FieldValueType.FLOAT == formField.getValue().getValueType()) { Float quantity = formField.getValue().asFloat(); System.out.printf("Quantity: %f, confidence: %.2f%n", quantity, formField.getConfidence()); } } })); } } } }); } /** * Code snippet for {@link FormRecognizerAsyncClient * options * * @throws IOException Exception thrown when there is an error in reading all the bytes from the File. */ public void beginRecognizeReceiptsWithOptions() throws IOException { File receipt = new File("{local/file_path/fileName.jpg}"); boolean includeFieldElements = true; Flux<ByteBuffer> buffer = toFluxByteBuffer(new ByteArrayInputStream(Files.readAllBytes(receipt.toPath()))); formRecognizerAsyncClient.beginRecognizeReceipts(buffer, receipt.length(), new RecognizeReceiptsOptions() .setContentType(FormContentType.IMAGE_JPEG) .setFieldElementsIncluded(includeFieldElements) .setPollInterval(Duration.ofSeconds(5))) .flatMap(AsyncPollResponse::getFinalResult) .subscribe(recognizedReceipts -> { for (int i = 0; i < recognizedReceipts.size(); i++) { RecognizedForm recognizedForm = recognizedReceipts.get(i); Map<String, FormField> recognizedFields = recognizedForm.getFields(); System.out.printf("----------- Recognized Receipt page %d -----------%n", i); FormField merchantNameField = recognizedFields.get("MerchantName"); if (merchantNameField != null) { if (FieldValueType.STRING == merchantNameField.getValue().getValueType()) { String merchantName = merchantNameField.getValue().asString(); System.out.printf("Merchant Name: %s, confidence: %.2f%n", merchantName, merchantNameField.getConfidence()); } } FormField merchantPhoneNumberField = recognizedFields.get("MerchantPhoneNumber"); if (merchantPhoneNumberField != null) { if (FieldValueType.PHONE_NUMBER == merchantPhoneNumberField.getValue().getValueType()) { String merchantAddress = merchantPhoneNumberField.getValue().asPhoneNumber(); System.out.printf("Merchant Phone number: %s, confidence: %.2f%n", merchantAddress, merchantPhoneNumberField.getConfidence()); } } FormField transactionDateField = recognizedFields.get("TransactionDate"); if (transactionDateField != null) { if (FieldValueType.DATE == transactionDateField.getValue().getValueType()) { LocalDate transactionDate = transactionDateField.getValue().asDate(); System.out.printf("Transaction Date: %s, confidence: %.2f%n", transactionDate, transactionDateField.getConfidence()); } } FormField receiptItemsField = recognizedFields.get("Items"); if (receiptItemsField != null) { System.out.printf("Receipt Items: %n"); if (FieldValueType.LIST == receiptItemsField.getValue().getValueType()) { List<FormField> receiptItems = receiptItemsField.getValue().asList(); receiptItems.stream() .filter(receiptItem -> FieldValueType.MAP == receiptItem.getValue().getValueType()) .map(formField -> formField.getValue().asMap()) .forEach(formFieldMap -> formFieldMap.forEach((key, formField) -> { if ("Quantity".equals(key)) { if (FieldValueType.FLOAT == formField.getValue().getValueType()) { Float quantity = formField.getValue().asFloat(); System.out.printf("Quantity: %f, confidence: %.2f%n", quantity, formField.getConfidence()); } } })); } } } }); } /** * Code snippet for {@link FormRecognizerAsyncClient */ /** * Code snippet for * {@link FormRecognizerAsyncClient */ public void beginRecognizeBusinessCardsFromUrlWithOptions() { String businessCardUrl = "{file_source_url}"; boolean includeFieldElements = true; formRecognizerAsyncClient.beginRecognizeBusinessCardsFromUrl(businessCardUrl, new RecognizeBusinessCardsOptions() .setFieldElementsIncluded(includeFieldElements) .setPollInterval(Duration.ofSeconds(5))) .flatMap(AsyncPollResponse::getFinalResult) .subscribe(recognizedBusinessCards -> { for (int i = 0; i < recognizedBusinessCards.size(); i++) { RecognizedForm recognizedBusinessCard = recognizedBusinessCards.get(i); Map<String, FormField> recognizedFields = recognizedBusinessCard.getFields(); System.out.printf("----------- Recognized Business Card page %d -----------%n", i); FormField contactNames = recognizedFields.get("ContactNames"); if (contactNames != null) { if (FieldValueType.LIST == contactNames.getValue().getValueType()) { List<FormField> businessCardItems = contactNames.getValue().asList(); businessCardItems.stream() .filter(businessCardItem -> FieldValueType.MAP == businessCardItem.getValue() .getValueType()) .map(formField -> formField.getValue().asMap()) .forEach(formFieldMap -> formFieldMap.forEach((key, formField) -> { if ("FirstName".equals(key)) { if (FieldValueType.STRING == formField.getValue().getValueType()) { String firstName = formField.getValue().asString(); System.out.printf("First Name: %s, confidence: %.2f%n", firstName, contactNames.getConfidence()); } } if ("LastName".equals(key)) { if (FieldValueType.STRING == formField.getValue().getValueType()) { String lastName = formField.getValue().asString(); System.out.printf("Last Name: %s, confidence: %.2f%n", lastName, contactNames.getConfidence()); } } })); } } FormField jobTitles = recognizedFields.get("JobTitles"); if (jobTitles != null) { if (FieldValueType.LIST == jobTitles.getValue().getValueType()) { List<FormField> jobTitlesItems = jobTitles.getValue().asList(); jobTitlesItems.stream().forEach(formField -> { if (FieldValueType.STRING == formField.getValue().getValueType()) { String jobTitle = formField.getValue().asString(); System.out.printf("Job Title: %s, confidence: %.2f%n", jobTitle, jobTitles.getConfidence()); } }); } } FormField addresses = recognizedFields.get("Addresses"); if (addresses != null) { if (FieldValueType.LIST == addresses.getValue().getValueType()) { List<FormField> addressesItems = addresses.getValue().asList(); addressesItems.stream().forEach(formField -> { if (FieldValueType.STRING == formField.getValue().getValueType()) { String address = formField.getValue().asString(); System.out.printf("Address: %s, confidence: %.2f%n", address, addresses.getConfidence()); } }); } } FormField companyName = recognizedFields.get("CompanyNames"); if (companyName != null) { if (FieldValueType.LIST == companyName.getValue().getValueType()) { List<FormField> companyNameItems = companyName.getValue().asList(); companyNameItems.stream().forEach(formField -> { if (FieldValueType.STRING == formField.getValue().getValueType()) { String companyNameValue = formField.getValue().asString(); System.out.printf("Company name: %s, confidence: %.2f%n", companyNameValue, companyName.getConfidence()); } }); } } } }); } /** * Code snippet for {@link FormRecognizerAsyncClient * * @throws IOException Exception thrown when there is an error in reading all the bytes from the File. */ public void beginRecognizeBusinessCards() throws IOException { File businessCard = new File("{file_source_url}"); Flux<ByteBuffer> buffer = toFluxByteBuffer(new ByteArrayInputStream(Files.readAllBytes(businessCard.toPath()))); formRecognizerAsyncClient.beginRecognizeBusinessCards(buffer, businessCard.length()) .flatMap(AsyncPollResponse::getFinalResult) .subscribe(recognizedBusinessCards -> { for (int i = 0; i < recognizedBusinessCards.size(); i++) { RecognizedForm recognizedForm = recognizedBusinessCards.get(i); Map<String, FormField> recognizedFields = recognizedForm.getFields(); System.out.printf("----------- Recognized Business Card page %d -----------%n", i); FormField contactNames = recognizedFields.get("ContactNames"); if (contactNames != null) { if (FieldValueType.LIST == contactNames.getValue().getValueType()) { List<FormField> businessCardItems = contactNames.getValue().asList(); businessCardItems.stream() .filter(businessCardItem -> FieldValueType.MAP == businessCardItem.getValue() .getValueType()) .map(formField -> formField.getValue().asMap()) .forEach(formFieldMap -> formFieldMap.forEach((key, formField) -> { if ("FirstName".equals(key)) { if (FieldValueType.STRING == formField.getValue().getValueType()) { String firstName = formField.getValue().asString(); System.out.printf("First Name: %s, confidence: %.2f%n", firstName, contactNames.getConfidence()); } } if ("LastName".equals(key)) { if (FieldValueType.STRING == formField.getValue().getValueType()) { String lastName = formField.getValue().asString(); System.out.printf("Last Name: %s, confidence: %.2f%n", lastName, contactNames.getConfidence()); } } })); } } FormField jobTitles = recognizedFields.get("JobTitles"); if (jobTitles != null) { if (FieldValueType.LIST == jobTitles.getValue().getValueType()) { List<FormField> jobTitlesItems = jobTitles.getValue().asList(); jobTitlesItems.stream().forEach(formField -> { if (FieldValueType.STRING == formField.getValue().getValueType()) { String jobTitle = formField.getValue().asString(); System.out.printf("Job Title: %s, confidence: %.2f%n", jobTitle, jobTitles.getConfidence()); } }); } } FormField addresses = recognizedFields.get("Addresses"); if (addresses != null) { if (FieldValueType.LIST == addresses.getValue().getValueType()) { List<FormField> addressesItems = addresses.getValue().asList(); addressesItems.stream().forEach(formField -> { if (FieldValueType.STRING == formField.getValue().getValueType()) { String address = formField.getValue().asString(); System.out.printf("Address: %s, confidence: %.2f%n", address, addresses.getConfidence()); } }); } } FormField companyName = recognizedFields.get("CompanyNames"); if (companyName != null) { if (FieldValueType.LIST == companyName.getValue().getValueType()) { List<FormField> companyNameItems = companyName.getValue().asList(); companyNameItems.stream().forEach(formField -> { if (FieldValueType.STRING == formField.getValue().getValueType()) { String companyNameValue = formField.getValue().asString(); System.out.printf("Company name: %s, confidence: %.2f%n", companyNameValue, companyName.getConfidence()); } }); } } } }); } /** * Code snippet for * {@link FormRecognizerAsyncClient * options * * @throws IOException Exception thrown when there is an error in reading all the bytes from the File. */ public void beginRecognizeBusinessCardsWithOptions() throws IOException { File businessCard = new File("{local/file_path/fileName.jpg}"); boolean includeFieldElements = true; Flux<ByteBuffer> buffer = toFluxByteBuffer(new ByteArrayInputStream(Files.readAllBytes(businessCard.toPath()))); formRecognizerAsyncClient.beginRecognizeBusinessCards(buffer, businessCard.length(), new RecognizeBusinessCardsOptions() .setContentType(FormContentType.IMAGE_JPEG) .setFieldElementsIncluded(includeFieldElements) .setPollInterval(Duration.ofSeconds(5))) .flatMap(AsyncPollResponse::getFinalResult) .subscribe(recognizedBusinessCards -> { for (int i = 0; i < recognizedBusinessCards.size(); i++) { RecognizedForm recognizedForm = recognizedBusinessCards.get(i); Map<String, FormField> recognizedFields = recognizedForm.getFields(); System.out.printf("----------- Recognized Business Card page %d -----------%n", i); FormField contactNames = recognizedFields.get("ContactNames"); if (contactNames != null) { if (FieldValueType.LIST == contactNames.getValue().getValueType()) { List<FormField> businessCardItems = contactNames.getValue().asList(); businessCardItems.stream() .filter(businessCardItem -> FieldValueType.MAP == businessCardItem.getValue() .getValueType()) .map(formField -> formField.getValue().asMap()) .forEach(formFieldMap -> formFieldMap.forEach((key, formField) -> { if ("FirstName".equals(key)) { if (FieldValueType.STRING == formField.getValue().getValueType()) { String firstName = formField.getValue().asString(); System.out.printf("First Name: %s, confidence: %.2f%n", firstName, contactNames.getConfidence()); } } if ("LastName".equals(key)) { if (FieldValueType.STRING == formField.getValue().getValueType()) { String lastName = formField.getValue().asString(); System.out.printf("Last Name: %s, confidence: %.2f%n", lastName, contactNames.getConfidence()); } } })); } } FormField jobTitles = recognizedFields.get("JobTitles"); if (jobTitles != null) { if (FieldValueType.LIST == jobTitles.getValue().getValueType()) { List<FormField> jobTitlesItems = jobTitles.getValue().asList(); jobTitlesItems.stream().forEach(formField -> { if (FieldValueType.STRING == formField.getValue().getValueType()) { String jobTitle = formField.getValue().asString(); System.out.printf("Job Title: %s, confidence: %.2f%n", jobTitle, jobTitles.getConfidence()); } }); } } FormField addresses = recognizedFields.get("Addresses"); if (addresses != null) { if (FieldValueType.LIST == addresses.getValue().getValueType()) { List<FormField> addressesItems = addresses.getValue().asList(); addressesItems.stream().forEach(formField -> { if (FieldValueType.STRING == formField.getValue().getValueType()) { String address = formField.getValue().asString(); System.out.printf("Address: %s, confidence: %.2f%n", address, addresses.getConfidence()); } }); } } FormField companyName = recognizedFields.get("CompanyNames"); if (companyName != null) { if (FieldValueType.LIST == companyName.getValue().getValueType()) { List<FormField> companyNameItems = companyName.getValue().asList(); companyNameItems.stream().forEach(formField -> { if (FieldValueType.STRING == formField.getValue().getValueType()) { String companyNameValue = formField.getValue().asString(); System.out.printf("Company name: %s, confidence: %.2f%n", companyNameValue, companyName.getConfidence()); } }); } } } }); } }
class FormRecognizerAsyncClientJavaDocCodeSnippets { FormRecognizerAsyncClient formRecognizerAsyncClient = new FormRecognizerClientBuilder().buildAsyncClient(); /** * Code snippet for creating a {@link FormRecognizerAsyncClient} */ public void createFormRecognizerAsyncClient() { FormRecognizerAsyncClient formRecognizerAsyncClient = new FormRecognizerClientBuilder() .credential(new AzureKeyCredential("{key}")) .endpoint("{endpoint}") .buildAsyncClient(); } /** * Code snippet for creating a {@link FormRecognizerAsyncClient} with pipeline */ public void createFormRecognizerAsyncClientWithPipeline() { HttpPipeline pipeline = new HttpPipelineBuilder() .policies(/* add policies */) .build(); FormRecognizerAsyncClient formRecognizerAsyncClient = new FormRecognizerClientBuilder() .credential(new AzureKeyCredential("{key}")) .endpoint("{endpoint}") .pipeline(pipeline) .buildAsyncClient(); } /** * Code snippet for {@link FormRecognizerAsyncClient */ public void beginRecognizeCustomFormsFromUrl() { String formUrl = "{form_url}"; String modelId = "{custom_trained_model_id}"; formRecognizerAsyncClient.beginRecognizeCustomFormsFromUrl(modelId, formUrl) .flatMap(AsyncPollResponse::getFinalResult) .flatMap(Flux::fromIterable) .subscribe(recognizedForm -> recognizedForm.getFields() .forEach((fieldText, formField) -> { System.out.printf("Field text: %s%n", fieldText); System.out.printf("Field value data text: %s%n", formField.getValueData().getText()); System.out.printf("Confidence score: %.2f%n", formField.getConfidence()); })); } /** * Code snippet for * {@link FormRecognizerAsyncClient */ public void beginRecognizeCustomFormsFromUrlWithOptions() { String formUrl = "{formUrl}"; String modelId = "{model_id}"; boolean includeFieldElements = true; formRecognizerAsyncClient.beginRecognizeCustomFormsFromUrl(modelId, formUrl, new RecognizeCustomFormsOptions() .setFieldElementsIncluded(includeFieldElements) .setPollInterval(Duration.ofSeconds(10))) .flatMap(AsyncPollResponse::getFinalResult) .flatMap(Flux::fromIterable) .subscribe(recognizedForm -> recognizedForm.getFields() .forEach((fieldText, formField) -> { System.out.printf("Field text: %s%n", fieldText); System.out.printf("Field value data text: %s%n", formField.getValueData().getText()); System.out.printf("Confidence score: %.2f%n", formField.getConfidence()); })); } /** * Code snippet for {@link FormRecognizerAsyncClient * * @throws IOException Exception thrown when there is an error in reading all the bytes from the File. */ public void beginRecognizeCustomForms() throws IOException { File form = new File("{local/file_path/fileName.jpg}"); String modelId = "{custom_trained_model_id}"; Flux<ByteBuffer> buffer = toFluxByteBuffer(new ByteArrayInputStream(Files.readAllBytes(form.toPath()))); formRecognizerAsyncClient.beginRecognizeCustomForms(modelId, buffer, form.length()) .flatMap(AsyncPollResponse::getFinalResult) .flatMap(Flux::fromIterable) .subscribe(recognizedForm -> recognizedForm.getFields() .forEach((fieldText, formField) -> { System.out.printf("Field text: %s%n", fieldText); System.out.printf("Field value data text: %s%n", formField.getValueData().getText()); System.out.printf("Confidence score: %.2f%n", formField.getConfidence()); })); } /** * Code snippet for * {@link FormRecognizerAsyncClient * with options * * @throws IOException Exception thrown when there is an error in reading all the bytes from the File. */ public void beginRecognizeCustomFormsWithOptions() throws IOException { File form = new File("{local/file_path/fileName.jpg}"); String modelId = "{custom_trained_model_id}"; boolean includeFieldElements = true; Flux<ByteBuffer> buffer = toFluxByteBuffer(new ByteArrayInputStream(Files.readAllBytes(form.toPath()))); formRecognizerAsyncClient.beginRecognizeCustomForms(modelId, buffer, form.length(), new RecognizeCustomFormsOptions() .setContentType(FormContentType.IMAGE_JPEG) .setFieldElementsIncluded(includeFieldElements) .setPollInterval(Duration.ofSeconds(5))) .flatMap(AsyncPollResponse::getFinalResult) .flatMap(Flux::fromIterable) .subscribe(recognizedForm -> recognizedForm.getFields() .forEach((fieldName, formField) -> { System.out.printf("Field text: %s%n", fieldName); System.out.printf("Field value data text: %s%n", formField.getValueData().getText()); System.out.printf("Confidence score: %.2f%n", formField.getConfidence()); })); } /** * Code snippet for {@link FormRecognizerAsyncClient */ public void beginRecognizeContentFromUrl() { String formUrl = "{formUrl}"; formRecognizerAsyncClient.beginRecognizeContentFromUrl(formUrl) .flatMap(AsyncPollResponse::getFinalResult) .flatMap(Flux::fromIterable) .subscribe(formPage -> { System.out.printf("Page Angle: %s%n", formPage.getTextAngle()); System.out.printf("Page Dimension unit: %s%n", formPage.getUnit()); System.out.println("Recognized Tables: "); formPage.getTables().forEach(formTable -> formTable.getCells().forEach(recognizedTableCell -> System.out.printf("%s ", recognizedTableCell.getText()))); }); } /** * Code snippet for {@link FormRecognizerAsyncClient * options */ public void beginRecognizeContentFromUrlWithOptions() { String formUrl = "{formUrl}"; formRecognizerAsyncClient.beginRecognizeContentFromUrl(formUrl, new RecognizeContentOptions().setPollInterval(Duration.ofSeconds(5))) .flatMap(AsyncPollResponse::getFinalResult) .flatMap(Flux::fromIterable) .subscribe(formPage -> { System.out.printf("Page Angle: %s%n", formPage.getTextAngle()); System.out.printf("Page Dimension unit: %s%n", formPage.getUnit()); System.out.println("Recognized Tables: "); formPage.getTables().forEach(formTable -> formTable.getCells().forEach(recognizedTableCell -> System.out.printf("%s ", recognizedTableCell.getText()))); }); } /** * Code snippet for {@link FormRecognizerAsyncClient * * @throws IOException Exception thrown when there is an error in reading all the bytes from the File. */ public void beginRecognizeContent() throws IOException { File form = new File("{local/file_path/fileName.jpg}"); Flux<ByteBuffer> buffer = toFluxByteBuffer(new ByteArrayInputStream(Files.readAllBytes(form.toPath()))); formRecognizerAsyncClient.beginRecognizeContent(buffer, form.length()) .flatMap(AsyncPollResponse::getFinalResult) .flatMap(Flux::fromIterable) .subscribe(formPage -> { System.out.printf("Page Angle: %s%n", formPage.getTextAngle()); System.out.printf("Page Dimension unit: %s%n", formPage.getUnit()); System.out.println("Recognized Tables: "); formPage.getTables().forEach(formTable -> formTable.getCells().forEach(recognizedTableCell -> System.out.printf("%s ", recognizedTableCell.getText()))); }); } /** * Code snippet for {@link FormRecognizerAsyncClient * options * * @throws IOException Exception thrown when there is an error in reading all the bytes from the File. */ public void beginRecognizeContentWithOptions() throws IOException { File form = new File("{local/file_path/fileName.jpg}"); Flux<ByteBuffer> buffer = toFluxByteBuffer(new ByteArrayInputStream(Files.readAllBytes(form.toPath()))); formRecognizerAsyncClient.beginRecognizeContent(buffer, form.length(), new RecognizeContentOptions() .setContentType(FormContentType.APPLICATION_PDF) .setPollInterval(Duration.ofSeconds(5))) .flatMap(AsyncPollResponse::getFinalResult) .flatMap(Flux::fromIterable) .subscribe(formPage -> { System.out.printf("Page Angle: %s%n", formPage.getTextAngle()); System.out.printf("Page Dimension unit: %s%n", formPage.getUnit()); System.out.println("Recognized Tables: "); formPage.getTables().forEach(formTable -> formTable.getCells().forEach(recognizedTableCell -> System.out.printf("%s ", recognizedTableCell.getText()))); }); } /** * Code snippet for {@link FormRecognizerAsyncClient */ public void beginRecognizeReceiptsFromUrl() { String receiptUrl = "{receiptUrl}"; formRecognizerAsyncClient.beginRecognizeReceiptsFromUrl(receiptUrl) .flatMap(AsyncPollResponse::getFinalResult) .subscribe(recognizedReceipts -> { for (int i = 0; i < recognizedReceipts.size(); i++) { RecognizedForm recognizedForm = recognizedReceipts.get(i); Map<String, FormField> recognizedFields = recognizedForm.getFields(); System.out.printf("----------- Recognized Receipt page %d -----------%n", i); FormField merchantNameField = recognizedFields.get("MerchantName"); if (merchantNameField != null) { if (FieldValueType.STRING == merchantNameField.getValue().getValueType()) { String merchantName = merchantNameField.getValue().asString(); System.out.printf("Merchant Name: %s, confidence: %.2f%n", merchantName, merchantNameField.getConfidence()); } } FormField merchantPhoneNumberField = recognizedFields.get("MerchantPhoneNumber"); if (merchantPhoneNumberField != null) { if (FieldValueType.PHONE_NUMBER == merchantPhoneNumberField.getValue().getValueType()) { String merchantAddress = merchantPhoneNumberField.getValue().asPhoneNumber(); System.out.printf("Merchant Phone number: %s, confidence: %.2f%n", merchantAddress, merchantPhoneNumberField.getConfidence()); } } FormField transactionDateField = recognizedFields.get("TransactionDate"); if (transactionDateField != null) { if (FieldValueType.DATE == transactionDateField.getValue().getValueType()) { LocalDate transactionDate = transactionDateField.getValue().asDate(); System.out.printf("Transaction Date: %s, confidence: %.2f%n", transactionDate, transactionDateField.getConfidence()); } } FormField receiptItemsField = recognizedFields.get("Items"); if (receiptItemsField != null) { System.out.printf("Receipt Items: %n"); if (FieldValueType.LIST == receiptItemsField.getValue().getValueType()) { List<FormField> receiptItems = receiptItemsField.getValue().asList(); receiptItems.stream() .filter(receiptItem -> FieldValueType.MAP == receiptItem.getValue().getValueType()) .map(formField -> formField.getValue().asMap()) .forEach(formFieldMap -> formFieldMap.forEach((key, formField) -> { if ("Quantity".equals(key)) { if (FieldValueType.FLOAT == formField.getValue().getValueType()) { Float quantity = formField.getValue().asFloat(); System.out.printf("Quantity: %f, confidence: %.2f%n", quantity, formField.getConfidence()); } } })); } } } }); } /** * Code snippet for {@link FormRecognizerAsyncClient */ public void beginRecognizeReceiptsFromUrlWithOptions() { String receiptUrl = "{receiptUrl}"; boolean includeFieldElements = true; formRecognizerAsyncClient.beginRecognizeReceiptsFromUrl(receiptUrl, new RecognizeReceiptsOptions() .setFieldElementsIncluded(includeFieldElements) .setPollInterval(Duration.ofSeconds(5))) .flatMap(AsyncPollResponse::getFinalResult) .subscribe(recognizedReceipts -> { for (int i = 0; i < recognizedReceipts.size(); i++) { RecognizedForm recognizedReceipt = recognizedReceipts.get(i); Map<String, FormField> recognizedFields = recognizedReceipt.getFields(); System.out.printf("----------- Recognized Receipt page %d -----------%n", i); FormField merchantNameField = recognizedFields.get("MerchantName"); if (merchantNameField != null) { if (FieldValueType.STRING == merchantNameField.getValue().getValueType()) { String merchantName = merchantNameField.getValue().asString(); System.out.printf("Merchant Name: %s, confidence: %.2f%n", merchantName, merchantNameField.getConfidence()); } } FormField merchantPhoneNumberField = recognizedFields.get("MerchantPhoneNumber"); if (merchantPhoneNumberField != null) { if (FieldValueType.PHONE_NUMBER == merchantPhoneNumberField.getValue().getValueType()) { String merchantAddress = merchantPhoneNumberField.getValue().asPhoneNumber(); System.out.printf("Merchant Phone number: %s, confidence: %.2f%n", merchantAddress, merchantPhoneNumberField.getConfidence()); } } FormField transactionDateField = recognizedFields.get("TransactionDate"); if (transactionDateField != null) { if (FieldValueType.DATE == transactionDateField.getValue().getValueType()) { LocalDate transactionDate = transactionDateField.getValue().asDate(); System.out.printf("Transaction Date: %s, confidence: %.2f%n", transactionDate, transactionDateField.getConfidence()); } } FormField receiptItemsField = recognizedFields.get("Items"); if (receiptItemsField != null) { System.out.printf("Receipt Items: %n"); if (FieldValueType.LIST == receiptItemsField.getValue().getValueType()) { List<FormField> receiptItems = receiptItemsField.getValue().asList(); receiptItems.stream() .filter(receiptItem -> FieldValueType.MAP == receiptItem.getValue().getValueType()) .map(formField -> formField.getValue().asMap()) .forEach(formFieldMap -> formFieldMap.forEach((key, formField) -> { if ("Quantity".equals(key)) { if (FieldValueType.FLOAT == formField.getValue().getValueType()) { Float quantity = formField.getValue().asFloat(); System.out.printf("Quantity: %f, confidence: %.2f%n", quantity, formField.getConfidence()); } } })); } } } }); } /** * Code snippet for {@link FormRecognizerAsyncClient * * @throws IOException Exception thrown when there is an error in reading all the bytes from the File. */ public void beginRecognizeReceipts() throws IOException { File receipt = new File("{file_source_url}"); Flux<ByteBuffer> buffer = toFluxByteBuffer(new ByteArrayInputStream(Files.readAllBytes(receipt.toPath()))); formRecognizerAsyncClient.beginRecognizeReceipts(buffer, receipt.length()) .flatMap(AsyncPollResponse::getFinalResult) .subscribe(recognizedReceipts -> { for (int i = 0; i < recognizedReceipts.size(); i++) { RecognizedForm recognizedForm = recognizedReceipts.get(i); Map<String, FormField> recognizedFields = recognizedForm.getFields(); System.out.printf("----------- Recognized Receipt page %d -----------%n", i); FormField merchantNameField = recognizedFields.get("MerchantName"); if (merchantNameField != null) { if (FieldValueType.STRING == merchantNameField.getValue().getValueType()) { String merchantName = merchantNameField.getValue().asString(); System.out.printf("Merchant Name: %s, confidence: %.2f%n", merchantName, merchantNameField.getConfidence()); } } FormField merchantPhoneNumberField = recognizedFields.get("MerchantPhoneNumber"); if (merchantPhoneNumberField != null) { if (FieldValueType.PHONE_NUMBER == merchantPhoneNumberField.getValue().getValueType()) { String merchantAddress = merchantPhoneNumberField.getValue().asPhoneNumber(); System.out.printf("Merchant Phone number: %s, confidence: %.2f%n", merchantAddress, merchantPhoneNumberField.getConfidence()); } } FormField transactionDateField = recognizedFields.get("TransactionDate"); if (transactionDateField != null) { if (FieldValueType.DATE == transactionDateField.getValue().getValueType()) { LocalDate transactionDate = transactionDateField.getValue().asDate(); System.out.printf("Transaction Date: %s, confidence: %.2f%n", transactionDate, transactionDateField.getConfidence()); } } FormField receiptItemsField = recognizedFields.get("Items"); if (receiptItemsField != null) { System.out.printf("Receipt Items: %n"); if (FieldValueType.LIST == receiptItemsField.getValue().getValueType()) { List<FormField> receiptItems = receiptItemsField.getValue().asList(); receiptItems.stream() .filter(receiptItem -> FieldValueType.MAP == receiptItem.getValue().getValueType()) .map(formField -> formField.getValue().asMap()) .forEach(formFieldMap -> formFieldMap.forEach((key, formField) -> { if ("Quantity".equals(key)) { if (FieldValueType.FLOAT == formField.getValue().getValueType()) { Float quantity = formField.getValue().asFloat(); System.out.printf("Quantity: %f, confidence: %.2f%n", quantity, formField.getConfidence()); } } })); } } } }); } /** * Code snippet for {@link FormRecognizerAsyncClient * options * * @throws IOException Exception thrown when there is an error in reading all the bytes from the File. */ public void beginRecognizeReceiptsWithOptions() throws IOException { File receipt = new File("{local/file_path/fileName.jpg}"); boolean includeFieldElements = true; Flux<ByteBuffer> buffer = toFluxByteBuffer(new ByteArrayInputStream(Files.readAllBytes(receipt.toPath()))); formRecognizerAsyncClient.beginRecognizeReceipts(buffer, receipt.length(), new RecognizeReceiptsOptions() .setContentType(FormContentType.IMAGE_JPEG) .setFieldElementsIncluded(includeFieldElements) .setPollInterval(Duration.ofSeconds(5))) .flatMap(AsyncPollResponse::getFinalResult) .subscribe(recognizedReceipts -> { for (int i = 0; i < recognizedReceipts.size(); i++) { RecognizedForm recognizedForm = recognizedReceipts.get(i); Map<String, FormField> recognizedFields = recognizedForm.getFields(); System.out.printf("----------- Recognized Receipt page %d -----------%n", i); FormField merchantNameField = recognizedFields.get("MerchantName"); if (merchantNameField != null) { if (FieldValueType.STRING == merchantNameField.getValue().getValueType()) { String merchantName = merchantNameField.getValue().asString(); System.out.printf("Merchant Name: %s, confidence: %.2f%n", merchantName, merchantNameField.getConfidence()); } } FormField merchantPhoneNumberField = recognizedFields.get("MerchantPhoneNumber"); if (merchantPhoneNumberField != null) { if (FieldValueType.PHONE_NUMBER == merchantPhoneNumberField.getValue().getValueType()) { String merchantAddress = merchantPhoneNumberField.getValue().asPhoneNumber(); System.out.printf("Merchant Phone number: %s, confidence: %.2f%n", merchantAddress, merchantPhoneNumberField.getConfidence()); } } FormField transactionDateField = recognizedFields.get("TransactionDate"); if (transactionDateField != null) { if (FieldValueType.DATE == transactionDateField.getValue().getValueType()) { LocalDate transactionDate = transactionDateField.getValue().asDate(); System.out.printf("Transaction Date: %s, confidence: %.2f%n", transactionDate, transactionDateField.getConfidence()); } } FormField receiptItemsField = recognizedFields.get("Items"); if (receiptItemsField != null) { System.out.printf("Receipt Items: %n"); if (FieldValueType.LIST == receiptItemsField.getValue().getValueType()) { List<FormField> receiptItems = receiptItemsField.getValue().asList(); receiptItems.stream() .filter(receiptItem -> FieldValueType.MAP == receiptItem.getValue().getValueType()) .map(formField -> formField.getValue().asMap()) .forEach(formFieldMap -> formFieldMap.forEach((key, formField) -> { if ("Quantity".equals(key)) { if (FieldValueType.FLOAT == formField.getValue().getValueType()) { Float quantity = formField.getValue().asFloat(); System.out.printf("Quantity: %f, confidence: %.2f%n", quantity, formField.getConfidence()); } } })); } } } }); } /** * Code snippet for {@link FormRecognizerAsyncClient */ /** * Code snippet for * {@link FormRecognizerAsyncClient */ public void beginRecognizeBusinessCardsFromUrlWithOptions() { String businessCardUrl = "{business_card_url}"; boolean includeFieldElements = true; formRecognizerAsyncClient.beginRecognizeBusinessCardsFromUrl(businessCardUrl, new RecognizeBusinessCardsOptions() .setFieldElementsIncluded(includeFieldElements) .setPollInterval(Duration.ofSeconds(5))) .flatMap(AsyncPollResponse::getFinalResult) .subscribe(recognizedBusinessCards -> { for (int i = 0; i < recognizedBusinessCards.size(); i++) { RecognizedForm recognizedBusinessCard = recognizedBusinessCards.get(i); Map<String, FormField> recognizedFields = recognizedBusinessCard.getFields(); System.out.printf("----------- Recognized Business Card page %d -----------%n", i); FormField contactNamesFormField = recognizedFields.get("ContactNames"); if (contactNamesFormField != null) { if (FieldValueType.LIST == contactNamesFormField.getValue().getValueType()) { List<FormField> contactNamesList = contactNamesFormField.getValue().asList(); contactNamesList.stream() .filter(contactName -> FieldValueType.MAP == contactName.getValue().getValueType()) .map(contactName -> { System.out.printf("Contact name: %s%n", contactName.getValueData().getText()); return contactName.getValue().asMap(); }) .forEach(contactNamesMap -> contactNamesMap.forEach((key, contactName) -> { if ("FirstName".equals(key)) { if (FieldValueType.STRING == contactName.getValue().getValueType()) { String firstName = contactName.getValue().asString(); System.out.printf("\tFirst Name: %s, confidence: %.2f%n", firstName, contactName.getConfidence()); } } if ("LastName".equals(key)) { if (FieldValueType.STRING == contactName.getValue().getValueType()) { String lastName = contactName.getValue().asString(); System.out.printf("\tLast Name: %s, confidence: %.2f%n", lastName, contactName.getConfidence()); } } })); } } FormField jobTitles = recognizedFields.get("JobTitles"); if (jobTitles != null) { if (FieldValueType.LIST == jobTitles.getValue().getValueType()) { List<FormField> jobTitlesItems = jobTitles.getValue().asList(); jobTitlesItems.stream().forEach(jobTitlesItem -> { if (FieldValueType.STRING == jobTitlesItem.getValue().getValueType()) { String jobTitle = jobTitlesItem.getValue().asString(); System.out.printf("Job Title: %s, confidence: %.2f%n", jobTitle, jobTitlesItem.getConfidence()); } }); } } } }); } /** * Code snippet for {@link FormRecognizerAsyncClient * * @throws IOException Exception thrown when there is an error in reading all the bytes from the File. */ public void beginRecognizeBusinessCards() throws IOException { File businessCard = new File("{local/file_path/fileName.jpg}"); Flux<ByteBuffer> buffer = toFluxByteBuffer(new ByteArrayInputStream(Files.readAllBytes(businessCard.toPath()))); formRecognizerAsyncClient.beginRecognizeBusinessCards(buffer, businessCard.length()) .flatMap(AsyncPollResponse::getFinalResult) .subscribe(recognizedBusinessCards -> { for (int i = 0; i < recognizedBusinessCards.size(); i++) { RecognizedForm recognizedForm = recognizedBusinessCards.get(i); Map<String, FormField> recognizedFields = recognizedForm.getFields(); System.out.printf("----------- Recognized Business Card page %d -----------%n", i); FormField contactNamesFormField = recognizedFields.get("ContactNames"); if (contactNamesFormField != null) { if (FieldValueType.LIST == contactNamesFormField.getValue().getValueType()) { List<FormField> contactNamesList = contactNamesFormField.getValue().asList(); contactNamesList.stream() .filter(contactName -> FieldValueType.MAP == contactName.getValue().getValueType()) .map(contactName -> { System.out.printf("Contact name: %s%n", contactName.getValueData().getText()); return contactName.getValue().asMap(); }) .forEach(contactNamesMap -> contactNamesMap.forEach((key, contactName) -> { if ("FirstName".equals(key)) { if (FieldValueType.STRING == contactName.getValue().getValueType()) { String firstName = contactName.getValue().asString(); System.out.printf("\tFirst Name: %s, confidence: %.2f%n", firstName, contactName.getConfidence()); } } if ("LastName".equals(key)) { if (FieldValueType.STRING == contactName.getValue().getValueType()) { String lastName = contactName.getValue().asString(); System.out.printf("\tLast Name: %s, confidence: %.2f%n", lastName, contactName.getConfidence()); } } })); } } FormField jobTitles = recognizedFields.get("JobTitles"); if (jobTitles != null) { if (FieldValueType.LIST == jobTitles.getValue().getValueType()) { List<FormField> jobTitlesItems = jobTitles.getValue().asList(); jobTitlesItems.stream().forEach(jobTitlesItem -> { if (FieldValueType.STRING == jobTitlesItem.getValue().getValueType()) { String jobTitle = jobTitlesItem.getValue().asString(); System.out.printf("Job Title: %s, confidence: %.2f%n", jobTitle, jobTitlesItem.getConfidence()); } }); } } } }); } /** * Code snippet for * {@link FormRecognizerAsyncClient * options * * @throws IOException Exception thrown when there is an error in reading all the bytes from the File. */ public void beginRecognizeBusinessCardsWithOptions() throws IOException { File businessCard = new File("{local/file_path/fileName.jpg}"); boolean includeFieldElements = true; Flux<ByteBuffer> buffer = toFluxByteBuffer(new ByteArrayInputStream(Files.readAllBytes(businessCard.toPath()))); formRecognizerAsyncClient.beginRecognizeBusinessCards(buffer, businessCard.length(), new RecognizeBusinessCardsOptions() .setContentType(FormContentType.IMAGE_JPEG) .setFieldElementsIncluded(includeFieldElements) .setPollInterval(Duration.ofSeconds(5))) .flatMap(AsyncPollResponse::getFinalResult) .subscribe(recognizedBusinessCards -> { for (int i = 0; i < recognizedBusinessCards.size(); i++) { RecognizedForm recognizedForm = recognizedBusinessCards.get(i); Map<String, FormField> recognizedFields = recognizedForm.getFields(); System.out.printf("----------- Recognized Business Card page %d -----------%n", i); FormField contactNamesFormField = recognizedFields.get("ContactNames"); if (contactNamesFormField != null) { if (FieldValueType.LIST == contactNamesFormField.getValue().getValueType()) { List<FormField> contactNamesList = contactNamesFormField.getValue().asList(); contactNamesList.stream() .filter(contactName -> FieldValueType.MAP == contactName.getValue().getValueType()) .map(contactName -> { System.out.printf("Contact name: %s%n", contactName.getValueData().getText()); return contactName.getValue().asMap(); }) .forEach(contactNamesMap -> contactNamesMap.forEach((key, contactName) -> { if ("FirstName".equals(key)) { if (FieldValueType.STRING == contactName.getValue().getValueType()) { String firstName = contactName.getValue().asString(); System.out.printf("\tFirst Name: %s, confidence: %.2f%n", firstName, contactName.getConfidence()); } } if ("LastName".equals(key)) { if (FieldValueType.STRING == contactName.getValue().getValueType()) { String lastName = contactName.getValue().asString(); System.out.printf("\tLast Name: %s, confidence: %.2f%n", lastName, contactName.getConfidence()); } } })); } } FormField jobTitles = recognizedFields.get("JobTitles"); if (jobTitles != null) { if (FieldValueType.LIST == jobTitles.getValue().getValueType()) { List<FormField> jobTitlesItems = jobTitles.getValue().asList(); jobTitlesItems.stream().forEach(jobTitlesItem -> { if (FieldValueType.STRING == jobTitlesItem.getValue().getValueType()) { String jobTitle = jobTitlesItem.getValue().asString(); System.out.printf("Job Title: %s, confidence: %.2f%n", jobTitle, jobTitlesItem.getConfidence()); } }); } } } }); } }
Consider removing to make the example short?
public void beginRecognizeBusinessCardsFromUrl() { String businessCardUrl = "{file_source_url}"; formRecognizerAsyncClient.beginRecognizeBusinessCardsFromUrl(businessCardUrl) .flatMap(AsyncPollResponse::getFinalResult) .subscribe(recognizedBusinessCards -> { for (int i = 0; i < recognizedBusinessCards.size(); i++) { RecognizedForm recognizedForm = recognizedBusinessCards.get(i); Map<String, FormField> recognizedFields = recognizedForm.getFields(); System.out.printf("----------- Recognized Business Card page %d -----------%n", i); FormField contactNames = recognizedFields.get("ContactNames"); if (contactNames != null) { if (FieldValueType.LIST == contactNames.getValue().getValueType()) { List<FormField> businessCardItems = contactNames.getValue().asList(); businessCardItems.stream() .filter(businessCardItem -> FieldValueType.MAP == businessCardItem.getValue() .getValueType()) .map(formField -> formField.getValue().asMap()) .forEach(formFieldMap -> formFieldMap.forEach((key, formField) -> { if ("FirstName".equals(key)) { if (FieldValueType.STRING == formField.getValue().getValueType()) { String firstName = formField.getValue().asString(); System.out.printf("First Name: %s, confidence: %.2f%n", firstName, contactNames.getConfidence()); } } if ("LastName".equals(key)) { if (FieldValueType.STRING == formField.getValue().getValueType()) { String lastName = formField.getValue().asString(); System.out.printf("Last Name: %s, confidence: %.2f%n", lastName, contactNames.getConfidence()); } } })); } } FormField jobTitles = recognizedFields.get("JobTitles"); if (jobTitles != null) { if (FieldValueType.LIST == jobTitles.getValue().getValueType()) { List<FormField> jobTitlesItems = jobTitles.getValue().asList(); jobTitlesItems.stream().forEach(formField -> { if (FieldValueType.STRING == formField.getValue().getValueType()) { String jobTitle = formField.getValue().asString(); System.out.printf("Job Title: %s, confidence: %.2f%n", jobTitle, jobTitles.getConfidence()); } }); } } FormField addresses = recognizedFields.get("Addresses"); if (addresses != null) { if (FieldValueType.LIST == addresses.getValue().getValueType()) { List<FormField> addressesItems = addresses.getValue().asList(); addressesItems.stream().forEach(formField -> { if (FieldValueType.STRING == formField.getValue().getValueType()) { String address = formField.getValue().asString(); System.out.printf("Address: %s, confidence: %.2f%n", address, addresses.getConfidence()); } }); } } FormField companyName = recognizedFields.get("CompanyNames"); if (companyName != null) { if (FieldValueType.LIST == companyName.getValue().getValueType()) { List<FormField> companyNameItems = companyName.getValue().asList(); companyNameItems.stream().forEach(formField -> { if (FieldValueType.STRING == formField.getValue().getValueType()) { String companyNameValue = formField.getValue().asString(); System.out.printf("Company name: %s, confidence: %.2f%n", companyNameValue, companyName.getConfidence()); } }); } } } }); }
}
public void beginRecognizeBusinessCardsFromUrl() { String businessCardUrl = "{business_card_url}"; formRecognizerAsyncClient.beginRecognizeBusinessCardsFromUrl(businessCardUrl) .flatMap(AsyncPollResponse::getFinalResult) .subscribe(recognizedBusinessCards -> { for (int i = 0; i < recognizedBusinessCards.size(); i++) { RecognizedForm recognizedForm = recognizedBusinessCards.get(i); Map<String, FormField> recognizedFields = recognizedForm.getFields(); System.out.printf("----------- Recognized Business Card page %d -----------%n", i); FormField contactNamesFormField = recognizedFields.get("ContactNames"); if (contactNamesFormField != null) { if (FieldValueType.LIST == contactNamesFormField.getValue().getValueType()) { List<FormField> contactNamesList = contactNamesFormField.getValue().asList(); contactNamesList.stream() .filter(contactName -> FieldValueType.MAP == contactName.getValue().getValueType()) .map(contactName -> { System.out.printf("Contact name: %s%n", contactName.getValueData().getText()); return contactName.getValue().asMap(); }) .forEach(contactNamesMap -> contactNamesMap.forEach((key, contactName) -> { if ("FirstName".equals(key)) { if (FieldValueType.STRING == contactName.getValue().getValueType()) { String firstName = contactName.getValue().asString(); System.out.printf("\tFirst Name: %s, confidence: %.2f%n", firstName, contactName.getConfidence()); } } if ("LastName".equals(key)) { if (FieldValueType.STRING == contactName.getValue().getValueType()) { String lastName = contactName.getValue().asString(); System.out.printf("\tLast Name: %s, confidence: %.2f%n", lastName, contactName.getConfidence()); } } })); } } FormField jobTitles = recognizedFields.get("JobTitles"); if (jobTitles != null) { if (FieldValueType.LIST == jobTitles.getValue().getValueType()) { List<FormField> jobTitlesItems = jobTitles.getValue().asList(); jobTitlesItems.stream().forEach(jobTitlesItem -> { if (FieldValueType.STRING == jobTitlesItem.getValue().getValueType()) { String jobTitle = jobTitlesItem.getValue().asString(); System.out.printf("Job Title: %s, confidence: %.2f%n", jobTitle, jobTitlesItem.getConfidence()); } }); } } } }); }
class FormRecognizerAsyncClientJavaDocCodeSnippets { FormRecognizerAsyncClient formRecognizerAsyncClient = new FormRecognizerClientBuilder().buildAsyncClient(); /** * Code snippet for creating a {@link FormRecognizerAsyncClient} */ public void createFormRecognizerAsyncClient() { FormRecognizerAsyncClient formRecognizerAsyncClient = new FormRecognizerClientBuilder() .credential(new AzureKeyCredential("{key}")) .endpoint("{endpoint}") .buildAsyncClient(); } /** * Code snippet for creating a {@link FormRecognizerAsyncClient} with pipeline */ public void createFormRecognizerAsyncClientWithPipeline() { HttpPipeline pipeline = new HttpPipelineBuilder() .policies(/* add policies */) .build(); FormRecognizerAsyncClient formRecognizerAsyncClient = new FormRecognizerClientBuilder() .credential(new AzureKeyCredential("{key}")) .endpoint("{endpoint}") .pipeline(pipeline) .buildAsyncClient(); } /** * Code snippet for {@link FormRecognizerAsyncClient */ public void beginRecognizeCustomFormsFromUrl() { String formUrl = "{form_url}"; String modelId = "{custom_trained_model_id}"; formRecognizerAsyncClient.beginRecognizeCustomFormsFromUrl(modelId, formUrl) .flatMap(AsyncPollResponse::getFinalResult) .flatMap(Flux::fromIterable) .subscribe(recognizedForm -> recognizedForm.getFields() .forEach((fieldText, formField) -> { System.out.printf("Field text: %s%n", fieldText); System.out.printf("Field value data text: %s%n", formField.getValueData().getText()); System.out.printf("Confidence score: %.2f%n", formField.getConfidence()); })); } /** * Code snippet for * {@link FormRecognizerAsyncClient */ public void beginRecognizeCustomFormsFromUrlWithOptions() { String formUrl = "{formUrl}"; String modelId = "{model_id}"; boolean includeFieldElements = true; formRecognizerAsyncClient.beginRecognizeCustomFormsFromUrl(modelId, formUrl, new RecognizeCustomFormsOptions() .setFieldElementsIncluded(includeFieldElements) .setPollInterval(Duration.ofSeconds(10))) .flatMap(AsyncPollResponse::getFinalResult) .flatMap(Flux::fromIterable) .subscribe(recognizedForm -> recognizedForm.getFields() .forEach((fieldText, formField) -> { System.out.printf("Field text: %s%n", fieldText); System.out.printf("Field value data text: %s%n", formField.getValueData().getText()); System.out.printf("Confidence score: %.2f%n", formField.getConfidence()); })); } /** * Code snippet for {@link FormRecognizerAsyncClient * * @throws IOException Exception thrown when there is an error in reading all the bytes from the File. */ public void beginRecognizeCustomForms() throws IOException { File form = new File("{local/file_path/fileName.jpg}"); String modelId = "{custom_trained_model_id}"; Flux<ByteBuffer> buffer = toFluxByteBuffer(new ByteArrayInputStream(Files.readAllBytes(form.toPath()))); formRecognizerAsyncClient.beginRecognizeCustomForms(modelId, buffer, form.length()) .flatMap(AsyncPollResponse::getFinalResult) .flatMap(Flux::fromIterable) .subscribe(recognizedForm -> recognizedForm.getFields() .forEach((fieldText, formField) -> { System.out.printf("Field text: %s%n", fieldText); System.out.printf("Field value data text: %s%n", formField.getValueData().getText()); System.out.printf("Confidence score: %.2f%n", formField.getConfidence()); })); } /** * Code snippet for * {@link FormRecognizerAsyncClient * with options * * @throws IOException Exception thrown when there is an error in reading all the bytes from the File. */ public void beginRecognizeCustomFormsWithOptions() throws IOException { File form = new File("{local/file_path/fileName.jpg}"); String modelId = "{custom_trained_model_id}"; boolean includeFieldElements = true; Flux<ByteBuffer> buffer = toFluxByteBuffer(new ByteArrayInputStream(Files.readAllBytes(form.toPath()))); formRecognizerAsyncClient.beginRecognizeCustomForms(modelId, buffer, form.length(), new RecognizeCustomFormsOptions() .setContentType(FormContentType.IMAGE_JPEG) .setFieldElementsIncluded(includeFieldElements) .setPollInterval(Duration.ofSeconds(5))) .flatMap(AsyncPollResponse::getFinalResult) .flatMap(Flux::fromIterable) .subscribe(recognizedForm -> recognizedForm.getFields() .forEach((fieldName, formField) -> { System.out.printf("Field text: %s%n", fieldName); System.out.printf("Field value data text: %s%n", formField.getValueData().getText()); System.out.printf("Confidence score: %.2f%n", formField.getConfidence()); })); } /** * Code snippet for {@link FormRecognizerAsyncClient */ public void beginRecognizeContentFromUrl() { String formUrl = "{formUrl}"; formRecognizerAsyncClient.beginRecognizeContentFromUrl(formUrl) .flatMap(AsyncPollResponse::getFinalResult) .flatMap(Flux::fromIterable) .subscribe(formPage -> { System.out.printf("Page Angle: %s%n", formPage.getTextAngle()); System.out.printf("Page Dimension unit: %s%n", formPage.getUnit()); System.out.println("Recognized Tables: "); formPage.getTables().forEach(formTable -> formTable.getCells().forEach(recognizedTableCell -> System.out.printf("%s ", recognizedTableCell.getText()))); }); } /** * Code snippet for {@link FormRecognizerAsyncClient * options */ public void beginRecognizeContentFromUrlWithOptions() { String formUrl = "{formUrl}"; formRecognizerAsyncClient.beginRecognizeContentFromUrl(formUrl, new RecognizeContentOptions().setPollInterval(Duration.ofSeconds(5))) .flatMap(AsyncPollResponse::getFinalResult) .flatMap(Flux::fromIterable) .subscribe(formPage -> { System.out.printf("Page Angle: %s%n", formPage.getTextAngle()); System.out.printf("Page Dimension unit: %s%n", formPage.getUnit()); System.out.println("Recognized Tables: "); formPage.getTables().forEach(formTable -> formTable.getCells().forEach(recognizedTableCell -> System.out.printf("%s ", recognizedTableCell.getText()))); }); } /** * Code snippet for {@link FormRecognizerAsyncClient * * @throws IOException Exception thrown when there is an error in reading all the bytes from the File. */ public void beginRecognizeContent() throws IOException { File form = new File("{local/file_path/fileName.jpg}"); Flux<ByteBuffer> buffer = toFluxByteBuffer(new ByteArrayInputStream(Files.readAllBytes(form.toPath()))); formRecognizerAsyncClient.beginRecognizeContent(buffer, form.length()) .flatMap(AsyncPollResponse::getFinalResult) .flatMap(Flux::fromIterable) .subscribe(formPage -> { System.out.printf("Page Angle: %s%n", formPage.getTextAngle()); System.out.printf("Page Dimension unit: %s%n", formPage.getUnit()); System.out.println("Recognized Tables: "); formPage.getTables().forEach(formTable -> formTable.getCells().forEach(recognizedTableCell -> System.out.printf("%s ", recognizedTableCell.getText()))); }); } /** * Code snippet for {@link FormRecognizerAsyncClient * options * * @throws IOException Exception thrown when there is an error in reading all the bytes from the File. */ public void beginRecognizeContentWithOptions() throws IOException { File form = new File("{local/file_path/fileName.jpg}"); Flux<ByteBuffer> buffer = toFluxByteBuffer(new ByteArrayInputStream(Files.readAllBytes(form.toPath()))); formRecognizerAsyncClient.beginRecognizeContent(buffer, form.length(), new RecognizeContentOptions() .setContentType(FormContentType.APPLICATION_PDF) .setPollInterval(Duration.ofSeconds(5))) .flatMap(AsyncPollResponse::getFinalResult) .flatMap(Flux::fromIterable) .subscribe(formPage -> { System.out.printf("Page Angle: %s%n", formPage.getTextAngle()); System.out.printf("Page Dimension unit: %s%n", formPage.getUnit()); System.out.println("Recognized Tables: "); formPage.getTables().forEach(formTable -> formTable.getCells().forEach(recognizedTableCell -> System.out.printf("%s ", recognizedTableCell.getText()))); }); } /** * Code snippet for {@link FormRecognizerAsyncClient */ public void beginRecognizeReceiptsFromUrl() { String receiptUrl = "{receiptUrl}"; formRecognizerAsyncClient.beginRecognizeReceiptsFromUrl(receiptUrl) .flatMap(AsyncPollResponse::getFinalResult) .subscribe(recognizedReceipts -> { for (int i = 0; i < recognizedReceipts.size(); i++) { RecognizedForm recognizedForm = recognizedReceipts.get(i); Map<String, FormField> recognizedFields = recognizedForm.getFields(); System.out.printf("----------- Recognized Receipt page %d -----------%n", i); FormField merchantNameField = recognizedFields.get("MerchantName"); if (merchantNameField != null) { if (FieldValueType.STRING == merchantNameField.getValue().getValueType()) { String merchantName = merchantNameField.getValue().asString(); System.out.printf("Merchant Name: %s, confidence: %.2f%n", merchantName, merchantNameField.getConfidence()); } } FormField merchantPhoneNumberField = recognizedFields.get("MerchantPhoneNumber"); if (merchantPhoneNumberField != null) { if (FieldValueType.PHONE_NUMBER == merchantPhoneNumberField.getValue().getValueType()) { String merchantAddress = merchantPhoneNumberField.getValue().asPhoneNumber(); System.out.printf("Merchant Phone number: %s, confidence: %.2f%n", merchantAddress, merchantPhoneNumberField.getConfidence()); } } FormField transactionDateField = recognizedFields.get("TransactionDate"); if (transactionDateField != null) { if (FieldValueType.DATE == transactionDateField.getValue().getValueType()) { LocalDate transactionDate = transactionDateField.getValue().asDate(); System.out.printf("Transaction Date: %s, confidence: %.2f%n", transactionDate, transactionDateField.getConfidence()); } } FormField receiptItemsField = recognizedFields.get("Items"); if (receiptItemsField != null) { System.out.printf("Receipt Items: %n"); if (FieldValueType.LIST == receiptItemsField.getValue().getValueType()) { List<FormField> receiptItems = receiptItemsField.getValue().asList(); receiptItems.stream() .filter(receiptItem -> FieldValueType.MAP == receiptItem.getValue().getValueType()) .map(formField -> formField.getValue().asMap()) .forEach(formFieldMap -> formFieldMap.forEach((key, formField) -> { if ("Quantity".equals(key)) { if (FieldValueType.FLOAT == formField.getValue().getValueType()) { Float quantity = formField.getValue().asFloat(); System.out.printf("Quantity: %f, confidence: %.2f%n", quantity, formField.getConfidence()); } } })); } } } }); } /** * Code snippet for {@link FormRecognizerAsyncClient */ public void beginRecognizeReceiptsFromUrlWithOptions() { String receiptUrl = "{receiptUrl}"; boolean includeFieldElements = true; formRecognizerAsyncClient.beginRecognizeReceiptsFromUrl(receiptUrl, new RecognizeReceiptsOptions() .setFieldElementsIncluded(includeFieldElements) .setPollInterval(Duration.ofSeconds(5))) .flatMap(AsyncPollResponse::getFinalResult) .subscribe(recognizedReceipts -> { for (int i = 0; i < recognizedReceipts.size(); i++) { RecognizedForm recognizedReceipt = recognizedReceipts.get(i); Map<String, FormField> recognizedFields = recognizedReceipt.getFields(); System.out.printf("----------- Recognized Receipt page %d -----------%n", i); FormField merchantNameField = recognizedFields.get("MerchantName"); if (merchantNameField != null) { if (FieldValueType.STRING == merchantNameField.getValue().getValueType()) { String merchantName = merchantNameField.getValue().asString(); System.out.printf("Merchant Name: %s, confidence: %.2f%n", merchantName, merchantNameField.getConfidence()); } } FormField merchantPhoneNumberField = recognizedFields.get("MerchantPhoneNumber"); if (merchantPhoneNumberField != null) { if (FieldValueType.PHONE_NUMBER == merchantPhoneNumberField.getValue().getValueType()) { String merchantAddress = merchantPhoneNumberField.getValue().asPhoneNumber(); System.out.printf("Merchant Phone number: %s, confidence: %.2f%n", merchantAddress, merchantPhoneNumberField.getConfidence()); } } FormField transactionDateField = recognizedFields.get("TransactionDate"); if (transactionDateField != null) { if (FieldValueType.DATE == transactionDateField.getValue().getValueType()) { LocalDate transactionDate = transactionDateField.getValue().asDate(); System.out.printf("Transaction Date: %s, confidence: %.2f%n", transactionDate, transactionDateField.getConfidence()); } } FormField receiptItemsField = recognizedFields.get("Items"); if (receiptItemsField != null) { System.out.printf("Receipt Items: %n"); if (FieldValueType.LIST == receiptItemsField.getValue().getValueType()) { List<FormField> receiptItems = receiptItemsField.getValue().asList(); receiptItems.stream() .filter(receiptItem -> FieldValueType.MAP == receiptItem.getValue().getValueType()) .map(formField -> formField.getValue().asMap()) .forEach(formFieldMap -> formFieldMap.forEach((key, formField) -> { if ("Quantity".equals(key)) { if (FieldValueType.FLOAT == formField.getValue().getValueType()) { Float quantity = formField.getValue().asFloat(); System.out.printf("Quantity: %f, confidence: %.2f%n", quantity, formField.getConfidence()); } } })); } } } }); } /** * Code snippet for {@link FormRecognizerAsyncClient * * @throws IOException Exception thrown when there is an error in reading all the bytes from the File. */ public void beginRecognizeReceipts() throws IOException { File receipt = new File("{file_source_url}"); Flux<ByteBuffer> buffer = toFluxByteBuffer(new ByteArrayInputStream(Files.readAllBytes(receipt.toPath()))); formRecognizerAsyncClient.beginRecognizeReceipts(buffer, receipt.length()) .flatMap(AsyncPollResponse::getFinalResult) .subscribe(recognizedReceipts -> { for (int i = 0; i < recognizedReceipts.size(); i++) { RecognizedForm recognizedForm = recognizedReceipts.get(i); Map<String, FormField> recognizedFields = recognizedForm.getFields(); System.out.printf("----------- Recognized Receipt page %d -----------%n", i); FormField merchantNameField = recognizedFields.get("MerchantName"); if (merchantNameField != null) { if (FieldValueType.STRING == merchantNameField.getValue().getValueType()) { String merchantName = merchantNameField.getValue().asString(); System.out.printf("Merchant Name: %s, confidence: %.2f%n", merchantName, merchantNameField.getConfidence()); } } FormField merchantPhoneNumberField = recognizedFields.get("MerchantPhoneNumber"); if (merchantPhoneNumberField != null) { if (FieldValueType.PHONE_NUMBER == merchantPhoneNumberField.getValue().getValueType()) { String merchantAddress = merchantPhoneNumberField.getValue().asPhoneNumber(); System.out.printf("Merchant Phone number: %s, confidence: %.2f%n", merchantAddress, merchantPhoneNumberField.getConfidence()); } } FormField transactionDateField = recognizedFields.get("TransactionDate"); if (transactionDateField != null) { if (FieldValueType.DATE == transactionDateField.getValue().getValueType()) { LocalDate transactionDate = transactionDateField.getValue().asDate(); System.out.printf("Transaction Date: %s, confidence: %.2f%n", transactionDate, transactionDateField.getConfidence()); } } FormField receiptItemsField = recognizedFields.get("Items"); if (receiptItemsField != null) { System.out.printf("Receipt Items: %n"); if (FieldValueType.LIST == receiptItemsField.getValue().getValueType()) { List<FormField> receiptItems = receiptItemsField.getValue().asList(); receiptItems.stream() .filter(receiptItem -> FieldValueType.MAP == receiptItem.getValue().getValueType()) .map(formField -> formField.getValue().asMap()) .forEach(formFieldMap -> formFieldMap.forEach((key, formField) -> { if ("Quantity".equals(key)) { if (FieldValueType.FLOAT == formField.getValue().getValueType()) { Float quantity = formField.getValue().asFloat(); System.out.printf("Quantity: %f, confidence: %.2f%n", quantity, formField.getConfidence()); } } })); } } } }); } /** * Code snippet for {@link FormRecognizerAsyncClient * options * * @throws IOException Exception thrown when there is an error in reading all the bytes from the File. */ public void beginRecognizeReceiptsWithOptions() throws IOException { File receipt = new File("{local/file_path/fileName.jpg}"); boolean includeFieldElements = true; Flux<ByteBuffer> buffer = toFluxByteBuffer(new ByteArrayInputStream(Files.readAllBytes(receipt.toPath()))); formRecognizerAsyncClient.beginRecognizeReceipts(buffer, receipt.length(), new RecognizeReceiptsOptions() .setContentType(FormContentType.IMAGE_JPEG) .setFieldElementsIncluded(includeFieldElements) .setPollInterval(Duration.ofSeconds(5))) .flatMap(AsyncPollResponse::getFinalResult) .subscribe(recognizedReceipts -> { for (int i = 0; i < recognizedReceipts.size(); i++) { RecognizedForm recognizedForm = recognizedReceipts.get(i); Map<String, FormField> recognizedFields = recognizedForm.getFields(); System.out.printf("----------- Recognized Receipt page %d -----------%n", i); FormField merchantNameField = recognizedFields.get("MerchantName"); if (merchantNameField != null) { if (FieldValueType.STRING == merchantNameField.getValue().getValueType()) { String merchantName = merchantNameField.getValue().asString(); System.out.printf("Merchant Name: %s, confidence: %.2f%n", merchantName, merchantNameField.getConfidence()); } } FormField merchantPhoneNumberField = recognizedFields.get("MerchantPhoneNumber"); if (merchantPhoneNumberField != null) { if (FieldValueType.PHONE_NUMBER == merchantPhoneNumberField.getValue().getValueType()) { String merchantAddress = merchantPhoneNumberField.getValue().asPhoneNumber(); System.out.printf("Merchant Phone number: %s, confidence: %.2f%n", merchantAddress, merchantPhoneNumberField.getConfidence()); } } FormField transactionDateField = recognizedFields.get("TransactionDate"); if (transactionDateField != null) { if (FieldValueType.DATE == transactionDateField.getValue().getValueType()) { LocalDate transactionDate = transactionDateField.getValue().asDate(); System.out.printf("Transaction Date: %s, confidence: %.2f%n", transactionDate, transactionDateField.getConfidence()); } } FormField receiptItemsField = recognizedFields.get("Items"); if (receiptItemsField != null) { System.out.printf("Receipt Items: %n"); if (FieldValueType.LIST == receiptItemsField.getValue().getValueType()) { List<FormField> receiptItems = receiptItemsField.getValue().asList(); receiptItems.stream() .filter(receiptItem -> FieldValueType.MAP == receiptItem.getValue().getValueType()) .map(formField -> formField.getValue().asMap()) .forEach(formFieldMap -> formFieldMap.forEach((key, formField) -> { if ("Quantity".equals(key)) { if (FieldValueType.FLOAT == formField.getValue().getValueType()) { Float quantity = formField.getValue().asFloat(); System.out.printf("Quantity: %f, confidence: %.2f%n", quantity, formField.getConfidence()); } } })); } } } }); } /** * Code snippet for {@link FormRecognizerAsyncClient */ /** * Code snippet for * {@link FormRecognizerAsyncClient */ public void beginRecognizeBusinessCardsFromUrlWithOptions() { String businessCardUrl = "{file_source_url}"; boolean includeFieldElements = true; formRecognizerAsyncClient.beginRecognizeBusinessCardsFromUrl(businessCardUrl, new RecognizeBusinessCardsOptions() .setFieldElementsIncluded(includeFieldElements) .setPollInterval(Duration.ofSeconds(5))) .flatMap(AsyncPollResponse::getFinalResult) .subscribe(recognizedBusinessCards -> { for (int i = 0; i < recognizedBusinessCards.size(); i++) { RecognizedForm recognizedBusinessCard = recognizedBusinessCards.get(i); Map<String, FormField> recognizedFields = recognizedBusinessCard.getFields(); System.out.printf("----------- Recognized Business Card page %d -----------%n", i); FormField contactNames = recognizedFields.get("ContactNames"); if (contactNames != null) { if (FieldValueType.LIST == contactNames.getValue().getValueType()) { List<FormField> businessCardItems = contactNames.getValue().asList(); businessCardItems.stream() .filter(businessCardItem -> FieldValueType.MAP == businessCardItem.getValue() .getValueType()) .map(formField -> formField.getValue().asMap()) .forEach(formFieldMap -> formFieldMap.forEach((key, formField) -> { if ("FirstName".equals(key)) { if (FieldValueType.STRING == formField.getValue().getValueType()) { String firstName = formField.getValue().asString(); System.out.printf("First Name: %s, confidence: %.2f%n", firstName, contactNames.getConfidence()); } } if ("LastName".equals(key)) { if (FieldValueType.STRING == formField.getValue().getValueType()) { String lastName = formField.getValue().asString(); System.out.printf("Last Name: %s, confidence: %.2f%n", lastName, contactNames.getConfidence()); } } })); } } FormField jobTitles = recognizedFields.get("JobTitles"); if (jobTitles != null) { if (FieldValueType.LIST == jobTitles.getValue().getValueType()) { List<FormField> jobTitlesItems = jobTitles.getValue().asList(); jobTitlesItems.stream().forEach(formField -> { if (FieldValueType.STRING == formField.getValue().getValueType()) { String jobTitle = formField.getValue().asString(); System.out.printf("Job Title: %s, confidence: %.2f%n", jobTitle, jobTitles.getConfidence()); } }); } } FormField addresses = recognizedFields.get("Addresses"); if (addresses != null) { if (FieldValueType.LIST == addresses.getValue().getValueType()) { List<FormField> addressesItems = addresses.getValue().asList(); addressesItems.stream().forEach(formField -> { if (FieldValueType.STRING == formField.getValue().getValueType()) { String address = formField.getValue().asString(); System.out.printf("Address: %s, confidence: %.2f%n", address, addresses.getConfidence()); } }); } } FormField companyName = recognizedFields.get("CompanyNames"); if (companyName != null) { if (FieldValueType.LIST == companyName.getValue().getValueType()) { List<FormField> companyNameItems = companyName.getValue().asList(); companyNameItems.stream().forEach(formField -> { if (FieldValueType.STRING == formField.getValue().getValueType()) { String companyNameValue = formField.getValue().asString(); System.out.printf("Company name: %s, confidence: %.2f%n", companyNameValue, companyName.getConfidence()); } }); } } } }); } /** * Code snippet for {@link FormRecognizerAsyncClient * * @throws IOException Exception thrown when there is an error in reading all the bytes from the File. */ public void beginRecognizeBusinessCards() throws IOException { File businessCard = new File("{file_source_url}"); Flux<ByteBuffer> buffer = toFluxByteBuffer(new ByteArrayInputStream(Files.readAllBytes(businessCard.toPath()))); formRecognizerAsyncClient.beginRecognizeBusinessCards(buffer, businessCard.length()) .flatMap(AsyncPollResponse::getFinalResult) .subscribe(recognizedBusinessCards -> { for (int i = 0; i < recognizedBusinessCards.size(); i++) { RecognizedForm recognizedForm = recognizedBusinessCards.get(i); Map<String, FormField> recognizedFields = recognizedForm.getFields(); System.out.printf("----------- Recognized Business Card page %d -----------%n", i); FormField contactNames = recognizedFields.get("ContactNames"); if (contactNames != null) { if (FieldValueType.LIST == contactNames.getValue().getValueType()) { List<FormField> businessCardItems = contactNames.getValue().asList(); businessCardItems.stream() .filter(businessCardItem -> FieldValueType.MAP == businessCardItem.getValue() .getValueType()) .map(formField -> formField.getValue().asMap()) .forEach(formFieldMap -> formFieldMap.forEach((key, formField) -> { if ("FirstName".equals(key)) { if (FieldValueType.STRING == formField.getValue().getValueType()) { String firstName = formField.getValue().asString(); System.out.printf("First Name: %s, confidence: %.2f%n", firstName, contactNames.getConfidence()); } } if ("LastName".equals(key)) { if (FieldValueType.STRING == formField.getValue().getValueType()) { String lastName = formField.getValue().asString(); System.out.printf("Last Name: %s, confidence: %.2f%n", lastName, contactNames.getConfidence()); } } })); } } FormField jobTitles = recognizedFields.get("JobTitles"); if (jobTitles != null) { if (FieldValueType.LIST == jobTitles.getValue().getValueType()) { List<FormField> jobTitlesItems = jobTitles.getValue().asList(); jobTitlesItems.stream().forEach(formField -> { if (FieldValueType.STRING == formField.getValue().getValueType()) { String jobTitle = formField.getValue().asString(); System.out.printf("Job Title: %s, confidence: %.2f%n", jobTitle, jobTitles.getConfidence()); } }); } } FormField addresses = recognizedFields.get("Addresses"); if (addresses != null) { if (FieldValueType.LIST == addresses.getValue().getValueType()) { List<FormField> addressesItems = addresses.getValue().asList(); addressesItems.stream().forEach(formField -> { if (FieldValueType.STRING == formField.getValue().getValueType()) { String address = formField.getValue().asString(); System.out.printf("Address: %s, confidence: %.2f%n", address, addresses.getConfidence()); } }); } } FormField companyName = recognizedFields.get("CompanyNames"); if (companyName != null) { if (FieldValueType.LIST == companyName.getValue().getValueType()) { List<FormField> companyNameItems = companyName.getValue().asList(); companyNameItems.stream().forEach(formField -> { if (FieldValueType.STRING == formField.getValue().getValueType()) { String companyNameValue = formField.getValue().asString(); System.out.printf("Company name: %s, confidence: %.2f%n", companyNameValue, companyName.getConfidence()); } }); } } } }); } /** * Code snippet for * {@link FormRecognizerAsyncClient * options * * @throws IOException Exception thrown when there is an error in reading all the bytes from the File. */ public void beginRecognizeBusinessCardsWithOptions() throws IOException { File businessCard = new File("{local/file_path/fileName.jpg}"); boolean includeFieldElements = true; Flux<ByteBuffer> buffer = toFluxByteBuffer(new ByteArrayInputStream(Files.readAllBytes(businessCard.toPath()))); formRecognizerAsyncClient.beginRecognizeBusinessCards(buffer, businessCard.length(), new RecognizeBusinessCardsOptions() .setContentType(FormContentType.IMAGE_JPEG) .setFieldElementsIncluded(includeFieldElements) .setPollInterval(Duration.ofSeconds(5))) .flatMap(AsyncPollResponse::getFinalResult) .subscribe(recognizedBusinessCards -> { for (int i = 0; i < recognizedBusinessCards.size(); i++) { RecognizedForm recognizedForm = recognizedBusinessCards.get(i); Map<String, FormField> recognizedFields = recognizedForm.getFields(); System.out.printf("----------- Recognized Business Card page %d -----------%n", i); FormField contactNames = recognizedFields.get("ContactNames"); if (contactNames != null) { if (FieldValueType.LIST == contactNames.getValue().getValueType()) { List<FormField> businessCardItems = contactNames.getValue().asList(); businessCardItems.stream() .filter(businessCardItem -> FieldValueType.MAP == businessCardItem.getValue() .getValueType()) .map(formField -> formField.getValue().asMap()) .forEach(formFieldMap -> formFieldMap.forEach((key, formField) -> { if ("FirstName".equals(key)) { if (FieldValueType.STRING == formField.getValue().getValueType()) { String firstName = formField.getValue().asString(); System.out.printf("First Name: %s, confidence: %.2f%n", firstName, contactNames.getConfidence()); } } if ("LastName".equals(key)) { if (FieldValueType.STRING == formField.getValue().getValueType()) { String lastName = formField.getValue().asString(); System.out.printf("Last Name: %s, confidence: %.2f%n", lastName, contactNames.getConfidence()); } } })); } } FormField jobTitles = recognizedFields.get("JobTitles"); if (jobTitles != null) { if (FieldValueType.LIST == jobTitles.getValue().getValueType()) { List<FormField> jobTitlesItems = jobTitles.getValue().asList(); jobTitlesItems.stream().forEach(formField -> { if (FieldValueType.STRING == formField.getValue().getValueType()) { String jobTitle = formField.getValue().asString(); System.out.printf("Job Title: %s, confidence: %.2f%n", jobTitle, jobTitles.getConfidence()); } }); } } FormField addresses = recognizedFields.get("Addresses"); if (addresses != null) { if (FieldValueType.LIST == addresses.getValue().getValueType()) { List<FormField> addressesItems = addresses.getValue().asList(); addressesItems.stream().forEach(formField -> { if (FieldValueType.STRING == formField.getValue().getValueType()) { String address = formField.getValue().asString(); System.out.printf("Address: %s, confidence: %.2f%n", address, addresses.getConfidence()); } }); } } FormField companyName = recognizedFields.get("CompanyNames"); if (companyName != null) { if (FieldValueType.LIST == companyName.getValue().getValueType()) { List<FormField> companyNameItems = companyName.getValue().asList(); companyNameItems.stream().forEach(formField -> { if (FieldValueType.STRING == formField.getValue().getValueType()) { String companyNameValue = formField.getValue().asString(); System.out.printf("Company name: %s, confidence: %.2f%n", companyNameValue, companyName.getConfidence()); } }); } } } }); } }
class FormRecognizerAsyncClientJavaDocCodeSnippets { FormRecognizerAsyncClient formRecognizerAsyncClient = new FormRecognizerClientBuilder().buildAsyncClient(); /** * Code snippet for creating a {@link FormRecognizerAsyncClient} */ public void createFormRecognizerAsyncClient() { FormRecognizerAsyncClient formRecognizerAsyncClient = new FormRecognizerClientBuilder() .credential(new AzureKeyCredential("{key}")) .endpoint("{endpoint}") .buildAsyncClient(); } /** * Code snippet for creating a {@link FormRecognizerAsyncClient} with pipeline */ public void createFormRecognizerAsyncClientWithPipeline() { HttpPipeline pipeline = new HttpPipelineBuilder() .policies(/* add policies */) .build(); FormRecognizerAsyncClient formRecognizerAsyncClient = new FormRecognizerClientBuilder() .credential(new AzureKeyCredential("{key}")) .endpoint("{endpoint}") .pipeline(pipeline) .buildAsyncClient(); } /** * Code snippet for {@link FormRecognizerAsyncClient */ public void beginRecognizeCustomFormsFromUrl() { String formUrl = "{form_url}"; String modelId = "{custom_trained_model_id}"; formRecognizerAsyncClient.beginRecognizeCustomFormsFromUrl(modelId, formUrl) .flatMap(AsyncPollResponse::getFinalResult) .flatMap(Flux::fromIterable) .subscribe(recognizedForm -> recognizedForm.getFields() .forEach((fieldText, formField) -> { System.out.printf("Field text: %s%n", fieldText); System.out.printf("Field value data text: %s%n", formField.getValueData().getText()); System.out.printf("Confidence score: %.2f%n", formField.getConfidence()); })); } /** * Code snippet for * {@link FormRecognizerAsyncClient */ public void beginRecognizeCustomFormsFromUrlWithOptions() { String formUrl = "{formUrl}"; String modelId = "{model_id}"; boolean includeFieldElements = true; formRecognizerAsyncClient.beginRecognizeCustomFormsFromUrl(modelId, formUrl, new RecognizeCustomFormsOptions() .setFieldElementsIncluded(includeFieldElements) .setPollInterval(Duration.ofSeconds(10))) .flatMap(AsyncPollResponse::getFinalResult) .flatMap(Flux::fromIterable) .subscribe(recognizedForm -> recognizedForm.getFields() .forEach((fieldText, formField) -> { System.out.printf("Field text: %s%n", fieldText); System.out.printf("Field value data text: %s%n", formField.getValueData().getText()); System.out.printf("Confidence score: %.2f%n", formField.getConfidence()); })); } /** * Code snippet for {@link FormRecognizerAsyncClient * * @throws IOException Exception thrown when there is an error in reading all the bytes from the File. */ public void beginRecognizeCustomForms() throws IOException { File form = new File("{local/file_path/fileName.jpg}"); String modelId = "{custom_trained_model_id}"; Flux<ByteBuffer> buffer = toFluxByteBuffer(new ByteArrayInputStream(Files.readAllBytes(form.toPath()))); formRecognizerAsyncClient.beginRecognizeCustomForms(modelId, buffer, form.length()) .flatMap(AsyncPollResponse::getFinalResult) .flatMap(Flux::fromIterable) .subscribe(recognizedForm -> recognizedForm.getFields() .forEach((fieldText, formField) -> { System.out.printf("Field text: %s%n", fieldText); System.out.printf("Field value data text: %s%n", formField.getValueData().getText()); System.out.printf("Confidence score: %.2f%n", formField.getConfidence()); })); } /** * Code snippet for * {@link FormRecognizerAsyncClient * with options * * @throws IOException Exception thrown when there is an error in reading all the bytes from the File. */ public void beginRecognizeCustomFormsWithOptions() throws IOException { File form = new File("{local/file_path/fileName.jpg}"); String modelId = "{custom_trained_model_id}"; boolean includeFieldElements = true; Flux<ByteBuffer> buffer = toFluxByteBuffer(new ByteArrayInputStream(Files.readAllBytes(form.toPath()))); formRecognizerAsyncClient.beginRecognizeCustomForms(modelId, buffer, form.length(), new RecognizeCustomFormsOptions() .setContentType(FormContentType.IMAGE_JPEG) .setFieldElementsIncluded(includeFieldElements) .setPollInterval(Duration.ofSeconds(5))) .flatMap(AsyncPollResponse::getFinalResult) .flatMap(Flux::fromIterable) .subscribe(recognizedForm -> recognizedForm.getFields() .forEach((fieldName, formField) -> { System.out.printf("Field text: %s%n", fieldName); System.out.printf("Field value data text: %s%n", formField.getValueData().getText()); System.out.printf("Confidence score: %.2f%n", formField.getConfidence()); })); } /** * Code snippet for {@link FormRecognizerAsyncClient */ public void beginRecognizeContentFromUrl() { String formUrl = "{formUrl}"; formRecognizerAsyncClient.beginRecognizeContentFromUrl(formUrl) .flatMap(AsyncPollResponse::getFinalResult) .flatMap(Flux::fromIterable) .subscribe(formPage -> { System.out.printf("Page Angle: %s%n", formPage.getTextAngle()); System.out.printf("Page Dimension unit: %s%n", formPage.getUnit()); System.out.println("Recognized Tables: "); formPage.getTables().forEach(formTable -> formTable.getCells().forEach(recognizedTableCell -> System.out.printf("%s ", recognizedTableCell.getText()))); }); } /** * Code snippet for {@link FormRecognizerAsyncClient * options */ public void beginRecognizeContentFromUrlWithOptions() { String formUrl = "{formUrl}"; formRecognizerAsyncClient.beginRecognizeContentFromUrl(formUrl, new RecognizeContentOptions().setPollInterval(Duration.ofSeconds(5))) .flatMap(AsyncPollResponse::getFinalResult) .flatMap(Flux::fromIterable) .subscribe(formPage -> { System.out.printf("Page Angle: %s%n", formPage.getTextAngle()); System.out.printf("Page Dimension unit: %s%n", formPage.getUnit()); System.out.println("Recognized Tables: "); formPage.getTables().forEach(formTable -> formTable.getCells().forEach(recognizedTableCell -> System.out.printf("%s ", recognizedTableCell.getText()))); }); } /** * Code snippet for {@link FormRecognizerAsyncClient * * @throws IOException Exception thrown when there is an error in reading all the bytes from the File. */ public void beginRecognizeContent() throws IOException { File form = new File("{local/file_path/fileName.jpg}"); Flux<ByteBuffer> buffer = toFluxByteBuffer(new ByteArrayInputStream(Files.readAllBytes(form.toPath()))); formRecognizerAsyncClient.beginRecognizeContent(buffer, form.length()) .flatMap(AsyncPollResponse::getFinalResult) .flatMap(Flux::fromIterable) .subscribe(formPage -> { System.out.printf("Page Angle: %s%n", formPage.getTextAngle()); System.out.printf("Page Dimension unit: %s%n", formPage.getUnit()); System.out.println("Recognized Tables: "); formPage.getTables().forEach(formTable -> formTable.getCells().forEach(recognizedTableCell -> System.out.printf("%s ", recognizedTableCell.getText()))); }); } /** * Code snippet for {@link FormRecognizerAsyncClient * options * * @throws IOException Exception thrown when there is an error in reading all the bytes from the File. */ public void beginRecognizeContentWithOptions() throws IOException { File form = new File("{local/file_path/fileName.jpg}"); Flux<ByteBuffer> buffer = toFluxByteBuffer(new ByteArrayInputStream(Files.readAllBytes(form.toPath()))); formRecognizerAsyncClient.beginRecognizeContent(buffer, form.length(), new RecognizeContentOptions() .setContentType(FormContentType.APPLICATION_PDF) .setPollInterval(Duration.ofSeconds(5))) .flatMap(AsyncPollResponse::getFinalResult) .flatMap(Flux::fromIterable) .subscribe(formPage -> { System.out.printf("Page Angle: %s%n", formPage.getTextAngle()); System.out.printf("Page Dimension unit: %s%n", formPage.getUnit()); System.out.println("Recognized Tables: "); formPage.getTables().forEach(formTable -> formTable.getCells().forEach(recognizedTableCell -> System.out.printf("%s ", recognizedTableCell.getText()))); }); } /** * Code snippet for {@link FormRecognizerAsyncClient */ public void beginRecognizeReceiptsFromUrl() { String receiptUrl = "{receiptUrl}"; formRecognizerAsyncClient.beginRecognizeReceiptsFromUrl(receiptUrl) .flatMap(AsyncPollResponse::getFinalResult) .subscribe(recognizedReceipts -> { for (int i = 0; i < recognizedReceipts.size(); i++) { RecognizedForm recognizedForm = recognizedReceipts.get(i); Map<String, FormField> recognizedFields = recognizedForm.getFields(); System.out.printf("----------- Recognized Receipt page %d -----------%n", i); FormField merchantNameField = recognizedFields.get("MerchantName"); if (merchantNameField != null) { if (FieldValueType.STRING == merchantNameField.getValue().getValueType()) { String merchantName = merchantNameField.getValue().asString(); System.out.printf("Merchant Name: %s, confidence: %.2f%n", merchantName, merchantNameField.getConfidence()); } } FormField merchantPhoneNumberField = recognizedFields.get("MerchantPhoneNumber"); if (merchantPhoneNumberField != null) { if (FieldValueType.PHONE_NUMBER == merchantPhoneNumberField.getValue().getValueType()) { String merchantAddress = merchantPhoneNumberField.getValue().asPhoneNumber(); System.out.printf("Merchant Phone number: %s, confidence: %.2f%n", merchantAddress, merchantPhoneNumberField.getConfidence()); } } FormField transactionDateField = recognizedFields.get("TransactionDate"); if (transactionDateField != null) { if (FieldValueType.DATE == transactionDateField.getValue().getValueType()) { LocalDate transactionDate = transactionDateField.getValue().asDate(); System.out.printf("Transaction Date: %s, confidence: %.2f%n", transactionDate, transactionDateField.getConfidence()); } } FormField receiptItemsField = recognizedFields.get("Items"); if (receiptItemsField != null) { System.out.printf("Receipt Items: %n"); if (FieldValueType.LIST == receiptItemsField.getValue().getValueType()) { List<FormField> receiptItems = receiptItemsField.getValue().asList(); receiptItems.stream() .filter(receiptItem -> FieldValueType.MAP == receiptItem.getValue().getValueType()) .map(formField -> formField.getValue().asMap()) .forEach(formFieldMap -> formFieldMap.forEach((key, formField) -> { if ("Quantity".equals(key)) { if (FieldValueType.FLOAT == formField.getValue().getValueType()) { Float quantity = formField.getValue().asFloat(); System.out.printf("Quantity: %f, confidence: %.2f%n", quantity, formField.getConfidence()); } } })); } } } }); } /** * Code snippet for {@link FormRecognizerAsyncClient */ public void beginRecognizeReceiptsFromUrlWithOptions() { String receiptUrl = "{receiptUrl}"; boolean includeFieldElements = true; formRecognizerAsyncClient.beginRecognizeReceiptsFromUrl(receiptUrl, new RecognizeReceiptsOptions() .setFieldElementsIncluded(includeFieldElements) .setPollInterval(Duration.ofSeconds(5))) .flatMap(AsyncPollResponse::getFinalResult) .subscribe(recognizedReceipts -> { for (int i = 0; i < recognizedReceipts.size(); i++) { RecognizedForm recognizedReceipt = recognizedReceipts.get(i); Map<String, FormField> recognizedFields = recognizedReceipt.getFields(); System.out.printf("----------- Recognized Receipt page %d -----------%n", i); FormField merchantNameField = recognizedFields.get("MerchantName"); if (merchantNameField != null) { if (FieldValueType.STRING == merchantNameField.getValue().getValueType()) { String merchantName = merchantNameField.getValue().asString(); System.out.printf("Merchant Name: %s, confidence: %.2f%n", merchantName, merchantNameField.getConfidence()); } } FormField merchantPhoneNumberField = recognizedFields.get("MerchantPhoneNumber"); if (merchantPhoneNumberField != null) { if (FieldValueType.PHONE_NUMBER == merchantPhoneNumberField.getValue().getValueType()) { String merchantAddress = merchantPhoneNumberField.getValue().asPhoneNumber(); System.out.printf("Merchant Phone number: %s, confidence: %.2f%n", merchantAddress, merchantPhoneNumberField.getConfidence()); } } FormField transactionDateField = recognizedFields.get("TransactionDate"); if (transactionDateField != null) { if (FieldValueType.DATE == transactionDateField.getValue().getValueType()) { LocalDate transactionDate = transactionDateField.getValue().asDate(); System.out.printf("Transaction Date: %s, confidence: %.2f%n", transactionDate, transactionDateField.getConfidence()); } } FormField receiptItemsField = recognizedFields.get("Items"); if (receiptItemsField != null) { System.out.printf("Receipt Items: %n"); if (FieldValueType.LIST == receiptItemsField.getValue().getValueType()) { List<FormField> receiptItems = receiptItemsField.getValue().asList(); receiptItems.stream() .filter(receiptItem -> FieldValueType.MAP == receiptItem.getValue().getValueType()) .map(formField -> formField.getValue().asMap()) .forEach(formFieldMap -> formFieldMap.forEach((key, formField) -> { if ("Quantity".equals(key)) { if (FieldValueType.FLOAT == formField.getValue().getValueType()) { Float quantity = formField.getValue().asFloat(); System.out.printf("Quantity: %f, confidence: %.2f%n", quantity, formField.getConfidence()); } } })); } } } }); } /** * Code snippet for {@link FormRecognizerAsyncClient * * @throws IOException Exception thrown when there is an error in reading all the bytes from the File. */ public void beginRecognizeReceipts() throws IOException { File receipt = new File("{file_source_url}"); Flux<ByteBuffer> buffer = toFluxByteBuffer(new ByteArrayInputStream(Files.readAllBytes(receipt.toPath()))); formRecognizerAsyncClient.beginRecognizeReceipts(buffer, receipt.length()) .flatMap(AsyncPollResponse::getFinalResult) .subscribe(recognizedReceipts -> { for (int i = 0; i < recognizedReceipts.size(); i++) { RecognizedForm recognizedForm = recognizedReceipts.get(i); Map<String, FormField> recognizedFields = recognizedForm.getFields(); System.out.printf("----------- Recognized Receipt page %d -----------%n", i); FormField merchantNameField = recognizedFields.get("MerchantName"); if (merchantNameField != null) { if (FieldValueType.STRING == merchantNameField.getValue().getValueType()) { String merchantName = merchantNameField.getValue().asString(); System.out.printf("Merchant Name: %s, confidence: %.2f%n", merchantName, merchantNameField.getConfidence()); } } FormField merchantPhoneNumberField = recognizedFields.get("MerchantPhoneNumber"); if (merchantPhoneNumberField != null) { if (FieldValueType.PHONE_NUMBER == merchantPhoneNumberField.getValue().getValueType()) { String merchantAddress = merchantPhoneNumberField.getValue().asPhoneNumber(); System.out.printf("Merchant Phone number: %s, confidence: %.2f%n", merchantAddress, merchantPhoneNumberField.getConfidence()); } } FormField transactionDateField = recognizedFields.get("TransactionDate"); if (transactionDateField != null) { if (FieldValueType.DATE == transactionDateField.getValue().getValueType()) { LocalDate transactionDate = transactionDateField.getValue().asDate(); System.out.printf("Transaction Date: %s, confidence: %.2f%n", transactionDate, transactionDateField.getConfidence()); } } FormField receiptItemsField = recognizedFields.get("Items"); if (receiptItemsField != null) { System.out.printf("Receipt Items: %n"); if (FieldValueType.LIST == receiptItemsField.getValue().getValueType()) { List<FormField> receiptItems = receiptItemsField.getValue().asList(); receiptItems.stream() .filter(receiptItem -> FieldValueType.MAP == receiptItem.getValue().getValueType()) .map(formField -> formField.getValue().asMap()) .forEach(formFieldMap -> formFieldMap.forEach((key, formField) -> { if ("Quantity".equals(key)) { if (FieldValueType.FLOAT == formField.getValue().getValueType()) { Float quantity = formField.getValue().asFloat(); System.out.printf("Quantity: %f, confidence: %.2f%n", quantity, formField.getConfidence()); } } })); } } } }); } /** * Code snippet for {@link FormRecognizerAsyncClient * options * * @throws IOException Exception thrown when there is an error in reading all the bytes from the File. */ public void beginRecognizeReceiptsWithOptions() throws IOException { File receipt = new File("{local/file_path/fileName.jpg}"); boolean includeFieldElements = true; Flux<ByteBuffer> buffer = toFluxByteBuffer(new ByteArrayInputStream(Files.readAllBytes(receipt.toPath()))); formRecognizerAsyncClient.beginRecognizeReceipts(buffer, receipt.length(), new RecognizeReceiptsOptions() .setContentType(FormContentType.IMAGE_JPEG) .setFieldElementsIncluded(includeFieldElements) .setPollInterval(Duration.ofSeconds(5))) .flatMap(AsyncPollResponse::getFinalResult) .subscribe(recognizedReceipts -> { for (int i = 0; i < recognizedReceipts.size(); i++) { RecognizedForm recognizedForm = recognizedReceipts.get(i); Map<String, FormField> recognizedFields = recognizedForm.getFields(); System.out.printf("----------- Recognized Receipt page %d -----------%n", i); FormField merchantNameField = recognizedFields.get("MerchantName"); if (merchantNameField != null) { if (FieldValueType.STRING == merchantNameField.getValue().getValueType()) { String merchantName = merchantNameField.getValue().asString(); System.out.printf("Merchant Name: %s, confidence: %.2f%n", merchantName, merchantNameField.getConfidence()); } } FormField merchantPhoneNumberField = recognizedFields.get("MerchantPhoneNumber"); if (merchantPhoneNumberField != null) { if (FieldValueType.PHONE_NUMBER == merchantPhoneNumberField.getValue().getValueType()) { String merchantAddress = merchantPhoneNumberField.getValue().asPhoneNumber(); System.out.printf("Merchant Phone number: %s, confidence: %.2f%n", merchantAddress, merchantPhoneNumberField.getConfidence()); } } FormField transactionDateField = recognizedFields.get("TransactionDate"); if (transactionDateField != null) { if (FieldValueType.DATE == transactionDateField.getValue().getValueType()) { LocalDate transactionDate = transactionDateField.getValue().asDate(); System.out.printf("Transaction Date: %s, confidence: %.2f%n", transactionDate, transactionDateField.getConfidence()); } } FormField receiptItemsField = recognizedFields.get("Items"); if (receiptItemsField != null) { System.out.printf("Receipt Items: %n"); if (FieldValueType.LIST == receiptItemsField.getValue().getValueType()) { List<FormField> receiptItems = receiptItemsField.getValue().asList(); receiptItems.stream() .filter(receiptItem -> FieldValueType.MAP == receiptItem.getValue().getValueType()) .map(formField -> formField.getValue().asMap()) .forEach(formFieldMap -> formFieldMap.forEach((key, formField) -> { if ("Quantity".equals(key)) { if (FieldValueType.FLOAT == formField.getValue().getValueType()) { Float quantity = formField.getValue().asFloat(); System.out.printf("Quantity: %f, confidence: %.2f%n", quantity, formField.getConfidence()); } } })); } } } }); } /** * Code snippet for {@link FormRecognizerAsyncClient */ /** * Code snippet for * {@link FormRecognizerAsyncClient */ public void beginRecognizeBusinessCardsFromUrlWithOptions() { String businessCardUrl = "{business_card_url}"; boolean includeFieldElements = true; formRecognizerAsyncClient.beginRecognizeBusinessCardsFromUrl(businessCardUrl, new RecognizeBusinessCardsOptions() .setFieldElementsIncluded(includeFieldElements) .setPollInterval(Duration.ofSeconds(5))) .flatMap(AsyncPollResponse::getFinalResult) .subscribe(recognizedBusinessCards -> { for (int i = 0; i < recognizedBusinessCards.size(); i++) { RecognizedForm recognizedBusinessCard = recognizedBusinessCards.get(i); Map<String, FormField> recognizedFields = recognizedBusinessCard.getFields(); System.out.printf("----------- Recognized Business Card page %d -----------%n", i); FormField contactNamesFormField = recognizedFields.get("ContactNames"); if (contactNamesFormField != null) { if (FieldValueType.LIST == contactNamesFormField.getValue().getValueType()) { List<FormField> contactNamesList = contactNamesFormField.getValue().asList(); contactNamesList.stream() .filter(contactName -> FieldValueType.MAP == contactName.getValue().getValueType()) .map(contactName -> { System.out.printf("Contact name: %s%n", contactName.getValueData().getText()); return contactName.getValue().asMap(); }) .forEach(contactNamesMap -> contactNamesMap.forEach((key, contactName) -> { if ("FirstName".equals(key)) { if (FieldValueType.STRING == contactName.getValue().getValueType()) { String firstName = contactName.getValue().asString(); System.out.printf("\tFirst Name: %s, confidence: %.2f%n", firstName, contactName.getConfidence()); } } if ("LastName".equals(key)) { if (FieldValueType.STRING == contactName.getValue().getValueType()) { String lastName = contactName.getValue().asString(); System.out.printf("\tLast Name: %s, confidence: %.2f%n", lastName, contactName.getConfidence()); } } })); } } FormField jobTitles = recognizedFields.get("JobTitles"); if (jobTitles != null) { if (FieldValueType.LIST == jobTitles.getValue().getValueType()) { List<FormField> jobTitlesItems = jobTitles.getValue().asList(); jobTitlesItems.stream().forEach(jobTitlesItem -> { if (FieldValueType.STRING == jobTitlesItem.getValue().getValueType()) { String jobTitle = jobTitlesItem.getValue().asString(); System.out.printf("Job Title: %s, confidence: %.2f%n", jobTitle, jobTitlesItem.getConfidence()); } }); } } } }); } /** * Code snippet for {@link FormRecognizerAsyncClient * * @throws IOException Exception thrown when there is an error in reading all the bytes from the File. */ public void beginRecognizeBusinessCards() throws IOException { File businessCard = new File("{local/file_path/fileName.jpg}"); Flux<ByteBuffer> buffer = toFluxByteBuffer(new ByteArrayInputStream(Files.readAllBytes(businessCard.toPath()))); formRecognizerAsyncClient.beginRecognizeBusinessCards(buffer, businessCard.length()) .flatMap(AsyncPollResponse::getFinalResult) .subscribe(recognizedBusinessCards -> { for (int i = 0; i < recognizedBusinessCards.size(); i++) { RecognizedForm recognizedForm = recognizedBusinessCards.get(i); Map<String, FormField> recognizedFields = recognizedForm.getFields(); System.out.printf("----------- Recognized Business Card page %d -----------%n", i); FormField contactNamesFormField = recognizedFields.get("ContactNames"); if (contactNamesFormField != null) { if (FieldValueType.LIST == contactNamesFormField.getValue().getValueType()) { List<FormField> contactNamesList = contactNamesFormField.getValue().asList(); contactNamesList.stream() .filter(contactName -> FieldValueType.MAP == contactName.getValue().getValueType()) .map(contactName -> { System.out.printf("Contact name: %s%n", contactName.getValueData().getText()); return contactName.getValue().asMap(); }) .forEach(contactNamesMap -> contactNamesMap.forEach((key, contactName) -> { if ("FirstName".equals(key)) { if (FieldValueType.STRING == contactName.getValue().getValueType()) { String firstName = contactName.getValue().asString(); System.out.printf("\tFirst Name: %s, confidence: %.2f%n", firstName, contactName.getConfidence()); } } if ("LastName".equals(key)) { if (FieldValueType.STRING == contactName.getValue().getValueType()) { String lastName = contactName.getValue().asString(); System.out.printf("\tLast Name: %s, confidence: %.2f%n", lastName, contactName.getConfidence()); } } })); } } FormField jobTitles = recognizedFields.get("JobTitles"); if (jobTitles != null) { if (FieldValueType.LIST == jobTitles.getValue().getValueType()) { List<FormField> jobTitlesItems = jobTitles.getValue().asList(); jobTitlesItems.stream().forEach(jobTitlesItem -> { if (FieldValueType.STRING == jobTitlesItem.getValue().getValueType()) { String jobTitle = jobTitlesItem.getValue().asString(); System.out.printf("Job Title: %s, confidence: %.2f%n", jobTitle, jobTitlesItem.getConfidence()); } }); } } } }); } /** * Code snippet for * {@link FormRecognizerAsyncClient * options * * @throws IOException Exception thrown when there is an error in reading all the bytes from the File. */ public void beginRecognizeBusinessCardsWithOptions() throws IOException { File businessCard = new File("{local/file_path/fileName.jpg}"); boolean includeFieldElements = true; Flux<ByteBuffer> buffer = toFluxByteBuffer(new ByteArrayInputStream(Files.readAllBytes(businessCard.toPath()))); formRecognizerAsyncClient.beginRecognizeBusinessCards(buffer, businessCard.length(), new RecognizeBusinessCardsOptions() .setContentType(FormContentType.IMAGE_JPEG) .setFieldElementsIncluded(includeFieldElements) .setPollInterval(Duration.ofSeconds(5))) .flatMap(AsyncPollResponse::getFinalResult) .subscribe(recognizedBusinessCards -> { for (int i = 0; i < recognizedBusinessCards.size(); i++) { RecognizedForm recognizedForm = recognizedBusinessCards.get(i); Map<String, FormField> recognizedFields = recognizedForm.getFields(); System.out.printf("----------- Recognized Business Card page %d -----------%n", i); FormField contactNamesFormField = recognizedFields.get("ContactNames"); if (contactNamesFormField != null) { if (FieldValueType.LIST == contactNamesFormField.getValue().getValueType()) { List<FormField> contactNamesList = contactNamesFormField.getValue().asList(); contactNamesList.stream() .filter(contactName -> FieldValueType.MAP == contactName.getValue().getValueType()) .map(contactName -> { System.out.printf("Contact name: %s%n", contactName.getValueData().getText()); return contactName.getValue().asMap(); }) .forEach(contactNamesMap -> contactNamesMap.forEach((key, contactName) -> { if ("FirstName".equals(key)) { if (FieldValueType.STRING == contactName.getValue().getValueType()) { String firstName = contactName.getValue().asString(); System.out.printf("\tFirst Name: %s, confidence: %.2f%n", firstName, contactName.getConfidence()); } } if ("LastName".equals(key)) { if (FieldValueType.STRING == contactName.getValue().getValueType()) { String lastName = contactName.getValue().asString(); System.out.printf("\tLast Name: %s, confidence: %.2f%n", lastName, contactName.getConfidence()); } } })); } } FormField jobTitles = recognizedFields.get("JobTitles"); if (jobTitles != null) { if (FieldValueType.LIST == jobTitles.getValue().getValueType()) { List<FormField> jobTitlesItems = jobTitles.getValue().asList(); jobTitlesItems.stream().forEach(jobTitlesItem -> { if (FieldValueType.STRING == jobTitlesItem.getValue().getValueType()) { String jobTitle = jobTitlesItem.getValue().asString(); System.out.printf("Job Title: %s, confidence: %.2f%n", jobTitle, jobTitlesItem.getConfidence()); } }); } } } }); } }
We don't need this check as whenever the fields value type == ARRAY it will always be set to null. We could keep the comment for future reference.
private static List<FormField> toFieldValueArray(List<FieldValue> valueArray, List<ReadResult> readResults) { return valueArray.stream() .map(fieldValue -> { FieldData valueData = null; if (ARRAY != fieldValue.getType()) { valueData = new FieldData(fieldValue.getText(), toBoundingBox(fieldValue.getBoundingBox()), fieldValue.getPage() == null ? -1 : fieldValue.getPage(), setReferenceElements(fieldValue.getElements(), readResults)); } return setFormField(null, valueData, fieldValue, readResults); }) .collect(Collectors.toList()); }
if (ARRAY != fieldValue.getType()) {
private static List<FormField> toFieldValueArray(List<FieldValue> valueArray, List<ReadResult> readResults) { return valueArray.stream() .map(fieldValue -> { FieldData valueData = null; if (ARRAY != fieldValue.getType()) { valueData = new FieldData(fieldValue.getText(), toBoundingBox(fieldValue.getBoundingBox()), fieldValue.getPage() == null ? 1 : fieldValue.getPage(), setReferenceElements(fieldValue.getElements(), readResults)); } return setFormField(null, valueData, fieldValue, readResults); }) .collect(Collectors.toList()); }
class Transforms { private static final ClientLogger LOGGER = new ClientLogger(Transforms.class); private static final Pattern NON_DIGIT_PATTERN = Pattern.compile("[^0-9]+"); private static final float DEFAULT_CONFIDENCE_VALUE = 1.0f; private static final int DEFAULT_TABLE_SPAN = 1; private Transforms() { } /** * Helper method to transform the service returned {@link AnalyzeResult} to SDK model {@link RecognizedForm}. * * @param analyzeResult The service returned result for analyze custom forms. * @param includeFieldElements Boolean to indicate if to set reference elements data on fields. * * @return The List of {@code RecognizedForm}. */ static List<RecognizedForm> toRecognizedForm(AnalyzeResult analyzeResult, boolean includeFieldElements) { List<ReadResult> readResults = analyzeResult.getReadResults(); List<DocumentResult> documentResults = analyzeResult.getDocumentResults(); List<PageResult> pageResults = analyzeResult.getPageResults(); List<RecognizedForm> extractedFormList; List<FormPage> formPages = toRecognizedLayout(analyzeResult, includeFieldElements); if (!CoreUtils.isNullOrEmpty(documentResults)) { extractedFormList = new ArrayList<>(); for (DocumentResult documentResultItem : documentResults) { FormPageRange formPageRange; List<Integer> documentPageRange = documentResultItem.getPageRange(); if (documentPageRange.size() == 2) { formPageRange = new FormPageRange(documentPageRange.get(0), documentPageRange.get(1)); } else { formPageRange = new FormPageRange(1, 1); } Map<String, FormField> extractedFieldMap = getLabeledFieldMap(documentResultItem, readResults); extractedFormList.add(new RecognizedForm( extractedFieldMap, documentResultItem.getDocType(), formPageRange, formPages.subList(formPageRange.getFirstPageNumber() - 1, formPageRange.getLastPageNumber()))); } } else { extractedFormList = new ArrayList<>(); forEachWithIndex(pageResults, ((index, pageResultItem) -> { StringBuilder formType = new StringBuilder("form-"); int pageNumber = pageResultItem.getPage(); Integer clusterId = pageResultItem.getClusterId(); if (clusterId != null) { formType.append(clusterId); } Map<String, FormField> extractedFieldMap = getUnlabeledFieldMap(includeFieldElements, readResults, pageResultItem, pageNumber); extractedFormList.add(new RecognizedForm( extractedFieldMap, formType.toString(), new FormPageRange(pageNumber, pageNumber), Collections.singletonList(formPages.get(index)))); })); } return extractedFormList; } /** * Helper method to transform the service returned {@link AnalyzeResult} to SDK model {@link FormPage}. * * @param analyzeResult The service returned result for analyze layouts. * @param includeFieldElements Boolean to indicate if to set reference elements data on fields. * * @return The List of {@code FormPage}. */ static List<FormPage> toRecognizedLayout(AnalyzeResult analyzeResult, boolean includeFieldElements) { List<ReadResult> readResults = analyzeResult.getReadResults(); List<PageResult> pageResults = analyzeResult.getPageResults(); List<FormPage> formPages = new ArrayList<>(); boolean pageResultsIsNullOrEmpty = CoreUtils.isNullOrEmpty(pageResults); forEachWithIndex(readResults, ((index, readResultItem) -> { List<FormTable> perPageTableList = new ArrayList<>(); if (!pageResultsIsNullOrEmpty) { PageResult pageResultItem = pageResults.get(index); perPageTableList = getPageTables(pageResultItem, readResults, pageResultItem.getPage()); } List<FormLine> perPageFormLineList = new ArrayList<>(); if (includeFieldElements && !CoreUtils.isNullOrEmpty(readResultItem.getLines())) { perPageFormLineList = getReadResultFormLines(readResultItem); } formPages.add(getFormPage(readResultItem, perPageTableList, perPageFormLineList)); })); return formPages; } /** * Helper method to get per-page table information. * * @param pageResultItem The extracted page level information returned by the service. * @param readResults The text extraction result returned by the service. * @param pageNumber The 1 based page number on which these fields exist. * * @return The list of per page {@code FormTable}. */ static List<FormTable> getPageTables(PageResult pageResultItem, List<ReadResult> readResults, int pageNumber) { return pageResultItem.getTables().stream() .map(dataTable -> new FormTable(dataTable.getRows(), dataTable.getColumns(), dataTable.getCells() .stream() .map(dataTableCell -> new FormTableCell( dataTableCell.getRowIndex(), dataTableCell.getColumnIndex(), dataTableCell.getRowSpan() == null ? DEFAULT_TABLE_SPAN : dataTableCell.getRowSpan(), dataTableCell.getColumnSpan() == null ? DEFAULT_TABLE_SPAN : dataTableCell.getColumnSpan(), dataTableCell.getText(), toBoundingBox(dataTableCell.getBoundingBox()), dataTableCell.getConfidence(), dataTableCell.isHeader() == null ? false : dataTableCell.isHeader(), dataTableCell.isFooter() == null ? false : dataTableCell.isFooter(), pageNumber, setReferenceElements(dataTableCell.getElements(), readResults))) .collect(Collectors.toList()), pageNumber)) .collect(Collectors.toList()); } /** * Helper method to convert the per page {@link ReadResult} item to {@link FormLine}. * * @param readResultItem The per page text extraction item result returned by the service. * * @return The list of {@code FormLine}. */ static List<FormLine> getReadResultFormLines(ReadResult readResultItem) { return readResultItem.getLines().stream() .map(textLine -> new FormLine( textLine.getText(), toBoundingBox(textLine.getBoundingBox()), readResultItem.getPage(), toWords(textLine.getWords(), readResultItem.getPage()))) .collect(Collectors.toList()); } /** * The field map returned on analyze with an unlabeled model id. * * @param documentResultItem The extracted document level information. * @param readResults The text extraction result returned by the service. * @return The {@link RecognizedForm */ private static Map<String, FormField> getLabeledFieldMap(DocumentResult documentResultItem, List<ReadResult> readResults) { Map<String, FormField> recognizedFieldMap = new LinkedHashMap<>(); if (!CoreUtils.isNullOrEmpty(documentResultItem.getFields())) { documentResultItem.getFields().forEach((key, fieldValue) -> { if (fieldValue != null) { List<FormElement> formElementList = setReferenceElements(fieldValue.getElements(), readResults); FieldData valueData; if ("ReceiptType".equals(key) || ARRAY == fieldValue.getType()) { valueData = null; } else { valueData = new FieldData(fieldValue.getText(), toBoundingBox(fieldValue.getBoundingBox()), fieldValue.getPage(), formElementList); } recognizedFieldMap.put(key, setFormField(key, valueData, fieldValue, readResults)); } else { recognizedFieldMap.put(key, new FormField(key, null, null, null, DEFAULT_CONFIDENCE_VALUE)); } }); } return recognizedFieldMap; } /** * Helper method that converts the incoming service field value to one of the strongly typed SDK level * {@link FormField} with reference elements set when {@code includeFieldElements} is set to true. * * @param name The name of the field. * @param fieldValue The named field values returned by the service. * @param valueData The value text of the field. * @param readResults The text extraction result returned by the service. * * @return The strongly typed {@link FormField} for the field input. */ private static FormField setFormField(String name, FieldData valueData, FieldValue fieldValue, List<ReadResult> readResults) { com.azure.ai.formrecognizer.models.FieldValue value; switch (fieldValue.getType()) { case PHONE_NUMBER: value = new com.azure.ai.formrecognizer.models.FieldValue(fieldValue.getValuePhoneNumber(), FieldValueType.PHONE_NUMBER); break; case STRING: value = new com.azure.ai.formrecognizer.models.FieldValue(fieldValue.getValueString(), FieldValueType.STRING); break; case TIME: LocalTime fieldTime = fieldValue.getValueTime() == null ? null : LocalTime .parse(fieldValue.getValueTime(), DateTimeFormatter.ofPattern("HH:mm:ss")); value = new com.azure.ai.formrecognizer.models.FieldValue(fieldTime, FieldValueType.TIME); break; case DATE: value = new com.azure.ai.formrecognizer.models.FieldValue(fieldValue.getValueDate(), FieldValueType.DATE); break; case INTEGER: com.azure.ai.formrecognizer.models.FieldValue longFieldValue; if (fieldValue.getValueInteger() == null) { longFieldValue = new com.azure.ai.formrecognizer.models.FieldValue(null, FieldValueType.LONG); } else { longFieldValue = new com.azure.ai.formrecognizer.models.FieldValue(fieldValue.getValueInteger().longValue(), FieldValueType.LONG); } value = longFieldValue; break; case NUMBER: value = new com.azure.ai.formrecognizer.models.FieldValue(fieldValue.getValueNumber(), FieldValueType.FLOAT); break; case ARRAY: value = new com.azure.ai.formrecognizer.models.FieldValue( toFieldValueArray(fieldValue.getValueArray(), readResults), FieldValueType.LIST); break; case OBJECT: value = new com.azure.ai.formrecognizer.models.FieldValue( toFieldValueObject(fieldValue.getValueObject(), readResults), FieldValueType.MAP); break; default: throw LOGGER.logExceptionAsError(new RuntimeException("FieldValue Type not supported")); } return new FormField(name, null, valueData, value, setDefaultConfidenceValue(fieldValue.getConfidence())); } /** * Helper method to set default confidence value if confidence returned by service is null. * * @param confidence the confidence returned by service. * * @return the field confidence value. */ private static float setDefaultConfidenceValue(Float confidence) { return confidence == null ? DEFAULT_CONFIDENCE_VALUE : confidence; } /** * Helper method to convert the service returned * {@link com.azure.ai.formrecognizer.implementation.models.FieldValue * to a SDK level map of {@link FormField}. * * @param valueObject The array of field values returned by the service in {@link FieldValue * * @return The Map of {@link FormField}. */ private static Map<String, FormField> toFieldValueObject(Map<String, FieldValue> valueObject, List<ReadResult> readResults) { Map<String, FormField> fieldValueObjectMap = new TreeMap<>(); valueObject.forEach((key, fieldValue) -> fieldValueObjectMap.put(key, setFormField(key, new FieldData(fieldValue.getText(), toBoundingBox(fieldValue.getBoundingBox()), fieldValue.getPage(), setReferenceElements(fieldValue.getElements(), readResults)), fieldValue, readResults) )); return fieldValueObjectMap; } /** * Helper method to convert the service returned * {@link com.azure.ai.formrecognizer.implementation.models.FieldValue * to a SDK level List of {@link FormField}. * * @param valueArray The array of field values returned by the service in {@link FieldValue * @param readResults The text extraction result returned by the service. * * @return The List of {@link FormField}. */ /** * Helper method to convert the page results to {@code FormPage form pages}. * * @param readResultItem The per page text extraction item result returned by the service. * @param perPageTableList The per page tables list. * @param perPageLineList The per page form lines. * * @return The per page {@code FormPage}. */ private static FormPage getFormPage(ReadResult readResultItem, List<FormTable> perPageTableList, List<FormLine> perPageLineList) { return new FormPage( readResultItem.getHeight(), readResultItem.getAngle(), LengthUnit.fromString(readResultItem.getUnit().toString()), readResultItem.getWidth(), perPageLineList, perPageTableList, readResultItem.getPage()); } /** * Helper method to set the {@link RecognizedForm * service. * * @param includeFieldElements Boolean to indicate if to set reference elements data on fields. * @param readResults The text extraction result returned by the service. * @param pageResultItem The extracted page level information returned by the service. * @param pageNumber The 1 based page number on which these fields exist. * * @return The fields populated on {@link RecognizedForm */ private static Map<String, FormField> getUnlabeledFieldMap(boolean includeFieldElements, List<ReadResult> readResults, PageResult pageResultItem, int pageNumber) { Map<String, FormField> formFieldMap = new LinkedHashMap<>(); List<KeyValuePair> keyValuePairs = pageResultItem.getKeyValuePairs(); forEachWithIndex(keyValuePairs, ((index, keyValuePair) -> { List<FormElement> formKeyContentList = null; List<FormElement> formValueContentList = null; if (includeFieldElements) { formKeyContentList = setReferenceElements(keyValuePair.getKey().getElements(), readResults); formValueContentList = setReferenceElements(keyValuePair.getValue().getElements(), readResults ); } FieldData labelData = new FieldData(keyValuePair.getKey().getText(), toBoundingBox(keyValuePair.getKey().getBoundingBox()), pageNumber, formKeyContentList); FieldData valueData = new FieldData(keyValuePair.getValue().getText(), toBoundingBox(keyValuePair.getValue().getBoundingBox()), pageNumber, formValueContentList); String fieldName = "field-" + index; FormField formField = new FormField(fieldName, labelData, valueData, new com.azure.ai.formrecognizer.models.FieldValue(keyValuePair.getValue().getText(), FieldValueType.STRING), setDefaultConfidenceValue(keyValuePair.getConfidence()) ); formFieldMap.put(fieldName, formField); })); return formFieldMap; } /** * Helper method to set the text reference elements on FieldValue/fields when {@code includeFieldElements} set to * true. * * @return The list if referenced elements. */ private static List<FormElement> setReferenceElements(List<String> elements, List<ReadResult> readResults) { if (CoreUtils.isNullOrEmpty(elements)) { return new ArrayList<>(); } List<FormElement> formElementList = new ArrayList<>(); elements.forEach(elementString -> { String[] indices = NON_DIGIT_PATTERN.matcher(elementString).replaceAll(" ").trim().split(" "); if (indices.length < 2) { throw LOGGER.logExceptionAsError(new RuntimeException("Cannot find corresponding reference elements " + "for the field value.")); } int readResultIndex = Integer.parseInt(indices[0]); int lineIndex = Integer.parseInt(indices[1]); if (indices.length == 3) { int wordIndex = Integer.parseInt(indices[2]); TextWord textWord = readResults.get(readResultIndex).getLines().get(lineIndex).getWords().get(wordIndex); FormWord wordElement = new FormWord(textWord.getText(), toBoundingBox(textWord.getBoundingBox()), readResultIndex + 1, setDefaultConfidenceValue(textWord.getConfidence())); formElementList.add(wordElement); } else { TextLine textLine = readResults.get(readResultIndex).getLines().get(lineIndex); FormLine lineElement = new FormLine(textLine.getText(), toBoundingBox(textLine.getBoundingBox()), readResultIndex + 1, toWords(textLine.getWords(), readResultIndex + 1)); formElementList.add(lineElement); } }); return formElementList; } /** * Helper method to convert the service level {@link TextWord} to list of SDK level model {@link FormWord}. * * @param words A list of word reference elements returned by the service. * @param pageNumber The 1 based page number on which this word element exists. * * @return The list of {@code FormWord words}. */ private static List<FormWord> toWords(List<TextWord> words, int pageNumber) { return words.stream() .map(textWord -> new FormWord( textWord.getText(), toBoundingBox(textWord.getBoundingBox()), pageNumber, setDefaultConfidenceValue(textWord.getConfidence())) ).collect(Collectors.toList()); } /** * Helper method to convert the service level modeled eight numbers representing the four points to SDK level * {@link FieldBoundingBox}. * * @param serviceBoundingBox A list of eight numbers representing the four points of a box. * * @return A {@link FieldBoundingBox}. */ private static FieldBoundingBox toBoundingBox(List<Float> serviceBoundingBox) { if (CoreUtils.isNullOrEmpty(serviceBoundingBox) || (serviceBoundingBox.size() % 2) != 0) { return null; } List<Point> pointList = new ArrayList<>(); for (int i = 0; i < serviceBoundingBox.size(); i++) { pointList.add(new Point(serviceBoundingBox.get(i), serviceBoundingBox.get(++i))); } return new FieldBoundingBox(pointList); } }
class Transforms { private static final ClientLogger LOGGER = new ClientLogger(Transforms.class); private static final Pattern NON_DIGIT_PATTERN = Pattern.compile("[^0-9]+"); private static final float DEFAULT_CONFIDENCE_VALUE = 1.0f; private static final int DEFAULT_TABLE_SPAN = 1; private Transforms() { } /** * Helper method to transform the service returned {@link AnalyzeResult} to SDK model {@link RecognizedForm}. * * @param analyzeResult The service returned result for analyze custom forms. * @param includeFieldElements Boolean to indicate if to set reference elements data on fields. * * @param modelId the unlabeled model Id used for recognition. * @return The List of {@code RecognizedForm}. */ static List<RecognizedForm> toRecognizedForm(AnalyzeResult analyzeResult, boolean includeFieldElements, String modelId) { List<ReadResult> readResults = analyzeResult.getReadResults(); List<DocumentResult> documentResults = analyzeResult.getDocumentResults(); List<PageResult> pageResults = analyzeResult.getPageResults(); List<RecognizedForm> extractedFormList; List<FormPage> formPages = toRecognizedLayout(analyzeResult, includeFieldElements); if (!CoreUtils.isNullOrEmpty(documentResults)) { extractedFormList = new ArrayList<>(); for (DocumentResult documentResultItem : documentResults) { FormPageRange formPageRange; List<Integer> documentPageRange = documentResultItem.getPageRange(); if (documentPageRange.size() == 2) { formPageRange = new FormPageRange(documentPageRange.get(0), documentPageRange.get(1)); } else { formPageRange = new FormPageRange(1, 1); } Map<String, FormField> extractedFieldMap = getLabeledFieldMap(documentResultItem, readResults); final RecognizedForm recognizedForm = new RecognizedForm( extractedFieldMap, documentResultItem.getDocType(), formPageRange, formPages.subList(formPageRange.getFirstPageNumber() - 1, formPageRange.getLastPageNumber())); PrivateFieldAccessHelper.set(recognizedForm, "formTypeConfidence", documentResultItem.getDocTypeConfidence()); if (documentResultItem.getModelId() != null) { PrivateFieldAccessHelper.set(recognizedForm, "modelId", documentResultItem.getModelId().toString()); } extractedFormList.add(recognizedForm); } } else { extractedFormList = new ArrayList<>(); forEachWithIndex(pageResults, ((index, pageResultItem) -> { StringBuilder formType = new StringBuilder("form-"); int pageNumber = pageResultItem.getPage(); Integer clusterId = pageResultItem.getClusterId(); if (clusterId != null) { formType.append(clusterId); } Map<String, FormField> extractedFieldMap = getUnlabeledFieldMap(includeFieldElements, readResults, pageResultItem, pageNumber); final RecognizedForm recognizedForm = new RecognizedForm( extractedFieldMap, formType.toString(), new FormPageRange(pageNumber, pageNumber), Collections.singletonList(formPages.get(index))); PrivateFieldAccessHelper.set(recognizedForm, "modelId", modelId); extractedFormList.add(recognizedForm); })); } return extractedFormList; } /** * Helper method to transform the service returned {@link AnalyzeResult} to SDK model {@link FormPage}. * * @param analyzeResult The service returned result for analyze layouts. * @param includeFieldElements Boolean to indicate if to set reference elements data on fields. * * @return The List of {@code FormPage}. */ static List<FormPage> toRecognizedLayout(AnalyzeResult analyzeResult, boolean includeFieldElements) { List<ReadResult> readResults = analyzeResult.getReadResults(); List<PageResult> pageResults = analyzeResult.getPageResults(); List<FormPage> formPages = new ArrayList<>(); boolean pageResultsIsNullOrEmpty = CoreUtils.isNullOrEmpty(pageResults); forEachWithIndex(readResults, ((index, readResultItem) -> { List<FormTable> perPageTableList = new ArrayList<>(); if (!pageResultsIsNullOrEmpty) { PageResult pageResultItem = pageResults.get(index); perPageTableList = getPageTables(pageResultItem, readResults, pageResultItem.getPage()); } List<FormLine> perPageFormLineList = new ArrayList<>(); if (includeFieldElements && !CoreUtils.isNullOrEmpty(readResultItem.getLines())) { perPageFormLineList = getReadResultFormLines(readResultItem); } formPages.add(getFormPage(readResultItem, perPageTableList, perPageFormLineList)); })); return formPages; } /** * Helper method to get per-page table information. * * @param pageResultItem The extracted page level information returned by the service. * @param readResults The text extraction result returned by the service. * @param pageNumber The 1 based page number on which these fields exist. * * @return The list of per page {@code FormTable}. */ static List<FormTable> getPageTables(PageResult pageResultItem, List<ReadResult> readResults, int pageNumber) { return pageResultItem.getTables().stream() .map(dataTable -> new FormTable(dataTable.getRows(), dataTable.getColumns(), dataTable.getCells() .stream() .map(dataTableCell -> new FormTableCell( dataTableCell.getRowIndex(), dataTableCell.getColumnIndex(), dataTableCell.getRowSpan() == null ? DEFAULT_TABLE_SPAN : dataTableCell.getRowSpan(), dataTableCell.getColumnSpan() == null ? DEFAULT_TABLE_SPAN : dataTableCell.getColumnSpan(), dataTableCell.getText(), toBoundingBox(dataTableCell.getBoundingBox()), dataTableCell.getConfidence(), dataTableCell.isHeader() == null ? false : dataTableCell.isHeader(), dataTableCell.isFooter() == null ? false : dataTableCell.isFooter(), pageNumber, setReferenceElements(dataTableCell.getElements(), readResults))) .collect(Collectors.toList()), pageNumber)) .collect(Collectors.toList()); } /** * Helper method to convert the per page {@link ReadResult} item to {@link FormLine}. * * @param readResultItem The per page text extraction item result returned by the service. * * @return The list of {@code FormLine}. */ static List<FormLine> getReadResultFormLines(ReadResult readResultItem) { return readResultItem.getLines().stream() .map(textLine -> new FormLine( textLine.getText(), toBoundingBox(textLine.getBoundingBox()), readResultItem.getPage(), toWords(textLine.getWords(), readResultItem.getPage()))) .collect(Collectors.toList()); } /** * The field map returned on analyze with an unlabeled model id. * * @param documentResultItem The extracted document level information. * @param readResults The text extraction result returned by the service. * @return The {@link RecognizedForm */ private static Map<String, FormField> getLabeledFieldMap(DocumentResult documentResultItem, List<ReadResult> readResults) { Map<String, FormField> recognizedFieldMap = new LinkedHashMap<>(); if (!CoreUtils.isNullOrEmpty(documentResultItem.getFields())) { documentResultItem.getFields().forEach((key, fieldValue) -> { if (fieldValue != null) { List<FormElement> formElementList = setReferenceElements(fieldValue.getElements(), readResults); FieldData valueData; if ("ReceiptType".equals(key) || ARRAY == fieldValue.getType()) { valueData = null; } else { valueData = new FieldData(fieldValue.getText(), toBoundingBox(fieldValue.getBoundingBox()), fieldValue.getPage(), formElementList); } recognizedFieldMap.put(key, setFormField(key, valueData, fieldValue, readResults)); } else { recognizedFieldMap.put(key, new FormField(key, null, null, null, DEFAULT_CONFIDENCE_VALUE)); } }); } return recognizedFieldMap; } /** * Helper method that converts the incoming service field value to one of the strongly typed SDK level * {@link FormField} with reference elements set when {@code includeFieldElements} is set to true. * * @param name The name of the field. * @param fieldValue The named field values returned by the service. * @param valueData The value text of the field. * @param readResults The text extraction result returned by the service. * * @return The strongly typed {@link FormField} for the field input. */ private static FormField setFormField(String name, FieldData valueData, FieldValue fieldValue, List<ReadResult> readResults) { com.azure.ai.formrecognizer.models.FieldValue value; switch (fieldValue.getType()) { case PHONE_NUMBER: value = new com.azure.ai.formrecognizer.models.FieldValue(fieldValue.getValuePhoneNumber(), FieldValueType.PHONE_NUMBER); break; case STRING: value = new com.azure.ai.formrecognizer.models.FieldValue(fieldValue.getValueString(), FieldValueType.STRING); break; case TIME: LocalTime fieldTime = fieldValue.getValueTime() == null ? null : LocalTime .parse(fieldValue.getValueTime(), DateTimeFormatter.ofPattern("HH:mm:ss")); value = new com.azure.ai.formrecognizer.models.FieldValue(fieldTime, FieldValueType.TIME); break; case DATE: value = new com.azure.ai.formrecognizer.models.FieldValue(fieldValue.getValueDate(), FieldValueType.DATE); break; case INTEGER: com.azure.ai.formrecognizer.models.FieldValue longFieldValue; if (fieldValue.getValueInteger() == null) { longFieldValue = new com.azure.ai.formrecognizer.models.FieldValue(null, FieldValueType.LONG); } else { longFieldValue = new com.azure.ai.formrecognizer.models.FieldValue(fieldValue.getValueInteger().longValue(), FieldValueType.LONG); } value = longFieldValue; break; case NUMBER: value = new com.azure.ai.formrecognizer.models.FieldValue(fieldValue.getValueNumber(), FieldValueType.FLOAT); break; case ARRAY: value = new com.azure.ai.formrecognizer.models.FieldValue( toFieldValueArray(fieldValue.getValueArray(), readResults), FieldValueType.LIST); break; case OBJECT: value = new com.azure.ai.formrecognizer.models.FieldValue( toFieldValueObject(fieldValue.getValueObject(), readResults), FieldValueType.MAP); break; default: throw LOGGER.logExceptionAsError(new RuntimeException("FieldValue Type not supported")); } return new FormField(name, null, valueData, value, setDefaultConfidenceValue(fieldValue.getConfidence())); } /** * Helper method to set default confidence value if confidence returned by service is null. * * @param confidence the confidence returned by service. * * @return the field confidence value. */ private static float setDefaultConfidenceValue(Float confidence) { return confidence == null ? DEFAULT_CONFIDENCE_VALUE : confidence; } /** * Helper method to convert the service returned * {@link com.azure.ai.formrecognizer.implementation.models.FieldValue * to a SDK level map of {@link FormField}. * * @param valueObject The array of field values returned by the service in {@link FieldValue * * @return The Map of {@link FormField}. */ private static Map<String, FormField> toFieldValueObject(Map<String, FieldValue> valueObject, List<ReadResult> readResults) { Map<String, FormField> fieldValueObjectMap = new TreeMap<>(); valueObject.forEach((key, fieldValue) -> fieldValueObjectMap.put(key, setFormField(key, new FieldData(fieldValue.getText(), toBoundingBox(fieldValue.getBoundingBox()), fieldValue.getPage(), setReferenceElements(fieldValue.getElements(), readResults)), fieldValue, readResults) )); return fieldValueObjectMap; } /** * Helper method to convert the service returned * {@link com.azure.ai.formrecognizer.implementation.models.FieldValue * to a SDK level List of {@link FormField}. * * @param valueArray The array of field values returned by the service in {@link FieldValue * @param readResults The text extraction result returned by the service. * * @return The List of {@link FormField}. */ /** * Helper method to convert the page results to {@code FormPage form pages}. * * @param readResultItem The per page text extraction item result returned by the service. * @param perPageTableList The per page tables list. * @param perPageLineList The per page form lines. * * @return The per page {@code FormPage}. */ private static FormPage getFormPage(ReadResult readResultItem, List<FormTable> perPageTableList, List<FormLine> perPageLineList) { return new FormPage( readResultItem.getHeight(), readResultItem.getAngle(), LengthUnit.fromString(readResultItem.getUnit().toString()), readResultItem.getWidth(), perPageLineList, perPageTableList, readResultItem.getPage()); } /** * Helper method to set the {@link RecognizedForm * service. * * @param includeFieldElements Boolean to indicate if to set reference elements data on fields. * @param readResults The text extraction result returned by the service. * @param pageResultItem The extracted page level information returned by the service. * @param pageNumber The 1 based page number on which these fields exist. * * @return The fields populated on {@link RecognizedForm */ private static Map<String, FormField> getUnlabeledFieldMap(boolean includeFieldElements, List<ReadResult> readResults, PageResult pageResultItem, int pageNumber) { Map<String, FormField> formFieldMap = new LinkedHashMap<>(); List<KeyValuePair> keyValuePairs = pageResultItem.getKeyValuePairs(); forEachWithIndex(keyValuePairs, ((index, keyValuePair) -> { List<FormElement> formKeyContentList = null; List<FormElement> formValueContentList = null; if (includeFieldElements) { formKeyContentList = setReferenceElements(keyValuePair.getKey().getElements(), readResults); formValueContentList = setReferenceElements(keyValuePair.getValue().getElements(), readResults ); } FieldData labelData = new FieldData(keyValuePair.getKey().getText(), toBoundingBox(keyValuePair.getKey().getBoundingBox()), pageNumber, formKeyContentList); FieldData valueData = new FieldData(keyValuePair.getValue().getText(), toBoundingBox(keyValuePair.getValue().getBoundingBox()), pageNumber, formValueContentList); String fieldName = "field-" + index; FormField formField = new FormField(fieldName, labelData, valueData, new com.azure.ai.formrecognizer.models.FieldValue(keyValuePair.getValue().getText(), FieldValueType.STRING), setDefaultConfidenceValue(keyValuePair.getConfidence()) ); formFieldMap.put(fieldName, formField); })); return formFieldMap; } /** * Helper method to set the text reference elements on FieldValue/fields when {@code includeFieldElements} set to * true. * * @return The list if referenced elements. */ private static List<FormElement> setReferenceElements(List<String> elements, List<ReadResult> readResults) { if (CoreUtils.isNullOrEmpty(elements)) { return new ArrayList<>(); } List<FormElement> formElementList = new ArrayList<>(); elements.forEach(elementString -> { String[] indices = NON_DIGIT_PATTERN.matcher(elementString).replaceAll(" ").trim().split(" "); if (indices.length < 2) { throw LOGGER.logExceptionAsError(new RuntimeException("Cannot find corresponding reference elements " + "for the field value.")); } int readResultIndex = Integer.parseInt(indices[0]); int lineIndex = Integer.parseInt(indices[1]); if (indices.length == 3) { int wordIndex = Integer.parseInt(indices[2]); TextWord textWord = readResults.get(readResultIndex).getLines().get(lineIndex).getWords().get(wordIndex); FormWord wordElement = new FormWord(textWord.getText(), toBoundingBox(textWord.getBoundingBox()), readResultIndex + 1, setDefaultConfidenceValue(textWord.getConfidence())); formElementList.add(wordElement); } else { TextLine textLine = readResults.get(readResultIndex).getLines().get(lineIndex); FormLine lineElement = new FormLine(textLine.getText(), toBoundingBox(textLine.getBoundingBox()), readResultIndex + 1, toWords(textLine.getWords(), readResultIndex + 1)); formElementList.add(lineElement); } }); return formElementList; } /** * Helper method to convert the service level {@link TextWord} to list of SDK level model {@link FormWord}. * * @param words A list of word reference elements returned by the service. * @param pageNumber The 1 based page number on which this word element exists. * * @return The list of {@code FormWord words}. */ private static List<FormWord> toWords(List<TextWord> words, int pageNumber) { return words.stream() .map(textWord -> new FormWord( textWord.getText(), toBoundingBox(textWord.getBoundingBox()), pageNumber, setDefaultConfidenceValue(textWord.getConfidence())) ).collect(Collectors.toList()); } /** * Helper method to convert the service level modeled eight numbers representing the four points to SDK level * {@link FieldBoundingBox}. * * @param serviceBoundingBox A list of eight numbers representing the four points of a box. * * @return A {@link FieldBoundingBox}. */ private static FieldBoundingBox toBoundingBox(List<Float> serviceBoundingBox) { if (CoreUtils.isNullOrEmpty(serviceBoundingBox) || (serviceBoundingBox.size() % 2) != 0) { return null; } List<Point> pointList = new ArrayList<>(); for (int i = 0; i < serviceBoundingBox.size(); i++) { pointList.add(new Point(serviceBoundingBox.get(i), serviceBoundingBox.get(++i))); } return new FieldBoundingBox(pointList); } }
Should this be `firstName.getConfidence()` ? Same comment for all samples/docsnippets.
public void beginRecognizeBusinessCardsFromUrl() { String businessCardUrl = "{business_card_url}"; formRecognizerClient.beginRecognizeBusinessCardsFromUrl(businessCardUrl) .getFinalResult() .forEach(recognizedBusinessCard -> { Map<String, FormField> recognizedFields = recognizedBusinessCard.getFields(); FormField contactNames = recognizedFields.get("ContactNames"); if (contactNames != null) { if (FieldValueType.LIST == contactNames.getValue().getValueType()) { List<FormField> businessCardItems = contactNames.getValue().asList(); businessCardItems.stream() .filter(businessCardItem -> FieldValueType.MAP == businessCardItem.getValue() .getValueType()) .map(formField -> formField.getValue().asMap()) .forEach(formFieldMap -> formFieldMap.forEach((key, formField) -> { if ("FirstName".equals(key)) { if (FieldValueType.STRING == formField.getValue().getValueType()) { String firstName = formField.getValue().asString(); System.out.printf("First Name: %s, confidence: %.2f%n", firstName, contactNames.getConfidence()); } } if ("LastName".equals(key)) { if (FieldValueType.STRING == formField.getValue().getValueType()) { String lastName = formField.getValue().asString(); System.out.printf("Last Name: %s, confidence: %.2f%n", lastName, contactNames.getConfidence()); } } })); } } FormField jobTitles = recognizedFields.get("JobTitles"); if (jobTitles != null) { if (FieldValueType.LIST == jobTitles.getValue().getValueType()) { List<FormField> jobTitlesItems = jobTitles.getValue().asList(); jobTitlesItems.stream().forEach(formField -> { if (FieldValueType.STRING == formField.getValue().getValueType()) { String jobTitle = formField.getValue().asString(); System.out.printf("Job Title: %s, confidence: %.2f%n", jobTitle, jobTitles.getConfidence()); } }); } } }); }
firstName, contactNames.getConfidence());
public void beginRecognizeBusinessCardsFromUrl() { String businessCardUrl = "{business_card_url}"; formRecognizerClient.beginRecognizeBusinessCardsFromUrl(businessCardUrl) .getFinalResult() .forEach(recognizedBusinessCard -> { Map<String, FormField> recognizedFields = recognizedBusinessCard.getFields(); FormField contactNamesFormField = recognizedFields.get("ContactNames"); if (contactNamesFormField != null) { if (FieldValueType.LIST == contactNamesFormField.getValue().getValueType()) { List<FormField> contactNamesList = contactNamesFormField.getValue().asList(); contactNamesList.stream() .filter(contactName -> FieldValueType.MAP == contactName.getValue().getValueType()) .map(contactName -> { System.out.printf("Contact name: %s%n", contactName.getValueData().getText()); return contactName.getValue().asMap(); }) .forEach(contactNamesMap -> contactNamesMap.forEach((key, contactName) -> { if ("FirstName".equals(key)) { if (FieldValueType.STRING == contactName.getValue().getValueType()) { String firstName = contactName.getValue().asString(); System.out.printf("\tFirst Name: %s, confidence: %.2f%n", firstName, contactName.getConfidence()); } } if ("LastName".equals(key)) { if (FieldValueType.STRING == contactName.getValue().getValueType()) { String lastName = contactName.getValue().asString(); System.out.printf("\tLast Name: %s, confidence: %.2f%n", lastName, contactName.getConfidence()); } } })); } } FormField jobTitles = recognizedFields.get("JobTitles"); if (jobTitles != null) { if (FieldValueType.LIST == jobTitles.getValue().getValueType()) { List<FormField> jobTitlesItems = jobTitles.getValue().asList(); jobTitlesItems.stream().forEach(jobTitlesItem -> { if (FieldValueType.STRING == jobTitlesItem.getValue().getValueType()) { String jobTitle = jobTitlesItem.getValue().asString(); System.out.printf("Job Title: %s, confidence: %.2f%n", jobTitle, jobTitlesItem.getConfidence()); } }); } } }); }
class FormRecognizerClientJavaDocCodeSnippets { private FormRecognizerClient formRecognizerClient = new FormRecognizerClientBuilder().buildClient(); /** * Code snippet for creating a {@link FormRecognizerClient} */ public void createFormRecognizerClient() { FormRecognizerClient formRecognizerClient = new FormRecognizerClientBuilder() .credential(new AzureKeyCredential("{key}")) .endpoint("{endpoint}") .buildClient(); } /** * Code snippet for creating a {@link FormRecognizerClient} with pipeline */ public void createFormRecognizerClientWithPipeline() { HttpPipeline pipeline = new HttpPipelineBuilder() .policies(/* add policies */) .build(); FormRecognizerClient formRecognizerClient = new FormRecognizerClientBuilder() .credential(new AzureKeyCredential("{key}")) .endpoint("{endpoint}") .pipeline(pipeline) .buildClient(); } /** * Code snippet for {@link FormRecognizerClient */ public void beginRecognizeCustomFormsFromUrl() { String formUrl = "{form_url}"; String modelId = "{custom_trained_model_id}"; formRecognizerClient.beginRecognizeCustomFormsFromUrl(modelId, formUrl).getFinalResult() .stream() .map(RecognizedForm::getFields) .forEach(formFieldMap -> formFieldMap.forEach((fieldText, formField) -> { System.out.printf("Field text: %s%n", fieldText); System.out.printf("Field value data text: %s%n", formField.getValueData().getText()); System.out.printf("Confidence score: %.2f%n", formField.getConfidence()); })); } /** * Code snippet for {@link FormRecognizerClient */ public void beginRecognizeCustomFormsFromUrlWithOptions() { String analyzeFilePath = "{file_source_url}"; String modelId = "{model_id}"; boolean includeFieldElements = true; formRecognizerClient.beginRecognizeCustomFormsFromUrl(modelId, analyzeFilePath, new RecognizeCustomFormsOptions() .setFieldElementsIncluded(includeFieldElements) .setPollInterval(Duration.ofSeconds(10)), Context.NONE) .getFinalResult() .stream() .map(RecognizedForm::getFields) .forEach(formFieldMap -> formFieldMap.forEach((fieldText, formField) -> { System.out.printf("Field text: %s%n", fieldText); System.out.printf("Field value data text: %s%n", formField.getValueData().getText()); System.out.printf("Confidence score: %.2f%n", formField.getConfidence()); })); } /** * Code snippet for * {@link FormRecognizerClient * * @throws IOException Exception thrown when there is an error in reading all the bytes from the File. */ public void beginRecognizeCustomForms() throws IOException { File form = new File("{local/file_path/fileName.jpg}"); String modelId = "{custom_trained_model_id}"; byte[] fileContent = Files.readAllBytes(form.toPath()); try (InputStream targetStream = new ByteArrayInputStream(fileContent)) { formRecognizerClient.beginRecognizeCustomForms(modelId, targetStream, form.length()) .getFinalResult() .stream() .map(RecognizedForm::getFields) .forEach(formFieldMap -> formFieldMap.forEach((fieldText, formField) -> { System.out.printf("Field text: %s%n", fieldText); System.out.printf("Field value data text: %s%n", formField.getValueData().getText()); System.out.printf("Confidence score: %.2f%n", formField.getConfidence()); })); } } /** * Code snippet for * {@link FormRecognizerClient * * @throws IOException Exception thrown when there is an error in reading all the bytes from the File. */ public void beginRecognizeCustomFormsWithOptions() throws IOException { File form = new File("{local/file_path/fileName.jpg}"); String modelId = "{custom_trained_model_id}"; boolean includeFieldElements = true; byte[] fileContent = Files.readAllBytes(form.toPath()); try (InputStream targetStream = new ByteArrayInputStream(fileContent)) { formRecognizerClient.beginRecognizeCustomForms(modelId, targetStream, form.length(), new RecognizeCustomFormsOptions() .setContentType(FormContentType.IMAGE_JPEG) .setFieldElementsIncluded(includeFieldElements) .setPollInterval(Duration.ofSeconds(10)), Context.NONE) .getFinalResult() .stream() .map(RecognizedForm::getFields) .forEach(formFieldMap -> formFieldMap.forEach((fieldText, formField) -> { System.out.printf("Field text: %s%n", fieldText); System.out.printf("Field value data text: %s%n", formField.getValueData().getText()); System.out.printf("Confidence score: %.2f%n", formField.getConfidence()); })); } } /** * Code snippet for {@link FormRecognizerClient */ public void beginRecognizeContentFromUrl() { String formUrl = "{form_url}"; formRecognizerClient.beginRecognizeContentFromUrl(formUrl) .getFinalResult() .forEach(formPage -> { System.out.printf("Page Angle: %s%n", formPage.getTextAngle()); System.out.printf("Page Dimension unit: %s%n", formPage.getUnit()); System.out.println("Recognized Tables: "); formPage.getTables() .stream() .flatMap(formTable -> formTable.getCells().stream()) .forEach(recognizedTableCell -> System.out.printf("%s ", recognizedTableCell.getText())); }); } /** * Code snippet for {@link FormRecognizerClient * options. */ public void beginRecognizeContentFromUrlWithOptions() { String formPath = "{file_source_url}"; formRecognizerClient.beginRecognizeContentFromUrl(formPath, new RecognizeContentOptions() .setPollInterval(Duration.ofSeconds(5)), Context.NONE) .getFinalResult() .forEach(formPage -> { System.out.printf("Page Angle: %s%n", formPage.getTextAngle()); System.out.printf("Page Dimension unit: %s%n", formPage.getUnit()); System.out.println("Recognized Tables: "); formPage.getTables() .stream() .flatMap(formTable -> formTable.getCells().stream()) .forEach(recognizedTableCell -> System.out.printf("%s ", recognizedTableCell.getText())); }); } /** * Code snippet for {@link FormRecognizerClient * * @throws IOException Exception thrown when there is an error in reading all the bytes from the File. */ public void beginRecognizeContent() throws IOException { File form = new File("{local/file_path/fileName.pdf}"); byte[] fileContent = Files.readAllBytes(form.toPath()); try (InputStream targetStream = new ByteArrayInputStream(fileContent)) { formRecognizerClient.beginRecognizeContent(targetStream, form.length()) .getFinalResult() .forEach(formPage -> { System.out.printf("Page Angle: %s%n", formPage.getTextAngle()); System.out.printf("Page Dimension unit: %s%n", formPage.getUnit()); System.out.println("Recognized Tables: "); formPage.getTables() .stream() .flatMap(formTable -> formTable.getCells().stream()) .forEach(recognizedTableCell -> System.out.printf("%s ", recognizedTableCell.getText())); }); } } /** * Code snippet for {@link FormRecognizerClient * options. * * @throws IOException Exception thrown when there is an error in reading all the bytes from the File. */ public void beginRecognizeContentWithOptions() throws IOException { File form = new File("{file_source_url}"); byte[] fileContent = Files.readAllBytes(form.toPath()); try (InputStream targetStream = new ByteArrayInputStream(fileContent)) { for (FormPage formPage : formRecognizerClient.beginRecognizeContent(targetStream, form.length(), new RecognizeContentOptions() .setPollInterval(Duration.ofSeconds(5)), Context.NONE) .getFinalResult()) { System.out.printf("Page Angle: %s%n", formPage.getTextAngle()); System.out.printf("Page Dimension unit: %s%n", formPage.getUnit()); System.out.println("Recognized Tables: "); formPage.getTables() .stream() .flatMap(formTable -> formTable.getCells().stream()) .forEach(recognizedTableCell -> System.out.printf("%s ", recognizedTableCell.getText())); } } } /** * Code snippet for {@link FormRecognizerClient */ public void beginRecognizeReceiptsFromUrl() { String receiptUrl = "{file_source_url}"; formRecognizerClient.beginRecognizeReceiptsFromUrl(receiptUrl) .getFinalResult() .forEach(recognizedReceipt -> { Map<String, FormField> recognizedFields = recognizedReceipt.getFields(); FormField merchantNameField = recognizedFields.get("MerchantName"); if (merchantNameField != null) { if (FieldValueType.STRING == merchantNameField.getValue().getValueType()) { String merchantName = merchantNameField.getValue().asString(); System.out.printf("Merchant Name: %s, confidence: %.2f%n", merchantName, merchantNameField.getConfidence()); } } FormField merchantPhoneNumberField = recognizedFields.get("MerchantPhoneNumber"); if (merchantPhoneNumberField != null) { if (FieldValueType.PHONE_NUMBER == merchantPhoneNumberField.getValue().getValueType()) { String merchantAddress = merchantPhoneNumberField.getValue().asPhoneNumber(); System.out.printf("Merchant Phone number: %s, confidence: %.2f%n", merchantAddress, merchantPhoneNumberField.getConfidence()); } } FormField transactionDateField = recognizedFields.get("TransactionDate"); if (transactionDateField != null) { if (FieldValueType.DATE == transactionDateField.getValue().getValueType()) { LocalDate transactionDate = transactionDateField.getValue().asDate(); System.out.printf("Transaction Date: %s, confidence: %.2f%n", transactionDate, transactionDateField.getConfidence()); } } FormField receiptItemsField = recognizedFields.get("Items"); if (receiptItemsField != null) { System.out.printf("Receipt Items: %n"); if (FieldValueType.LIST == receiptItemsField.getValue().getValueType()) { List<FormField> receiptItems = receiptItemsField.getValue().asList(); receiptItems.stream() .filter(receiptItem -> FieldValueType.MAP == receiptItem.getValue().getValueType()) .map(formField -> formField.getValue().asMap()) .forEach(formFieldMap -> formFieldMap.forEach((key, formField) -> { if ("Quantity".equals(key)) { if (FieldValueType.FLOAT == formField.getValue().getValueType()) { Float quantity = formField.getValue().asFloat(); System.out.printf("Quantity: %f, confidence: %.2f%n", quantity, formField.getConfidence()); } } })); } } }); } /** * Code snippet for {@link FormRecognizerClient */ public void beginRecognizeReceiptsFromUrlWithOptions() { String receiptUrl = "{receipt_url}"; formRecognizerClient.beginRecognizeReceiptsFromUrl(receiptUrl, new RecognizeReceiptsOptions() .setPollInterval(Duration.ofSeconds(5)) .setFieldElementsIncluded(true), Context.NONE).getFinalResult() .forEach(recognizedReceipt -> { Map<String, FormField> recognizedFields = recognizedReceipt.getFields(); FormField merchantNameField = recognizedFields.get("MerchantName"); if (merchantNameField != null) { if (FieldValueType.STRING == merchantNameField.getValue().getValueType()) { String merchantName = merchantNameField.getValue().asString(); System.out.printf("Merchant Name: %s, confidence: %.2f%n", merchantName, merchantNameField.getConfidence()); } } FormField merchantPhoneNumberField = recognizedFields.get("MerchantPhoneNumber"); if (merchantPhoneNumberField != null) { if (FieldValueType.PHONE_NUMBER == merchantPhoneNumberField.getValue().getValueType()) { String merchantAddress = merchantPhoneNumberField.getValue().asPhoneNumber(); System.out.printf("Merchant Phone number: %s, confidence: %.2f%n", merchantAddress, merchantPhoneNumberField.getConfidence()); } } FormField transactionDateField = recognizedFields.get("TransactionDate"); if (transactionDateField != null) { if (FieldValueType.DATE == transactionDateField.getValue().getValueType()) { LocalDate transactionDate = transactionDateField.getValue().asDate(); System.out.printf("Transaction Date: %s, confidence: %.2f%n", transactionDate, transactionDateField.getConfidence()); } } FormField receiptItemsField = recognizedFields.get("Items"); if (receiptItemsField != null) { System.out.printf("Receipt Items: %n"); if (FieldValueType.LIST == receiptItemsField.getValue().getValueType()) { List<FormField> receiptItems = receiptItemsField.getValue().asList(); receiptItems.stream() .filter(receiptItem -> FieldValueType.MAP == receiptItem.getValue().getValueType()) .map(formField -> formField.getValue().asMap()) .forEach(formFieldMap -> formFieldMap.forEach((key, formField) -> { if ("Quantity".equals(key)) { if (FieldValueType.FLOAT == formField.getValue().getValueType()) { Float quantity = formField.getValue().asFloat(); System.out.printf("Quantity: %f, confidence: %.2f%n", quantity, formField.getConfidence()); } } })); } } }); } /** * Code snippet for {@link FormRecognizerClient * * @throws IOException Exception thrown when there is an error in reading all the bytes from the File. */ public void beginRecognizeReceipts() throws IOException { File receipt = new File("{receipt_url}"); byte[] fileContent = Files.readAllBytes(receipt.toPath()); try (InputStream targetStream = new ByteArrayInputStream(fileContent)) { formRecognizerClient.beginRecognizeReceipts(targetStream, receipt.length()).getFinalResult() .forEach(recognizedReceipt -> { Map<String, FormField> recognizedFields = recognizedReceipt.getFields(); FormField merchantNameField = recognizedFields.get("MerchantName"); if (merchantNameField != null) { if (FieldValueType.STRING == merchantNameField.getValue().getValueType()) { String merchantName = merchantNameField.getValue().asString(); System.out.printf("Merchant Name: %s, confidence: %.2f%n", merchantName, merchantNameField.getConfidence()); } } FormField merchantPhoneNumberField = recognizedFields.get("MerchantPhoneNumber"); if (merchantPhoneNumberField != null) { if (FieldValueType.PHONE_NUMBER == merchantPhoneNumberField.getValue().getValueType()) { String merchantAddress = merchantPhoneNumberField.getValue().asPhoneNumber(); System.out.printf("Merchant Phone number: %s, confidence: %.2f%n", merchantAddress, merchantPhoneNumberField.getConfidence()); } } FormField transactionDateField = recognizedFields.get("TransactionDate"); if (transactionDateField != null) { if (FieldValueType.DATE == transactionDateField.getValue().getValueType()) { LocalDate transactionDate = transactionDateField.getValue().asDate(); System.out.printf("Transaction Date: %s, confidence: %.2f%n", transactionDate, transactionDateField.getConfidence()); } } FormField receiptItemsField = recognizedFields.get("Items"); if (receiptItemsField != null) { System.out.printf("Receipt Items: %n"); if (FieldValueType.LIST == receiptItemsField.getValue().getValueType()) { List<FormField> receiptItems = receiptItemsField.getValue().asList(); receiptItems.stream() .filter(receiptItem -> FieldValueType.MAP == receiptItem.getValue().getValueType()) .map(formField -> formField.getValue().asMap()) .forEach(formFieldMap -> formFieldMap.forEach((key, formField) -> { if ("Quantity".equals(key)) { if (FieldValueType.FLOAT == formField.getValue().getValueType()) { Float quantity = formField.getValue().asFloat(); System.out.printf("Quantity: %f, confidence: %.2f%n", quantity, formField.getConfidence()); } } })); } } }); } } /** * Code snippet for {@link FormRecognizerClient * with options * * @throws IOException Exception thrown when there is an error in reading all the bytes from the File. */ public void beginRecognizeReceiptsWithOptions() throws IOException { File receipt = new File("{local/file_path/fileName.jpg}"); boolean includeFieldElements = true; byte[] fileContent = Files.readAllBytes(receipt.toPath()); try (InputStream targetStream = new ByteArrayInputStream(fileContent)) { for (RecognizedForm recognizedForm : formRecognizerClient.beginRecognizeReceipts(targetStream, receipt.length(), new RecognizeReceiptsOptions() .setContentType(FormContentType.IMAGE_JPEG) .setFieldElementsIncluded(includeFieldElements) .setPollInterval(Duration.ofSeconds(5)), Context.NONE) .getFinalResult()) { Map<String, FormField> recognizedFields = recognizedForm.getFields(); FormField merchantNameField = recognizedFields.get("MerchantName"); if (merchantNameField != null) { if (FieldValueType.STRING == merchantNameField.getValue().getValueType()) { String merchantName = merchantNameField.getValue().asString(); System.out.printf("Merchant Name: %s, confidence: %.2f%n", merchantName, merchantNameField.getConfidence()); } } FormField merchantPhoneNumberField = recognizedFields.get("MerchantPhoneNumber"); if (merchantPhoneNumberField != null) { if (FieldValueType.PHONE_NUMBER == merchantPhoneNumberField.getValue().getValueType()) { String merchantAddress = merchantPhoneNumberField.getValue().asPhoneNumber(); System.out.printf("Merchant Phone number: %s, confidence: %.2f%n", merchantAddress, merchantPhoneNumberField.getConfidence()); } } FormField transactionDateField = recognizedFields.get("TransactionDate"); if (transactionDateField != null) { if (FieldValueType.DATE == transactionDateField.getValue().getValueType()) { LocalDate transactionDate = transactionDateField.getValue().asDate(); System.out.printf("Transaction Date: %s, confidence: %.2f%n", transactionDate, transactionDateField.getConfidence()); } } FormField receiptItemsField = recognizedFields.get("Items"); if (receiptItemsField != null) { System.out.printf("Receipt Items: %n"); if (FieldValueType.LIST == receiptItemsField.getValue().getValueType()) { List<FormField> receiptItems = receiptItemsField.getValue().asList(); receiptItems.stream() .filter(receiptItem -> FieldValueType.MAP == receiptItem.getValue().getValueType()) .map(formField -> formField.getValue().asMap()) .forEach(formFieldMap -> formFieldMap.forEach((key, formField) -> { if ("Quantity".equals(key)) { if (FieldValueType.FLOAT == formField.getValue().getValueType()) { Float quantity = formField.getValue().asFloat(); System.out.printf("Quantity: %f, confidence: %.2f%n", quantity, formField.getConfidence()); } } })); } } } } } /** * Code snippet for {@link FormRecognizerClient */ /** * Code snippet for * {@link FormRecognizerClient */ public void beginRecognizeBusinessCardsFromUrlWithOptions() { String businessCardUrl = "{business_card_url}"; formRecognizerClient.beginRecognizeBusinessCardsFromUrl(businessCardUrl, new RecognizeBusinessCardsOptions() .setPollInterval(Duration.ofSeconds(5)) .setFieldElementsIncluded(true), Context.NONE).getFinalResult() .forEach(recognizedBusinessCard -> { Map<String, FormField> recognizedFields = recognizedBusinessCard.getFields(); FormField contactNames = recognizedFields.get("ContactNames"); if (contactNames != null) { if (FieldValueType.LIST == contactNames.getValue().getValueType()) { List<FormField> businessCardItems = contactNames.getValue().asList(); businessCardItems.stream() .filter(businessCardItem -> FieldValueType.MAP == businessCardItem.getValue() .getValueType()) .map(formField -> formField.getValue().asMap()) .forEach(formFieldMap -> formFieldMap.forEach((key, formField) -> { if ("FirstName".equals(key)) { if (FieldValueType.STRING == formField.getValue().getValueType()) { String firstName = formField.getValue().asString(); System.out.printf("First Name: %s, confidence: %.2f%n", firstName, contactNames.getConfidence()); } } if ("LastName".equals(key)) { if (FieldValueType.STRING == formField.getValue().getValueType()) { String lastName = formField.getValue().asString(); System.out.printf("Last Name: %s, confidence: %.2f%n", lastName, contactNames.getConfidence()); } } })); } } FormField jobTitles = recognizedFields.get("JobTitles"); if (jobTitles != null) { if (FieldValueType.LIST == jobTitles.getValue().getValueType()) { List<FormField> jobTitlesItems = jobTitles.getValue().asList(); jobTitlesItems.stream().forEach(formField -> { if (FieldValueType.STRING == formField.getValue().getValueType()) { String jobTitle = formField.getValue().asString(); System.out.printf("Job Title: %s, confidence: %.2f%n", jobTitle, jobTitles.getConfidence()); } }); } } }); } /** * Code snippet for {@link FormRecognizerClient * * @throws IOException Exception thrown when there is an error in reading all the bytes from the File. */ public void beginRecognizeBusinessCards() throws IOException { File businessCard = new File("{local/file_path/fileName.jpg}"); byte[] fileContent = Files.readAllBytes(businessCard.toPath()); try (InputStream targetStream = new ByteArrayInputStream(fileContent)) { formRecognizerClient.beginRecognizeBusinessCards(targetStream, businessCard.length()).getFinalResult() .forEach(recognizedBusinessCard -> { Map<String, FormField> recognizedFields = recognizedBusinessCard.getFields(); FormField contactNames = recognizedFields.get("ContactNames"); if (contactNames != null) { if (FieldValueType.LIST == contactNames.getValue().getValueType()) { List<FormField> businessCardItems = contactNames.getValue().asList(); businessCardItems.stream() .filter(businessCardItem -> FieldValueType.MAP == businessCardItem.getValue() .getValueType()) .map(formField -> formField.getValue().asMap()) .forEach(formFieldMap -> formFieldMap.forEach((key, formField) -> { if ("FirstName".equals(key)) { if (FieldValueType.STRING == formField.getValue().getValueType()) { String firstName = formField.getValue().asString(); System.out.printf("First Name: %s, confidence: %.2f%n", firstName, contactNames.getConfidence()); } } if ("LastName".equals(key)) { if (FieldValueType.STRING == formField.getValue().getValueType()) { String lastName = formField.getValue().asString(); System.out.printf("Last Name: %s, confidence: %.2f%n", lastName, contactNames.getConfidence()); } } })); } } FormField jobTitles = recognizedFields.get("JobTitles"); if (jobTitles != null) { if (FieldValueType.LIST == jobTitles.getValue().getValueType()) { List<FormField> jobTitlesItems = jobTitles.getValue().asList(); jobTitlesItems.stream().forEach(formField -> { if (FieldValueType.STRING == formField.getValue().getValueType()) { String jobTitle = formField.getValue().asString(); System.out.printf("Job Title: %s, confidence: %.2f%n", jobTitle, jobTitles.getConfidence()); } }); } } }); } } /** * Code snippet for * {@link FormRecognizerClient * Context)} with options * * @throws IOException Exception thrown when there is an error in reading all the bytes from the File. */ public void beginRecognizeBusinessCardsWithOptions() throws IOException { File businessCard = new File("{local/file_path/fileName.jpg}"); boolean includeFieldElements = true; byte[] fileContent = Files.readAllBytes(businessCard.toPath()); try (InputStream targetStream = new ByteArrayInputStream(fileContent)) { for (RecognizedForm recognizedForm : formRecognizerClient.beginRecognizeBusinessCards(targetStream, businessCard.length(), new RecognizeBusinessCardsOptions() .setContentType(FormContentType.IMAGE_JPEG) .setFieldElementsIncluded(includeFieldElements) .setPollInterval(Duration.ofSeconds(5)), Context.NONE) .getFinalResult()) { Map<String, FormField> recognizedFields = recognizedForm.getFields(); FormField contactNames = recognizedFields.get("ContactNames"); if (contactNames != null) { if (FieldValueType.LIST == contactNames.getValue().getValueType()) { List<FormField> businessCardItems = contactNames.getValue().asList(); businessCardItems.stream() .filter(businessCardItem -> FieldValueType.MAP == businessCardItem.getValue() .getValueType()) .map(formField -> formField.getValue().asMap()) .forEach(formFieldMap -> formFieldMap.forEach((key, formField) -> { if ("FirstName".equals(key)) { if (FieldValueType.STRING == formField.getValue().getValueType()) { String firstName = formField.getValue().asString(); System.out.printf("First Name: %s, confidence: %.2f%n", firstName, contactNames.getConfidence()); } } if ("LastName".equals(key)) { if (FieldValueType.STRING == formField.getValue().getValueType()) { String lastName = formField.getValue().asString(); System.out.printf("Last Name: %s, confidence: %.2f%n", lastName, contactNames.getConfidence()); } } })); } } FormField jobTitles = recognizedFields.get("JobTitles"); if (jobTitles != null) { if (FieldValueType.LIST == jobTitles.getValue().getValueType()) { List<FormField> jobTitlesItems = jobTitles.getValue().asList(); jobTitlesItems.stream().forEach(formField -> { if (FieldValueType.STRING == formField.getValue().getValueType()) { String jobTitle = formField.getValue().asString(); System.out.printf("Job Title: %s, confidence: %.2f%n", jobTitle, jobTitles.getConfidence()); } }); } } } } } }
class FormRecognizerClientJavaDocCodeSnippets { private FormRecognizerClient formRecognizerClient = new FormRecognizerClientBuilder().buildClient(); /** * Code snippet for creating a {@link FormRecognizerClient} */ public void createFormRecognizerClient() { FormRecognizerClient formRecognizerClient = new FormRecognizerClientBuilder() .credential(new AzureKeyCredential("{key}")) .endpoint("{endpoint}") .buildClient(); } /** * Code snippet for creating a {@link FormRecognizerClient} with pipeline */ public void createFormRecognizerClientWithPipeline() { HttpPipeline pipeline = new HttpPipelineBuilder() .policies(/* add policies */) .build(); FormRecognizerClient formRecognizerClient = new FormRecognizerClientBuilder() .credential(new AzureKeyCredential("{key}")) .endpoint("{endpoint}") .pipeline(pipeline) .buildClient(); } /** * Code snippet for {@link FormRecognizerClient */ public void beginRecognizeCustomFormsFromUrl() { String formUrl = "{form_url}"; String modelId = "{custom_trained_model_id}"; formRecognizerClient.beginRecognizeCustomFormsFromUrl(modelId, formUrl).getFinalResult() .stream() .map(RecognizedForm::getFields) .forEach(formFieldMap -> formFieldMap.forEach((fieldText, formField) -> { System.out.printf("Field text: %s%n", fieldText); System.out.printf("Field value data text: %s%n", formField.getValueData().getText()); System.out.printf("Confidence score: %.2f%n", formField.getConfidence()); })); } /** * Code snippet for {@link FormRecognizerClient */ public void beginRecognizeCustomFormsFromUrlWithOptions() { String analyzeFilePath = "{file_source_url}"; String modelId = "{model_id}"; boolean includeFieldElements = true; formRecognizerClient.beginRecognizeCustomFormsFromUrl(modelId, analyzeFilePath, new RecognizeCustomFormsOptions() .setFieldElementsIncluded(includeFieldElements) .setPollInterval(Duration.ofSeconds(10)), Context.NONE) .getFinalResult() .stream() .map(RecognizedForm::getFields) .forEach(formFieldMap -> formFieldMap.forEach((fieldText, formField) -> { System.out.printf("Field text: %s%n", fieldText); System.out.printf("Field value data text: %s%n", formField.getValueData().getText()); System.out.printf("Confidence score: %.2f%n", formField.getConfidence()); })); } /** * Code snippet for * {@link FormRecognizerClient * * @throws IOException Exception thrown when there is an error in reading all the bytes from the File. */ public void beginRecognizeCustomForms() throws IOException { File form = new File("{local/file_path/fileName.jpg}"); String modelId = "{custom_trained_model_id}"; byte[] fileContent = Files.readAllBytes(form.toPath()); try (InputStream targetStream = new ByteArrayInputStream(fileContent)) { formRecognizerClient.beginRecognizeCustomForms(modelId, targetStream, form.length()) .getFinalResult() .stream() .map(RecognizedForm::getFields) .forEach(formFieldMap -> formFieldMap.forEach((fieldText, formField) -> { System.out.printf("Field text: %s%n", fieldText); System.out.printf("Field value data text: %s%n", formField.getValueData().getText()); System.out.printf("Confidence score: %.2f%n", formField.getConfidence()); })); } } /** * Code snippet for * {@link FormRecognizerClient * * @throws IOException Exception thrown when there is an error in reading all the bytes from the File. */ public void beginRecognizeCustomFormsWithOptions() throws IOException { File form = new File("{local/file_path/fileName.jpg}"); String modelId = "{custom_trained_model_id}"; boolean includeFieldElements = true; byte[] fileContent = Files.readAllBytes(form.toPath()); try (InputStream targetStream = new ByteArrayInputStream(fileContent)) { formRecognizerClient.beginRecognizeCustomForms(modelId, targetStream, form.length(), new RecognizeCustomFormsOptions() .setContentType(FormContentType.IMAGE_JPEG) .setFieldElementsIncluded(includeFieldElements) .setPollInterval(Duration.ofSeconds(10)), Context.NONE) .getFinalResult() .stream() .map(RecognizedForm::getFields) .forEach(formFieldMap -> formFieldMap.forEach((fieldText, formField) -> { System.out.printf("Field text: %s%n", fieldText); System.out.printf("Field value data text: %s%n", formField.getValueData().getText()); System.out.printf("Confidence score: %.2f%n", formField.getConfidence()); })); } } /** * Code snippet for {@link FormRecognizerClient */ public void beginRecognizeContentFromUrl() { String formUrl = "{form_url}"; formRecognizerClient.beginRecognizeContentFromUrl(formUrl) .getFinalResult() .forEach(formPage -> { System.out.printf("Page Angle: %s%n", formPage.getTextAngle()); System.out.printf("Page Dimension unit: %s%n", formPage.getUnit()); System.out.println("Recognized Tables: "); formPage.getTables() .stream() .flatMap(formTable -> formTable.getCells().stream()) .forEach(recognizedTableCell -> System.out.printf("%s ", recognizedTableCell.getText())); }); } /** * Code snippet for {@link FormRecognizerClient * options. */ public void beginRecognizeContentFromUrlWithOptions() { String formPath = "{file_source_url}"; formRecognizerClient.beginRecognizeContentFromUrl(formPath, new RecognizeContentOptions() .setPollInterval(Duration.ofSeconds(5)), Context.NONE) .getFinalResult() .forEach(formPage -> { System.out.printf("Page Angle: %s%n", formPage.getTextAngle()); System.out.printf("Page Dimension unit: %s%n", formPage.getUnit()); System.out.println("Recognized Tables: "); formPage.getTables() .stream() .flatMap(formTable -> formTable.getCells().stream()) .forEach(recognizedTableCell -> System.out.printf("%s ", recognizedTableCell.getText())); }); } /** * Code snippet for {@link FormRecognizerClient * * @throws IOException Exception thrown when there is an error in reading all the bytes from the File. */ public void beginRecognizeContent() throws IOException { File form = new File("{local/file_path/fileName.pdf}"); byte[] fileContent = Files.readAllBytes(form.toPath()); try (InputStream targetStream = new ByteArrayInputStream(fileContent)) { formRecognizerClient.beginRecognizeContent(targetStream, form.length()) .getFinalResult() .forEach(formPage -> { System.out.printf("Page Angle: %s%n", formPage.getTextAngle()); System.out.printf("Page Dimension unit: %s%n", formPage.getUnit()); System.out.println("Recognized Tables: "); formPage.getTables() .stream() .flatMap(formTable -> formTable.getCells().stream()) .forEach(recognizedTableCell -> System.out.printf("%s ", recognizedTableCell.getText())); }); } } /** * Code snippet for {@link FormRecognizerClient * options. * * @throws IOException Exception thrown when there is an error in reading all the bytes from the File. */ public void beginRecognizeContentWithOptions() throws IOException { File form = new File("{file_source_url}"); byte[] fileContent = Files.readAllBytes(form.toPath()); try (InputStream targetStream = new ByteArrayInputStream(fileContent)) { for (FormPage formPage : formRecognizerClient.beginRecognizeContent(targetStream, form.length(), new RecognizeContentOptions() .setPollInterval(Duration.ofSeconds(5)), Context.NONE) .getFinalResult()) { System.out.printf("Page Angle: %s%n", formPage.getTextAngle()); System.out.printf("Page Dimension unit: %s%n", formPage.getUnit()); System.out.println("Recognized Tables: "); formPage.getTables() .stream() .flatMap(formTable -> formTable.getCells().stream()) .forEach(recognizedTableCell -> System.out.printf("%s ", recognizedTableCell.getText())); } } } /** * Code snippet for {@link FormRecognizerClient */ public void beginRecognizeReceiptsFromUrl() { String receiptUrl = "{file_source_url}"; formRecognizerClient.beginRecognizeReceiptsFromUrl(receiptUrl) .getFinalResult() .forEach(recognizedReceipt -> { Map<String, FormField> recognizedFields = recognizedReceipt.getFields(); FormField merchantNameField = recognizedFields.get("MerchantName"); if (merchantNameField != null) { if (FieldValueType.STRING == merchantNameField.getValue().getValueType()) { String merchantName = merchantNameField.getValue().asString(); System.out.printf("Merchant Name: %s, confidence: %.2f%n", merchantName, merchantNameField.getConfidence()); } } FormField merchantPhoneNumberField = recognizedFields.get("MerchantPhoneNumber"); if (merchantPhoneNumberField != null) { if (FieldValueType.PHONE_NUMBER == merchantPhoneNumberField.getValue().getValueType()) { String merchantAddress = merchantPhoneNumberField.getValue().asPhoneNumber(); System.out.printf("Merchant Phone number: %s, confidence: %.2f%n", merchantAddress, merchantPhoneNumberField.getConfidence()); } } FormField transactionDateField = recognizedFields.get("TransactionDate"); if (transactionDateField != null) { if (FieldValueType.DATE == transactionDateField.getValue().getValueType()) { LocalDate transactionDate = transactionDateField.getValue().asDate(); System.out.printf("Transaction Date: %s, confidence: %.2f%n", transactionDate, transactionDateField.getConfidence()); } } FormField receiptItemsField = recognizedFields.get("Items"); if (receiptItemsField != null) { System.out.printf("Receipt Items: %n"); if (FieldValueType.LIST == receiptItemsField.getValue().getValueType()) { List<FormField> receiptItems = receiptItemsField.getValue().asList(); receiptItems.stream() .filter(receiptItem -> FieldValueType.MAP == receiptItem.getValue().getValueType()) .map(formField -> formField.getValue().asMap()) .forEach(formFieldMap -> formFieldMap.forEach((key, formField) -> { if ("Quantity".equals(key)) { if (FieldValueType.FLOAT == formField.getValue().getValueType()) { Float quantity = formField.getValue().asFloat(); System.out.printf("Quantity: %f, confidence: %.2f%n", quantity, formField.getConfidence()); } } })); } } }); } /** * Code snippet for {@link FormRecognizerClient */ public void beginRecognizeReceiptsFromUrlWithOptions() { String receiptUrl = "{receipt_url}"; formRecognizerClient.beginRecognizeReceiptsFromUrl(receiptUrl, new RecognizeReceiptsOptions() .setPollInterval(Duration.ofSeconds(5)) .setFieldElementsIncluded(true), Context.NONE).getFinalResult() .forEach(recognizedReceipt -> { Map<String, FormField> recognizedFields = recognizedReceipt.getFields(); FormField merchantNameField = recognizedFields.get("MerchantName"); if (merchantNameField != null) { if (FieldValueType.STRING == merchantNameField.getValue().getValueType()) { String merchantName = merchantNameField.getValue().asString(); System.out.printf("Merchant Name: %s, confidence: %.2f%n", merchantName, merchantNameField.getConfidence()); } } FormField merchantPhoneNumberField = recognizedFields.get("MerchantPhoneNumber"); if (merchantPhoneNumberField != null) { if (FieldValueType.PHONE_NUMBER == merchantPhoneNumberField.getValue().getValueType()) { String merchantAddress = merchantPhoneNumberField.getValue().asPhoneNumber(); System.out.printf("Merchant Phone number: %s, confidence: %.2f%n", merchantAddress, merchantPhoneNumberField.getConfidence()); } } FormField transactionDateField = recognizedFields.get("TransactionDate"); if (transactionDateField != null) { if (FieldValueType.DATE == transactionDateField.getValue().getValueType()) { LocalDate transactionDate = transactionDateField.getValue().asDate(); System.out.printf("Transaction Date: %s, confidence: %.2f%n", transactionDate, transactionDateField.getConfidence()); } } FormField receiptItemsField = recognizedFields.get("Items"); if (receiptItemsField != null) { System.out.printf("Receipt Items: %n"); if (FieldValueType.LIST == receiptItemsField.getValue().getValueType()) { List<FormField> receiptItems = receiptItemsField.getValue().asList(); receiptItems.stream() .filter(receiptItem -> FieldValueType.MAP == receiptItem.getValue().getValueType()) .map(formField -> formField.getValue().asMap()) .forEach(formFieldMap -> formFieldMap.forEach((key, formField) -> { if ("Quantity".equals(key)) { if (FieldValueType.FLOAT == formField.getValue().getValueType()) { Float quantity = formField.getValue().asFloat(); System.out.printf("Quantity: %f, confidence: %.2f%n", quantity, formField.getConfidence()); } } })); } } }); } /** * Code snippet for {@link FormRecognizerClient * * @throws IOException Exception thrown when there is an error in reading all the bytes from the File. */ public void beginRecognizeReceipts() throws IOException { File receipt = new File("{receipt_url}"); byte[] fileContent = Files.readAllBytes(receipt.toPath()); try (InputStream targetStream = new ByteArrayInputStream(fileContent)) { formRecognizerClient.beginRecognizeReceipts(targetStream, receipt.length()).getFinalResult() .forEach(recognizedReceipt -> { Map<String, FormField> recognizedFields = recognizedReceipt.getFields(); FormField merchantNameField = recognizedFields.get("MerchantName"); if (merchantNameField != null) { if (FieldValueType.STRING == merchantNameField.getValue().getValueType()) { String merchantName = merchantNameField.getValue().asString(); System.out.printf("Merchant Name: %s, confidence: %.2f%n", merchantName, merchantNameField.getConfidence()); } } FormField merchantPhoneNumberField = recognizedFields.get("MerchantPhoneNumber"); if (merchantPhoneNumberField != null) { if (FieldValueType.PHONE_NUMBER == merchantPhoneNumberField.getValue().getValueType()) { String merchantAddress = merchantPhoneNumberField.getValue().asPhoneNumber(); System.out.printf("Merchant Phone number: %s, confidence: %.2f%n", merchantAddress, merchantPhoneNumberField.getConfidence()); } } FormField transactionDateField = recognizedFields.get("TransactionDate"); if (transactionDateField != null) { if (FieldValueType.DATE == transactionDateField.getValue().getValueType()) { LocalDate transactionDate = transactionDateField.getValue().asDate(); System.out.printf("Transaction Date: %s, confidence: %.2f%n", transactionDate, transactionDateField.getConfidence()); } } FormField receiptItemsField = recognizedFields.get("Items"); if (receiptItemsField != null) { System.out.printf("Receipt Items: %n"); if (FieldValueType.LIST == receiptItemsField.getValue().getValueType()) { List<FormField> receiptItems = receiptItemsField.getValue().asList(); receiptItems.stream() .filter(receiptItem -> FieldValueType.MAP == receiptItem.getValue().getValueType()) .map(formField -> formField.getValue().asMap()) .forEach(formFieldMap -> formFieldMap.forEach((key, formField) -> { if ("Quantity".equals(key)) { if (FieldValueType.FLOAT == formField.getValue().getValueType()) { Float quantity = formField.getValue().asFloat(); System.out.printf("Quantity: %f, confidence: %.2f%n", quantity, formField.getConfidence()); } } })); } } }); } } /** * Code snippet for {@link FormRecognizerClient * with options * * @throws IOException Exception thrown when there is an error in reading all the bytes from the File. */ public void beginRecognizeReceiptsWithOptions() throws IOException { File receipt = new File("{local/file_path/fileName.jpg}"); boolean includeFieldElements = true; byte[] fileContent = Files.readAllBytes(receipt.toPath()); try (InputStream targetStream = new ByteArrayInputStream(fileContent)) { for (RecognizedForm recognizedForm : formRecognizerClient.beginRecognizeReceipts(targetStream, receipt.length(), new RecognizeReceiptsOptions() .setContentType(FormContentType.IMAGE_JPEG) .setFieldElementsIncluded(includeFieldElements) .setPollInterval(Duration.ofSeconds(5)), Context.NONE) .getFinalResult()) { Map<String, FormField> recognizedFields = recognizedForm.getFields(); FormField merchantNameField = recognizedFields.get("MerchantName"); if (merchantNameField != null) { if (FieldValueType.STRING == merchantNameField.getValue().getValueType()) { String merchantName = merchantNameField.getValue().asString(); System.out.printf("Merchant Name: %s, confidence: %.2f%n", merchantName, merchantNameField.getConfidence()); } } FormField merchantPhoneNumberField = recognizedFields.get("MerchantPhoneNumber"); if (merchantPhoneNumberField != null) { if (FieldValueType.PHONE_NUMBER == merchantPhoneNumberField.getValue().getValueType()) { String merchantAddress = merchantPhoneNumberField.getValue().asPhoneNumber(); System.out.printf("Merchant Phone number: %s, confidence: %.2f%n", merchantAddress, merchantPhoneNumberField.getConfidence()); } } FormField transactionDateField = recognizedFields.get("TransactionDate"); if (transactionDateField != null) { if (FieldValueType.DATE == transactionDateField.getValue().getValueType()) { LocalDate transactionDate = transactionDateField.getValue().asDate(); System.out.printf("Transaction Date: %s, confidence: %.2f%n", transactionDate, transactionDateField.getConfidence()); } } FormField receiptItemsField = recognizedFields.get("Items"); if (receiptItemsField != null) { System.out.printf("Receipt Items: %n"); if (FieldValueType.LIST == receiptItemsField.getValue().getValueType()) { List<FormField> receiptItems = receiptItemsField.getValue().asList(); receiptItems.stream() .filter(receiptItem -> FieldValueType.MAP == receiptItem.getValue().getValueType()) .map(formField -> formField.getValue().asMap()) .forEach(formFieldMap -> formFieldMap.forEach((key, formField) -> { if ("Quantity".equals(key)) { if (FieldValueType.FLOAT == formField.getValue().getValueType()) { Float quantity = formField.getValue().asFloat(); System.out.printf("Quantity: %f, confidence: %.2f%n", quantity, formField.getConfidence()); } } })); } } } } } /** * Code snippet for {@link FormRecognizerClient */ /** * Code snippet for * {@link FormRecognizerClient */ public void beginRecognizeBusinessCardsFromUrlWithOptions() { String businessCardUrl = "{business_card_url}"; formRecognizerClient.beginRecognizeBusinessCardsFromUrl(businessCardUrl, new RecognizeBusinessCardsOptions() .setPollInterval(Duration.ofSeconds(5)) .setFieldElementsIncluded(true), Context.NONE).getFinalResult() .forEach(recognizedBusinessCard -> { Map<String, FormField> recognizedFields = recognizedBusinessCard.getFields(); FormField contactNamesFormField = recognizedFields.get("ContactNames"); if (contactNamesFormField != null) { if (FieldValueType.LIST == contactNamesFormField.getValue().getValueType()) { List<FormField> contactNamesList = contactNamesFormField.getValue().asList(); contactNamesList.stream() .filter(contactName -> FieldValueType.MAP == contactName.getValue().getValueType()) .map(contactName -> { System.out.printf("Contact name: %s%n", contactName.getValueData().getText()); return contactName.getValue().asMap(); }) .forEach(contactNamesMap -> contactNamesMap.forEach((key, contactName) -> { if ("FirstName".equals(key)) { if (FieldValueType.STRING == contactName.getValue().getValueType()) { String firstName = contactName.getValue().asString(); System.out.printf("\tFirst Name: %s, confidence: %.2f%n", firstName, contactName.getConfidence()); } } if ("LastName".equals(key)) { if (FieldValueType.STRING == contactName.getValue().getValueType()) { String lastName = contactName.getValue().asString(); System.out.printf("\tLast Name: %s, confidence: %.2f%n", lastName, contactName.getConfidence()); } } })); } } FormField jobTitles = recognizedFields.get("JobTitles"); if (jobTitles != null) { if (FieldValueType.LIST == jobTitles.getValue().getValueType()) { List<FormField> jobTitlesItems = jobTitles.getValue().asList(); jobTitlesItems.stream().forEach(jobTitlesItem -> { if (FieldValueType.STRING == jobTitlesItem.getValue().getValueType()) { String jobTitle = jobTitlesItem.getValue().asString(); System.out.printf("Job Title: %s, confidence: %.2f%n", jobTitle, jobTitlesItem.getConfidence()); } }); } } }); } /** * Code snippet for {@link FormRecognizerClient * * @throws IOException Exception thrown when there is an error in reading all the bytes from the File. */ public void beginRecognizeBusinessCards() throws IOException { File businessCard = new File("{local/file_path/fileName.jpg}"); byte[] fileContent = Files.readAllBytes(businessCard.toPath()); try (InputStream targetStream = new ByteArrayInputStream(fileContent)) { formRecognizerClient.beginRecognizeBusinessCards(targetStream, businessCard.length()).getFinalResult() .forEach(recognizedBusinessCard -> { Map<String, FormField> recognizedFields = recognizedBusinessCard.getFields(); FormField contactNamesFormField = recognizedFields.get("ContactNames"); if (contactNamesFormField != null) { if (FieldValueType.LIST == contactNamesFormField.getValue().getValueType()) { List<FormField> contactNamesList = contactNamesFormField.getValue().asList(); contactNamesList.stream() .filter(contactName -> FieldValueType.MAP == contactName.getValue().getValueType()) .map(contactName -> { System.out.printf("Contact name: %s%n", contactName.getValueData().getText()); return contactName.getValue().asMap(); }) .forEach(contactNamesMap -> contactNamesMap.forEach((key, contactName) -> { if ("FirstName".equals(key)) { if (FieldValueType.STRING == contactName.getValue().getValueType()) { String firstName = contactName.getValue().asString(); System.out.printf("\tFirst Name: %s, confidence: %.2f%n", firstName, contactName.getConfidence()); } } if ("LastName".equals(key)) { if (FieldValueType.STRING == contactName.getValue().getValueType()) { String lastName = contactName.getValue().asString(); System.out.printf("\tLast Name: %s, confidence: %.2f%n", lastName, contactName.getConfidence()); } } })); } } FormField jobTitles = recognizedFields.get("JobTitles"); if (jobTitles != null) { if (FieldValueType.LIST == jobTitles.getValue().getValueType()) { List<FormField> jobTitlesItems = jobTitles.getValue().asList(); jobTitlesItems.stream().forEach(jobTitlesItem -> { if (FieldValueType.STRING == jobTitlesItem.getValue().getValueType()) { String jobTitle = jobTitlesItem.getValue().asString(); System.out.printf("Job Title: %s, confidence: %.2f%n", jobTitle, jobTitlesItem.getConfidence()); } }); } } }); } } /** * Code snippet for * {@link FormRecognizerClient * Context)} with options * * @throws IOException Exception thrown when there is an error in reading all the bytes from the File. */ public void beginRecognizeBusinessCardsWithOptions() throws IOException { File businessCard = new File("{local/file_path/fileName.jpg}"); boolean includeFieldElements = true; byte[] fileContent = Files.readAllBytes(businessCard.toPath()); try (InputStream targetStream = new ByteArrayInputStream(fileContent)) { for (RecognizedForm recognizedForm : formRecognizerClient.beginRecognizeBusinessCards(targetStream, businessCard.length(), new RecognizeBusinessCardsOptions() .setContentType(FormContentType.IMAGE_JPEG) .setFieldElementsIncluded(includeFieldElements) .setPollInterval(Duration.ofSeconds(5)), Context.NONE) .getFinalResult()) { Map<String, FormField> recognizedFields = recognizedForm.getFields(); FormField contactNamesFormField = recognizedFields.get("ContactNames"); if (contactNamesFormField != null) { if (FieldValueType.LIST == contactNamesFormField.getValue().getValueType()) { List<FormField> contactNamesList = contactNamesFormField.getValue().asList(); contactNamesList.stream() .filter(contactName -> FieldValueType.MAP == contactName.getValue().getValueType()) .map(contactName -> { System.out.printf("Contact name: %s%n", contactName.getValueData().getText()); return contactName.getValue().asMap(); }) .forEach(contactNamesMap -> contactNamesMap.forEach((key, contactName) -> { if ("FirstName".equals(key)) { if (FieldValueType.STRING == contactName.getValue().getValueType()) { String firstName = contactName.getValue().asString(); System.out.printf("\tFirst Name: %s, confidence: %.2f%n", firstName, contactName.getConfidence()); } } if ("LastName".equals(key)) { if (FieldValueType.STRING == contactName.getValue().getValueType()) { String lastName = contactName.getValue().asString(); System.out.printf("\tLast Name: %s, confidence: %.2f%n", lastName, contactName.getConfidence()); } } })); } } FormField jobTitles = recognizedFields.get("JobTitles"); if (jobTitles != null) { if (FieldValueType.LIST == jobTitles.getValue().getValueType()) { List<FormField> jobTitlesItems = jobTitles.getValue().asList(); jobTitlesItems.stream().forEach(jobTitlesItem -> { if (FieldValueType.STRING == jobTitlesItem.getValue().getValueType()) { String jobTitle = jobTitlesItem.getValue().asString(); System.out.printf("Job Title: %s, confidence: %.2f%n", jobTitle, jobTitlesItem.getConfidence()); } }); } } } } } }
Why was this removed?
static void validateMultiPageDataLabeled(List<RecognizedForm> actualRecognizedFormsList) { actualRecognizedFormsList.forEach(recognizedForm -> { assertEquals(1, recognizedForm.getPageRange().getFirstPageNumber()); assertEquals(3, recognizedForm.getPageRange().getLastPageNumber()); assertEquals(3, recognizedForm.getPages().size()); recognizedForm.getFields().forEach((label, formField) -> { assertNotNull(formField.getName()); assertNotNull(formField.getValue()); assertNotNull(formField.getValueData().getText()); }); }); }
assertNotNull(formField.getValueData().getText());
static void validateMultiPageDataLabeled(List<RecognizedForm> actualRecognizedFormsList) { actualRecognizedFormsList.forEach(recognizedForm -> { assertEquals(1, recognizedForm.getPageRange().getFirstPageNumber()); assertEquals(3, recognizedForm.getPageRange().getLastPageNumber()); assertEquals(3, recognizedForm.getPages().size()); recognizedForm.getFields().forEach((label, formField) -> { assertNotNull(formField.getName()); assertNotNull(formField.getValue()); assertNotNull(formField.getValueData().getText()); assertNull(formField.getLabelData()); }); }); }
class FormRecognizerClientTestBase extends TestBase { private static final Pattern NON_DIGIT_PATTERN = Pattern.compile("[^0-9]+"); private static final String EXPECTED_MULTIPAGE_ADDRESS_VALUE = "123 Hobbit Lane 567 Main St. Redmond, WA Redmond," + " WA"; private static final String EXPECTED_MULTIPAGE_PHONE_NUMBER_VALUE = "+15555555555"; private static final String ITEMIZED_RECEIPT_VALUE = "Itemized"; static final String RECEIPT_CONTOSO_JPG = "contoso-allinone.jpg"; static final String RECEIPT_CONTOSO_PNG = "contoso-receipt.png"; static final String INVOICE_6_PDF = "Invoice_6.pdf"; static final String MULTIPAGE_INVOICE_PDF = "multipage_invoice1.pdf"; static final String BUSINESS_CARD_JPG = "businessCard.jpg"; static final String BUSINESS_CARD_PNG = "businessCard.png"; static final String BAD_ARGUMENT_CODE = "BadArgument"; static final String INVALID_IMAGE_ERROR_CODE = "InvalidImage"; static final String INVALID_MODEL_ID_ERROR_CODE = "1001"; static final String MODEL_ID_NOT_FOUND_ERROR_CODE = "1022"; static final String URL_BADLY_FORMATTED_ERROR_CODE = "2001"; static final String UNABLE_TO_READ_FILE_ERROR_CODE = "2005"; static final String HTTPS_EXCEPTION_MESSAGE = "Max retries 3 times exceeded. Error Details: Key credentials require HTTPS to prevent leaking the key."; static final String INVALID_UUID_EXCEPTION_MESSAGE = "Invalid UUID string: "; static final String MODEL_ID_IS_REQUIRED_EXCEPTION_MESSAGE = "'modelId' is required and cannot be null."; static final String INVALID_ENDPOINT = "https: static final String LOCAL_FILE_PATH = "src/test/resources/sample_files/Test/"; static final String ENCODED_EMPTY_SPACE = "{\"source\":\"https: static final String CONTACT_NAMES = "ContactNames"; static final String JOB_TITLES = "JobTitles"; static final String DEPARTMENTS = "Departments"; static final String EMAILS = "Emails"; static final String WEBSITES = "Websites"; static final String MOBILE_PHONES = "MobilePhones"; static final String OTHER_PHONES = "OtherPhones"; static final String FAXES = "Faxes"; static final String ADDRESSES = "Addresses"; static final String COMPANY_NAMES = "CompanyNames"; Duration durationTestMode; /** * Use duration of nearly zero value for PLAYBACK test mode, otherwise, use default duration value for LIVE mode. */ @Override protected void beforeTest() { if (interceptorManager.isPlaybackMode()) { durationTestMode = ONE_NANO_DURATION; } else { durationTestMode = DEFAULT_DURATION; } } FormRecognizerClientBuilder getFormRecognizerClientBuilder(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { FormRecognizerClientBuilder builder = new FormRecognizerClientBuilder() .endpoint(getEndpoint()) .httpClient(httpClient == null ? interceptorManager.getPlaybackClient() : httpClient) .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)) .serviceVersion(serviceVersion) .addPolicy(interceptorManager.getRecordPolicy()); if (getTestMode() == TestMode.PLAYBACK) { builder.credential(new AzureKeyCredential(INVALID_KEY)); } else { builder.credential(new AzureKeyCredential( Configuration.getGlobalConfiguration().get(AZURE_FORM_RECOGNIZER_API_KEY))); } return builder; } FormTrainingClientBuilder getFormTrainingClientBuilder(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { FormTrainingClientBuilder builder = new FormTrainingClientBuilder() .endpoint(getEndpoint()) .httpClient(httpClient == null ? interceptorManager.getPlaybackClient() : httpClient) .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)) .serviceVersion(serviceVersion) .addPolicy(interceptorManager.getRecordPolicy()); if (getTestMode() == TestMode.PLAYBACK) { builder.credential(new AzureKeyCredential(INVALID_KEY)); } else { builder.credential(new AzureKeyCredential( Configuration.getGlobalConfiguration().get(AZURE_FORM_RECOGNIZER_API_KEY))); } return builder; } private static void validateReferenceElementsData(List<String> expectedElements, List<FormElement> actualFormElementList, List<ReadResult> readResults) { if (expectedElements != null && actualFormElementList != null) { assertEquals(expectedElements.size(), actualFormElementList.size()); for (int i = 0; i < actualFormElementList.size(); i++) { String[] indices = NON_DIGIT_PATTERN.matcher(expectedElements.get(i)).replaceAll(" ").trim().split(" "); if (indices.length < 2) { return; } int readResultIndex = Integer.parseInt(indices[0]); int lineIndex = Integer.parseInt(indices[1]); if (indices.length == 3) { int wordIndex = Integer.parseInt(indices[2]); TextWord expectedTextWord = readResults.get(readResultIndex).getLines().get(lineIndex).getWords().get(wordIndex); TextLine expectedTextLine = readResults.get(readResultIndex).getLines().get(lineIndex); if (actualFormElementList.get(i) instanceof FormLine) { FormLine actualFormLine = (FormLine) actualFormElementList.get(i); validateFormWordData(expectedTextLine.getWords(), actualFormLine.getWords()); } FormWord actualFormWord = (FormWord) actualFormElementList.get(i); assertEquals(expectedTextWord.getText(), actualFormWord.getText()); if (expectedTextWord.getConfidence() != null) { assertEquals(expectedTextWord.getConfidence(), actualFormWord.getConfidence()); } else { assertEquals(1.0f, actualFormWord.getConfidence()); } validateBoundingBoxData(expectedTextWord.getBoundingBox(), actualFormWord.getBoundingBox()); } } } } private static void validateFormTableData(List<DataTable> expectedFormTables, List<FormTable> actualFormTable, List<ReadResult> readResults, boolean includeFieldElements, int pageNumber) { assertEquals(expectedFormTables.size(), actualFormTable.size()); for (int i = 0; i < actualFormTable.size(); i++) { DataTable expectedTable = expectedFormTables.get(i); FormTable actualTable = actualFormTable.get(i); assertEquals(pageNumber, actualTable.getPageNumber()); assertEquals(expectedTable.getColumns(), actualTable.getColumnCount()); validateCellData(expectedTable.getCells(), actualTable.getCells(), readResults, includeFieldElements); assertEquals(expectedTable.getRows(), actualTable.getRowCount()); } } private static void validateCellData(List<DataTableCell> expectedTableCells, List<FormTableCell> actualTableCellList, List<ReadResult> readResults, boolean includeFieldElements) { assertEquals(expectedTableCells.size(), actualTableCellList.size()); for (int i = 0; i < actualTableCellList.size(); i++) { DataTableCell expectedTableCell = expectedTableCells.get(i); FormTableCell actualTableCell = actualTableCellList.get(i); assertEquals(expectedTableCell.getColumnIndex(), actualTableCell.getColumnIndex()); if (expectedTableCell.getColumnSpan() != null) { assertEquals(expectedTableCell.getColumnSpan(), actualTableCell.getColumnSpan()); } assertNotNull(actualTableCell.getColumnSpan()); assertEquals(expectedTableCell.getRowIndex(), actualTableCell.getRowIndex()); if (expectedTableCell.getRowSpan() != null) { assertEquals(expectedTableCell.getRowSpan(), actualTableCell.getRowSpan()); } assertNotNull(actualTableCell.getRowSpan()); validateBoundingBoxData(expectedTableCell.getBoundingBox(), actualTableCell.getBoundingBox()); if (includeFieldElements) { validateReferenceElementsData(expectedTableCell.getElements(), actualTableCell.getFieldElements(), readResults); } } } private static void validateFormLineData(List<TextLine> expectedLines, List<FormLine> actualLineList) { assertEquals(expectedLines.size(), actualLineList.size()); for (int i = 0; i < actualLineList.size(); i++) { TextLine expectedLine = expectedLines.get(i); FormLine actualLine = actualLineList.get(i); assertEquals(expectedLine.getText(), actualLine.getText()); validateBoundingBoxData(expectedLine.getBoundingBox(), actualLine.getBoundingBox()); validateFormWordData(expectedLine.getWords(), actualLine.getWords()); } } private static void validateFormWordData(List<TextWord> expectedFormWords, List<FormWord> actualFormWordList) { assertEquals(expectedFormWords.size(), actualFormWordList.size()); for (int i = 0; i < actualFormWordList.size(); i++) { TextWord expectedWord = expectedFormWords.get(i); FormWord actualWord = actualFormWordList.get(i); assertEquals(expectedWord.getText(), actualWord.getText()); validateBoundingBoxData(expectedWord.getBoundingBox(), actualWord.getBoundingBox()); if (expectedWord.getConfidence() != null) { assertEquals(expectedWord.getConfidence(), actualWord.getConfidence()); } else { assertEquals(1.0f, actualWord.getConfidence()); } } } private static void validateBoundingBoxData(List<Float> expectedBoundingBox, FieldBoundingBox actualFieldBoundingBox) { if (actualFieldBoundingBox != null && actualFieldBoundingBox.getPoints() != null) { int i = 0; for (Point point : actualFieldBoundingBox.getPoints()) { assertEquals(expectedBoundingBox.get(i), point.getX()); assertEquals(expectedBoundingBox.get(++i), point.getY()); i++; } } } @SuppressWarnings("unchecked") private static void validateFieldValueTransforms(FieldValue expectedFieldValue, FormField actualFormField, List<ReadResult> readResults, boolean includeFieldElements) { if (expectedFieldValue != null) { if (expectedFieldValue.getBoundingBox() != null) { validateBoundingBoxData(expectedFieldValue.getBoundingBox(), actualFormField.getValueData().getBoundingBox()); } if (includeFieldElements && expectedFieldValue.getElements() != null) { validateReferenceElementsData(expectedFieldValue.getElements(), actualFormField.getValueData().getFieldElements(), readResults); } switch (expectedFieldValue.getType()) { case NUMBER: if (expectedFieldValue.getValueNumber() != null) { assertEquals(expectedFieldValue.getValueNumber(), actualFormField.getValue().asFloat()); } break; case DATE: assertEquals(expectedFieldValue.getValueDate(), actualFormField.getValue().asDate()); break; case TIME: assertEquals(LocalTime.parse(expectedFieldValue.getValueTime(), DateTimeFormatter.ofPattern("HH:mm:ss")), actualFormField.getValue().asTime()); break; case STRING: if (actualFormField.getName() != "ReceiptType") { assertEquals(expectedFieldValue.getValueString(), actualFormField.getValue().asString()); } break; case INTEGER: assertEquals(expectedFieldValue.getValueInteger(), actualFormField.getValue().asLong()); break; case PHONE_NUMBER: assertEquals(expectedFieldValue.getValuePhoneNumber(), actualFormField.getValue().asPhoneNumber()); break; case OBJECT: expectedFieldValue.getValueObject().forEach((key, formField) -> { FormField actualFormFieldValue = actualFormField.getValue().asMap().get(key); validateFieldValueTransforms(formField, actualFormFieldValue, readResults, includeFieldElements); }); break; case ARRAY: assertEquals(expectedFieldValue.getValueArray().size(), actualFormField.getValue().asList().size()); for (int i = 0; i < expectedFieldValue.getValueArray().size(); i++) { FieldValue expectedReceiptItem = expectedFieldValue.getValueArray().get(i); FormField actualReceiptItem = actualFormField.getValue().asList().get(i); validateFieldValueTransforms(expectedReceiptItem, actualReceiptItem, readResults, includeFieldElements); } break; default: assertFalse(false, "Field type not supported."); } } } private static void validatePageRangeData(int expectedPageInfo, FormPageRange actualPageInfo) { assertEquals(expectedPageInfo, actualPageInfo.getFirstPageNumber()); assertEquals(expectedPageInfo, actualPageInfo.getLastPageNumber()); } @Test abstract void recognizeReceiptData(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeReceiptDataNullData(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeReceiptDataWithContentTypeAutoDetection(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeReceiptDataIncludeFieldElements(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeReceiptDataWithPngFile(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeReceiptDataWithBlankPdf(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeReceiptFromDataMultiPage(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeReceiptSourceUrl(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeReceiptInvalidSourceUrl(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeReceiptFromUrlIncludeFieldElements(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeReceiptSourceUrlWithPngFile(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeReceiptFromUrlMultiPage(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeContent(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeContentResultWithNullData(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeContentResultWithContentTypeAutoDetection(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeContentResultWithBlankPdf(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeContentFromDataMultiPage(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeContentFromUrl(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeContentFromUrlWithPdf(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeContentInvalidSourceUrl(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeContentFromUrlMultiPage(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormLabeledData(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormLabeledDataWithJpgContentType(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormLabeledDataWithBlankPdfContentType(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormLabeledDataExcludeFieldElements(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormLabeledDataWithNullFormData(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormLabeledDataWithNullModelId(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormLabeledDataWithEmptyModelId(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormInvalidStatus(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormLabeledDataWithContentTypeAutoDetection(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormMultiPageLabeled(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormUnlabeledData(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormUnlabeledDataIncludeFieldElements(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormMultiPageUnlabeled(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormUnlabeledDataWithJpgContentType(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormUnlabeledDataWithBlankPdfContentType(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormUrlUnlabeledData(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormUrlUnlabeledDataIncludeFieldElements(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormUrlMultiPageUnlabeled(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormInvalidSourceUrl(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormFromUrlLabeledDataWithNullModelId(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormFromUrlLabeledDataWithEmptyModelId(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormUrlLabeledData(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormUrlLabeledDataIncludeFieldElements(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormUrlMultiPageLabeled(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeBusinessCardData(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeBusinessCardDataNullData(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeBusinessCardDataWithContentTypeAutoDetection(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeBusinessCardDataIncludeFieldElements(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeBusinessCardDataWithPngFile(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeBusinessCardDataWithBlankPdf(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeBusinessCardFromDamagedPdf(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeBusinessCardSourceUrl(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeBusinessCardFromUrlWithEncodedBlankSpaceSourceUrl(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeBusinessCardInvalidSourceUrl(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeBusinessCardFromUrlIncludeFieldElements(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeBusinessCardSourceUrlWithPngFile(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); void validateReceiptDataFields(Map<String, FormField> actualRecognizedReceiptFields, boolean includeFieldElements) { final AnalyzeResult analyzeResult = getAnalyzeRawResponse().getAnalyzeResult(); List<ReadResult> readResults = analyzeResult.getReadResults(); DocumentResult documentResult = analyzeResult.getDocumentResults().get(0); Map<String, FieldValue> expectedReceiptFields = documentResult.getFields(); assertEquals(expectedReceiptFields.get("ReceiptType").getValueString(), actualRecognizedReceiptFields.get("ReceiptType").getValue().asString()); assertEquals(expectedReceiptFields.get("ReceiptType").getConfidence(), actualRecognizedReceiptFields.get("ReceiptType").getConfidence()); validateFieldValueTransforms(expectedReceiptFields.get("MerchantName"), actualRecognizedReceiptFields.get("MerchantName"), readResults, includeFieldElements); validateFieldValueTransforms(expectedReceiptFields.get("MerchantPhoneNumber"), actualRecognizedReceiptFields.get("MerchantPhoneNumber"), readResults, includeFieldElements); validateFieldValueTransforms(expectedReceiptFields.get("MerchantAddress"), actualRecognizedReceiptFields.get("MerchantAddress"), readResults, includeFieldElements); validateFieldValueTransforms(expectedReceiptFields.get("Total"), actualRecognizedReceiptFields.get("Total"), readResults, includeFieldElements); validateFieldValueTransforms(expectedReceiptFields.get("Subtotal"), actualRecognizedReceiptFields.get("Subtotal"), readResults, includeFieldElements); validateFieldValueTransforms(expectedReceiptFields.get("Tax"), actualRecognizedReceiptFields.get("Tax"), readResults, includeFieldElements); validateFieldValueTransforms(expectedReceiptFields.get("TransactionDate"), actualRecognizedReceiptFields.get("TransactionDate"), readResults, includeFieldElements); validateFieldValueTransforms(expectedReceiptFields.get("TransactionTime"), actualRecognizedReceiptFields.get("TransactionTime"), readResults, includeFieldElements); validateFieldValueTransforms(expectedReceiptFields.get("Items"), actualRecognizedReceiptFields.get("Items"), readResults, includeFieldElements); } void validateContentResultData(List<FormPage> actualFormPageList, boolean includeFieldElements) { AnalyzeResult analyzeResult = getAnalyzeRawResponse().getAnalyzeResult(); final List<PageResult> pageResults = analyzeResult.getPageResults(); final List<ReadResult> readResults = analyzeResult.getReadResults(); for (int i = 0; i < actualFormPageList.size(); i++) { FormPage actualFormPage = actualFormPageList.get(i); ReadResult readResult = readResults.get(i); if (readResult.getAngle() > 180) { assertEquals(readResult.getAngle() - 360, actualFormPage.getTextAngle()); } else { assertEquals(readResult.getAngle(), actualFormPage.getTextAngle()); } assertEquals(readResult.getWidth(), actualFormPage.getWidth()); assertEquals(readResult.getHeight(), actualFormPage.getHeight()); assertEquals(readResult.getUnit().toString(), actualFormPage.getUnit().toString()); assertEquals(readResult.getPage(), actualFormPage.getPageNumber()); if (includeFieldElements) { validateFormLineData(readResult.getLines(), actualFormPage.getLines()); } if (pageResults != null) { validateFormTableData(pageResults.get(i).getTables(), actualFormPage.getTables(), readResults, includeFieldElements, pageResults.get(i).getPage()); } } } void validateReceiptResultData(List<RecognizedForm> actualReceiptList, boolean includeFieldElements) { final AnalyzeResult rawResponse = getAnalyzeRawResponse().getAnalyzeResult(); for (int i = 0; i < actualReceiptList.size(); i++) { final RecognizedForm actualReceipt = actualReceiptList.get(i); validateLabeledData(actualReceipt, includeFieldElements, rawResponse.getReadResults(), rawResponse.getDocumentResults().get(i)); validateReceiptDataFields(actualReceipt.getFields(), includeFieldElements); } } void validateBlankPdfResultData(List<RecognizedForm> actualReceiptList) { assertEquals(1, actualReceiptList.size()); final RecognizedForm actualReceipt = actualReceiptList.get(0); assertTrue(actualReceipt.getFields().isEmpty()); } void validateRecognizedResult(List<RecognizedForm> actualFormList, boolean includeFieldElements, boolean isLabeled) { final AnalyzeResult rawResponse = getAnalyzeRawResponse().getAnalyzeResult(); List<ReadResult> readResults = rawResponse.getReadResults(); List<PageResult> pageResults = rawResponse.getPageResults(); List<DocumentResult> documentResults = rawResponse.getDocumentResults(); for (int i = 0; i < actualFormList.size(); i++) { validateContentResultData(actualFormList.get(i).getPages(), includeFieldElements); if (isLabeled) { validateLabeledData(actualFormList.get(i), includeFieldElements, readResults, documentResults.get(i)); } else { validateUnLabeledResult(actualFormList.get(i), includeFieldElements, readResults, pageResults.get(i)); } } } void validateBusinessCardDataFields(Map<String, FormField> actualRecognizedBusinessCardFields, boolean includeFieldElements) { final AnalyzeResult analyzeResult = getAnalyzeRawResponse().getAnalyzeResult(); List<ReadResult> readResults = analyzeResult.getReadResults(); DocumentResult documentResult = analyzeResult.getDocumentResults().get(0); Map<String, FieldValue> expectedReceiptFields = documentResult.getFields(); validateFieldValueTransforms(expectedReceiptFields.get(CONTACT_NAMES), actualRecognizedBusinessCardFields.get(CONTACT_NAMES), readResults, includeFieldElements); validateFieldValueTransforms(expectedReceiptFields.get(JOB_TITLES), actualRecognizedBusinessCardFields.get(JOB_TITLES), readResults, includeFieldElements); validateFieldValueTransforms(expectedReceiptFields.get(DEPARTMENTS), actualRecognizedBusinessCardFields.get(DEPARTMENTS), readResults, includeFieldElements); validateFieldValueTransforms(expectedReceiptFields.get(EMAILS), actualRecognizedBusinessCardFields.get(EMAILS), readResults, includeFieldElements); validateFieldValueTransforms(expectedReceiptFields.get(WEBSITES), actualRecognizedBusinessCardFields.get(WEBSITES), readResults, includeFieldElements); validateFieldValueTransforms(expectedReceiptFields.get(MOBILE_PHONES), actualRecognizedBusinessCardFields.get(MOBILE_PHONES), readResults, includeFieldElements); validateFieldValueTransforms(expectedReceiptFields.get(OTHER_PHONES), actualRecognizedBusinessCardFields.get(OTHER_PHONES), readResults, includeFieldElements); validateFieldValueTransforms(expectedReceiptFields.get(FAXES), actualRecognizedBusinessCardFields.get(FAXES), readResults, includeFieldElements); validateFieldValueTransforms(expectedReceiptFields.get(ADDRESSES), actualRecognizedBusinessCardFields.get(ADDRESSES), readResults, includeFieldElements); validateFieldValueTransforms(expectedReceiptFields.get(COMPANY_NAMES), actualRecognizedBusinessCardFields.get(COMPANY_NAMES), readResults, includeFieldElements); } void validateBusinessCardResultData(List<RecognizedForm> actualBusinessCardList, boolean includeFieldElements) { final AnalyzeResult rawResponse = getAnalyzeRawResponse().getAnalyzeResult(); for (int i = 0; i < actualBusinessCardList.size(); i++) { final RecognizedForm actualBusinessCard = actualBusinessCardList.get(i); validateLabeledData(actualBusinessCard, includeFieldElements, rawResponse.getReadResults(), rawResponse.getDocumentResults().get(i)); validateBusinessCardDataFields(actualBusinessCard.getFields(), includeFieldElements); } } void invalidSourceUrlRunner(Consumer<String> testRunner) { testRunner.accept(TestUtils.INVALID_RECEIPT_URL); } void encodedBlankSpaceSourceUrlRunner(Consumer<String> testRunner) { testRunner.accept(FAKE_ENCODED_EMPTY_SPACE_URL); } void urlRunner(Consumer<String> testRunner, String fileName) { testRunner.accept(URL_TEST_FILE_FORMAT + fileName); } void storageUrlRunner(Consumer<String> testRunner, String fileName) { testRunner.accept(getStorageTestingFileUrl(fileName)); } void urlPdfUnlabeledRunner(Consumer<String> testRunner) { testRunner.accept(getStorageTestingFileUrl(MULTIPAGE_INVOICE_PDF)); } void dataRunner(BiConsumer<InputStream, Long> testRunner, String fileName) { final long fileLength = new File(LOCAL_FILE_PATH + fileName).length(); if (interceptorManager.isPlaybackMode()) { testRunner.accept(new ByteArrayInputStream(TEST_DATA_PNG.getBytes(StandardCharsets.UTF_8)), fileLength); } else { try { testRunner.accept(new FileInputStream(LOCAL_FILE_PATH + fileName), fileLength); } catch (FileNotFoundException e) { throw new RuntimeException("Local file not found.", e); } } } void localFilePathRunner(BiConsumer<String, Long> testRunner, String fileName) { final long fileLength = new File(LOCAL_FILE_PATH + fileName).length(); testRunner.accept(LOCAL_FILE_PATH + fileName, fileLength); } void damagedPdfDataRunner(BiConsumer<InputStream, Integer> testRunner) { testRunner.accept(new ByteArrayInputStream(new byte[]{0x25, 0x50, 0x44, 0x46, 0x55, 0x55, 0x55}), 7); } void beginTrainingUnlabeledRunner(BiConsumer<String, Boolean> testRunner) { testRunner.accept(getTrainingSasUri(), false); } void beginTrainingLabeledRunner(BiConsumer<String, Boolean> testRunner) { testRunner.accept(getTrainingSasUri(), true); } void beginTrainingMultipageRunner(Consumer<String> testRunner) { testRunner.accept(getMultipageTrainingSasUri()); } private void validateUnLabeledResult(RecognizedForm actualForm, boolean includeFieldElements, List<ReadResult> readResults, PageResult expectedPage) { validatePageRangeData(expectedPage.getPage(), actualForm.getPageRange()); int i = 0; for (Map.Entry<String, FormField> entry : actualForm.getFields().entrySet()) { FormField actualFormField = entry.getValue(); final KeyValuePair expectedFormField = expectedPage.getKeyValuePairs().get(i++); assertEquals(expectedFormField.getConfidence(), actualFormField.getConfidence()); assertEquals(expectedFormField.getKey().getText(), actualFormField.getLabelData().getText()); validateBoundingBoxData(expectedFormField.getKey().getBoundingBox(), actualFormField.getLabelData().getBoundingBox()); if (includeFieldElements) { validateReferenceElementsData(expectedFormField.getKey().getElements(), actualFormField.getLabelData().getFieldElements(), readResults); validateReferenceElementsData(expectedFormField.getValue().getElements(), actualFormField.getValueData().getFieldElements(), readResults); } assertEquals(expectedFormField.getValue().getText(), actualFormField.getValueData().getText()); validateBoundingBoxData(expectedFormField.getValue().getBoundingBox(), actualFormField.getValueData().getBoundingBox()); } } private void validateLabeledData(RecognizedForm actualForm, boolean includeFieldElements, List<ReadResult> readResults, DocumentResult documentResult) { assertEquals(documentResult.getPageRange().get(0), actualForm.getPageRange().getFirstPageNumber()); assertEquals(documentResult.getPageRange().get(1), actualForm.getPageRange().getLastPageNumber()); assertEquals(documentResult.getFields().keySet(), actualForm.getFields().keySet()); documentResult.getFields().forEach((label, expectedFieldValue) -> { final FormField actualFormField = actualForm.getFields().get(label); assertEquals(label, actualFormField.getName()); if (expectedFieldValue != null) { if (expectedFieldValue.getConfidence() != null) { assertEquals(expectedFieldValue.getConfidence(), actualFormField.getConfidence()); } else { assertEquals(1.0f, actualFormField.getConfidence()); } validateFieldValueTransforms(expectedFieldValue, actualFormField, readResults, includeFieldElements); } }); } static void validateMultiPageDataUnlabeled(List<RecognizedForm> actualRecognizedFormsList) { actualRecognizedFormsList.forEach(recognizedForm -> { assertNotNull(recognizedForm.getFormType()); assertEquals(1, (long) recognizedForm.getPages().size()); recognizedForm.getFields().forEach((label, formField) -> { assertNotNull(formField.getName()); assertNotNull(formField.getValue()); assertNotNull(formField.getValueData().getText()); assertNotNull(formField.getLabelData().getText()); }); }); } static void validateMultipageReceiptData(List<RecognizedForm> recognizedReceipts) { assertEquals(3, recognizedReceipts.size()); RecognizedForm receiptPage1 = recognizedReceipts.get(0); RecognizedForm receiptPage2 = recognizedReceipts.get(1); RecognizedForm receiptPage3 = recognizedReceipts.get(2); assertEquals(1, receiptPage1.getPageRange().getFirstPageNumber()); assertEquals(1, receiptPage1.getPageRange().getLastPageNumber()); Map<String, FormField> receiptPage1Fields = receiptPage1.getFields(); assertEquals(EXPECTED_MULTIPAGE_ADDRESS_VALUE, receiptPage1Fields.get("MerchantAddress") .getValue().asString()); assertEquals("Bilbo Baggins", receiptPage1Fields.get("MerchantName") .getValue().asString()); assertEquals(EXPECTED_MULTIPAGE_PHONE_NUMBER_VALUE, receiptPage1Fields.get("MerchantPhoneNumber") .getValue().asPhoneNumber()); assertNotNull(receiptPage1Fields.get("Total").getValue().asFloat()); assertNotNull(receiptPage1.getPages()); assertEquals(ITEMIZED_RECEIPT_VALUE, receiptPage1Fields.get("ReceiptType").getValue().asString()); assertEquals(0, receiptPage2.getFields().size()); List<FormPage> receipt2Pages = receiptPage2.getPages(); assertEquals(1, receipt2Pages.size()); assertEquals(0, receipt2Pages.stream().findFirst().get().getTables().size()); assertEquals(0, receipt2Pages.stream().findFirst().get().getLines().size()); assertEquals(2, receiptPage2.getPageRange().getFirstPageNumber()); assertEquals(2, receiptPage2.getPageRange().getLastPageNumber()); assertEquals(3, receiptPage3.getPageRange().getFirstPageNumber()); assertEquals(3, receiptPage3.getPageRange().getLastPageNumber()); Map<String, FormField> receiptPage3Fields = receiptPage3.getFields(); assertEquals(EXPECTED_MULTIPAGE_ADDRESS_VALUE, receiptPage3Fields.get("MerchantAddress").getValue().asString()); assertEquals("Frodo Baggins", receiptPage3Fields.get("MerchantName").getValue().asString()); assertEquals(EXPECTED_MULTIPAGE_PHONE_NUMBER_VALUE, receiptPage3Fields.get("MerchantPhoneNumber").getValue().asPhoneNumber()); assertNotNull(receiptPage3Fields.get("Total").getValue().asFloat()); assertEquals(3000.0f, receiptPage3Fields.get("Subtotal").getValue().asFloat()); assertEquals(ITEMIZED_RECEIPT_VALUE, receiptPage3Fields.get("ReceiptType").getValue().asString()); } protected String getEndpoint() { return interceptorManager.isPlaybackMode() ? "https: : Configuration.getGlobalConfiguration().get(AZURE_FORM_RECOGNIZER_ENDPOINT); } /** * Get the training data set SAS Url value based on the test running mode. * * @return the training data set Url */ private String getTrainingSasUri() { if (interceptorManager.isPlaybackMode()) { return "https: } else { return Configuration.getGlobalConfiguration().get(FORM_RECOGNIZER_TRAINING_BLOB_CONTAINER_SAS_URL); } } /** * Get the training data set SAS Url value based on the test running mode. * * @return the training data set Url */ private String getMultipageTrainingSasUri() { if (interceptorManager.isPlaybackMode()) { return "https: } else { return Configuration.getGlobalConfiguration() .get(FORM_RECOGNIZER_MULTIPAGE_TRAINING_BLOB_CONTAINER_SAS_URL); } } /** * Get the testing data set SAS Url value based on the test running mode. * * @return the testing data set Url */ private String getTestingSasUri() { if (interceptorManager.isPlaybackMode()) { return "https: } else { return Configuration.getGlobalConfiguration().get("FORM_RECOGNIZER_TESTING_BLOB_CONTAINER_SAS_URL"); } } /** * Prepare the file url from the testing data set SAS Url value. * * @return the testing data specific file Url */ private String getStorageTestingFileUrl(String fileName) { if (interceptorManager.isPlaybackMode()) { return "https: } else { final String[] urlParts = getTestingSasUri().split("\\?"); return urlParts[0] + "/" + fileName + "?" + urlParts[1]; } } /** * Prepare the expected test data from service raw response. * * @return the {@code AnalyzeOperationResult} test data */ private AnalyzeOperationResult getAnalyzeRawResponse() { final SerializerAdapter serializerAdapter = getSerializerAdapter(); final NetworkCallRecord networkCallRecord = interceptorManager.getRecordedData().findFirstAndRemoveNetworkCall(record -> { AnalyzeOperationResult rawModelResponse = deserializeRawResponse(serializerAdapter, record, AnalyzeOperationResult.class); return rawModelResponse != null && rawModelResponse.getStatus() == OperationStatus.SUCCEEDED; }); interceptorManager.getRecordedData().addNetworkCall(networkCallRecord); return deserializeRawResponse(serializerAdapter, networkCallRecord, AnalyzeOperationResult.class); } }
class FormRecognizerClientTestBase extends TestBase { private static final Pattern NON_DIGIT_PATTERN = Pattern.compile("[^0-9]+"); private static final String EXPECTED_MULTIPAGE_ADDRESS_VALUE = "123 Hobbit Lane 567 Main St. Redmond, WA Redmond," + " WA"; private static final String EXPECTED_MULTIPAGE_PHONE_NUMBER_VALUE = "+15555555555"; private static final String ITEMIZED_RECEIPT_VALUE = "Itemized"; static final String RECEIPT_CONTOSO_JPG = "contoso-allinone.jpg"; static final String RECEIPT_CONTOSO_PNG = "contoso-receipt.png"; static final String INVOICE_6_PDF = "Invoice_6.pdf"; static final String MULTIPAGE_INVOICE_PDF = "multipage_invoice1.pdf"; static final String BUSINESS_CARD_JPG = "businessCard.jpg"; static final String BUSINESS_CARD_PNG = "businessCard.png"; static final String BAD_ARGUMENT_CODE = "BadArgument"; static final String INVALID_IMAGE_ERROR_CODE = "InvalidImage"; static final String INVALID_MODEL_ID_ERROR_CODE = "1001"; static final String MODEL_ID_NOT_FOUND_ERROR_CODE = "1022"; static final String URL_BADLY_FORMATTED_ERROR_CODE = "2001"; static final String UNABLE_TO_READ_FILE_ERROR_CODE = "2005"; static final String HTTPS_EXCEPTION_MESSAGE = "Max retries 3 times exceeded. Error Details: Key credentials require HTTPS to prevent leaking the key."; static final String INVALID_UUID_EXCEPTION_MESSAGE = "Invalid UUID string: "; static final String MODEL_ID_IS_REQUIRED_EXCEPTION_MESSAGE = "'modelId' is required and cannot be null."; static final String INVALID_ENDPOINT = "https: static final String LOCAL_FILE_PATH = "src/test/resources/sample_files/Test/"; static final String ENCODED_EMPTY_SPACE = "{\"source\":\"https: static final List<String> BUSINESS_CARD_FIELDS = Arrays.asList("ContactNames", "JobTitles", "Departments", "Emails", "Websites", "MobilePhones", "OtherPhones", "Faxes", "Addresses", "CompanyNames"); Duration durationTestMode; /** * Use duration of nearly zero value for PLAYBACK test mode, otherwise, use default duration value for LIVE mode. */ @Override protected void beforeTest() { if (interceptorManager.isPlaybackMode()) { durationTestMode = ONE_NANO_DURATION; } else { durationTestMode = DEFAULT_DURATION; } } FormRecognizerClientBuilder getFormRecognizerClientBuilder(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { FormRecognizerClientBuilder builder = new FormRecognizerClientBuilder() .endpoint(getEndpoint()) .httpClient(httpClient == null ? interceptorManager.getPlaybackClient() : httpClient) .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)) .serviceVersion(serviceVersion) .addPolicy(interceptorManager.getRecordPolicy()); if (getTestMode() == TestMode.PLAYBACK) { builder.credential(new AzureKeyCredential(INVALID_KEY)); } else { builder.credential(new DefaultAzureCredentialBuilder().build()); } return builder; } FormTrainingClientBuilder getFormTrainingClientBuilder(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { FormTrainingClientBuilder builder = new FormTrainingClientBuilder() .endpoint(getEndpoint()) .httpClient(httpClient == null ? interceptorManager.getPlaybackClient() : httpClient) .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)) .serviceVersion(serviceVersion) .addPolicy(interceptorManager.getRecordPolicy()); if (getTestMode() == TestMode.PLAYBACK) { builder.credential(new AzureKeyCredential(INVALID_KEY)); } else { builder.credential(new AzureKeyCredential(Configuration.getGlobalConfiguration().get(AZURE_FORM_RECOGNIZER_API_KEY))); } return builder; } private static void validateReferenceElementsData(List<String> expectedElements, List<FormElement> actualFormElementList, List<ReadResult> readResults) { if (expectedElements != null && actualFormElementList != null) { assertEquals(expectedElements.size(), actualFormElementList.size()); for (int i = 0; i < actualFormElementList.size(); i++) { String[] indices = NON_DIGIT_PATTERN.matcher(expectedElements.get(i)).replaceAll(" ").trim().split(" "); if (indices.length < 2) { return; } int readResultIndex = Integer.parseInt(indices[0]); int lineIndex = Integer.parseInt(indices[1]); if (indices.length == 3) { int wordIndex = Integer.parseInt(indices[2]); TextWord expectedTextWord = readResults.get(readResultIndex).getLines().get(lineIndex).getWords().get(wordIndex); TextLine expectedTextLine = readResults.get(readResultIndex).getLines().get(lineIndex); if (actualFormElementList.get(i) instanceof FormLine) { FormLine actualFormLine = (FormLine) actualFormElementList.get(i); validateFormWordData(expectedTextLine.getWords(), actualFormLine.getWords()); } FormWord actualFormWord = (FormWord) actualFormElementList.get(i); assertEquals(expectedTextWord.getText(), actualFormWord.getText()); if (expectedTextWord.getConfidence() != null) { assertEquals(expectedTextWord.getConfidence(), actualFormWord.getConfidence()); } else { assertEquals(1.0f, actualFormWord.getConfidence()); } validateBoundingBoxData(expectedTextWord.getBoundingBox(), actualFormWord.getBoundingBox()); } } } } private static void validateFormTableData(List<DataTable> expectedFormTables, List<FormTable> actualFormTable, List<ReadResult> readResults, boolean includeFieldElements, int pageNumber) { assertEquals(expectedFormTables.size(), actualFormTable.size()); for (int i = 0; i < actualFormTable.size(); i++) { DataTable expectedTable = expectedFormTables.get(i); FormTable actualTable = actualFormTable.get(i); assertEquals(pageNumber, actualTable.getPageNumber()); assertEquals(expectedTable.getColumns(), actualTable.getColumnCount()); validateCellData(expectedTable.getCells(), actualTable.getCells(), readResults, includeFieldElements); assertEquals(expectedTable.getRows(), actualTable.getRowCount()); } } private static void validateCellData(List<DataTableCell> expectedTableCells, List<FormTableCell> actualTableCellList, List<ReadResult> readResults, boolean includeFieldElements) { assertEquals(expectedTableCells.size(), actualTableCellList.size()); for (int i = 0; i < actualTableCellList.size(); i++) { DataTableCell expectedTableCell = expectedTableCells.get(i); FormTableCell actualTableCell = actualTableCellList.get(i); assertEquals(expectedTableCell.getColumnIndex(), actualTableCell.getColumnIndex()); if (expectedTableCell.getColumnSpan() != null) { assertEquals(expectedTableCell.getColumnSpan(), actualTableCell.getColumnSpan()); } assertNotNull(actualTableCell.getColumnSpan()); assertEquals(expectedTableCell.getRowIndex(), actualTableCell.getRowIndex()); if (expectedTableCell.getRowSpan() != null) { assertEquals(expectedTableCell.getRowSpan(), actualTableCell.getRowSpan()); } assertNotNull(actualTableCell.getRowSpan()); validateBoundingBoxData(expectedTableCell.getBoundingBox(), actualTableCell.getBoundingBox()); if (includeFieldElements) { validateReferenceElementsData(expectedTableCell.getElements(), actualTableCell.getFieldElements(), readResults); } } } private static void validateFormLineData(List<TextLine> expectedLines, List<FormLine> actualLineList) { assertEquals(expectedLines.size(), actualLineList.size()); for (int i = 0; i < actualLineList.size(); i++) { TextLine expectedLine = expectedLines.get(i); FormLine actualLine = actualLineList.get(i); assertEquals(expectedLine.getText(), actualLine.getText()); validateBoundingBoxData(expectedLine.getBoundingBox(), actualLine.getBoundingBox()); validateFormWordData(expectedLine.getWords(), actualLine.getWords()); } } private static void validateFormWordData(List<TextWord> expectedFormWords, List<FormWord> actualFormWordList) { assertEquals(expectedFormWords.size(), actualFormWordList.size()); for (int i = 0; i < actualFormWordList.size(); i++) { TextWord expectedWord = expectedFormWords.get(i); FormWord actualWord = actualFormWordList.get(i); assertEquals(expectedWord.getText(), actualWord.getText()); validateBoundingBoxData(expectedWord.getBoundingBox(), actualWord.getBoundingBox()); if (expectedWord.getConfidence() != null) { assertEquals(expectedWord.getConfidence(), actualWord.getConfidence()); } else { assertEquals(1.0f, actualWord.getConfidence()); } } } private static void validateBoundingBoxData(List<Float> expectedBoundingBox, FieldBoundingBox actualFieldBoundingBox) { if (actualFieldBoundingBox != null && actualFieldBoundingBox.getPoints() != null) { int i = 0; for (Point point : actualFieldBoundingBox.getPoints()) { assertEquals(expectedBoundingBox.get(i), point.getX()); assertEquals(expectedBoundingBox.get(++i), point.getY()); i++; } } } @SuppressWarnings("unchecked") private static void validateFieldValueTransforms(FieldValue expectedFieldValue, FormField actualFormField, List<ReadResult> readResults, boolean includeFieldElements) { if (expectedFieldValue != null) { if (expectedFieldValue.getBoundingBox() != null) { validateBoundingBoxData(expectedFieldValue.getBoundingBox(), actualFormField.getValueData().getBoundingBox()); } if (includeFieldElements && expectedFieldValue.getElements() != null) { validateReferenceElementsData(expectedFieldValue.getElements(), actualFormField.getValueData().getFieldElements(), readResults); } switch (expectedFieldValue.getType()) { case NUMBER: if (expectedFieldValue.getValueNumber() != null) { assertEquals(expectedFieldValue.getValueNumber(), actualFormField.getValue().asFloat()); } break; case DATE: assertEquals(expectedFieldValue.getValueDate(), actualFormField.getValue().asDate()); break; case TIME: assertEquals(LocalTime.parse(expectedFieldValue.getValueTime(), DateTimeFormatter.ofPattern("HH:mm:ss")), actualFormField.getValue().asTime()); break; case STRING: if (actualFormField.getName() != "ReceiptType") { assertEquals(expectedFieldValue.getValueString(), actualFormField.getValue().asString()); } break; case INTEGER: assertEquals(expectedFieldValue.getValueInteger(), actualFormField.getValue().asLong()); break; case PHONE_NUMBER: assertEquals(expectedFieldValue.getValuePhoneNumber(), actualFormField.getValue().asPhoneNumber()); break; case OBJECT: expectedFieldValue.getValueObject().forEach((key, formField) -> { FormField actualFormFieldValue = actualFormField.getValue().asMap().get(key); validateFieldValueTransforms(formField, actualFormFieldValue, readResults, includeFieldElements); }); break; case ARRAY: assertEquals(expectedFieldValue.getValueArray().size(), actualFormField.getValue().asList().size()); for (int i = 0; i < expectedFieldValue.getValueArray().size(); i++) { FieldValue expectedReceiptItem = expectedFieldValue.getValueArray().get(i); FormField actualReceiptItem = actualFormField.getValue().asList().get(i); validateFieldValueTransforms(expectedReceiptItem, actualReceiptItem, readResults, includeFieldElements); } break; default: assertFalse(false, "Field type not supported."); } } } private static void validatePageRangeData(int expectedPageInfo, FormPageRange actualPageInfo) { assertEquals(expectedPageInfo, actualPageInfo.getFirstPageNumber()); assertEquals(expectedPageInfo, actualPageInfo.getLastPageNumber()); } @Test abstract void recognizeReceiptData(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeReceiptDataNullData(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeReceiptDataWithContentTypeAutoDetection(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeReceiptDataIncludeFieldElements(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeReceiptDataWithPngFile(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeReceiptDataWithBlankPdf(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeReceiptFromDataMultiPage(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeReceiptSourceUrl(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeReceiptInvalidSourceUrl(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeReceiptFromUrlIncludeFieldElements(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeReceiptSourceUrlWithPngFile(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeReceiptFromUrlMultiPage(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeContent(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeContentResultWithNullData(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeContentResultWithContentTypeAutoDetection(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeContentResultWithBlankPdf(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeContentFromDataMultiPage(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeContentFromUrl(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeContentFromUrlWithPdf(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeContentInvalidSourceUrl(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeContentFromUrlMultiPage(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormLabeledData(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormLabeledDataWithJpgContentType(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormLabeledDataWithBlankPdfContentType(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormLabeledDataExcludeFieldElements(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormLabeledDataWithNullFormData(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormLabeledDataWithNullModelId(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormLabeledDataWithEmptyModelId(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormInvalidStatus(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormLabeledDataWithContentTypeAutoDetection(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormMultiPageLabeled(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormUnlabeledData(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormUnlabeledDataIncludeFieldElements(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormMultiPageUnlabeled(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormUnlabeledDataWithJpgContentType(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormUnlabeledDataWithBlankPdfContentType(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormUrlUnlabeledData(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormUrlUnlabeledDataIncludeFieldElements(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormUrlMultiPageUnlabeled(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormInvalidSourceUrl(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormFromUrlLabeledDataWithNullModelId(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormFromUrlLabeledDataWithEmptyModelId(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormUrlLabeledData(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormUrlLabeledDataIncludeFieldElements(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormUrlMultiPageLabeled(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeBusinessCardData(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeBusinessCardDataNullData(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeBusinessCardDataWithContentTypeAutoDetection(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeBusinessCardDataIncludeFieldElements(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeBusinessCardDataWithPngFile(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeBusinessCardDataWithBlankPdf(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeBusinessCardFromDamagedPdf(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeBusinessCardSourceUrl(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeBusinessCardFromUrlWithEncodedBlankSpaceSourceUrl(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeBusinessCardInvalidSourceUrl(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeBusinessCardFromUrlIncludeFieldElements(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeBusinessCardSourceUrlWithPngFile(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); void validateReceiptDataFields(Map<String, FormField> actualRecognizedReceiptFields, boolean includeFieldElements) { final AnalyzeResult analyzeResult = getAnalyzeRawResponse().getAnalyzeResult(); List<ReadResult> readResults = analyzeResult.getReadResults(); DocumentResult documentResult = analyzeResult.getDocumentResults().get(0); Map<String, FieldValue> expectedReceiptFields = documentResult.getFields(); assertEquals(expectedReceiptFields.get("ReceiptType").getValueString(), actualRecognizedReceiptFields.get("ReceiptType").getValue().asString()); assertEquals(expectedReceiptFields.get("ReceiptType").getConfidence(), actualRecognizedReceiptFields.get("ReceiptType").getConfidence()); validateFieldValueTransforms(expectedReceiptFields.get("MerchantName"), actualRecognizedReceiptFields.get("MerchantName"), readResults, includeFieldElements); validateFieldValueTransforms(expectedReceiptFields.get("MerchantPhoneNumber"), actualRecognizedReceiptFields.get("MerchantPhoneNumber"), readResults, includeFieldElements); validateFieldValueTransforms(expectedReceiptFields.get("MerchantAddress"), actualRecognizedReceiptFields.get("MerchantAddress"), readResults, includeFieldElements); validateFieldValueTransforms(expectedReceiptFields.get("Total"), actualRecognizedReceiptFields.get("Total"), readResults, includeFieldElements); validateFieldValueTransforms(expectedReceiptFields.get("Subtotal"), actualRecognizedReceiptFields.get("Subtotal"), readResults, includeFieldElements); validateFieldValueTransforms(expectedReceiptFields.get("Tax"), actualRecognizedReceiptFields.get("Tax"), readResults, includeFieldElements); validateFieldValueTransforms(expectedReceiptFields.get("TransactionDate"), actualRecognizedReceiptFields.get("TransactionDate"), readResults, includeFieldElements); validateFieldValueTransforms(expectedReceiptFields.get("TransactionTime"), actualRecognizedReceiptFields.get("TransactionTime"), readResults, includeFieldElements); validateFieldValueTransforms(expectedReceiptFields.get("Items"), actualRecognizedReceiptFields.get("Items"), readResults, includeFieldElements); } void validateContentResultData(List<FormPage> actualFormPageList, boolean includeFieldElements) { AnalyzeResult analyzeResult = getAnalyzeRawResponse().getAnalyzeResult(); final List<PageResult> pageResults = analyzeResult.getPageResults(); final List<ReadResult> readResults = analyzeResult.getReadResults(); for (int i = 0; i < actualFormPageList.size(); i++) { FormPage actualFormPage = actualFormPageList.get(i); ReadResult readResult = readResults.get(i); if (readResult.getAngle() > 180) { assertEquals(readResult.getAngle() - 360, actualFormPage.getTextAngle()); } else { assertEquals(readResult.getAngle(), actualFormPage.getTextAngle()); } assertEquals(readResult.getWidth(), actualFormPage.getWidth()); assertEquals(readResult.getHeight(), actualFormPage.getHeight()); assertEquals(readResult.getUnit().toString(), actualFormPage.getUnit().toString()); assertEquals(readResult.getPage(), actualFormPage.getPageNumber()); if (includeFieldElements) { validateFormLineData(readResult.getLines(), actualFormPage.getLines()); } if (pageResults != null) { validateFormTableData(pageResults.get(i).getTables(), actualFormPage.getTables(), readResults, includeFieldElements, pageResults.get(i).getPage()); } } } void validateReceiptResultData(List<RecognizedForm> actualReceiptList, boolean includeFieldElements) { final AnalyzeResult rawResponse = getAnalyzeRawResponse().getAnalyzeResult(); for (int i = 0; i < actualReceiptList.size(); i++) { final RecognizedForm actualReceipt = actualReceiptList.get(i); validateLabeledData(actualReceipt, includeFieldElements, rawResponse.getReadResults(), rawResponse.getDocumentResults().get(i)); validateReceiptDataFields(actualReceipt.getFields(), includeFieldElements); } } void validateBlankPdfResultData(List<RecognizedForm> actualReceiptList) { assertEquals(1, actualReceiptList.size()); final RecognizedForm actualReceipt = actualReceiptList.get(0); assertTrue(actualReceipt.getFields().isEmpty()); } void validateRecognizedResult(List<RecognizedForm> actualFormList, boolean includeFieldElements, boolean isLabeled) { final AnalyzeResult rawResponse = getAnalyzeRawResponse().getAnalyzeResult(); List<ReadResult> readResults = rawResponse.getReadResults(); List<PageResult> pageResults = rawResponse.getPageResults(); List<DocumentResult> documentResults = rawResponse.getDocumentResults(); for (int i = 0; i < actualFormList.size(); i++) { validateContentResultData(actualFormList.get(i).getPages(), includeFieldElements); if (isLabeled) { validateLabeledData(actualFormList.get(i), includeFieldElements, readResults, documentResults.get(i)); } else { validateUnLabeledResult(actualFormList.get(i), includeFieldElements, readResults, pageResults.get(i)); } } } void validateBusinessCardDataFields(Map<String, FormField> actualRecognizedBusinessCardFields, boolean includeFieldElements) { final AnalyzeResult analyzeResult = getAnalyzeRawResponse().getAnalyzeResult(); List<ReadResult> readResults = analyzeResult.getReadResults(); DocumentResult documentResult = analyzeResult.getDocumentResults().get(0); Map<String, FieldValue> expectedReceiptFields = documentResult.getFields(); BUSINESS_CARD_FIELDS.forEach(businessCardField -> validateFieldValueTransforms(expectedReceiptFields.get(businessCardField), actualRecognizedBusinessCardFields.get(businessCardField), readResults, includeFieldElements)); } void validateBusinessCardResultData(List<RecognizedForm> actualBusinessCardList, boolean includeFieldElements) { final AnalyzeResult rawResponse = getAnalyzeRawResponse().getAnalyzeResult(); for (int i = 0; i < actualBusinessCardList.size(); i++) { final RecognizedForm actualBusinessCard = actualBusinessCardList.get(i); validateLabeledData(actualBusinessCard, includeFieldElements, rawResponse.getReadResults(), rawResponse.getDocumentResults().get(i)); validateBusinessCardDataFields(actualBusinessCard.getFields(), includeFieldElements); } } void invalidSourceUrlRunner(Consumer<String> testRunner) { testRunner.accept(TestUtils.INVALID_RECEIPT_URL); } void encodedBlankSpaceSourceUrlRunner(Consumer<String> testRunner) { testRunner.accept(FAKE_ENCODED_EMPTY_SPACE_URL); } void urlRunner(Consumer<String> testRunner, String fileName) { testRunner.accept(URL_TEST_FILE_FORMAT + fileName); } void storageUrlRunner(Consumer<String> testRunner, String fileName) { testRunner.accept(getStorageTestingFileUrl(fileName)); } void urlPdfUnlabeledRunner(Consumer<String> testRunner) { testRunner.accept(getStorageTestingFileUrl(MULTIPAGE_INVOICE_PDF)); } void dataRunner(BiConsumer<InputStream, Long> testRunner, String fileName) { final long fileLength = new File(LOCAL_FILE_PATH + fileName).length(); if (interceptorManager.isPlaybackMode()) { testRunner.accept(new ByteArrayInputStream(TEST_DATA_PNG.getBytes(StandardCharsets.UTF_8)), fileLength); } else { try { testRunner.accept(new FileInputStream(LOCAL_FILE_PATH + fileName), fileLength); } catch (FileNotFoundException e) { throw new RuntimeException("Local file not found.", e); } } } void localFilePathRunner(BiConsumer<String, Long> testRunner, String fileName) { final long fileLength = new File(LOCAL_FILE_PATH + fileName).length(); testRunner.accept(LOCAL_FILE_PATH + fileName, fileLength); } void damagedPdfDataRunner(BiConsumer<InputStream, Integer> testRunner) { testRunner.accept(new ByteArrayInputStream(new byte[]{0x25, 0x50, 0x44, 0x46, 0x55, 0x55, 0x55}), 7); } void beginTrainingUnlabeledRunner(BiConsumer<String, Boolean> testRunner) { testRunner.accept(getTrainingSasUri(), false); } void beginTrainingLabeledRunner(BiConsumer<String, Boolean> testRunner) { testRunner.accept(getTrainingSasUri(), true); } void beginTrainingMultipageRunner(Consumer<String> testRunner) { testRunner.accept(getMultipageTrainingSasUri()); } private void validateUnLabeledResult(RecognizedForm actualForm, boolean includeFieldElements, List<ReadResult> readResults, PageResult expectedPage) { validatePageRangeData(expectedPage.getPage(), actualForm.getPageRange()); int i = 0; for (Map.Entry<String, FormField> entry : actualForm.getFields().entrySet()) { FormField actualFormField = entry.getValue(); final KeyValuePair expectedFormField = expectedPage.getKeyValuePairs().get(i++); assertEquals(expectedFormField.getConfidence(), actualFormField.getConfidence()); assertEquals(expectedFormField.getKey().getText(), actualFormField.getLabelData().getText()); validateBoundingBoxData(expectedFormField.getKey().getBoundingBox(), actualFormField.getLabelData().getBoundingBox()); if (includeFieldElements) { validateReferenceElementsData(expectedFormField.getKey().getElements(), actualFormField.getLabelData().getFieldElements(), readResults); validateReferenceElementsData(expectedFormField.getValue().getElements(), actualFormField.getValueData().getFieldElements(), readResults); } assertEquals(expectedFormField.getValue().getText(), actualFormField.getValueData().getText()); validateBoundingBoxData(expectedFormField.getValue().getBoundingBox(), actualFormField.getValueData().getBoundingBox()); } } private void validateLabeledData(RecognizedForm actualForm, boolean includeFieldElements, List<ReadResult> readResults, DocumentResult documentResult) { assertEquals(documentResult.getPageRange().get(0), actualForm.getPageRange().getFirstPageNumber()); assertEquals(documentResult.getPageRange().get(1), actualForm.getPageRange().getLastPageNumber()); assertEquals(documentResult.getFields().keySet(), actualForm.getFields().keySet()); documentResult.getFields().forEach((label, expectedFieldValue) -> { final FormField actualFormField = actualForm.getFields().get(label); assertEquals(label, actualFormField.getName()); if (expectedFieldValue != null) { if (expectedFieldValue.getConfidence() != null) { assertEquals(expectedFieldValue.getConfidence(), actualFormField.getConfidence()); } else { assertEquals(1.0f, actualFormField.getConfidence()); } validateFieldValueTransforms(expectedFieldValue, actualFormField, readResults, includeFieldElements); } }); } static void validateMultiPageDataUnlabeled(List<RecognizedForm> actualRecognizedFormsList) { actualRecognizedFormsList.forEach(recognizedForm -> { assertNotNull(recognizedForm.getFormType()); assertEquals(1, (long) recognizedForm.getPages().size()); recognizedForm.getFields().forEach((label, formField) -> { assertNotNull(formField.getName()); assertNotNull(formField.getValue()); assertNotNull(formField.getValueData().getText()); assertNotNull(formField.getLabelData().getText()); }); }); } static void validateMultipageReceiptData(List<RecognizedForm> recognizedReceipts) { assertEquals(3, recognizedReceipts.size()); RecognizedForm receiptPage1 = recognizedReceipts.get(0); RecognizedForm receiptPage2 = recognizedReceipts.get(1); RecognizedForm receiptPage3 = recognizedReceipts.get(2); assertEquals(1, receiptPage1.getPageRange().getFirstPageNumber()); assertEquals(1, receiptPage1.getPageRange().getLastPageNumber()); Map<String, FormField> receiptPage1Fields = receiptPage1.getFields(); assertEquals(EXPECTED_MULTIPAGE_ADDRESS_VALUE, receiptPage1Fields.get("MerchantAddress") .getValue().asString()); assertEquals("Bilbo Baggins", receiptPage1Fields.get("MerchantName") .getValue().asString()); assertEquals(EXPECTED_MULTIPAGE_PHONE_NUMBER_VALUE, receiptPage1Fields.get("MerchantPhoneNumber") .getValue().asPhoneNumber()); assertNotNull(receiptPage1Fields.get("Total").getValue().asFloat()); assertNotNull(receiptPage1.getPages()); assertEquals(ITEMIZED_RECEIPT_VALUE, receiptPage1Fields.get("ReceiptType").getValue().asString()); assertEquals(0, receiptPage2.getFields().size()); List<FormPage> receipt2Pages = receiptPage2.getPages(); assertEquals(1, receipt2Pages.size()); assertEquals(0, receipt2Pages.stream().findFirst().get().getTables().size()); assertEquals(0, receipt2Pages.stream().findFirst().get().getLines().size()); assertEquals(2, receiptPage2.getPageRange().getFirstPageNumber()); assertEquals(2, receiptPage2.getPageRange().getLastPageNumber()); assertEquals(3, receiptPage3.getPageRange().getFirstPageNumber()); assertEquals(3, receiptPage3.getPageRange().getLastPageNumber()); Map<String, FormField> receiptPage3Fields = receiptPage3.getFields(); assertEquals(EXPECTED_MULTIPAGE_ADDRESS_VALUE, receiptPage3Fields.get("MerchantAddress").getValue().asString()); assertEquals("Frodo Baggins", receiptPage3Fields.get("MerchantName").getValue().asString()); assertEquals(EXPECTED_MULTIPAGE_PHONE_NUMBER_VALUE, receiptPage3Fields.get("MerchantPhoneNumber").getValue().asPhoneNumber()); assertNotNull(receiptPage3Fields.get("Total").getValue().asFloat()); assertEquals(3000.0f, receiptPage3Fields.get("Subtotal").getValue().asFloat()); assertEquals(ITEMIZED_RECEIPT_VALUE, receiptPage3Fields.get("ReceiptType").getValue().asString()); } protected String getEndpoint() { return interceptorManager.isPlaybackMode() ? "https: : Configuration.getGlobalConfiguration().get(AZURE_FORM_RECOGNIZER_ENDPOINT); } /** * Get the training data set SAS Url value based on the test running mode. * * @return the training data set Url */ private String getTrainingSasUri() { if (interceptorManager.isPlaybackMode()) { return "https: } else { return Configuration.getGlobalConfiguration().get(FORM_RECOGNIZER_TRAINING_BLOB_CONTAINER_SAS_URL); } } /** * Get the training data set SAS Url value based on the test running mode. * * @return the training data set Url */ private String getMultipageTrainingSasUri() { if (interceptorManager.isPlaybackMode()) { return "https: } else { return Configuration.getGlobalConfiguration() .get(FORM_RECOGNIZER_MULTIPAGE_TRAINING_BLOB_CONTAINER_SAS_URL); } } /** * Get the testing data set SAS Url value based on the test running mode. * * @return the testing data set Url */ private String getTestingSasUri() { if (interceptorManager.isPlaybackMode()) { return "https: } else { return Configuration.getGlobalConfiguration().get("FORM_RECOGNIZER_TESTING_BLOB_CONTAINER_SAS_URL"); } } /** * Prepare the file url from the testing data set SAS Url value. * * @return the testing data specific file Url */ private String getStorageTestingFileUrl(String fileName) { if (interceptorManager.isPlaybackMode()) { return "https: } else { final String[] urlParts = getTestingSasUri().split("\\?"); return urlParts[0] + "/" + fileName + "?" + urlParts[1]; } } /** * Prepare the expected test data from service raw response. * * @return the {@code AnalyzeOperationResult} test data */ private AnalyzeOperationResult getAnalyzeRawResponse() { final SerializerAdapter serializerAdapter = getSerializerAdapter(); final NetworkCallRecord networkCallRecord = interceptorManager.getRecordedData().findFirstAndRemoveNetworkCall(record -> { AnalyzeOperationResult rawModelResponse = deserializeRawResponse(serializerAdapter, record, AnalyzeOperationResult.class); return rawModelResponse != null && rawModelResponse.getStatus() == OperationStatus.SUCCEEDED; }); interceptorManager.getRecordedData().addNetworkCall(networkCallRecord); return deserializeRawResponse(serializerAdapter, networkCallRecord, AnalyzeOperationResult.class); } }
if we don't have this array type check, the valueData won't be null. We pass this valueData into setFormField(), which directly apply the valueData to `FormField(name, null, valueData, value, setDefaultConfidenceValue(fieldValue.getConfidence()));`
private static List<FormField> toFieldValueArray(List<FieldValue> valueArray, List<ReadResult> readResults) { return valueArray.stream() .map(fieldValue -> { FieldData valueData = null; if (ARRAY != fieldValue.getType()) { valueData = new FieldData(fieldValue.getText(), toBoundingBox(fieldValue.getBoundingBox()), fieldValue.getPage() == null ? -1 : fieldValue.getPage(), setReferenceElements(fieldValue.getElements(), readResults)); } return setFormField(null, valueData, fieldValue, readResults); }) .collect(Collectors.toList()); }
if (ARRAY != fieldValue.getType()) {
private static List<FormField> toFieldValueArray(List<FieldValue> valueArray, List<ReadResult> readResults) { return valueArray.stream() .map(fieldValue -> { FieldData valueData = null; if (ARRAY != fieldValue.getType()) { valueData = new FieldData(fieldValue.getText(), toBoundingBox(fieldValue.getBoundingBox()), fieldValue.getPage() == null ? 1 : fieldValue.getPage(), setReferenceElements(fieldValue.getElements(), readResults)); } return setFormField(null, valueData, fieldValue, readResults); }) .collect(Collectors.toList()); }
class Transforms { private static final ClientLogger LOGGER = new ClientLogger(Transforms.class); private static final Pattern NON_DIGIT_PATTERN = Pattern.compile("[^0-9]+"); private static final float DEFAULT_CONFIDENCE_VALUE = 1.0f; private static final int DEFAULT_TABLE_SPAN = 1; private Transforms() { } /** * Helper method to transform the service returned {@link AnalyzeResult} to SDK model {@link RecognizedForm}. * * @param analyzeResult The service returned result for analyze custom forms. * @param includeFieldElements Boolean to indicate if to set reference elements data on fields. * * @return The List of {@code RecognizedForm}. */ static List<RecognizedForm> toRecognizedForm(AnalyzeResult analyzeResult, boolean includeFieldElements) { List<ReadResult> readResults = analyzeResult.getReadResults(); List<DocumentResult> documentResults = analyzeResult.getDocumentResults(); List<PageResult> pageResults = analyzeResult.getPageResults(); List<RecognizedForm> extractedFormList; List<FormPage> formPages = toRecognizedLayout(analyzeResult, includeFieldElements); if (!CoreUtils.isNullOrEmpty(documentResults)) { extractedFormList = new ArrayList<>(); for (DocumentResult documentResultItem : documentResults) { FormPageRange formPageRange; List<Integer> documentPageRange = documentResultItem.getPageRange(); if (documentPageRange.size() == 2) { formPageRange = new FormPageRange(documentPageRange.get(0), documentPageRange.get(1)); } else { formPageRange = new FormPageRange(1, 1); } Map<String, FormField> extractedFieldMap = getLabeledFieldMap(documentResultItem, readResults); extractedFormList.add(new RecognizedForm( extractedFieldMap, documentResultItem.getDocType(), formPageRange, formPages.subList(formPageRange.getFirstPageNumber() - 1, formPageRange.getLastPageNumber()))); } } else { extractedFormList = new ArrayList<>(); forEachWithIndex(pageResults, ((index, pageResultItem) -> { StringBuilder formType = new StringBuilder("form-"); int pageNumber = pageResultItem.getPage(); Integer clusterId = pageResultItem.getClusterId(); if (clusterId != null) { formType.append(clusterId); } Map<String, FormField> extractedFieldMap = getUnlabeledFieldMap(includeFieldElements, readResults, pageResultItem, pageNumber); extractedFormList.add(new RecognizedForm( extractedFieldMap, formType.toString(), new FormPageRange(pageNumber, pageNumber), Collections.singletonList(formPages.get(index)))); })); } return extractedFormList; } /** * Helper method to transform the service returned {@link AnalyzeResult} to SDK model {@link FormPage}. * * @param analyzeResult The service returned result for analyze layouts. * @param includeFieldElements Boolean to indicate if to set reference elements data on fields. * * @return The List of {@code FormPage}. */ static List<FormPage> toRecognizedLayout(AnalyzeResult analyzeResult, boolean includeFieldElements) { List<ReadResult> readResults = analyzeResult.getReadResults(); List<PageResult> pageResults = analyzeResult.getPageResults(); List<FormPage> formPages = new ArrayList<>(); boolean pageResultsIsNullOrEmpty = CoreUtils.isNullOrEmpty(pageResults); forEachWithIndex(readResults, ((index, readResultItem) -> { List<FormTable> perPageTableList = new ArrayList<>(); if (!pageResultsIsNullOrEmpty) { PageResult pageResultItem = pageResults.get(index); perPageTableList = getPageTables(pageResultItem, readResults, pageResultItem.getPage()); } List<FormLine> perPageFormLineList = new ArrayList<>(); if (includeFieldElements && !CoreUtils.isNullOrEmpty(readResultItem.getLines())) { perPageFormLineList = getReadResultFormLines(readResultItem); } formPages.add(getFormPage(readResultItem, perPageTableList, perPageFormLineList)); })); return formPages; } /** * Helper method to get per-page table information. * * @param pageResultItem The extracted page level information returned by the service. * @param readResults The text extraction result returned by the service. * @param pageNumber The 1 based page number on which these fields exist. * * @return The list of per page {@code FormTable}. */ static List<FormTable> getPageTables(PageResult pageResultItem, List<ReadResult> readResults, int pageNumber) { return pageResultItem.getTables().stream() .map(dataTable -> new FormTable(dataTable.getRows(), dataTable.getColumns(), dataTable.getCells() .stream() .map(dataTableCell -> new FormTableCell( dataTableCell.getRowIndex(), dataTableCell.getColumnIndex(), dataTableCell.getRowSpan() == null ? DEFAULT_TABLE_SPAN : dataTableCell.getRowSpan(), dataTableCell.getColumnSpan() == null ? DEFAULT_TABLE_SPAN : dataTableCell.getColumnSpan(), dataTableCell.getText(), toBoundingBox(dataTableCell.getBoundingBox()), dataTableCell.getConfidence(), dataTableCell.isHeader() == null ? false : dataTableCell.isHeader(), dataTableCell.isFooter() == null ? false : dataTableCell.isFooter(), pageNumber, setReferenceElements(dataTableCell.getElements(), readResults))) .collect(Collectors.toList()), pageNumber)) .collect(Collectors.toList()); } /** * Helper method to convert the per page {@link ReadResult} item to {@link FormLine}. * * @param readResultItem The per page text extraction item result returned by the service. * * @return The list of {@code FormLine}. */ static List<FormLine> getReadResultFormLines(ReadResult readResultItem) { return readResultItem.getLines().stream() .map(textLine -> new FormLine( textLine.getText(), toBoundingBox(textLine.getBoundingBox()), readResultItem.getPage(), toWords(textLine.getWords(), readResultItem.getPage()))) .collect(Collectors.toList()); } /** * The field map returned on analyze with an unlabeled model id. * * @param documentResultItem The extracted document level information. * @param readResults The text extraction result returned by the service. * @return The {@link RecognizedForm */ private static Map<String, FormField> getLabeledFieldMap(DocumentResult documentResultItem, List<ReadResult> readResults) { Map<String, FormField> recognizedFieldMap = new LinkedHashMap<>(); if (!CoreUtils.isNullOrEmpty(documentResultItem.getFields())) { documentResultItem.getFields().forEach((key, fieldValue) -> { if (fieldValue != null) { List<FormElement> formElementList = setReferenceElements(fieldValue.getElements(), readResults); FieldData valueData; if ("ReceiptType".equals(key) || ARRAY == fieldValue.getType()) { valueData = null; } else { valueData = new FieldData(fieldValue.getText(), toBoundingBox(fieldValue.getBoundingBox()), fieldValue.getPage(), formElementList); } recognizedFieldMap.put(key, setFormField(key, valueData, fieldValue, readResults)); } else { recognizedFieldMap.put(key, new FormField(key, null, null, null, DEFAULT_CONFIDENCE_VALUE)); } }); } return recognizedFieldMap; } /** * Helper method that converts the incoming service field value to one of the strongly typed SDK level * {@link FormField} with reference elements set when {@code includeFieldElements} is set to true. * * @param name The name of the field. * @param fieldValue The named field values returned by the service. * @param valueData The value text of the field. * @param readResults The text extraction result returned by the service. * * @return The strongly typed {@link FormField} for the field input. */ private static FormField setFormField(String name, FieldData valueData, FieldValue fieldValue, List<ReadResult> readResults) { com.azure.ai.formrecognizer.models.FieldValue value; switch (fieldValue.getType()) { case PHONE_NUMBER: value = new com.azure.ai.formrecognizer.models.FieldValue(fieldValue.getValuePhoneNumber(), FieldValueType.PHONE_NUMBER); break; case STRING: value = new com.azure.ai.formrecognizer.models.FieldValue(fieldValue.getValueString(), FieldValueType.STRING); break; case TIME: LocalTime fieldTime = fieldValue.getValueTime() == null ? null : LocalTime .parse(fieldValue.getValueTime(), DateTimeFormatter.ofPattern("HH:mm:ss")); value = new com.azure.ai.formrecognizer.models.FieldValue(fieldTime, FieldValueType.TIME); break; case DATE: value = new com.azure.ai.formrecognizer.models.FieldValue(fieldValue.getValueDate(), FieldValueType.DATE); break; case INTEGER: com.azure.ai.formrecognizer.models.FieldValue longFieldValue; if (fieldValue.getValueInteger() == null) { longFieldValue = new com.azure.ai.formrecognizer.models.FieldValue(null, FieldValueType.LONG); } else { longFieldValue = new com.azure.ai.formrecognizer.models.FieldValue(fieldValue.getValueInteger().longValue(), FieldValueType.LONG); } value = longFieldValue; break; case NUMBER: value = new com.azure.ai.formrecognizer.models.FieldValue(fieldValue.getValueNumber(), FieldValueType.FLOAT); break; case ARRAY: value = new com.azure.ai.formrecognizer.models.FieldValue( toFieldValueArray(fieldValue.getValueArray(), readResults), FieldValueType.LIST); break; case OBJECT: value = new com.azure.ai.formrecognizer.models.FieldValue( toFieldValueObject(fieldValue.getValueObject(), readResults), FieldValueType.MAP); break; default: throw LOGGER.logExceptionAsError(new RuntimeException("FieldValue Type not supported")); } return new FormField(name, null, valueData, value, setDefaultConfidenceValue(fieldValue.getConfidence())); } /** * Helper method to set default confidence value if confidence returned by service is null. * * @param confidence the confidence returned by service. * * @return the field confidence value. */ private static float setDefaultConfidenceValue(Float confidence) { return confidence == null ? DEFAULT_CONFIDENCE_VALUE : confidence; } /** * Helper method to convert the service returned * {@link com.azure.ai.formrecognizer.implementation.models.FieldValue * to a SDK level map of {@link FormField}. * * @param valueObject The array of field values returned by the service in {@link FieldValue * * @return The Map of {@link FormField}. */ private static Map<String, FormField> toFieldValueObject(Map<String, FieldValue> valueObject, List<ReadResult> readResults) { Map<String, FormField> fieldValueObjectMap = new TreeMap<>(); valueObject.forEach((key, fieldValue) -> fieldValueObjectMap.put(key, setFormField(key, new FieldData(fieldValue.getText(), toBoundingBox(fieldValue.getBoundingBox()), fieldValue.getPage(), setReferenceElements(fieldValue.getElements(), readResults)), fieldValue, readResults) )); return fieldValueObjectMap; } /** * Helper method to convert the service returned * {@link com.azure.ai.formrecognizer.implementation.models.FieldValue * to a SDK level List of {@link FormField}. * * @param valueArray The array of field values returned by the service in {@link FieldValue * @param readResults The text extraction result returned by the service. * * @return The List of {@link FormField}. */ /** * Helper method to convert the page results to {@code FormPage form pages}. * * @param readResultItem The per page text extraction item result returned by the service. * @param perPageTableList The per page tables list. * @param perPageLineList The per page form lines. * * @return The per page {@code FormPage}. */ private static FormPage getFormPage(ReadResult readResultItem, List<FormTable> perPageTableList, List<FormLine> perPageLineList) { return new FormPage( readResultItem.getHeight(), readResultItem.getAngle(), LengthUnit.fromString(readResultItem.getUnit().toString()), readResultItem.getWidth(), perPageLineList, perPageTableList, readResultItem.getPage()); } /** * Helper method to set the {@link RecognizedForm * service. * * @param includeFieldElements Boolean to indicate if to set reference elements data on fields. * @param readResults The text extraction result returned by the service. * @param pageResultItem The extracted page level information returned by the service. * @param pageNumber The 1 based page number on which these fields exist. * * @return The fields populated on {@link RecognizedForm */ private static Map<String, FormField> getUnlabeledFieldMap(boolean includeFieldElements, List<ReadResult> readResults, PageResult pageResultItem, int pageNumber) { Map<String, FormField> formFieldMap = new LinkedHashMap<>(); List<KeyValuePair> keyValuePairs = pageResultItem.getKeyValuePairs(); forEachWithIndex(keyValuePairs, ((index, keyValuePair) -> { List<FormElement> formKeyContentList = null; List<FormElement> formValueContentList = null; if (includeFieldElements) { formKeyContentList = setReferenceElements(keyValuePair.getKey().getElements(), readResults); formValueContentList = setReferenceElements(keyValuePair.getValue().getElements(), readResults ); } FieldData labelData = new FieldData(keyValuePair.getKey().getText(), toBoundingBox(keyValuePair.getKey().getBoundingBox()), pageNumber, formKeyContentList); FieldData valueData = new FieldData(keyValuePair.getValue().getText(), toBoundingBox(keyValuePair.getValue().getBoundingBox()), pageNumber, formValueContentList); String fieldName = "field-" + index; FormField formField = new FormField(fieldName, labelData, valueData, new com.azure.ai.formrecognizer.models.FieldValue(keyValuePair.getValue().getText(), FieldValueType.STRING), setDefaultConfidenceValue(keyValuePair.getConfidence()) ); formFieldMap.put(fieldName, formField); })); return formFieldMap; } /** * Helper method to set the text reference elements on FieldValue/fields when {@code includeFieldElements} set to * true. * * @return The list if referenced elements. */ private static List<FormElement> setReferenceElements(List<String> elements, List<ReadResult> readResults) { if (CoreUtils.isNullOrEmpty(elements)) { return new ArrayList<>(); } List<FormElement> formElementList = new ArrayList<>(); elements.forEach(elementString -> { String[] indices = NON_DIGIT_PATTERN.matcher(elementString).replaceAll(" ").trim().split(" "); if (indices.length < 2) { throw LOGGER.logExceptionAsError(new RuntimeException("Cannot find corresponding reference elements " + "for the field value.")); } int readResultIndex = Integer.parseInt(indices[0]); int lineIndex = Integer.parseInt(indices[1]); if (indices.length == 3) { int wordIndex = Integer.parseInt(indices[2]); TextWord textWord = readResults.get(readResultIndex).getLines().get(lineIndex).getWords().get(wordIndex); FormWord wordElement = new FormWord(textWord.getText(), toBoundingBox(textWord.getBoundingBox()), readResultIndex + 1, setDefaultConfidenceValue(textWord.getConfidence())); formElementList.add(wordElement); } else { TextLine textLine = readResults.get(readResultIndex).getLines().get(lineIndex); FormLine lineElement = new FormLine(textLine.getText(), toBoundingBox(textLine.getBoundingBox()), readResultIndex + 1, toWords(textLine.getWords(), readResultIndex + 1)); formElementList.add(lineElement); } }); return formElementList; } /** * Helper method to convert the service level {@link TextWord} to list of SDK level model {@link FormWord}. * * @param words A list of word reference elements returned by the service. * @param pageNumber The 1 based page number on which this word element exists. * * @return The list of {@code FormWord words}. */ private static List<FormWord> toWords(List<TextWord> words, int pageNumber) { return words.stream() .map(textWord -> new FormWord( textWord.getText(), toBoundingBox(textWord.getBoundingBox()), pageNumber, setDefaultConfidenceValue(textWord.getConfidence())) ).collect(Collectors.toList()); } /** * Helper method to convert the service level modeled eight numbers representing the four points to SDK level * {@link FieldBoundingBox}. * * @param serviceBoundingBox A list of eight numbers representing the four points of a box. * * @return A {@link FieldBoundingBox}. */ private static FieldBoundingBox toBoundingBox(List<Float> serviceBoundingBox) { if (CoreUtils.isNullOrEmpty(serviceBoundingBox) || (serviceBoundingBox.size() % 2) != 0) { return null; } List<Point> pointList = new ArrayList<>(); for (int i = 0; i < serviceBoundingBox.size(); i++) { pointList.add(new Point(serviceBoundingBox.get(i), serviceBoundingBox.get(++i))); } return new FieldBoundingBox(pointList); } }
class Transforms { private static final ClientLogger LOGGER = new ClientLogger(Transforms.class); private static final Pattern NON_DIGIT_PATTERN = Pattern.compile("[^0-9]+"); private static final float DEFAULT_CONFIDENCE_VALUE = 1.0f; private static final int DEFAULT_TABLE_SPAN = 1; private Transforms() { } /** * Helper method to transform the service returned {@link AnalyzeResult} to SDK model {@link RecognizedForm}. * * @param analyzeResult The service returned result for analyze custom forms. * @param includeFieldElements Boolean to indicate if to set reference elements data on fields. * * @param modelId the unlabeled model Id used for recognition. * @return The List of {@code RecognizedForm}. */ static List<RecognizedForm> toRecognizedForm(AnalyzeResult analyzeResult, boolean includeFieldElements, String modelId) { List<ReadResult> readResults = analyzeResult.getReadResults(); List<DocumentResult> documentResults = analyzeResult.getDocumentResults(); List<PageResult> pageResults = analyzeResult.getPageResults(); List<RecognizedForm> extractedFormList; List<FormPage> formPages = toRecognizedLayout(analyzeResult, includeFieldElements); if (!CoreUtils.isNullOrEmpty(documentResults)) { extractedFormList = new ArrayList<>(); for (DocumentResult documentResultItem : documentResults) { FormPageRange formPageRange; List<Integer> documentPageRange = documentResultItem.getPageRange(); if (documentPageRange.size() == 2) { formPageRange = new FormPageRange(documentPageRange.get(0), documentPageRange.get(1)); } else { formPageRange = new FormPageRange(1, 1); } Map<String, FormField> extractedFieldMap = getLabeledFieldMap(documentResultItem, readResults); final RecognizedForm recognizedForm = new RecognizedForm( extractedFieldMap, documentResultItem.getDocType(), formPageRange, formPages.subList(formPageRange.getFirstPageNumber() - 1, formPageRange.getLastPageNumber())); PrivateFieldAccessHelper.set(recognizedForm, "formTypeConfidence", documentResultItem.getDocTypeConfidence()); if (documentResultItem.getModelId() != null) { PrivateFieldAccessHelper.set(recognizedForm, "modelId", documentResultItem.getModelId().toString()); } extractedFormList.add(recognizedForm); } } else { extractedFormList = new ArrayList<>(); forEachWithIndex(pageResults, ((index, pageResultItem) -> { StringBuilder formType = new StringBuilder("form-"); int pageNumber = pageResultItem.getPage(); Integer clusterId = pageResultItem.getClusterId(); if (clusterId != null) { formType.append(clusterId); } Map<String, FormField> extractedFieldMap = getUnlabeledFieldMap(includeFieldElements, readResults, pageResultItem, pageNumber); final RecognizedForm recognizedForm = new RecognizedForm( extractedFieldMap, formType.toString(), new FormPageRange(pageNumber, pageNumber), Collections.singletonList(formPages.get(index))); PrivateFieldAccessHelper.set(recognizedForm, "modelId", modelId); extractedFormList.add(recognizedForm); })); } return extractedFormList; } /** * Helper method to transform the service returned {@link AnalyzeResult} to SDK model {@link FormPage}. * * @param analyzeResult The service returned result for analyze layouts. * @param includeFieldElements Boolean to indicate if to set reference elements data on fields. * * @return The List of {@code FormPage}. */ static List<FormPage> toRecognizedLayout(AnalyzeResult analyzeResult, boolean includeFieldElements) { List<ReadResult> readResults = analyzeResult.getReadResults(); List<PageResult> pageResults = analyzeResult.getPageResults(); List<FormPage> formPages = new ArrayList<>(); boolean pageResultsIsNullOrEmpty = CoreUtils.isNullOrEmpty(pageResults); forEachWithIndex(readResults, ((index, readResultItem) -> { List<FormTable> perPageTableList = new ArrayList<>(); if (!pageResultsIsNullOrEmpty) { PageResult pageResultItem = pageResults.get(index); perPageTableList = getPageTables(pageResultItem, readResults, pageResultItem.getPage()); } List<FormLine> perPageFormLineList = new ArrayList<>(); if (includeFieldElements && !CoreUtils.isNullOrEmpty(readResultItem.getLines())) { perPageFormLineList = getReadResultFormLines(readResultItem); } formPages.add(getFormPage(readResultItem, perPageTableList, perPageFormLineList)); })); return formPages; } /** * Helper method to get per-page table information. * * @param pageResultItem The extracted page level information returned by the service. * @param readResults The text extraction result returned by the service. * @param pageNumber The 1 based page number on which these fields exist. * * @return The list of per page {@code FormTable}. */ static List<FormTable> getPageTables(PageResult pageResultItem, List<ReadResult> readResults, int pageNumber) { return pageResultItem.getTables().stream() .map(dataTable -> new FormTable(dataTable.getRows(), dataTable.getColumns(), dataTable.getCells() .stream() .map(dataTableCell -> new FormTableCell( dataTableCell.getRowIndex(), dataTableCell.getColumnIndex(), dataTableCell.getRowSpan() == null ? DEFAULT_TABLE_SPAN : dataTableCell.getRowSpan(), dataTableCell.getColumnSpan() == null ? DEFAULT_TABLE_SPAN : dataTableCell.getColumnSpan(), dataTableCell.getText(), toBoundingBox(dataTableCell.getBoundingBox()), dataTableCell.getConfidence(), dataTableCell.isHeader() == null ? false : dataTableCell.isHeader(), dataTableCell.isFooter() == null ? false : dataTableCell.isFooter(), pageNumber, setReferenceElements(dataTableCell.getElements(), readResults))) .collect(Collectors.toList()), pageNumber)) .collect(Collectors.toList()); } /** * Helper method to convert the per page {@link ReadResult} item to {@link FormLine}. * * @param readResultItem The per page text extraction item result returned by the service. * * @return The list of {@code FormLine}. */ static List<FormLine> getReadResultFormLines(ReadResult readResultItem) { return readResultItem.getLines().stream() .map(textLine -> new FormLine( textLine.getText(), toBoundingBox(textLine.getBoundingBox()), readResultItem.getPage(), toWords(textLine.getWords(), readResultItem.getPage()))) .collect(Collectors.toList()); } /** * The field map returned on analyze with an unlabeled model id. * * @param documentResultItem The extracted document level information. * @param readResults The text extraction result returned by the service. * @return The {@link RecognizedForm */ private static Map<String, FormField> getLabeledFieldMap(DocumentResult documentResultItem, List<ReadResult> readResults) { Map<String, FormField> recognizedFieldMap = new LinkedHashMap<>(); if (!CoreUtils.isNullOrEmpty(documentResultItem.getFields())) { documentResultItem.getFields().forEach((key, fieldValue) -> { if (fieldValue != null) { List<FormElement> formElementList = setReferenceElements(fieldValue.getElements(), readResults); FieldData valueData; if ("ReceiptType".equals(key) || ARRAY == fieldValue.getType()) { valueData = null; } else { valueData = new FieldData(fieldValue.getText(), toBoundingBox(fieldValue.getBoundingBox()), fieldValue.getPage(), formElementList); } recognizedFieldMap.put(key, setFormField(key, valueData, fieldValue, readResults)); } else { recognizedFieldMap.put(key, new FormField(key, null, null, null, DEFAULT_CONFIDENCE_VALUE)); } }); } return recognizedFieldMap; } /** * Helper method that converts the incoming service field value to one of the strongly typed SDK level * {@link FormField} with reference elements set when {@code includeFieldElements} is set to true. * * @param name The name of the field. * @param fieldValue The named field values returned by the service. * @param valueData The value text of the field. * @param readResults The text extraction result returned by the service. * * @return The strongly typed {@link FormField} for the field input. */ private static FormField setFormField(String name, FieldData valueData, FieldValue fieldValue, List<ReadResult> readResults) { com.azure.ai.formrecognizer.models.FieldValue value; switch (fieldValue.getType()) { case PHONE_NUMBER: value = new com.azure.ai.formrecognizer.models.FieldValue(fieldValue.getValuePhoneNumber(), FieldValueType.PHONE_NUMBER); break; case STRING: value = new com.azure.ai.formrecognizer.models.FieldValue(fieldValue.getValueString(), FieldValueType.STRING); break; case TIME: LocalTime fieldTime = fieldValue.getValueTime() == null ? null : LocalTime .parse(fieldValue.getValueTime(), DateTimeFormatter.ofPattern("HH:mm:ss")); value = new com.azure.ai.formrecognizer.models.FieldValue(fieldTime, FieldValueType.TIME); break; case DATE: value = new com.azure.ai.formrecognizer.models.FieldValue(fieldValue.getValueDate(), FieldValueType.DATE); break; case INTEGER: com.azure.ai.formrecognizer.models.FieldValue longFieldValue; if (fieldValue.getValueInteger() == null) { longFieldValue = new com.azure.ai.formrecognizer.models.FieldValue(null, FieldValueType.LONG); } else { longFieldValue = new com.azure.ai.formrecognizer.models.FieldValue(fieldValue.getValueInteger().longValue(), FieldValueType.LONG); } value = longFieldValue; break; case NUMBER: value = new com.azure.ai.formrecognizer.models.FieldValue(fieldValue.getValueNumber(), FieldValueType.FLOAT); break; case ARRAY: value = new com.azure.ai.formrecognizer.models.FieldValue( toFieldValueArray(fieldValue.getValueArray(), readResults), FieldValueType.LIST); break; case OBJECT: value = new com.azure.ai.formrecognizer.models.FieldValue( toFieldValueObject(fieldValue.getValueObject(), readResults), FieldValueType.MAP); break; default: throw LOGGER.logExceptionAsError(new RuntimeException("FieldValue Type not supported")); } return new FormField(name, null, valueData, value, setDefaultConfidenceValue(fieldValue.getConfidence())); } /** * Helper method to set default confidence value if confidence returned by service is null. * * @param confidence the confidence returned by service. * * @return the field confidence value. */ private static float setDefaultConfidenceValue(Float confidence) { return confidence == null ? DEFAULT_CONFIDENCE_VALUE : confidence; } /** * Helper method to convert the service returned * {@link com.azure.ai.formrecognizer.implementation.models.FieldValue * to a SDK level map of {@link FormField}. * * @param valueObject The array of field values returned by the service in {@link FieldValue * * @return The Map of {@link FormField}. */ private static Map<String, FormField> toFieldValueObject(Map<String, FieldValue> valueObject, List<ReadResult> readResults) { Map<String, FormField> fieldValueObjectMap = new TreeMap<>(); valueObject.forEach((key, fieldValue) -> fieldValueObjectMap.put(key, setFormField(key, new FieldData(fieldValue.getText(), toBoundingBox(fieldValue.getBoundingBox()), fieldValue.getPage(), setReferenceElements(fieldValue.getElements(), readResults)), fieldValue, readResults) )); return fieldValueObjectMap; } /** * Helper method to convert the service returned * {@link com.azure.ai.formrecognizer.implementation.models.FieldValue * to a SDK level List of {@link FormField}. * * @param valueArray The array of field values returned by the service in {@link FieldValue * @param readResults The text extraction result returned by the service. * * @return The List of {@link FormField}. */ /** * Helper method to convert the page results to {@code FormPage form pages}. * * @param readResultItem The per page text extraction item result returned by the service. * @param perPageTableList The per page tables list. * @param perPageLineList The per page form lines. * * @return The per page {@code FormPage}. */ private static FormPage getFormPage(ReadResult readResultItem, List<FormTable> perPageTableList, List<FormLine> perPageLineList) { return new FormPage( readResultItem.getHeight(), readResultItem.getAngle(), LengthUnit.fromString(readResultItem.getUnit().toString()), readResultItem.getWidth(), perPageLineList, perPageTableList, readResultItem.getPage()); } /** * Helper method to set the {@link RecognizedForm * service. * * @param includeFieldElements Boolean to indicate if to set reference elements data on fields. * @param readResults The text extraction result returned by the service. * @param pageResultItem The extracted page level information returned by the service. * @param pageNumber The 1 based page number on which these fields exist. * * @return The fields populated on {@link RecognizedForm */ private static Map<String, FormField> getUnlabeledFieldMap(boolean includeFieldElements, List<ReadResult> readResults, PageResult pageResultItem, int pageNumber) { Map<String, FormField> formFieldMap = new LinkedHashMap<>(); List<KeyValuePair> keyValuePairs = pageResultItem.getKeyValuePairs(); forEachWithIndex(keyValuePairs, ((index, keyValuePair) -> { List<FormElement> formKeyContentList = null; List<FormElement> formValueContentList = null; if (includeFieldElements) { formKeyContentList = setReferenceElements(keyValuePair.getKey().getElements(), readResults); formValueContentList = setReferenceElements(keyValuePair.getValue().getElements(), readResults ); } FieldData labelData = new FieldData(keyValuePair.getKey().getText(), toBoundingBox(keyValuePair.getKey().getBoundingBox()), pageNumber, formKeyContentList); FieldData valueData = new FieldData(keyValuePair.getValue().getText(), toBoundingBox(keyValuePair.getValue().getBoundingBox()), pageNumber, formValueContentList); String fieldName = "field-" + index; FormField formField = new FormField(fieldName, labelData, valueData, new com.azure.ai.formrecognizer.models.FieldValue(keyValuePair.getValue().getText(), FieldValueType.STRING), setDefaultConfidenceValue(keyValuePair.getConfidence()) ); formFieldMap.put(fieldName, formField); })); return formFieldMap; } /** * Helper method to set the text reference elements on FieldValue/fields when {@code includeFieldElements} set to * true. * * @return The list if referenced elements. */ private static List<FormElement> setReferenceElements(List<String> elements, List<ReadResult> readResults) { if (CoreUtils.isNullOrEmpty(elements)) { return new ArrayList<>(); } List<FormElement> formElementList = new ArrayList<>(); elements.forEach(elementString -> { String[] indices = NON_DIGIT_PATTERN.matcher(elementString).replaceAll(" ").trim().split(" "); if (indices.length < 2) { throw LOGGER.logExceptionAsError(new RuntimeException("Cannot find corresponding reference elements " + "for the field value.")); } int readResultIndex = Integer.parseInt(indices[0]); int lineIndex = Integer.parseInt(indices[1]); if (indices.length == 3) { int wordIndex = Integer.parseInt(indices[2]); TextWord textWord = readResults.get(readResultIndex).getLines().get(lineIndex).getWords().get(wordIndex); FormWord wordElement = new FormWord(textWord.getText(), toBoundingBox(textWord.getBoundingBox()), readResultIndex + 1, setDefaultConfidenceValue(textWord.getConfidence())); formElementList.add(wordElement); } else { TextLine textLine = readResults.get(readResultIndex).getLines().get(lineIndex); FormLine lineElement = new FormLine(textLine.getText(), toBoundingBox(textLine.getBoundingBox()), readResultIndex + 1, toWords(textLine.getWords(), readResultIndex + 1)); formElementList.add(lineElement); } }); return formElementList; } /** * Helper method to convert the service level {@link TextWord} to list of SDK level model {@link FormWord}. * * @param words A list of word reference elements returned by the service. * @param pageNumber The 1 based page number on which this word element exists. * * @return The list of {@code FormWord words}. */ private static List<FormWord> toWords(List<TextWord> words, int pageNumber) { return words.stream() .map(textWord -> new FormWord( textWord.getText(), toBoundingBox(textWord.getBoundingBox()), pageNumber, setDefaultConfidenceValue(textWord.getConfidence())) ).collect(Collectors.toList()); } /** * Helper method to convert the service level modeled eight numbers representing the four points to SDK level * {@link FieldBoundingBox}. * * @param serviceBoundingBox A list of eight numbers representing the four points of a box. * * @return A {@link FieldBoundingBox}. */ private static FieldBoundingBox toBoundingBox(List<Float> serviceBoundingBox) { if (CoreUtils.isNullOrEmpty(serviceBoundingBox) || (serviceBoundingBox.size() % 2) != 0) { return null; } List<Point> pointList = new ArrayList<>(); for (int i = 0; i < serviceBoundingBox.size(); i++) { pointList.add(new Point(serviceBoundingBox.get(i), serviceBoundingBox.get(++i))); } return new FieldBoundingBox(pointList); } }
Yes. It should not be contactNames. It should be formField.getConfidence.
public void beginRecognizeBusinessCardsFromUrl() { String businessCardUrl = "{business_card_url}"; formRecognizerClient.beginRecognizeBusinessCardsFromUrl(businessCardUrl) .getFinalResult() .forEach(recognizedBusinessCard -> { Map<String, FormField> recognizedFields = recognizedBusinessCard.getFields(); FormField contactNames = recognizedFields.get("ContactNames"); if (contactNames != null) { if (FieldValueType.LIST == contactNames.getValue().getValueType()) { List<FormField> businessCardItems = contactNames.getValue().asList(); businessCardItems.stream() .filter(businessCardItem -> FieldValueType.MAP == businessCardItem.getValue() .getValueType()) .map(formField -> formField.getValue().asMap()) .forEach(formFieldMap -> formFieldMap.forEach((key, formField) -> { if ("FirstName".equals(key)) { if (FieldValueType.STRING == formField.getValue().getValueType()) { String firstName = formField.getValue().asString(); System.out.printf("First Name: %s, confidence: %.2f%n", firstName, contactNames.getConfidence()); } } if ("LastName".equals(key)) { if (FieldValueType.STRING == formField.getValue().getValueType()) { String lastName = formField.getValue().asString(); System.out.printf("Last Name: %s, confidence: %.2f%n", lastName, contactNames.getConfidence()); } } })); } } FormField jobTitles = recognizedFields.get("JobTitles"); if (jobTitles != null) { if (FieldValueType.LIST == jobTitles.getValue().getValueType()) { List<FormField> jobTitlesItems = jobTitles.getValue().asList(); jobTitlesItems.stream().forEach(formField -> { if (FieldValueType.STRING == formField.getValue().getValueType()) { String jobTitle = formField.getValue().asString(); System.out.printf("Job Title: %s, confidence: %.2f%n", jobTitle, jobTitles.getConfidence()); } }); } } }); }
firstName, contactNames.getConfidence());
public void beginRecognizeBusinessCardsFromUrl() { String businessCardUrl = "{business_card_url}"; formRecognizerClient.beginRecognizeBusinessCardsFromUrl(businessCardUrl) .getFinalResult() .forEach(recognizedBusinessCard -> { Map<String, FormField> recognizedFields = recognizedBusinessCard.getFields(); FormField contactNamesFormField = recognizedFields.get("ContactNames"); if (contactNamesFormField != null) { if (FieldValueType.LIST == contactNamesFormField.getValue().getValueType()) { List<FormField> contactNamesList = contactNamesFormField.getValue().asList(); contactNamesList.stream() .filter(contactName -> FieldValueType.MAP == contactName.getValue().getValueType()) .map(contactName -> { System.out.printf("Contact name: %s%n", contactName.getValueData().getText()); return contactName.getValue().asMap(); }) .forEach(contactNamesMap -> contactNamesMap.forEach((key, contactName) -> { if ("FirstName".equals(key)) { if (FieldValueType.STRING == contactName.getValue().getValueType()) { String firstName = contactName.getValue().asString(); System.out.printf("\tFirst Name: %s, confidence: %.2f%n", firstName, contactName.getConfidence()); } } if ("LastName".equals(key)) { if (FieldValueType.STRING == contactName.getValue().getValueType()) { String lastName = contactName.getValue().asString(); System.out.printf("\tLast Name: %s, confidence: %.2f%n", lastName, contactName.getConfidence()); } } })); } } FormField jobTitles = recognizedFields.get("JobTitles"); if (jobTitles != null) { if (FieldValueType.LIST == jobTitles.getValue().getValueType()) { List<FormField> jobTitlesItems = jobTitles.getValue().asList(); jobTitlesItems.stream().forEach(jobTitlesItem -> { if (FieldValueType.STRING == jobTitlesItem.getValue().getValueType()) { String jobTitle = jobTitlesItem.getValue().asString(); System.out.printf("Job Title: %s, confidence: %.2f%n", jobTitle, jobTitlesItem.getConfidence()); } }); } } }); }
class FormRecognizerClientJavaDocCodeSnippets { private FormRecognizerClient formRecognizerClient = new FormRecognizerClientBuilder().buildClient(); /** * Code snippet for creating a {@link FormRecognizerClient} */ public void createFormRecognizerClient() { FormRecognizerClient formRecognizerClient = new FormRecognizerClientBuilder() .credential(new AzureKeyCredential("{key}")) .endpoint("{endpoint}") .buildClient(); } /** * Code snippet for creating a {@link FormRecognizerClient} with pipeline */ public void createFormRecognizerClientWithPipeline() { HttpPipeline pipeline = new HttpPipelineBuilder() .policies(/* add policies */) .build(); FormRecognizerClient formRecognizerClient = new FormRecognizerClientBuilder() .credential(new AzureKeyCredential("{key}")) .endpoint("{endpoint}") .pipeline(pipeline) .buildClient(); } /** * Code snippet for {@link FormRecognizerClient */ public void beginRecognizeCustomFormsFromUrl() { String formUrl = "{form_url}"; String modelId = "{custom_trained_model_id}"; formRecognizerClient.beginRecognizeCustomFormsFromUrl(modelId, formUrl).getFinalResult() .stream() .map(RecognizedForm::getFields) .forEach(formFieldMap -> formFieldMap.forEach((fieldText, formField) -> { System.out.printf("Field text: %s%n", fieldText); System.out.printf("Field value data text: %s%n", formField.getValueData().getText()); System.out.printf("Confidence score: %.2f%n", formField.getConfidence()); })); } /** * Code snippet for {@link FormRecognizerClient */ public void beginRecognizeCustomFormsFromUrlWithOptions() { String analyzeFilePath = "{file_source_url}"; String modelId = "{model_id}"; boolean includeFieldElements = true; formRecognizerClient.beginRecognizeCustomFormsFromUrl(modelId, analyzeFilePath, new RecognizeCustomFormsOptions() .setFieldElementsIncluded(includeFieldElements) .setPollInterval(Duration.ofSeconds(10)), Context.NONE) .getFinalResult() .stream() .map(RecognizedForm::getFields) .forEach(formFieldMap -> formFieldMap.forEach((fieldText, formField) -> { System.out.printf("Field text: %s%n", fieldText); System.out.printf("Field value data text: %s%n", formField.getValueData().getText()); System.out.printf("Confidence score: %.2f%n", formField.getConfidence()); })); } /** * Code snippet for * {@link FormRecognizerClient * * @throws IOException Exception thrown when there is an error in reading all the bytes from the File. */ public void beginRecognizeCustomForms() throws IOException { File form = new File("{local/file_path/fileName.jpg}"); String modelId = "{custom_trained_model_id}"; byte[] fileContent = Files.readAllBytes(form.toPath()); try (InputStream targetStream = new ByteArrayInputStream(fileContent)) { formRecognizerClient.beginRecognizeCustomForms(modelId, targetStream, form.length()) .getFinalResult() .stream() .map(RecognizedForm::getFields) .forEach(formFieldMap -> formFieldMap.forEach((fieldText, formField) -> { System.out.printf("Field text: %s%n", fieldText); System.out.printf("Field value data text: %s%n", formField.getValueData().getText()); System.out.printf("Confidence score: %.2f%n", formField.getConfidence()); })); } } /** * Code snippet for * {@link FormRecognizerClient * * @throws IOException Exception thrown when there is an error in reading all the bytes from the File. */ public void beginRecognizeCustomFormsWithOptions() throws IOException { File form = new File("{local/file_path/fileName.jpg}"); String modelId = "{custom_trained_model_id}"; boolean includeFieldElements = true; byte[] fileContent = Files.readAllBytes(form.toPath()); try (InputStream targetStream = new ByteArrayInputStream(fileContent)) { formRecognizerClient.beginRecognizeCustomForms(modelId, targetStream, form.length(), new RecognizeCustomFormsOptions() .setContentType(FormContentType.IMAGE_JPEG) .setFieldElementsIncluded(includeFieldElements) .setPollInterval(Duration.ofSeconds(10)), Context.NONE) .getFinalResult() .stream() .map(RecognizedForm::getFields) .forEach(formFieldMap -> formFieldMap.forEach((fieldText, formField) -> { System.out.printf("Field text: %s%n", fieldText); System.out.printf("Field value data text: %s%n", formField.getValueData().getText()); System.out.printf("Confidence score: %.2f%n", formField.getConfidence()); })); } } /** * Code snippet for {@link FormRecognizerClient */ public void beginRecognizeContentFromUrl() { String formUrl = "{form_url}"; formRecognizerClient.beginRecognizeContentFromUrl(formUrl) .getFinalResult() .forEach(formPage -> { System.out.printf("Page Angle: %s%n", formPage.getTextAngle()); System.out.printf("Page Dimension unit: %s%n", formPage.getUnit()); System.out.println("Recognized Tables: "); formPage.getTables() .stream() .flatMap(formTable -> formTable.getCells().stream()) .forEach(recognizedTableCell -> System.out.printf("%s ", recognizedTableCell.getText())); }); } /** * Code snippet for {@link FormRecognizerClient * options. */ public void beginRecognizeContentFromUrlWithOptions() { String formPath = "{file_source_url}"; formRecognizerClient.beginRecognizeContentFromUrl(formPath, new RecognizeContentOptions() .setPollInterval(Duration.ofSeconds(5)), Context.NONE) .getFinalResult() .forEach(formPage -> { System.out.printf("Page Angle: %s%n", formPage.getTextAngle()); System.out.printf("Page Dimension unit: %s%n", formPage.getUnit()); System.out.println("Recognized Tables: "); formPage.getTables() .stream() .flatMap(formTable -> formTable.getCells().stream()) .forEach(recognizedTableCell -> System.out.printf("%s ", recognizedTableCell.getText())); }); } /** * Code snippet for {@link FormRecognizerClient * * @throws IOException Exception thrown when there is an error in reading all the bytes from the File. */ public void beginRecognizeContent() throws IOException { File form = new File("{local/file_path/fileName.pdf}"); byte[] fileContent = Files.readAllBytes(form.toPath()); try (InputStream targetStream = new ByteArrayInputStream(fileContent)) { formRecognizerClient.beginRecognizeContent(targetStream, form.length()) .getFinalResult() .forEach(formPage -> { System.out.printf("Page Angle: %s%n", formPage.getTextAngle()); System.out.printf("Page Dimension unit: %s%n", formPage.getUnit()); System.out.println("Recognized Tables: "); formPage.getTables() .stream() .flatMap(formTable -> formTable.getCells().stream()) .forEach(recognizedTableCell -> System.out.printf("%s ", recognizedTableCell.getText())); }); } } /** * Code snippet for {@link FormRecognizerClient * options. * * @throws IOException Exception thrown when there is an error in reading all the bytes from the File. */ public void beginRecognizeContentWithOptions() throws IOException { File form = new File("{file_source_url}"); byte[] fileContent = Files.readAllBytes(form.toPath()); try (InputStream targetStream = new ByteArrayInputStream(fileContent)) { for (FormPage formPage : formRecognizerClient.beginRecognizeContent(targetStream, form.length(), new RecognizeContentOptions() .setPollInterval(Duration.ofSeconds(5)), Context.NONE) .getFinalResult()) { System.out.printf("Page Angle: %s%n", formPage.getTextAngle()); System.out.printf("Page Dimension unit: %s%n", formPage.getUnit()); System.out.println("Recognized Tables: "); formPage.getTables() .stream() .flatMap(formTable -> formTable.getCells().stream()) .forEach(recognizedTableCell -> System.out.printf("%s ", recognizedTableCell.getText())); } } } /** * Code snippet for {@link FormRecognizerClient */ public void beginRecognizeReceiptsFromUrl() { String receiptUrl = "{file_source_url}"; formRecognizerClient.beginRecognizeReceiptsFromUrl(receiptUrl) .getFinalResult() .forEach(recognizedReceipt -> { Map<String, FormField> recognizedFields = recognizedReceipt.getFields(); FormField merchantNameField = recognizedFields.get("MerchantName"); if (merchantNameField != null) { if (FieldValueType.STRING == merchantNameField.getValue().getValueType()) { String merchantName = merchantNameField.getValue().asString(); System.out.printf("Merchant Name: %s, confidence: %.2f%n", merchantName, merchantNameField.getConfidence()); } } FormField merchantPhoneNumberField = recognizedFields.get("MerchantPhoneNumber"); if (merchantPhoneNumberField != null) { if (FieldValueType.PHONE_NUMBER == merchantPhoneNumberField.getValue().getValueType()) { String merchantAddress = merchantPhoneNumberField.getValue().asPhoneNumber(); System.out.printf("Merchant Phone number: %s, confidence: %.2f%n", merchantAddress, merchantPhoneNumberField.getConfidence()); } } FormField transactionDateField = recognizedFields.get("TransactionDate"); if (transactionDateField != null) { if (FieldValueType.DATE == transactionDateField.getValue().getValueType()) { LocalDate transactionDate = transactionDateField.getValue().asDate(); System.out.printf("Transaction Date: %s, confidence: %.2f%n", transactionDate, transactionDateField.getConfidence()); } } FormField receiptItemsField = recognizedFields.get("Items"); if (receiptItemsField != null) { System.out.printf("Receipt Items: %n"); if (FieldValueType.LIST == receiptItemsField.getValue().getValueType()) { List<FormField> receiptItems = receiptItemsField.getValue().asList(); receiptItems.stream() .filter(receiptItem -> FieldValueType.MAP == receiptItem.getValue().getValueType()) .map(formField -> formField.getValue().asMap()) .forEach(formFieldMap -> formFieldMap.forEach((key, formField) -> { if ("Quantity".equals(key)) { if (FieldValueType.FLOAT == formField.getValue().getValueType()) { Float quantity = formField.getValue().asFloat(); System.out.printf("Quantity: %f, confidence: %.2f%n", quantity, formField.getConfidence()); } } })); } } }); } /** * Code snippet for {@link FormRecognizerClient */ public void beginRecognizeReceiptsFromUrlWithOptions() { String receiptUrl = "{receipt_url}"; formRecognizerClient.beginRecognizeReceiptsFromUrl(receiptUrl, new RecognizeReceiptsOptions() .setPollInterval(Duration.ofSeconds(5)) .setFieldElementsIncluded(true), Context.NONE).getFinalResult() .forEach(recognizedReceipt -> { Map<String, FormField> recognizedFields = recognizedReceipt.getFields(); FormField merchantNameField = recognizedFields.get("MerchantName"); if (merchantNameField != null) { if (FieldValueType.STRING == merchantNameField.getValue().getValueType()) { String merchantName = merchantNameField.getValue().asString(); System.out.printf("Merchant Name: %s, confidence: %.2f%n", merchantName, merchantNameField.getConfidence()); } } FormField merchantPhoneNumberField = recognizedFields.get("MerchantPhoneNumber"); if (merchantPhoneNumberField != null) { if (FieldValueType.PHONE_NUMBER == merchantPhoneNumberField.getValue().getValueType()) { String merchantAddress = merchantPhoneNumberField.getValue().asPhoneNumber(); System.out.printf("Merchant Phone number: %s, confidence: %.2f%n", merchantAddress, merchantPhoneNumberField.getConfidence()); } } FormField transactionDateField = recognizedFields.get("TransactionDate"); if (transactionDateField != null) { if (FieldValueType.DATE == transactionDateField.getValue().getValueType()) { LocalDate transactionDate = transactionDateField.getValue().asDate(); System.out.printf("Transaction Date: %s, confidence: %.2f%n", transactionDate, transactionDateField.getConfidence()); } } FormField receiptItemsField = recognizedFields.get("Items"); if (receiptItemsField != null) { System.out.printf("Receipt Items: %n"); if (FieldValueType.LIST == receiptItemsField.getValue().getValueType()) { List<FormField> receiptItems = receiptItemsField.getValue().asList(); receiptItems.stream() .filter(receiptItem -> FieldValueType.MAP == receiptItem.getValue().getValueType()) .map(formField -> formField.getValue().asMap()) .forEach(formFieldMap -> formFieldMap.forEach((key, formField) -> { if ("Quantity".equals(key)) { if (FieldValueType.FLOAT == formField.getValue().getValueType()) { Float quantity = formField.getValue().asFloat(); System.out.printf("Quantity: %f, confidence: %.2f%n", quantity, formField.getConfidence()); } } })); } } }); } /** * Code snippet for {@link FormRecognizerClient * * @throws IOException Exception thrown when there is an error in reading all the bytes from the File. */ public void beginRecognizeReceipts() throws IOException { File receipt = new File("{receipt_url}"); byte[] fileContent = Files.readAllBytes(receipt.toPath()); try (InputStream targetStream = new ByteArrayInputStream(fileContent)) { formRecognizerClient.beginRecognizeReceipts(targetStream, receipt.length()).getFinalResult() .forEach(recognizedReceipt -> { Map<String, FormField> recognizedFields = recognizedReceipt.getFields(); FormField merchantNameField = recognizedFields.get("MerchantName"); if (merchantNameField != null) { if (FieldValueType.STRING == merchantNameField.getValue().getValueType()) { String merchantName = merchantNameField.getValue().asString(); System.out.printf("Merchant Name: %s, confidence: %.2f%n", merchantName, merchantNameField.getConfidence()); } } FormField merchantPhoneNumberField = recognizedFields.get("MerchantPhoneNumber"); if (merchantPhoneNumberField != null) { if (FieldValueType.PHONE_NUMBER == merchantPhoneNumberField.getValue().getValueType()) { String merchantAddress = merchantPhoneNumberField.getValue().asPhoneNumber(); System.out.printf("Merchant Phone number: %s, confidence: %.2f%n", merchantAddress, merchantPhoneNumberField.getConfidence()); } } FormField transactionDateField = recognizedFields.get("TransactionDate"); if (transactionDateField != null) { if (FieldValueType.DATE == transactionDateField.getValue().getValueType()) { LocalDate transactionDate = transactionDateField.getValue().asDate(); System.out.printf("Transaction Date: %s, confidence: %.2f%n", transactionDate, transactionDateField.getConfidence()); } } FormField receiptItemsField = recognizedFields.get("Items"); if (receiptItemsField != null) { System.out.printf("Receipt Items: %n"); if (FieldValueType.LIST == receiptItemsField.getValue().getValueType()) { List<FormField> receiptItems = receiptItemsField.getValue().asList(); receiptItems.stream() .filter(receiptItem -> FieldValueType.MAP == receiptItem.getValue().getValueType()) .map(formField -> formField.getValue().asMap()) .forEach(formFieldMap -> formFieldMap.forEach((key, formField) -> { if ("Quantity".equals(key)) { if (FieldValueType.FLOAT == formField.getValue().getValueType()) { Float quantity = formField.getValue().asFloat(); System.out.printf("Quantity: %f, confidence: %.2f%n", quantity, formField.getConfidence()); } } })); } } }); } } /** * Code snippet for {@link FormRecognizerClient * with options * * @throws IOException Exception thrown when there is an error in reading all the bytes from the File. */ public void beginRecognizeReceiptsWithOptions() throws IOException { File receipt = new File("{local/file_path/fileName.jpg}"); boolean includeFieldElements = true; byte[] fileContent = Files.readAllBytes(receipt.toPath()); try (InputStream targetStream = new ByteArrayInputStream(fileContent)) { for (RecognizedForm recognizedForm : formRecognizerClient.beginRecognizeReceipts(targetStream, receipt.length(), new RecognizeReceiptsOptions() .setContentType(FormContentType.IMAGE_JPEG) .setFieldElementsIncluded(includeFieldElements) .setPollInterval(Duration.ofSeconds(5)), Context.NONE) .getFinalResult()) { Map<String, FormField> recognizedFields = recognizedForm.getFields(); FormField merchantNameField = recognizedFields.get("MerchantName"); if (merchantNameField != null) { if (FieldValueType.STRING == merchantNameField.getValue().getValueType()) { String merchantName = merchantNameField.getValue().asString(); System.out.printf("Merchant Name: %s, confidence: %.2f%n", merchantName, merchantNameField.getConfidence()); } } FormField merchantPhoneNumberField = recognizedFields.get("MerchantPhoneNumber"); if (merchantPhoneNumberField != null) { if (FieldValueType.PHONE_NUMBER == merchantPhoneNumberField.getValue().getValueType()) { String merchantAddress = merchantPhoneNumberField.getValue().asPhoneNumber(); System.out.printf("Merchant Phone number: %s, confidence: %.2f%n", merchantAddress, merchantPhoneNumberField.getConfidence()); } } FormField transactionDateField = recognizedFields.get("TransactionDate"); if (transactionDateField != null) { if (FieldValueType.DATE == transactionDateField.getValue().getValueType()) { LocalDate transactionDate = transactionDateField.getValue().asDate(); System.out.printf("Transaction Date: %s, confidence: %.2f%n", transactionDate, transactionDateField.getConfidence()); } } FormField receiptItemsField = recognizedFields.get("Items"); if (receiptItemsField != null) { System.out.printf("Receipt Items: %n"); if (FieldValueType.LIST == receiptItemsField.getValue().getValueType()) { List<FormField> receiptItems = receiptItemsField.getValue().asList(); receiptItems.stream() .filter(receiptItem -> FieldValueType.MAP == receiptItem.getValue().getValueType()) .map(formField -> formField.getValue().asMap()) .forEach(formFieldMap -> formFieldMap.forEach((key, formField) -> { if ("Quantity".equals(key)) { if (FieldValueType.FLOAT == formField.getValue().getValueType()) { Float quantity = formField.getValue().asFloat(); System.out.printf("Quantity: %f, confidence: %.2f%n", quantity, formField.getConfidence()); } } })); } } } } } /** * Code snippet for {@link FormRecognizerClient */ /** * Code snippet for * {@link FormRecognizerClient */ public void beginRecognizeBusinessCardsFromUrlWithOptions() { String businessCardUrl = "{business_card_url}"; formRecognizerClient.beginRecognizeBusinessCardsFromUrl(businessCardUrl, new RecognizeBusinessCardsOptions() .setPollInterval(Duration.ofSeconds(5)) .setFieldElementsIncluded(true), Context.NONE).getFinalResult() .forEach(recognizedBusinessCard -> { Map<String, FormField> recognizedFields = recognizedBusinessCard.getFields(); FormField contactNames = recognizedFields.get("ContactNames"); if (contactNames != null) { if (FieldValueType.LIST == contactNames.getValue().getValueType()) { List<FormField> businessCardItems = contactNames.getValue().asList(); businessCardItems.stream() .filter(businessCardItem -> FieldValueType.MAP == businessCardItem.getValue() .getValueType()) .map(formField -> formField.getValue().asMap()) .forEach(formFieldMap -> formFieldMap.forEach((key, formField) -> { if ("FirstName".equals(key)) { if (FieldValueType.STRING == formField.getValue().getValueType()) { String firstName = formField.getValue().asString(); System.out.printf("First Name: %s, confidence: %.2f%n", firstName, contactNames.getConfidence()); } } if ("LastName".equals(key)) { if (FieldValueType.STRING == formField.getValue().getValueType()) { String lastName = formField.getValue().asString(); System.out.printf("Last Name: %s, confidence: %.2f%n", lastName, contactNames.getConfidence()); } } })); } } FormField jobTitles = recognizedFields.get("JobTitles"); if (jobTitles != null) { if (FieldValueType.LIST == jobTitles.getValue().getValueType()) { List<FormField> jobTitlesItems = jobTitles.getValue().asList(); jobTitlesItems.stream().forEach(formField -> { if (FieldValueType.STRING == formField.getValue().getValueType()) { String jobTitle = formField.getValue().asString(); System.out.printf("Job Title: %s, confidence: %.2f%n", jobTitle, jobTitles.getConfidence()); } }); } } }); } /** * Code snippet for {@link FormRecognizerClient * * @throws IOException Exception thrown when there is an error in reading all the bytes from the File. */ public void beginRecognizeBusinessCards() throws IOException { File businessCard = new File("{local/file_path/fileName.jpg}"); byte[] fileContent = Files.readAllBytes(businessCard.toPath()); try (InputStream targetStream = new ByteArrayInputStream(fileContent)) { formRecognizerClient.beginRecognizeBusinessCards(targetStream, businessCard.length()).getFinalResult() .forEach(recognizedBusinessCard -> { Map<String, FormField> recognizedFields = recognizedBusinessCard.getFields(); FormField contactNames = recognizedFields.get("ContactNames"); if (contactNames != null) { if (FieldValueType.LIST == contactNames.getValue().getValueType()) { List<FormField> businessCardItems = contactNames.getValue().asList(); businessCardItems.stream() .filter(businessCardItem -> FieldValueType.MAP == businessCardItem.getValue() .getValueType()) .map(formField -> formField.getValue().asMap()) .forEach(formFieldMap -> formFieldMap.forEach((key, formField) -> { if ("FirstName".equals(key)) { if (FieldValueType.STRING == formField.getValue().getValueType()) { String firstName = formField.getValue().asString(); System.out.printf("First Name: %s, confidence: %.2f%n", firstName, contactNames.getConfidence()); } } if ("LastName".equals(key)) { if (FieldValueType.STRING == formField.getValue().getValueType()) { String lastName = formField.getValue().asString(); System.out.printf("Last Name: %s, confidence: %.2f%n", lastName, contactNames.getConfidence()); } } })); } } FormField jobTitles = recognizedFields.get("JobTitles"); if (jobTitles != null) { if (FieldValueType.LIST == jobTitles.getValue().getValueType()) { List<FormField> jobTitlesItems = jobTitles.getValue().asList(); jobTitlesItems.stream().forEach(formField -> { if (FieldValueType.STRING == formField.getValue().getValueType()) { String jobTitle = formField.getValue().asString(); System.out.printf("Job Title: %s, confidence: %.2f%n", jobTitle, jobTitles.getConfidence()); } }); } } }); } } /** * Code snippet for * {@link FormRecognizerClient * Context)} with options * * @throws IOException Exception thrown when there is an error in reading all the bytes from the File. */ public void beginRecognizeBusinessCardsWithOptions() throws IOException { File businessCard = new File("{local/file_path/fileName.jpg}"); boolean includeFieldElements = true; byte[] fileContent = Files.readAllBytes(businessCard.toPath()); try (InputStream targetStream = new ByteArrayInputStream(fileContent)) { for (RecognizedForm recognizedForm : formRecognizerClient.beginRecognizeBusinessCards(targetStream, businessCard.length(), new RecognizeBusinessCardsOptions() .setContentType(FormContentType.IMAGE_JPEG) .setFieldElementsIncluded(includeFieldElements) .setPollInterval(Duration.ofSeconds(5)), Context.NONE) .getFinalResult()) { Map<String, FormField> recognizedFields = recognizedForm.getFields(); FormField contactNames = recognizedFields.get("ContactNames"); if (contactNames != null) { if (FieldValueType.LIST == contactNames.getValue().getValueType()) { List<FormField> businessCardItems = contactNames.getValue().asList(); businessCardItems.stream() .filter(businessCardItem -> FieldValueType.MAP == businessCardItem.getValue() .getValueType()) .map(formField -> formField.getValue().asMap()) .forEach(formFieldMap -> formFieldMap.forEach((key, formField) -> { if ("FirstName".equals(key)) { if (FieldValueType.STRING == formField.getValue().getValueType()) { String firstName = formField.getValue().asString(); System.out.printf("First Name: %s, confidence: %.2f%n", firstName, contactNames.getConfidence()); } } if ("LastName".equals(key)) { if (FieldValueType.STRING == formField.getValue().getValueType()) { String lastName = formField.getValue().asString(); System.out.printf("Last Name: %s, confidence: %.2f%n", lastName, contactNames.getConfidence()); } } })); } } FormField jobTitles = recognizedFields.get("JobTitles"); if (jobTitles != null) { if (FieldValueType.LIST == jobTitles.getValue().getValueType()) { List<FormField> jobTitlesItems = jobTitles.getValue().asList(); jobTitlesItems.stream().forEach(formField -> { if (FieldValueType.STRING == formField.getValue().getValueType()) { String jobTitle = formField.getValue().asString(); System.out.printf("Job Title: %s, confidence: %.2f%n", jobTitle, jobTitles.getConfidence()); } }); } } } } } }
class FormRecognizerClientJavaDocCodeSnippets { private FormRecognizerClient formRecognizerClient = new FormRecognizerClientBuilder().buildClient(); /** * Code snippet for creating a {@link FormRecognizerClient} */ public void createFormRecognizerClient() { FormRecognizerClient formRecognizerClient = new FormRecognizerClientBuilder() .credential(new AzureKeyCredential("{key}")) .endpoint("{endpoint}") .buildClient(); } /** * Code snippet for creating a {@link FormRecognizerClient} with pipeline */ public void createFormRecognizerClientWithPipeline() { HttpPipeline pipeline = new HttpPipelineBuilder() .policies(/* add policies */) .build(); FormRecognizerClient formRecognizerClient = new FormRecognizerClientBuilder() .credential(new AzureKeyCredential("{key}")) .endpoint("{endpoint}") .pipeline(pipeline) .buildClient(); } /** * Code snippet for {@link FormRecognizerClient */ public void beginRecognizeCustomFormsFromUrl() { String formUrl = "{form_url}"; String modelId = "{custom_trained_model_id}"; formRecognizerClient.beginRecognizeCustomFormsFromUrl(modelId, formUrl).getFinalResult() .stream() .map(RecognizedForm::getFields) .forEach(formFieldMap -> formFieldMap.forEach((fieldText, formField) -> { System.out.printf("Field text: %s%n", fieldText); System.out.printf("Field value data text: %s%n", formField.getValueData().getText()); System.out.printf("Confidence score: %.2f%n", formField.getConfidence()); })); } /** * Code snippet for {@link FormRecognizerClient */ public void beginRecognizeCustomFormsFromUrlWithOptions() { String analyzeFilePath = "{file_source_url}"; String modelId = "{model_id}"; boolean includeFieldElements = true; formRecognizerClient.beginRecognizeCustomFormsFromUrl(modelId, analyzeFilePath, new RecognizeCustomFormsOptions() .setFieldElementsIncluded(includeFieldElements) .setPollInterval(Duration.ofSeconds(10)), Context.NONE) .getFinalResult() .stream() .map(RecognizedForm::getFields) .forEach(formFieldMap -> formFieldMap.forEach((fieldText, formField) -> { System.out.printf("Field text: %s%n", fieldText); System.out.printf("Field value data text: %s%n", formField.getValueData().getText()); System.out.printf("Confidence score: %.2f%n", formField.getConfidence()); })); } /** * Code snippet for * {@link FormRecognizerClient * * @throws IOException Exception thrown when there is an error in reading all the bytes from the File. */ public void beginRecognizeCustomForms() throws IOException { File form = new File("{local/file_path/fileName.jpg}"); String modelId = "{custom_trained_model_id}"; byte[] fileContent = Files.readAllBytes(form.toPath()); try (InputStream targetStream = new ByteArrayInputStream(fileContent)) { formRecognizerClient.beginRecognizeCustomForms(modelId, targetStream, form.length()) .getFinalResult() .stream() .map(RecognizedForm::getFields) .forEach(formFieldMap -> formFieldMap.forEach((fieldText, formField) -> { System.out.printf("Field text: %s%n", fieldText); System.out.printf("Field value data text: %s%n", formField.getValueData().getText()); System.out.printf("Confidence score: %.2f%n", formField.getConfidence()); })); } } /** * Code snippet for * {@link FormRecognizerClient * * @throws IOException Exception thrown when there is an error in reading all the bytes from the File. */ public void beginRecognizeCustomFormsWithOptions() throws IOException { File form = new File("{local/file_path/fileName.jpg}"); String modelId = "{custom_trained_model_id}"; boolean includeFieldElements = true; byte[] fileContent = Files.readAllBytes(form.toPath()); try (InputStream targetStream = new ByteArrayInputStream(fileContent)) { formRecognizerClient.beginRecognizeCustomForms(modelId, targetStream, form.length(), new RecognizeCustomFormsOptions() .setContentType(FormContentType.IMAGE_JPEG) .setFieldElementsIncluded(includeFieldElements) .setPollInterval(Duration.ofSeconds(10)), Context.NONE) .getFinalResult() .stream() .map(RecognizedForm::getFields) .forEach(formFieldMap -> formFieldMap.forEach((fieldText, formField) -> { System.out.printf("Field text: %s%n", fieldText); System.out.printf("Field value data text: %s%n", formField.getValueData().getText()); System.out.printf("Confidence score: %.2f%n", formField.getConfidence()); })); } } /** * Code snippet for {@link FormRecognizerClient */ public void beginRecognizeContentFromUrl() { String formUrl = "{form_url}"; formRecognizerClient.beginRecognizeContentFromUrl(formUrl) .getFinalResult() .forEach(formPage -> { System.out.printf("Page Angle: %s%n", formPage.getTextAngle()); System.out.printf("Page Dimension unit: %s%n", formPage.getUnit()); System.out.println("Recognized Tables: "); formPage.getTables() .stream() .flatMap(formTable -> formTable.getCells().stream()) .forEach(recognizedTableCell -> System.out.printf("%s ", recognizedTableCell.getText())); }); } /** * Code snippet for {@link FormRecognizerClient * options. */ public void beginRecognizeContentFromUrlWithOptions() { String formPath = "{file_source_url}"; formRecognizerClient.beginRecognizeContentFromUrl(formPath, new RecognizeContentOptions() .setPollInterval(Duration.ofSeconds(5)), Context.NONE) .getFinalResult() .forEach(formPage -> { System.out.printf("Page Angle: %s%n", formPage.getTextAngle()); System.out.printf("Page Dimension unit: %s%n", formPage.getUnit()); System.out.println("Recognized Tables: "); formPage.getTables() .stream() .flatMap(formTable -> formTable.getCells().stream()) .forEach(recognizedTableCell -> System.out.printf("%s ", recognizedTableCell.getText())); }); } /** * Code snippet for {@link FormRecognizerClient * * @throws IOException Exception thrown when there is an error in reading all the bytes from the File. */ public void beginRecognizeContent() throws IOException { File form = new File("{local/file_path/fileName.pdf}"); byte[] fileContent = Files.readAllBytes(form.toPath()); try (InputStream targetStream = new ByteArrayInputStream(fileContent)) { formRecognizerClient.beginRecognizeContent(targetStream, form.length()) .getFinalResult() .forEach(formPage -> { System.out.printf("Page Angle: %s%n", formPage.getTextAngle()); System.out.printf("Page Dimension unit: %s%n", formPage.getUnit()); System.out.println("Recognized Tables: "); formPage.getTables() .stream() .flatMap(formTable -> formTable.getCells().stream()) .forEach(recognizedTableCell -> System.out.printf("%s ", recognizedTableCell.getText())); }); } } /** * Code snippet for {@link FormRecognizerClient * options. * * @throws IOException Exception thrown when there is an error in reading all the bytes from the File. */ public void beginRecognizeContentWithOptions() throws IOException { File form = new File("{file_source_url}"); byte[] fileContent = Files.readAllBytes(form.toPath()); try (InputStream targetStream = new ByteArrayInputStream(fileContent)) { for (FormPage formPage : formRecognizerClient.beginRecognizeContent(targetStream, form.length(), new RecognizeContentOptions() .setPollInterval(Duration.ofSeconds(5)), Context.NONE) .getFinalResult()) { System.out.printf("Page Angle: %s%n", formPage.getTextAngle()); System.out.printf("Page Dimension unit: %s%n", formPage.getUnit()); System.out.println("Recognized Tables: "); formPage.getTables() .stream() .flatMap(formTable -> formTable.getCells().stream()) .forEach(recognizedTableCell -> System.out.printf("%s ", recognizedTableCell.getText())); } } } /** * Code snippet for {@link FormRecognizerClient */ public void beginRecognizeReceiptsFromUrl() { String receiptUrl = "{file_source_url}"; formRecognizerClient.beginRecognizeReceiptsFromUrl(receiptUrl) .getFinalResult() .forEach(recognizedReceipt -> { Map<String, FormField> recognizedFields = recognizedReceipt.getFields(); FormField merchantNameField = recognizedFields.get("MerchantName"); if (merchantNameField != null) { if (FieldValueType.STRING == merchantNameField.getValue().getValueType()) { String merchantName = merchantNameField.getValue().asString(); System.out.printf("Merchant Name: %s, confidence: %.2f%n", merchantName, merchantNameField.getConfidence()); } } FormField merchantPhoneNumberField = recognizedFields.get("MerchantPhoneNumber"); if (merchantPhoneNumberField != null) { if (FieldValueType.PHONE_NUMBER == merchantPhoneNumberField.getValue().getValueType()) { String merchantAddress = merchantPhoneNumberField.getValue().asPhoneNumber(); System.out.printf("Merchant Phone number: %s, confidence: %.2f%n", merchantAddress, merchantPhoneNumberField.getConfidence()); } } FormField transactionDateField = recognizedFields.get("TransactionDate"); if (transactionDateField != null) { if (FieldValueType.DATE == transactionDateField.getValue().getValueType()) { LocalDate transactionDate = transactionDateField.getValue().asDate(); System.out.printf("Transaction Date: %s, confidence: %.2f%n", transactionDate, transactionDateField.getConfidence()); } } FormField receiptItemsField = recognizedFields.get("Items"); if (receiptItemsField != null) { System.out.printf("Receipt Items: %n"); if (FieldValueType.LIST == receiptItemsField.getValue().getValueType()) { List<FormField> receiptItems = receiptItemsField.getValue().asList(); receiptItems.stream() .filter(receiptItem -> FieldValueType.MAP == receiptItem.getValue().getValueType()) .map(formField -> formField.getValue().asMap()) .forEach(formFieldMap -> formFieldMap.forEach((key, formField) -> { if ("Quantity".equals(key)) { if (FieldValueType.FLOAT == formField.getValue().getValueType()) { Float quantity = formField.getValue().asFloat(); System.out.printf("Quantity: %f, confidence: %.2f%n", quantity, formField.getConfidence()); } } })); } } }); } /** * Code snippet for {@link FormRecognizerClient */ public void beginRecognizeReceiptsFromUrlWithOptions() { String receiptUrl = "{receipt_url}"; formRecognizerClient.beginRecognizeReceiptsFromUrl(receiptUrl, new RecognizeReceiptsOptions() .setPollInterval(Duration.ofSeconds(5)) .setFieldElementsIncluded(true), Context.NONE).getFinalResult() .forEach(recognizedReceipt -> { Map<String, FormField> recognizedFields = recognizedReceipt.getFields(); FormField merchantNameField = recognizedFields.get("MerchantName"); if (merchantNameField != null) { if (FieldValueType.STRING == merchantNameField.getValue().getValueType()) { String merchantName = merchantNameField.getValue().asString(); System.out.printf("Merchant Name: %s, confidence: %.2f%n", merchantName, merchantNameField.getConfidence()); } } FormField merchantPhoneNumberField = recognizedFields.get("MerchantPhoneNumber"); if (merchantPhoneNumberField != null) { if (FieldValueType.PHONE_NUMBER == merchantPhoneNumberField.getValue().getValueType()) { String merchantAddress = merchantPhoneNumberField.getValue().asPhoneNumber(); System.out.printf("Merchant Phone number: %s, confidence: %.2f%n", merchantAddress, merchantPhoneNumberField.getConfidence()); } } FormField transactionDateField = recognizedFields.get("TransactionDate"); if (transactionDateField != null) { if (FieldValueType.DATE == transactionDateField.getValue().getValueType()) { LocalDate transactionDate = transactionDateField.getValue().asDate(); System.out.printf("Transaction Date: %s, confidence: %.2f%n", transactionDate, transactionDateField.getConfidence()); } } FormField receiptItemsField = recognizedFields.get("Items"); if (receiptItemsField != null) { System.out.printf("Receipt Items: %n"); if (FieldValueType.LIST == receiptItemsField.getValue().getValueType()) { List<FormField> receiptItems = receiptItemsField.getValue().asList(); receiptItems.stream() .filter(receiptItem -> FieldValueType.MAP == receiptItem.getValue().getValueType()) .map(formField -> formField.getValue().asMap()) .forEach(formFieldMap -> formFieldMap.forEach((key, formField) -> { if ("Quantity".equals(key)) { if (FieldValueType.FLOAT == formField.getValue().getValueType()) { Float quantity = formField.getValue().asFloat(); System.out.printf("Quantity: %f, confidence: %.2f%n", quantity, formField.getConfidence()); } } })); } } }); } /** * Code snippet for {@link FormRecognizerClient * * @throws IOException Exception thrown when there is an error in reading all the bytes from the File. */ public void beginRecognizeReceipts() throws IOException { File receipt = new File("{receipt_url}"); byte[] fileContent = Files.readAllBytes(receipt.toPath()); try (InputStream targetStream = new ByteArrayInputStream(fileContent)) { formRecognizerClient.beginRecognizeReceipts(targetStream, receipt.length()).getFinalResult() .forEach(recognizedReceipt -> { Map<String, FormField> recognizedFields = recognizedReceipt.getFields(); FormField merchantNameField = recognizedFields.get("MerchantName"); if (merchantNameField != null) { if (FieldValueType.STRING == merchantNameField.getValue().getValueType()) { String merchantName = merchantNameField.getValue().asString(); System.out.printf("Merchant Name: %s, confidence: %.2f%n", merchantName, merchantNameField.getConfidence()); } } FormField merchantPhoneNumberField = recognizedFields.get("MerchantPhoneNumber"); if (merchantPhoneNumberField != null) { if (FieldValueType.PHONE_NUMBER == merchantPhoneNumberField.getValue().getValueType()) { String merchantAddress = merchantPhoneNumberField.getValue().asPhoneNumber(); System.out.printf("Merchant Phone number: %s, confidence: %.2f%n", merchantAddress, merchantPhoneNumberField.getConfidence()); } } FormField transactionDateField = recognizedFields.get("TransactionDate"); if (transactionDateField != null) { if (FieldValueType.DATE == transactionDateField.getValue().getValueType()) { LocalDate transactionDate = transactionDateField.getValue().asDate(); System.out.printf("Transaction Date: %s, confidence: %.2f%n", transactionDate, transactionDateField.getConfidence()); } } FormField receiptItemsField = recognizedFields.get("Items"); if (receiptItemsField != null) { System.out.printf("Receipt Items: %n"); if (FieldValueType.LIST == receiptItemsField.getValue().getValueType()) { List<FormField> receiptItems = receiptItemsField.getValue().asList(); receiptItems.stream() .filter(receiptItem -> FieldValueType.MAP == receiptItem.getValue().getValueType()) .map(formField -> formField.getValue().asMap()) .forEach(formFieldMap -> formFieldMap.forEach((key, formField) -> { if ("Quantity".equals(key)) { if (FieldValueType.FLOAT == formField.getValue().getValueType()) { Float quantity = formField.getValue().asFloat(); System.out.printf("Quantity: %f, confidence: %.2f%n", quantity, formField.getConfidence()); } } })); } } }); } } /** * Code snippet for {@link FormRecognizerClient * with options * * @throws IOException Exception thrown when there is an error in reading all the bytes from the File. */ public void beginRecognizeReceiptsWithOptions() throws IOException { File receipt = new File("{local/file_path/fileName.jpg}"); boolean includeFieldElements = true; byte[] fileContent = Files.readAllBytes(receipt.toPath()); try (InputStream targetStream = new ByteArrayInputStream(fileContent)) { for (RecognizedForm recognizedForm : formRecognizerClient.beginRecognizeReceipts(targetStream, receipt.length(), new RecognizeReceiptsOptions() .setContentType(FormContentType.IMAGE_JPEG) .setFieldElementsIncluded(includeFieldElements) .setPollInterval(Duration.ofSeconds(5)), Context.NONE) .getFinalResult()) { Map<String, FormField> recognizedFields = recognizedForm.getFields(); FormField merchantNameField = recognizedFields.get("MerchantName"); if (merchantNameField != null) { if (FieldValueType.STRING == merchantNameField.getValue().getValueType()) { String merchantName = merchantNameField.getValue().asString(); System.out.printf("Merchant Name: %s, confidence: %.2f%n", merchantName, merchantNameField.getConfidence()); } } FormField merchantPhoneNumberField = recognizedFields.get("MerchantPhoneNumber"); if (merchantPhoneNumberField != null) { if (FieldValueType.PHONE_NUMBER == merchantPhoneNumberField.getValue().getValueType()) { String merchantAddress = merchantPhoneNumberField.getValue().asPhoneNumber(); System.out.printf("Merchant Phone number: %s, confidence: %.2f%n", merchantAddress, merchantPhoneNumberField.getConfidence()); } } FormField transactionDateField = recognizedFields.get("TransactionDate"); if (transactionDateField != null) { if (FieldValueType.DATE == transactionDateField.getValue().getValueType()) { LocalDate transactionDate = transactionDateField.getValue().asDate(); System.out.printf("Transaction Date: %s, confidence: %.2f%n", transactionDate, transactionDateField.getConfidence()); } } FormField receiptItemsField = recognizedFields.get("Items"); if (receiptItemsField != null) { System.out.printf("Receipt Items: %n"); if (FieldValueType.LIST == receiptItemsField.getValue().getValueType()) { List<FormField> receiptItems = receiptItemsField.getValue().asList(); receiptItems.stream() .filter(receiptItem -> FieldValueType.MAP == receiptItem.getValue().getValueType()) .map(formField -> formField.getValue().asMap()) .forEach(formFieldMap -> formFieldMap.forEach((key, formField) -> { if ("Quantity".equals(key)) { if (FieldValueType.FLOAT == formField.getValue().getValueType()) { Float quantity = formField.getValue().asFloat(); System.out.printf("Quantity: %f, confidence: %.2f%n", quantity, formField.getConfidence()); } } })); } } } } } /** * Code snippet for {@link FormRecognizerClient */ /** * Code snippet for * {@link FormRecognizerClient */ public void beginRecognizeBusinessCardsFromUrlWithOptions() { String businessCardUrl = "{business_card_url}"; formRecognizerClient.beginRecognizeBusinessCardsFromUrl(businessCardUrl, new RecognizeBusinessCardsOptions() .setPollInterval(Duration.ofSeconds(5)) .setFieldElementsIncluded(true), Context.NONE).getFinalResult() .forEach(recognizedBusinessCard -> { Map<String, FormField> recognizedFields = recognizedBusinessCard.getFields(); FormField contactNamesFormField = recognizedFields.get("ContactNames"); if (contactNamesFormField != null) { if (FieldValueType.LIST == contactNamesFormField.getValue().getValueType()) { List<FormField> contactNamesList = contactNamesFormField.getValue().asList(); contactNamesList.stream() .filter(contactName -> FieldValueType.MAP == contactName.getValue().getValueType()) .map(contactName -> { System.out.printf("Contact name: %s%n", contactName.getValueData().getText()); return contactName.getValue().asMap(); }) .forEach(contactNamesMap -> contactNamesMap.forEach((key, contactName) -> { if ("FirstName".equals(key)) { if (FieldValueType.STRING == contactName.getValue().getValueType()) { String firstName = contactName.getValue().asString(); System.out.printf("\tFirst Name: %s, confidence: %.2f%n", firstName, contactName.getConfidence()); } } if ("LastName".equals(key)) { if (FieldValueType.STRING == contactName.getValue().getValueType()) { String lastName = contactName.getValue().asString(); System.out.printf("\tLast Name: %s, confidence: %.2f%n", lastName, contactName.getConfidence()); } } })); } } FormField jobTitles = recognizedFields.get("JobTitles"); if (jobTitles != null) { if (FieldValueType.LIST == jobTitles.getValue().getValueType()) { List<FormField> jobTitlesItems = jobTitles.getValue().asList(); jobTitlesItems.stream().forEach(jobTitlesItem -> { if (FieldValueType.STRING == jobTitlesItem.getValue().getValueType()) { String jobTitle = jobTitlesItem.getValue().asString(); System.out.printf("Job Title: %s, confidence: %.2f%n", jobTitle, jobTitlesItem.getConfidence()); } }); } } }); } /** * Code snippet for {@link FormRecognizerClient * * @throws IOException Exception thrown when there is an error in reading all the bytes from the File. */ public void beginRecognizeBusinessCards() throws IOException { File businessCard = new File("{local/file_path/fileName.jpg}"); byte[] fileContent = Files.readAllBytes(businessCard.toPath()); try (InputStream targetStream = new ByteArrayInputStream(fileContent)) { formRecognizerClient.beginRecognizeBusinessCards(targetStream, businessCard.length()).getFinalResult() .forEach(recognizedBusinessCard -> { Map<String, FormField> recognizedFields = recognizedBusinessCard.getFields(); FormField contactNamesFormField = recognizedFields.get("ContactNames"); if (contactNamesFormField != null) { if (FieldValueType.LIST == contactNamesFormField.getValue().getValueType()) { List<FormField> contactNamesList = contactNamesFormField.getValue().asList(); contactNamesList.stream() .filter(contactName -> FieldValueType.MAP == contactName.getValue().getValueType()) .map(contactName -> { System.out.printf("Contact name: %s%n", contactName.getValueData().getText()); return contactName.getValue().asMap(); }) .forEach(contactNamesMap -> contactNamesMap.forEach((key, contactName) -> { if ("FirstName".equals(key)) { if (FieldValueType.STRING == contactName.getValue().getValueType()) { String firstName = contactName.getValue().asString(); System.out.printf("\tFirst Name: %s, confidence: %.2f%n", firstName, contactName.getConfidence()); } } if ("LastName".equals(key)) { if (FieldValueType.STRING == contactName.getValue().getValueType()) { String lastName = contactName.getValue().asString(); System.out.printf("\tLast Name: %s, confidence: %.2f%n", lastName, contactName.getConfidence()); } } })); } } FormField jobTitles = recognizedFields.get("JobTitles"); if (jobTitles != null) { if (FieldValueType.LIST == jobTitles.getValue().getValueType()) { List<FormField> jobTitlesItems = jobTitles.getValue().asList(); jobTitlesItems.stream().forEach(jobTitlesItem -> { if (FieldValueType.STRING == jobTitlesItem.getValue().getValueType()) { String jobTitle = jobTitlesItem.getValue().asString(); System.out.printf("Job Title: %s, confidence: %.2f%n", jobTitle, jobTitlesItem.getConfidence()); } }); } } }); } } /** * Code snippet for * {@link FormRecognizerClient * Context)} with options * * @throws IOException Exception thrown when there is an error in reading all the bytes from the File. */ public void beginRecognizeBusinessCardsWithOptions() throws IOException { File businessCard = new File("{local/file_path/fileName.jpg}"); boolean includeFieldElements = true; byte[] fileContent = Files.readAllBytes(businessCard.toPath()); try (InputStream targetStream = new ByteArrayInputStream(fileContent)) { for (RecognizedForm recognizedForm : formRecognizerClient.beginRecognizeBusinessCards(targetStream, businessCard.length(), new RecognizeBusinessCardsOptions() .setContentType(FormContentType.IMAGE_JPEG) .setFieldElementsIncluded(includeFieldElements) .setPollInterval(Duration.ofSeconds(5)), Context.NONE) .getFinalResult()) { Map<String, FormField> recognizedFields = recognizedForm.getFields(); FormField contactNamesFormField = recognizedFields.get("ContactNames"); if (contactNamesFormField != null) { if (FieldValueType.LIST == contactNamesFormField.getValue().getValueType()) { List<FormField> contactNamesList = contactNamesFormField.getValue().asList(); contactNamesList.stream() .filter(contactName -> FieldValueType.MAP == contactName.getValue().getValueType()) .map(contactName -> { System.out.printf("Contact name: %s%n", contactName.getValueData().getText()); return contactName.getValue().asMap(); }) .forEach(contactNamesMap -> contactNamesMap.forEach((key, contactName) -> { if ("FirstName".equals(key)) { if (FieldValueType.STRING == contactName.getValue().getValueType()) { String firstName = contactName.getValue().asString(); System.out.printf("\tFirst Name: %s, confidence: %.2f%n", firstName, contactName.getConfidence()); } } if ("LastName".equals(key)) { if (FieldValueType.STRING == contactName.getValue().getValueType()) { String lastName = contactName.getValue().asString(); System.out.printf("\tLast Name: %s, confidence: %.2f%n", lastName, contactName.getConfidence()); } } })); } } FormField jobTitles = recognizedFields.get("JobTitles"); if (jobTitles != null) { if (FieldValueType.LIST == jobTitles.getValue().getValueType()) { List<FormField> jobTitlesItems = jobTitles.getValue().asList(); jobTitlesItems.stream().forEach(jobTitlesItem -> { if (FieldValueType.STRING == jobTitlesItem.getValue().getValueType()) { String jobTitle = jobTitlesItem.getValue().asString(); System.out.printf("Job Title: %s, confidence: %.2f%n", jobTitle, jobTitlesItem.getConfidence()); } }); } } } } } }
my bad. It used to cause some tests failed with previous implementation, but no longer a case now. Will bring it back.
static void validateMultiPageDataLabeled(List<RecognizedForm> actualRecognizedFormsList) { actualRecognizedFormsList.forEach(recognizedForm -> { assertEquals(1, recognizedForm.getPageRange().getFirstPageNumber()); assertEquals(3, recognizedForm.getPageRange().getLastPageNumber()); assertEquals(3, recognizedForm.getPages().size()); recognizedForm.getFields().forEach((label, formField) -> { assertNotNull(formField.getName()); assertNotNull(formField.getValue()); assertNotNull(formField.getValueData().getText()); }); }); }
assertNotNull(formField.getValueData().getText());
static void validateMultiPageDataLabeled(List<RecognizedForm> actualRecognizedFormsList) { actualRecognizedFormsList.forEach(recognizedForm -> { assertEquals(1, recognizedForm.getPageRange().getFirstPageNumber()); assertEquals(3, recognizedForm.getPageRange().getLastPageNumber()); assertEquals(3, recognizedForm.getPages().size()); recognizedForm.getFields().forEach((label, formField) -> { assertNotNull(formField.getName()); assertNotNull(formField.getValue()); assertNotNull(formField.getValueData().getText()); assertNull(formField.getLabelData()); }); }); }
class FormRecognizerClientTestBase extends TestBase { private static final Pattern NON_DIGIT_PATTERN = Pattern.compile("[^0-9]+"); private static final String EXPECTED_MULTIPAGE_ADDRESS_VALUE = "123 Hobbit Lane 567 Main St. Redmond, WA Redmond," + " WA"; private static final String EXPECTED_MULTIPAGE_PHONE_NUMBER_VALUE = "+15555555555"; private static final String ITEMIZED_RECEIPT_VALUE = "Itemized"; static final String RECEIPT_CONTOSO_JPG = "contoso-allinone.jpg"; static final String RECEIPT_CONTOSO_PNG = "contoso-receipt.png"; static final String INVOICE_6_PDF = "Invoice_6.pdf"; static final String MULTIPAGE_INVOICE_PDF = "multipage_invoice1.pdf"; static final String BUSINESS_CARD_JPG = "businessCard.jpg"; static final String BUSINESS_CARD_PNG = "businessCard.png"; static final String BAD_ARGUMENT_CODE = "BadArgument"; static final String INVALID_IMAGE_ERROR_CODE = "InvalidImage"; static final String INVALID_MODEL_ID_ERROR_CODE = "1001"; static final String MODEL_ID_NOT_FOUND_ERROR_CODE = "1022"; static final String URL_BADLY_FORMATTED_ERROR_CODE = "2001"; static final String UNABLE_TO_READ_FILE_ERROR_CODE = "2005"; static final String HTTPS_EXCEPTION_MESSAGE = "Max retries 3 times exceeded. Error Details: Key credentials require HTTPS to prevent leaking the key."; static final String INVALID_UUID_EXCEPTION_MESSAGE = "Invalid UUID string: "; static final String MODEL_ID_IS_REQUIRED_EXCEPTION_MESSAGE = "'modelId' is required and cannot be null."; static final String INVALID_ENDPOINT = "https: static final String LOCAL_FILE_PATH = "src/test/resources/sample_files/Test/"; static final String ENCODED_EMPTY_SPACE = "{\"source\":\"https: static final String CONTACT_NAMES = "ContactNames"; static final String JOB_TITLES = "JobTitles"; static final String DEPARTMENTS = "Departments"; static final String EMAILS = "Emails"; static final String WEBSITES = "Websites"; static final String MOBILE_PHONES = "MobilePhones"; static final String OTHER_PHONES = "OtherPhones"; static final String FAXES = "Faxes"; static final String ADDRESSES = "Addresses"; static final String COMPANY_NAMES = "CompanyNames"; Duration durationTestMode; /** * Use duration of nearly zero value for PLAYBACK test mode, otherwise, use default duration value for LIVE mode. */ @Override protected void beforeTest() { if (interceptorManager.isPlaybackMode()) { durationTestMode = ONE_NANO_DURATION; } else { durationTestMode = DEFAULT_DURATION; } } FormRecognizerClientBuilder getFormRecognizerClientBuilder(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { FormRecognizerClientBuilder builder = new FormRecognizerClientBuilder() .endpoint(getEndpoint()) .httpClient(httpClient == null ? interceptorManager.getPlaybackClient() : httpClient) .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)) .serviceVersion(serviceVersion) .addPolicy(interceptorManager.getRecordPolicy()); if (getTestMode() == TestMode.PLAYBACK) { builder.credential(new AzureKeyCredential(INVALID_KEY)); } else { builder.credential(new AzureKeyCredential( Configuration.getGlobalConfiguration().get(AZURE_FORM_RECOGNIZER_API_KEY))); } return builder; } FormTrainingClientBuilder getFormTrainingClientBuilder(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { FormTrainingClientBuilder builder = new FormTrainingClientBuilder() .endpoint(getEndpoint()) .httpClient(httpClient == null ? interceptorManager.getPlaybackClient() : httpClient) .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)) .serviceVersion(serviceVersion) .addPolicy(interceptorManager.getRecordPolicy()); if (getTestMode() == TestMode.PLAYBACK) { builder.credential(new AzureKeyCredential(INVALID_KEY)); } else { builder.credential(new AzureKeyCredential( Configuration.getGlobalConfiguration().get(AZURE_FORM_RECOGNIZER_API_KEY))); } return builder; } private static void validateReferenceElementsData(List<String> expectedElements, List<FormElement> actualFormElementList, List<ReadResult> readResults) { if (expectedElements != null && actualFormElementList != null) { assertEquals(expectedElements.size(), actualFormElementList.size()); for (int i = 0; i < actualFormElementList.size(); i++) { String[] indices = NON_DIGIT_PATTERN.matcher(expectedElements.get(i)).replaceAll(" ").trim().split(" "); if (indices.length < 2) { return; } int readResultIndex = Integer.parseInt(indices[0]); int lineIndex = Integer.parseInt(indices[1]); if (indices.length == 3) { int wordIndex = Integer.parseInt(indices[2]); TextWord expectedTextWord = readResults.get(readResultIndex).getLines().get(lineIndex).getWords().get(wordIndex); TextLine expectedTextLine = readResults.get(readResultIndex).getLines().get(lineIndex); if (actualFormElementList.get(i) instanceof FormLine) { FormLine actualFormLine = (FormLine) actualFormElementList.get(i); validateFormWordData(expectedTextLine.getWords(), actualFormLine.getWords()); } FormWord actualFormWord = (FormWord) actualFormElementList.get(i); assertEquals(expectedTextWord.getText(), actualFormWord.getText()); if (expectedTextWord.getConfidence() != null) { assertEquals(expectedTextWord.getConfidence(), actualFormWord.getConfidence()); } else { assertEquals(1.0f, actualFormWord.getConfidence()); } validateBoundingBoxData(expectedTextWord.getBoundingBox(), actualFormWord.getBoundingBox()); } } } } private static void validateFormTableData(List<DataTable> expectedFormTables, List<FormTable> actualFormTable, List<ReadResult> readResults, boolean includeFieldElements, int pageNumber) { assertEquals(expectedFormTables.size(), actualFormTable.size()); for (int i = 0; i < actualFormTable.size(); i++) { DataTable expectedTable = expectedFormTables.get(i); FormTable actualTable = actualFormTable.get(i); assertEquals(pageNumber, actualTable.getPageNumber()); assertEquals(expectedTable.getColumns(), actualTable.getColumnCount()); validateCellData(expectedTable.getCells(), actualTable.getCells(), readResults, includeFieldElements); assertEquals(expectedTable.getRows(), actualTable.getRowCount()); } } private static void validateCellData(List<DataTableCell> expectedTableCells, List<FormTableCell> actualTableCellList, List<ReadResult> readResults, boolean includeFieldElements) { assertEquals(expectedTableCells.size(), actualTableCellList.size()); for (int i = 0; i < actualTableCellList.size(); i++) { DataTableCell expectedTableCell = expectedTableCells.get(i); FormTableCell actualTableCell = actualTableCellList.get(i); assertEquals(expectedTableCell.getColumnIndex(), actualTableCell.getColumnIndex()); if (expectedTableCell.getColumnSpan() != null) { assertEquals(expectedTableCell.getColumnSpan(), actualTableCell.getColumnSpan()); } assertNotNull(actualTableCell.getColumnSpan()); assertEquals(expectedTableCell.getRowIndex(), actualTableCell.getRowIndex()); if (expectedTableCell.getRowSpan() != null) { assertEquals(expectedTableCell.getRowSpan(), actualTableCell.getRowSpan()); } assertNotNull(actualTableCell.getRowSpan()); validateBoundingBoxData(expectedTableCell.getBoundingBox(), actualTableCell.getBoundingBox()); if (includeFieldElements) { validateReferenceElementsData(expectedTableCell.getElements(), actualTableCell.getFieldElements(), readResults); } } } private static void validateFormLineData(List<TextLine> expectedLines, List<FormLine> actualLineList) { assertEquals(expectedLines.size(), actualLineList.size()); for (int i = 0; i < actualLineList.size(); i++) { TextLine expectedLine = expectedLines.get(i); FormLine actualLine = actualLineList.get(i); assertEquals(expectedLine.getText(), actualLine.getText()); validateBoundingBoxData(expectedLine.getBoundingBox(), actualLine.getBoundingBox()); validateFormWordData(expectedLine.getWords(), actualLine.getWords()); } } private static void validateFormWordData(List<TextWord> expectedFormWords, List<FormWord> actualFormWordList) { assertEquals(expectedFormWords.size(), actualFormWordList.size()); for (int i = 0; i < actualFormWordList.size(); i++) { TextWord expectedWord = expectedFormWords.get(i); FormWord actualWord = actualFormWordList.get(i); assertEquals(expectedWord.getText(), actualWord.getText()); validateBoundingBoxData(expectedWord.getBoundingBox(), actualWord.getBoundingBox()); if (expectedWord.getConfidence() != null) { assertEquals(expectedWord.getConfidence(), actualWord.getConfidence()); } else { assertEquals(1.0f, actualWord.getConfidence()); } } } private static void validateBoundingBoxData(List<Float> expectedBoundingBox, FieldBoundingBox actualFieldBoundingBox) { if (actualFieldBoundingBox != null && actualFieldBoundingBox.getPoints() != null) { int i = 0; for (Point point : actualFieldBoundingBox.getPoints()) { assertEquals(expectedBoundingBox.get(i), point.getX()); assertEquals(expectedBoundingBox.get(++i), point.getY()); i++; } } } @SuppressWarnings("unchecked") private static void validateFieldValueTransforms(FieldValue expectedFieldValue, FormField actualFormField, List<ReadResult> readResults, boolean includeFieldElements) { if (expectedFieldValue != null) { if (expectedFieldValue.getBoundingBox() != null) { validateBoundingBoxData(expectedFieldValue.getBoundingBox(), actualFormField.getValueData().getBoundingBox()); } if (includeFieldElements && expectedFieldValue.getElements() != null) { validateReferenceElementsData(expectedFieldValue.getElements(), actualFormField.getValueData().getFieldElements(), readResults); } switch (expectedFieldValue.getType()) { case NUMBER: if (expectedFieldValue.getValueNumber() != null) { assertEquals(expectedFieldValue.getValueNumber(), actualFormField.getValue().asFloat()); } break; case DATE: assertEquals(expectedFieldValue.getValueDate(), actualFormField.getValue().asDate()); break; case TIME: assertEquals(LocalTime.parse(expectedFieldValue.getValueTime(), DateTimeFormatter.ofPattern("HH:mm:ss")), actualFormField.getValue().asTime()); break; case STRING: if (actualFormField.getName() != "ReceiptType") { assertEquals(expectedFieldValue.getValueString(), actualFormField.getValue().asString()); } break; case INTEGER: assertEquals(expectedFieldValue.getValueInteger(), actualFormField.getValue().asLong()); break; case PHONE_NUMBER: assertEquals(expectedFieldValue.getValuePhoneNumber(), actualFormField.getValue().asPhoneNumber()); break; case OBJECT: expectedFieldValue.getValueObject().forEach((key, formField) -> { FormField actualFormFieldValue = actualFormField.getValue().asMap().get(key); validateFieldValueTransforms(formField, actualFormFieldValue, readResults, includeFieldElements); }); break; case ARRAY: assertEquals(expectedFieldValue.getValueArray().size(), actualFormField.getValue().asList().size()); for (int i = 0; i < expectedFieldValue.getValueArray().size(); i++) { FieldValue expectedReceiptItem = expectedFieldValue.getValueArray().get(i); FormField actualReceiptItem = actualFormField.getValue().asList().get(i); validateFieldValueTransforms(expectedReceiptItem, actualReceiptItem, readResults, includeFieldElements); } break; default: assertFalse(false, "Field type not supported."); } } } private static void validatePageRangeData(int expectedPageInfo, FormPageRange actualPageInfo) { assertEquals(expectedPageInfo, actualPageInfo.getFirstPageNumber()); assertEquals(expectedPageInfo, actualPageInfo.getLastPageNumber()); } @Test abstract void recognizeReceiptData(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeReceiptDataNullData(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeReceiptDataWithContentTypeAutoDetection(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeReceiptDataIncludeFieldElements(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeReceiptDataWithPngFile(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeReceiptDataWithBlankPdf(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeReceiptFromDataMultiPage(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeReceiptSourceUrl(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeReceiptInvalidSourceUrl(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeReceiptFromUrlIncludeFieldElements(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeReceiptSourceUrlWithPngFile(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeReceiptFromUrlMultiPage(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeContent(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeContentResultWithNullData(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeContentResultWithContentTypeAutoDetection(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeContentResultWithBlankPdf(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeContentFromDataMultiPage(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeContentFromUrl(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeContentFromUrlWithPdf(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeContentInvalidSourceUrl(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeContentFromUrlMultiPage(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormLabeledData(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormLabeledDataWithJpgContentType(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormLabeledDataWithBlankPdfContentType(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormLabeledDataExcludeFieldElements(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormLabeledDataWithNullFormData(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormLabeledDataWithNullModelId(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormLabeledDataWithEmptyModelId(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormInvalidStatus(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormLabeledDataWithContentTypeAutoDetection(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormMultiPageLabeled(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormUnlabeledData(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormUnlabeledDataIncludeFieldElements(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormMultiPageUnlabeled(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormUnlabeledDataWithJpgContentType(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormUnlabeledDataWithBlankPdfContentType(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormUrlUnlabeledData(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormUrlUnlabeledDataIncludeFieldElements(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormUrlMultiPageUnlabeled(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormInvalidSourceUrl(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormFromUrlLabeledDataWithNullModelId(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormFromUrlLabeledDataWithEmptyModelId(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormUrlLabeledData(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormUrlLabeledDataIncludeFieldElements(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormUrlMultiPageLabeled(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeBusinessCardData(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeBusinessCardDataNullData(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeBusinessCardDataWithContentTypeAutoDetection(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeBusinessCardDataIncludeFieldElements(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeBusinessCardDataWithPngFile(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeBusinessCardDataWithBlankPdf(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeBusinessCardFromDamagedPdf(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeBusinessCardSourceUrl(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeBusinessCardFromUrlWithEncodedBlankSpaceSourceUrl(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeBusinessCardInvalidSourceUrl(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeBusinessCardFromUrlIncludeFieldElements(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeBusinessCardSourceUrlWithPngFile(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); void validateReceiptDataFields(Map<String, FormField> actualRecognizedReceiptFields, boolean includeFieldElements) { final AnalyzeResult analyzeResult = getAnalyzeRawResponse().getAnalyzeResult(); List<ReadResult> readResults = analyzeResult.getReadResults(); DocumentResult documentResult = analyzeResult.getDocumentResults().get(0); Map<String, FieldValue> expectedReceiptFields = documentResult.getFields(); assertEquals(expectedReceiptFields.get("ReceiptType").getValueString(), actualRecognizedReceiptFields.get("ReceiptType").getValue().asString()); assertEquals(expectedReceiptFields.get("ReceiptType").getConfidence(), actualRecognizedReceiptFields.get("ReceiptType").getConfidence()); validateFieldValueTransforms(expectedReceiptFields.get("MerchantName"), actualRecognizedReceiptFields.get("MerchantName"), readResults, includeFieldElements); validateFieldValueTransforms(expectedReceiptFields.get("MerchantPhoneNumber"), actualRecognizedReceiptFields.get("MerchantPhoneNumber"), readResults, includeFieldElements); validateFieldValueTransforms(expectedReceiptFields.get("MerchantAddress"), actualRecognizedReceiptFields.get("MerchantAddress"), readResults, includeFieldElements); validateFieldValueTransforms(expectedReceiptFields.get("Total"), actualRecognizedReceiptFields.get("Total"), readResults, includeFieldElements); validateFieldValueTransforms(expectedReceiptFields.get("Subtotal"), actualRecognizedReceiptFields.get("Subtotal"), readResults, includeFieldElements); validateFieldValueTransforms(expectedReceiptFields.get("Tax"), actualRecognizedReceiptFields.get("Tax"), readResults, includeFieldElements); validateFieldValueTransforms(expectedReceiptFields.get("TransactionDate"), actualRecognizedReceiptFields.get("TransactionDate"), readResults, includeFieldElements); validateFieldValueTransforms(expectedReceiptFields.get("TransactionTime"), actualRecognizedReceiptFields.get("TransactionTime"), readResults, includeFieldElements); validateFieldValueTransforms(expectedReceiptFields.get("Items"), actualRecognizedReceiptFields.get("Items"), readResults, includeFieldElements); } void validateContentResultData(List<FormPage> actualFormPageList, boolean includeFieldElements) { AnalyzeResult analyzeResult = getAnalyzeRawResponse().getAnalyzeResult(); final List<PageResult> pageResults = analyzeResult.getPageResults(); final List<ReadResult> readResults = analyzeResult.getReadResults(); for (int i = 0; i < actualFormPageList.size(); i++) { FormPage actualFormPage = actualFormPageList.get(i); ReadResult readResult = readResults.get(i); if (readResult.getAngle() > 180) { assertEquals(readResult.getAngle() - 360, actualFormPage.getTextAngle()); } else { assertEquals(readResult.getAngle(), actualFormPage.getTextAngle()); } assertEquals(readResult.getWidth(), actualFormPage.getWidth()); assertEquals(readResult.getHeight(), actualFormPage.getHeight()); assertEquals(readResult.getUnit().toString(), actualFormPage.getUnit().toString()); assertEquals(readResult.getPage(), actualFormPage.getPageNumber()); if (includeFieldElements) { validateFormLineData(readResult.getLines(), actualFormPage.getLines()); } if (pageResults != null) { validateFormTableData(pageResults.get(i).getTables(), actualFormPage.getTables(), readResults, includeFieldElements, pageResults.get(i).getPage()); } } } void validateReceiptResultData(List<RecognizedForm> actualReceiptList, boolean includeFieldElements) { final AnalyzeResult rawResponse = getAnalyzeRawResponse().getAnalyzeResult(); for (int i = 0; i < actualReceiptList.size(); i++) { final RecognizedForm actualReceipt = actualReceiptList.get(i); validateLabeledData(actualReceipt, includeFieldElements, rawResponse.getReadResults(), rawResponse.getDocumentResults().get(i)); validateReceiptDataFields(actualReceipt.getFields(), includeFieldElements); } } void validateBlankPdfResultData(List<RecognizedForm> actualReceiptList) { assertEquals(1, actualReceiptList.size()); final RecognizedForm actualReceipt = actualReceiptList.get(0); assertTrue(actualReceipt.getFields().isEmpty()); } void validateRecognizedResult(List<RecognizedForm> actualFormList, boolean includeFieldElements, boolean isLabeled) { final AnalyzeResult rawResponse = getAnalyzeRawResponse().getAnalyzeResult(); List<ReadResult> readResults = rawResponse.getReadResults(); List<PageResult> pageResults = rawResponse.getPageResults(); List<DocumentResult> documentResults = rawResponse.getDocumentResults(); for (int i = 0; i < actualFormList.size(); i++) { validateContentResultData(actualFormList.get(i).getPages(), includeFieldElements); if (isLabeled) { validateLabeledData(actualFormList.get(i), includeFieldElements, readResults, documentResults.get(i)); } else { validateUnLabeledResult(actualFormList.get(i), includeFieldElements, readResults, pageResults.get(i)); } } } void validateBusinessCardDataFields(Map<String, FormField> actualRecognizedBusinessCardFields, boolean includeFieldElements) { final AnalyzeResult analyzeResult = getAnalyzeRawResponse().getAnalyzeResult(); List<ReadResult> readResults = analyzeResult.getReadResults(); DocumentResult documentResult = analyzeResult.getDocumentResults().get(0); Map<String, FieldValue> expectedReceiptFields = documentResult.getFields(); validateFieldValueTransforms(expectedReceiptFields.get(CONTACT_NAMES), actualRecognizedBusinessCardFields.get(CONTACT_NAMES), readResults, includeFieldElements); validateFieldValueTransforms(expectedReceiptFields.get(JOB_TITLES), actualRecognizedBusinessCardFields.get(JOB_TITLES), readResults, includeFieldElements); validateFieldValueTransforms(expectedReceiptFields.get(DEPARTMENTS), actualRecognizedBusinessCardFields.get(DEPARTMENTS), readResults, includeFieldElements); validateFieldValueTransforms(expectedReceiptFields.get(EMAILS), actualRecognizedBusinessCardFields.get(EMAILS), readResults, includeFieldElements); validateFieldValueTransforms(expectedReceiptFields.get(WEBSITES), actualRecognizedBusinessCardFields.get(WEBSITES), readResults, includeFieldElements); validateFieldValueTransforms(expectedReceiptFields.get(MOBILE_PHONES), actualRecognizedBusinessCardFields.get(MOBILE_PHONES), readResults, includeFieldElements); validateFieldValueTransforms(expectedReceiptFields.get(OTHER_PHONES), actualRecognizedBusinessCardFields.get(OTHER_PHONES), readResults, includeFieldElements); validateFieldValueTransforms(expectedReceiptFields.get(FAXES), actualRecognizedBusinessCardFields.get(FAXES), readResults, includeFieldElements); validateFieldValueTransforms(expectedReceiptFields.get(ADDRESSES), actualRecognizedBusinessCardFields.get(ADDRESSES), readResults, includeFieldElements); validateFieldValueTransforms(expectedReceiptFields.get(COMPANY_NAMES), actualRecognizedBusinessCardFields.get(COMPANY_NAMES), readResults, includeFieldElements); } void validateBusinessCardResultData(List<RecognizedForm> actualBusinessCardList, boolean includeFieldElements) { final AnalyzeResult rawResponse = getAnalyzeRawResponse().getAnalyzeResult(); for (int i = 0; i < actualBusinessCardList.size(); i++) { final RecognizedForm actualBusinessCard = actualBusinessCardList.get(i); validateLabeledData(actualBusinessCard, includeFieldElements, rawResponse.getReadResults(), rawResponse.getDocumentResults().get(i)); validateBusinessCardDataFields(actualBusinessCard.getFields(), includeFieldElements); } } void invalidSourceUrlRunner(Consumer<String> testRunner) { testRunner.accept(TestUtils.INVALID_RECEIPT_URL); } void encodedBlankSpaceSourceUrlRunner(Consumer<String> testRunner) { testRunner.accept(FAKE_ENCODED_EMPTY_SPACE_URL); } void urlRunner(Consumer<String> testRunner, String fileName) { testRunner.accept(URL_TEST_FILE_FORMAT + fileName); } void storageUrlRunner(Consumer<String> testRunner, String fileName) { testRunner.accept(getStorageTestingFileUrl(fileName)); } void urlPdfUnlabeledRunner(Consumer<String> testRunner) { testRunner.accept(getStorageTestingFileUrl(MULTIPAGE_INVOICE_PDF)); } void dataRunner(BiConsumer<InputStream, Long> testRunner, String fileName) { final long fileLength = new File(LOCAL_FILE_PATH + fileName).length(); if (interceptorManager.isPlaybackMode()) { testRunner.accept(new ByteArrayInputStream(TEST_DATA_PNG.getBytes(StandardCharsets.UTF_8)), fileLength); } else { try { testRunner.accept(new FileInputStream(LOCAL_FILE_PATH + fileName), fileLength); } catch (FileNotFoundException e) { throw new RuntimeException("Local file not found.", e); } } } void localFilePathRunner(BiConsumer<String, Long> testRunner, String fileName) { final long fileLength = new File(LOCAL_FILE_PATH + fileName).length(); testRunner.accept(LOCAL_FILE_PATH + fileName, fileLength); } void damagedPdfDataRunner(BiConsumer<InputStream, Integer> testRunner) { testRunner.accept(new ByteArrayInputStream(new byte[]{0x25, 0x50, 0x44, 0x46, 0x55, 0x55, 0x55}), 7); } void beginTrainingUnlabeledRunner(BiConsumer<String, Boolean> testRunner) { testRunner.accept(getTrainingSasUri(), false); } void beginTrainingLabeledRunner(BiConsumer<String, Boolean> testRunner) { testRunner.accept(getTrainingSasUri(), true); } void beginTrainingMultipageRunner(Consumer<String> testRunner) { testRunner.accept(getMultipageTrainingSasUri()); } private void validateUnLabeledResult(RecognizedForm actualForm, boolean includeFieldElements, List<ReadResult> readResults, PageResult expectedPage) { validatePageRangeData(expectedPage.getPage(), actualForm.getPageRange()); int i = 0; for (Map.Entry<String, FormField> entry : actualForm.getFields().entrySet()) { FormField actualFormField = entry.getValue(); final KeyValuePair expectedFormField = expectedPage.getKeyValuePairs().get(i++); assertEquals(expectedFormField.getConfidence(), actualFormField.getConfidence()); assertEquals(expectedFormField.getKey().getText(), actualFormField.getLabelData().getText()); validateBoundingBoxData(expectedFormField.getKey().getBoundingBox(), actualFormField.getLabelData().getBoundingBox()); if (includeFieldElements) { validateReferenceElementsData(expectedFormField.getKey().getElements(), actualFormField.getLabelData().getFieldElements(), readResults); validateReferenceElementsData(expectedFormField.getValue().getElements(), actualFormField.getValueData().getFieldElements(), readResults); } assertEquals(expectedFormField.getValue().getText(), actualFormField.getValueData().getText()); validateBoundingBoxData(expectedFormField.getValue().getBoundingBox(), actualFormField.getValueData().getBoundingBox()); } } private void validateLabeledData(RecognizedForm actualForm, boolean includeFieldElements, List<ReadResult> readResults, DocumentResult documentResult) { assertEquals(documentResult.getPageRange().get(0), actualForm.getPageRange().getFirstPageNumber()); assertEquals(documentResult.getPageRange().get(1), actualForm.getPageRange().getLastPageNumber()); assertEquals(documentResult.getFields().keySet(), actualForm.getFields().keySet()); documentResult.getFields().forEach((label, expectedFieldValue) -> { final FormField actualFormField = actualForm.getFields().get(label); assertEquals(label, actualFormField.getName()); if (expectedFieldValue != null) { if (expectedFieldValue.getConfidence() != null) { assertEquals(expectedFieldValue.getConfidence(), actualFormField.getConfidence()); } else { assertEquals(1.0f, actualFormField.getConfidence()); } validateFieldValueTransforms(expectedFieldValue, actualFormField, readResults, includeFieldElements); } }); } static void validateMultiPageDataUnlabeled(List<RecognizedForm> actualRecognizedFormsList) { actualRecognizedFormsList.forEach(recognizedForm -> { assertNotNull(recognizedForm.getFormType()); assertEquals(1, (long) recognizedForm.getPages().size()); recognizedForm.getFields().forEach((label, formField) -> { assertNotNull(formField.getName()); assertNotNull(formField.getValue()); assertNotNull(formField.getValueData().getText()); assertNotNull(formField.getLabelData().getText()); }); }); } static void validateMultipageReceiptData(List<RecognizedForm> recognizedReceipts) { assertEquals(3, recognizedReceipts.size()); RecognizedForm receiptPage1 = recognizedReceipts.get(0); RecognizedForm receiptPage2 = recognizedReceipts.get(1); RecognizedForm receiptPage3 = recognizedReceipts.get(2); assertEquals(1, receiptPage1.getPageRange().getFirstPageNumber()); assertEquals(1, receiptPage1.getPageRange().getLastPageNumber()); Map<String, FormField> receiptPage1Fields = receiptPage1.getFields(); assertEquals(EXPECTED_MULTIPAGE_ADDRESS_VALUE, receiptPage1Fields.get("MerchantAddress") .getValue().asString()); assertEquals("Bilbo Baggins", receiptPage1Fields.get("MerchantName") .getValue().asString()); assertEquals(EXPECTED_MULTIPAGE_PHONE_NUMBER_VALUE, receiptPage1Fields.get("MerchantPhoneNumber") .getValue().asPhoneNumber()); assertNotNull(receiptPage1Fields.get("Total").getValue().asFloat()); assertNotNull(receiptPage1.getPages()); assertEquals(ITEMIZED_RECEIPT_VALUE, receiptPage1Fields.get("ReceiptType").getValue().asString()); assertEquals(0, receiptPage2.getFields().size()); List<FormPage> receipt2Pages = receiptPage2.getPages(); assertEquals(1, receipt2Pages.size()); assertEquals(0, receipt2Pages.stream().findFirst().get().getTables().size()); assertEquals(0, receipt2Pages.stream().findFirst().get().getLines().size()); assertEquals(2, receiptPage2.getPageRange().getFirstPageNumber()); assertEquals(2, receiptPage2.getPageRange().getLastPageNumber()); assertEquals(3, receiptPage3.getPageRange().getFirstPageNumber()); assertEquals(3, receiptPage3.getPageRange().getLastPageNumber()); Map<String, FormField> receiptPage3Fields = receiptPage3.getFields(); assertEquals(EXPECTED_MULTIPAGE_ADDRESS_VALUE, receiptPage3Fields.get("MerchantAddress").getValue().asString()); assertEquals("Frodo Baggins", receiptPage3Fields.get("MerchantName").getValue().asString()); assertEquals(EXPECTED_MULTIPAGE_PHONE_NUMBER_VALUE, receiptPage3Fields.get("MerchantPhoneNumber").getValue().asPhoneNumber()); assertNotNull(receiptPage3Fields.get("Total").getValue().asFloat()); assertEquals(3000.0f, receiptPage3Fields.get("Subtotal").getValue().asFloat()); assertEquals(ITEMIZED_RECEIPT_VALUE, receiptPage3Fields.get("ReceiptType").getValue().asString()); } protected String getEndpoint() { return interceptorManager.isPlaybackMode() ? "https: : Configuration.getGlobalConfiguration().get(AZURE_FORM_RECOGNIZER_ENDPOINT); } /** * Get the training data set SAS Url value based on the test running mode. * * @return the training data set Url */ private String getTrainingSasUri() { if (interceptorManager.isPlaybackMode()) { return "https: } else { return Configuration.getGlobalConfiguration().get(FORM_RECOGNIZER_TRAINING_BLOB_CONTAINER_SAS_URL); } } /** * Get the training data set SAS Url value based on the test running mode. * * @return the training data set Url */ private String getMultipageTrainingSasUri() { if (interceptorManager.isPlaybackMode()) { return "https: } else { return Configuration.getGlobalConfiguration() .get(FORM_RECOGNIZER_MULTIPAGE_TRAINING_BLOB_CONTAINER_SAS_URL); } } /** * Get the testing data set SAS Url value based on the test running mode. * * @return the testing data set Url */ private String getTestingSasUri() { if (interceptorManager.isPlaybackMode()) { return "https: } else { return Configuration.getGlobalConfiguration().get("FORM_RECOGNIZER_TESTING_BLOB_CONTAINER_SAS_URL"); } } /** * Prepare the file url from the testing data set SAS Url value. * * @return the testing data specific file Url */ private String getStorageTestingFileUrl(String fileName) { if (interceptorManager.isPlaybackMode()) { return "https: } else { final String[] urlParts = getTestingSasUri().split("\\?"); return urlParts[0] + "/" + fileName + "?" + urlParts[1]; } } /** * Prepare the expected test data from service raw response. * * @return the {@code AnalyzeOperationResult} test data */ private AnalyzeOperationResult getAnalyzeRawResponse() { final SerializerAdapter serializerAdapter = getSerializerAdapter(); final NetworkCallRecord networkCallRecord = interceptorManager.getRecordedData().findFirstAndRemoveNetworkCall(record -> { AnalyzeOperationResult rawModelResponse = deserializeRawResponse(serializerAdapter, record, AnalyzeOperationResult.class); return rawModelResponse != null && rawModelResponse.getStatus() == OperationStatus.SUCCEEDED; }); interceptorManager.getRecordedData().addNetworkCall(networkCallRecord); return deserializeRawResponse(serializerAdapter, networkCallRecord, AnalyzeOperationResult.class); } }
class FormRecognizerClientTestBase extends TestBase { private static final Pattern NON_DIGIT_PATTERN = Pattern.compile("[^0-9]+"); private static final String EXPECTED_MULTIPAGE_ADDRESS_VALUE = "123 Hobbit Lane 567 Main St. Redmond, WA Redmond," + " WA"; private static final String EXPECTED_MULTIPAGE_PHONE_NUMBER_VALUE = "+15555555555"; private static final String ITEMIZED_RECEIPT_VALUE = "Itemized"; static final String RECEIPT_CONTOSO_JPG = "contoso-allinone.jpg"; static final String RECEIPT_CONTOSO_PNG = "contoso-receipt.png"; static final String INVOICE_6_PDF = "Invoice_6.pdf"; static final String MULTIPAGE_INVOICE_PDF = "multipage_invoice1.pdf"; static final String BUSINESS_CARD_JPG = "businessCard.jpg"; static final String BUSINESS_CARD_PNG = "businessCard.png"; static final String BAD_ARGUMENT_CODE = "BadArgument"; static final String INVALID_IMAGE_ERROR_CODE = "InvalidImage"; static final String INVALID_MODEL_ID_ERROR_CODE = "1001"; static final String MODEL_ID_NOT_FOUND_ERROR_CODE = "1022"; static final String URL_BADLY_FORMATTED_ERROR_CODE = "2001"; static final String UNABLE_TO_READ_FILE_ERROR_CODE = "2005"; static final String HTTPS_EXCEPTION_MESSAGE = "Max retries 3 times exceeded. Error Details: Key credentials require HTTPS to prevent leaking the key."; static final String INVALID_UUID_EXCEPTION_MESSAGE = "Invalid UUID string: "; static final String MODEL_ID_IS_REQUIRED_EXCEPTION_MESSAGE = "'modelId' is required and cannot be null."; static final String INVALID_ENDPOINT = "https: static final String LOCAL_FILE_PATH = "src/test/resources/sample_files/Test/"; static final String ENCODED_EMPTY_SPACE = "{\"source\":\"https: static final List<String> BUSINESS_CARD_FIELDS = Arrays.asList("ContactNames", "JobTitles", "Departments", "Emails", "Websites", "MobilePhones", "OtherPhones", "Faxes", "Addresses", "CompanyNames"); Duration durationTestMode; /** * Use duration of nearly zero value for PLAYBACK test mode, otherwise, use default duration value for LIVE mode. */ @Override protected void beforeTest() { if (interceptorManager.isPlaybackMode()) { durationTestMode = ONE_NANO_DURATION; } else { durationTestMode = DEFAULT_DURATION; } } FormRecognizerClientBuilder getFormRecognizerClientBuilder(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { FormRecognizerClientBuilder builder = new FormRecognizerClientBuilder() .endpoint(getEndpoint()) .httpClient(httpClient == null ? interceptorManager.getPlaybackClient() : httpClient) .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)) .serviceVersion(serviceVersion) .addPolicy(interceptorManager.getRecordPolicy()); if (getTestMode() == TestMode.PLAYBACK) { builder.credential(new AzureKeyCredential(INVALID_KEY)); } else { builder.credential(new DefaultAzureCredentialBuilder().build()); } return builder; } FormTrainingClientBuilder getFormTrainingClientBuilder(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { FormTrainingClientBuilder builder = new FormTrainingClientBuilder() .endpoint(getEndpoint()) .httpClient(httpClient == null ? interceptorManager.getPlaybackClient() : httpClient) .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)) .serviceVersion(serviceVersion) .addPolicy(interceptorManager.getRecordPolicy()); if (getTestMode() == TestMode.PLAYBACK) { builder.credential(new AzureKeyCredential(INVALID_KEY)); } else { builder.credential(new AzureKeyCredential(Configuration.getGlobalConfiguration().get(AZURE_FORM_RECOGNIZER_API_KEY))); } return builder; } private static void validateReferenceElementsData(List<String> expectedElements, List<FormElement> actualFormElementList, List<ReadResult> readResults) { if (expectedElements != null && actualFormElementList != null) { assertEquals(expectedElements.size(), actualFormElementList.size()); for (int i = 0; i < actualFormElementList.size(); i++) { String[] indices = NON_DIGIT_PATTERN.matcher(expectedElements.get(i)).replaceAll(" ").trim().split(" "); if (indices.length < 2) { return; } int readResultIndex = Integer.parseInt(indices[0]); int lineIndex = Integer.parseInt(indices[1]); if (indices.length == 3) { int wordIndex = Integer.parseInt(indices[2]); TextWord expectedTextWord = readResults.get(readResultIndex).getLines().get(lineIndex).getWords().get(wordIndex); TextLine expectedTextLine = readResults.get(readResultIndex).getLines().get(lineIndex); if (actualFormElementList.get(i) instanceof FormLine) { FormLine actualFormLine = (FormLine) actualFormElementList.get(i); validateFormWordData(expectedTextLine.getWords(), actualFormLine.getWords()); } FormWord actualFormWord = (FormWord) actualFormElementList.get(i); assertEquals(expectedTextWord.getText(), actualFormWord.getText()); if (expectedTextWord.getConfidence() != null) { assertEquals(expectedTextWord.getConfidence(), actualFormWord.getConfidence()); } else { assertEquals(1.0f, actualFormWord.getConfidence()); } validateBoundingBoxData(expectedTextWord.getBoundingBox(), actualFormWord.getBoundingBox()); } } } } private static void validateFormTableData(List<DataTable> expectedFormTables, List<FormTable> actualFormTable, List<ReadResult> readResults, boolean includeFieldElements, int pageNumber) { assertEquals(expectedFormTables.size(), actualFormTable.size()); for (int i = 0; i < actualFormTable.size(); i++) { DataTable expectedTable = expectedFormTables.get(i); FormTable actualTable = actualFormTable.get(i); assertEquals(pageNumber, actualTable.getPageNumber()); assertEquals(expectedTable.getColumns(), actualTable.getColumnCount()); validateCellData(expectedTable.getCells(), actualTable.getCells(), readResults, includeFieldElements); assertEquals(expectedTable.getRows(), actualTable.getRowCount()); } } private static void validateCellData(List<DataTableCell> expectedTableCells, List<FormTableCell> actualTableCellList, List<ReadResult> readResults, boolean includeFieldElements) { assertEquals(expectedTableCells.size(), actualTableCellList.size()); for (int i = 0; i < actualTableCellList.size(); i++) { DataTableCell expectedTableCell = expectedTableCells.get(i); FormTableCell actualTableCell = actualTableCellList.get(i); assertEquals(expectedTableCell.getColumnIndex(), actualTableCell.getColumnIndex()); if (expectedTableCell.getColumnSpan() != null) { assertEquals(expectedTableCell.getColumnSpan(), actualTableCell.getColumnSpan()); } assertNotNull(actualTableCell.getColumnSpan()); assertEquals(expectedTableCell.getRowIndex(), actualTableCell.getRowIndex()); if (expectedTableCell.getRowSpan() != null) { assertEquals(expectedTableCell.getRowSpan(), actualTableCell.getRowSpan()); } assertNotNull(actualTableCell.getRowSpan()); validateBoundingBoxData(expectedTableCell.getBoundingBox(), actualTableCell.getBoundingBox()); if (includeFieldElements) { validateReferenceElementsData(expectedTableCell.getElements(), actualTableCell.getFieldElements(), readResults); } } } private static void validateFormLineData(List<TextLine> expectedLines, List<FormLine> actualLineList) { assertEquals(expectedLines.size(), actualLineList.size()); for (int i = 0; i < actualLineList.size(); i++) { TextLine expectedLine = expectedLines.get(i); FormLine actualLine = actualLineList.get(i); assertEquals(expectedLine.getText(), actualLine.getText()); validateBoundingBoxData(expectedLine.getBoundingBox(), actualLine.getBoundingBox()); validateFormWordData(expectedLine.getWords(), actualLine.getWords()); } } private static void validateFormWordData(List<TextWord> expectedFormWords, List<FormWord> actualFormWordList) { assertEquals(expectedFormWords.size(), actualFormWordList.size()); for (int i = 0; i < actualFormWordList.size(); i++) { TextWord expectedWord = expectedFormWords.get(i); FormWord actualWord = actualFormWordList.get(i); assertEquals(expectedWord.getText(), actualWord.getText()); validateBoundingBoxData(expectedWord.getBoundingBox(), actualWord.getBoundingBox()); if (expectedWord.getConfidence() != null) { assertEquals(expectedWord.getConfidence(), actualWord.getConfidence()); } else { assertEquals(1.0f, actualWord.getConfidence()); } } } private static void validateBoundingBoxData(List<Float> expectedBoundingBox, FieldBoundingBox actualFieldBoundingBox) { if (actualFieldBoundingBox != null && actualFieldBoundingBox.getPoints() != null) { int i = 0; for (Point point : actualFieldBoundingBox.getPoints()) { assertEquals(expectedBoundingBox.get(i), point.getX()); assertEquals(expectedBoundingBox.get(++i), point.getY()); i++; } } } @SuppressWarnings("unchecked") private static void validateFieldValueTransforms(FieldValue expectedFieldValue, FormField actualFormField, List<ReadResult> readResults, boolean includeFieldElements) { if (expectedFieldValue != null) { if (expectedFieldValue.getBoundingBox() != null) { validateBoundingBoxData(expectedFieldValue.getBoundingBox(), actualFormField.getValueData().getBoundingBox()); } if (includeFieldElements && expectedFieldValue.getElements() != null) { validateReferenceElementsData(expectedFieldValue.getElements(), actualFormField.getValueData().getFieldElements(), readResults); } switch (expectedFieldValue.getType()) { case NUMBER: if (expectedFieldValue.getValueNumber() != null) { assertEquals(expectedFieldValue.getValueNumber(), actualFormField.getValue().asFloat()); } break; case DATE: assertEquals(expectedFieldValue.getValueDate(), actualFormField.getValue().asDate()); break; case TIME: assertEquals(LocalTime.parse(expectedFieldValue.getValueTime(), DateTimeFormatter.ofPattern("HH:mm:ss")), actualFormField.getValue().asTime()); break; case STRING: if (actualFormField.getName() != "ReceiptType") { assertEquals(expectedFieldValue.getValueString(), actualFormField.getValue().asString()); } break; case INTEGER: assertEquals(expectedFieldValue.getValueInteger(), actualFormField.getValue().asLong()); break; case PHONE_NUMBER: assertEquals(expectedFieldValue.getValuePhoneNumber(), actualFormField.getValue().asPhoneNumber()); break; case OBJECT: expectedFieldValue.getValueObject().forEach((key, formField) -> { FormField actualFormFieldValue = actualFormField.getValue().asMap().get(key); validateFieldValueTransforms(formField, actualFormFieldValue, readResults, includeFieldElements); }); break; case ARRAY: assertEquals(expectedFieldValue.getValueArray().size(), actualFormField.getValue().asList().size()); for (int i = 0; i < expectedFieldValue.getValueArray().size(); i++) { FieldValue expectedReceiptItem = expectedFieldValue.getValueArray().get(i); FormField actualReceiptItem = actualFormField.getValue().asList().get(i); validateFieldValueTransforms(expectedReceiptItem, actualReceiptItem, readResults, includeFieldElements); } break; default: assertFalse(false, "Field type not supported."); } } } private static void validatePageRangeData(int expectedPageInfo, FormPageRange actualPageInfo) { assertEquals(expectedPageInfo, actualPageInfo.getFirstPageNumber()); assertEquals(expectedPageInfo, actualPageInfo.getLastPageNumber()); } @Test abstract void recognizeReceiptData(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeReceiptDataNullData(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeReceiptDataWithContentTypeAutoDetection(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeReceiptDataIncludeFieldElements(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeReceiptDataWithPngFile(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeReceiptDataWithBlankPdf(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeReceiptFromDataMultiPage(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeReceiptSourceUrl(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeReceiptInvalidSourceUrl(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeReceiptFromUrlIncludeFieldElements(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeReceiptSourceUrlWithPngFile(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeReceiptFromUrlMultiPage(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeContent(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeContentResultWithNullData(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeContentResultWithContentTypeAutoDetection(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeContentResultWithBlankPdf(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeContentFromDataMultiPage(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeContentFromUrl(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeContentFromUrlWithPdf(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeContentInvalidSourceUrl(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeContentFromUrlMultiPage(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormLabeledData(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormLabeledDataWithJpgContentType(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormLabeledDataWithBlankPdfContentType(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormLabeledDataExcludeFieldElements(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormLabeledDataWithNullFormData(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormLabeledDataWithNullModelId(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormLabeledDataWithEmptyModelId(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormInvalidStatus(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormLabeledDataWithContentTypeAutoDetection(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormMultiPageLabeled(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormUnlabeledData(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormUnlabeledDataIncludeFieldElements(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormMultiPageUnlabeled(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormUnlabeledDataWithJpgContentType(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormUnlabeledDataWithBlankPdfContentType(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormUrlUnlabeledData(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormUrlUnlabeledDataIncludeFieldElements(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormUrlMultiPageUnlabeled(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormInvalidSourceUrl(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormFromUrlLabeledDataWithNullModelId(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormFromUrlLabeledDataWithEmptyModelId(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormUrlLabeledData(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormUrlLabeledDataIncludeFieldElements(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormUrlMultiPageLabeled(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeBusinessCardData(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeBusinessCardDataNullData(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeBusinessCardDataWithContentTypeAutoDetection(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeBusinessCardDataIncludeFieldElements(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeBusinessCardDataWithPngFile(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeBusinessCardDataWithBlankPdf(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeBusinessCardFromDamagedPdf(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeBusinessCardSourceUrl(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeBusinessCardFromUrlWithEncodedBlankSpaceSourceUrl(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeBusinessCardInvalidSourceUrl(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeBusinessCardFromUrlIncludeFieldElements(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeBusinessCardSourceUrlWithPngFile(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); void validateReceiptDataFields(Map<String, FormField> actualRecognizedReceiptFields, boolean includeFieldElements) { final AnalyzeResult analyzeResult = getAnalyzeRawResponse().getAnalyzeResult(); List<ReadResult> readResults = analyzeResult.getReadResults(); DocumentResult documentResult = analyzeResult.getDocumentResults().get(0); Map<String, FieldValue> expectedReceiptFields = documentResult.getFields(); assertEquals(expectedReceiptFields.get("ReceiptType").getValueString(), actualRecognizedReceiptFields.get("ReceiptType").getValue().asString()); assertEquals(expectedReceiptFields.get("ReceiptType").getConfidence(), actualRecognizedReceiptFields.get("ReceiptType").getConfidence()); validateFieldValueTransforms(expectedReceiptFields.get("MerchantName"), actualRecognizedReceiptFields.get("MerchantName"), readResults, includeFieldElements); validateFieldValueTransforms(expectedReceiptFields.get("MerchantPhoneNumber"), actualRecognizedReceiptFields.get("MerchantPhoneNumber"), readResults, includeFieldElements); validateFieldValueTransforms(expectedReceiptFields.get("MerchantAddress"), actualRecognizedReceiptFields.get("MerchantAddress"), readResults, includeFieldElements); validateFieldValueTransforms(expectedReceiptFields.get("Total"), actualRecognizedReceiptFields.get("Total"), readResults, includeFieldElements); validateFieldValueTransforms(expectedReceiptFields.get("Subtotal"), actualRecognizedReceiptFields.get("Subtotal"), readResults, includeFieldElements); validateFieldValueTransforms(expectedReceiptFields.get("Tax"), actualRecognizedReceiptFields.get("Tax"), readResults, includeFieldElements); validateFieldValueTransforms(expectedReceiptFields.get("TransactionDate"), actualRecognizedReceiptFields.get("TransactionDate"), readResults, includeFieldElements); validateFieldValueTransforms(expectedReceiptFields.get("TransactionTime"), actualRecognizedReceiptFields.get("TransactionTime"), readResults, includeFieldElements); validateFieldValueTransforms(expectedReceiptFields.get("Items"), actualRecognizedReceiptFields.get("Items"), readResults, includeFieldElements); } void validateContentResultData(List<FormPage> actualFormPageList, boolean includeFieldElements) { AnalyzeResult analyzeResult = getAnalyzeRawResponse().getAnalyzeResult(); final List<PageResult> pageResults = analyzeResult.getPageResults(); final List<ReadResult> readResults = analyzeResult.getReadResults(); for (int i = 0; i < actualFormPageList.size(); i++) { FormPage actualFormPage = actualFormPageList.get(i); ReadResult readResult = readResults.get(i); if (readResult.getAngle() > 180) { assertEquals(readResult.getAngle() - 360, actualFormPage.getTextAngle()); } else { assertEquals(readResult.getAngle(), actualFormPage.getTextAngle()); } assertEquals(readResult.getWidth(), actualFormPage.getWidth()); assertEquals(readResult.getHeight(), actualFormPage.getHeight()); assertEquals(readResult.getUnit().toString(), actualFormPage.getUnit().toString()); assertEquals(readResult.getPage(), actualFormPage.getPageNumber()); if (includeFieldElements) { validateFormLineData(readResult.getLines(), actualFormPage.getLines()); } if (pageResults != null) { validateFormTableData(pageResults.get(i).getTables(), actualFormPage.getTables(), readResults, includeFieldElements, pageResults.get(i).getPage()); } } } void validateReceiptResultData(List<RecognizedForm> actualReceiptList, boolean includeFieldElements) { final AnalyzeResult rawResponse = getAnalyzeRawResponse().getAnalyzeResult(); for (int i = 0; i < actualReceiptList.size(); i++) { final RecognizedForm actualReceipt = actualReceiptList.get(i); validateLabeledData(actualReceipt, includeFieldElements, rawResponse.getReadResults(), rawResponse.getDocumentResults().get(i)); validateReceiptDataFields(actualReceipt.getFields(), includeFieldElements); } } void validateBlankPdfResultData(List<RecognizedForm> actualReceiptList) { assertEquals(1, actualReceiptList.size()); final RecognizedForm actualReceipt = actualReceiptList.get(0); assertTrue(actualReceipt.getFields().isEmpty()); } void validateRecognizedResult(List<RecognizedForm> actualFormList, boolean includeFieldElements, boolean isLabeled) { final AnalyzeResult rawResponse = getAnalyzeRawResponse().getAnalyzeResult(); List<ReadResult> readResults = rawResponse.getReadResults(); List<PageResult> pageResults = rawResponse.getPageResults(); List<DocumentResult> documentResults = rawResponse.getDocumentResults(); for (int i = 0; i < actualFormList.size(); i++) { validateContentResultData(actualFormList.get(i).getPages(), includeFieldElements); if (isLabeled) { validateLabeledData(actualFormList.get(i), includeFieldElements, readResults, documentResults.get(i)); } else { validateUnLabeledResult(actualFormList.get(i), includeFieldElements, readResults, pageResults.get(i)); } } } void validateBusinessCardDataFields(Map<String, FormField> actualRecognizedBusinessCardFields, boolean includeFieldElements) { final AnalyzeResult analyzeResult = getAnalyzeRawResponse().getAnalyzeResult(); List<ReadResult> readResults = analyzeResult.getReadResults(); DocumentResult documentResult = analyzeResult.getDocumentResults().get(0); Map<String, FieldValue> expectedReceiptFields = documentResult.getFields(); BUSINESS_CARD_FIELDS.forEach(businessCardField -> validateFieldValueTransforms(expectedReceiptFields.get(businessCardField), actualRecognizedBusinessCardFields.get(businessCardField), readResults, includeFieldElements)); } void validateBusinessCardResultData(List<RecognizedForm> actualBusinessCardList, boolean includeFieldElements) { final AnalyzeResult rawResponse = getAnalyzeRawResponse().getAnalyzeResult(); for (int i = 0; i < actualBusinessCardList.size(); i++) { final RecognizedForm actualBusinessCard = actualBusinessCardList.get(i); validateLabeledData(actualBusinessCard, includeFieldElements, rawResponse.getReadResults(), rawResponse.getDocumentResults().get(i)); validateBusinessCardDataFields(actualBusinessCard.getFields(), includeFieldElements); } } void invalidSourceUrlRunner(Consumer<String> testRunner) { testRunner.accept(TestUtils.INVALID_RECEIPT_URL); } void encodedBlankSpaceSourceUrlRunner(Consumer<String> testRunner) { testRunner.accept(FAKE_ENCODED_EMPTY_SPACE_URL); } void urlRunner(Consumer<String> testRunner, String fileName) { testRunner.accept(URL_TEST_FILE_FORMAT + fileName); } void storageUrlRunner(Consumer<String> testRunner, String fileName) { testRunner.accept(getStorageTestingFileUrl(fileName)); } void urlPdfUnlabeledRunner(Consumer<String> testRunner) { testRunner.accept(getStorageTestingFileUrl(MULTIPAGE_INVOICE_PDF)); } void dataRunner(BiConsumer<InputStream, Long> testRunner, String fileName) { final long fileLength = new File(LOCAL_FILE_PATH + fileName).length(); if (interceptorManager.isPlaybackMode()) { testRunner.accept(new ByteArrayInputStream(TEST_DATA_PNG.getBytes(StandardCharsets.UTF_8)), fileLength); } else { try { testRunner.accept(new FileInputStream(LOCAL_FILE_PATH + fileName), fileLength); } catch (FileNotFoundException e) { throw new RuntimeException("Local file not found.", e); } } } void localFilePathRunner(BiConsumer<String, Long> testRunner, String fileName) { final long fileLength = new File(LOCAL_FILE_PATH + fileName).length(); testRunner.accept(LOCAL_FILE_PATH + fileName, fileLength); } void damagedPdfDataRunner(BiConsumer<InputStream, Integer> testRunner) { testRunner.accept(new ByteArrayInputStream(new byte[]{0x25, 0x50, 0x44, 0x46, 0x55, 0x55, 0x55}), 7); } void beginTrainingUnlabeledRunner(BiConsumer<String, Boolean> testRunner) { testRunner.accept(getTrainingSasUri(), false); } void beginTrainingLabeledRunner(BiConsumer<String, Boolean> testRunner) { testRunner.accept(getTrainingSasUri(), true); } void beginTrainingMultipageRunner(Consumer<String> testRunner) { testRunner.accept(getMultipageTrainingSasUri()); } private void validateUnLabeledResult(RecognizedForm actualForm, boolean includeFieldElements, List<ReadResult> readResults, PageResult expectedPage) { validatePageRangeData(expectedPage.getPage(), actualForm.getPageRange()); int i = 0; for (Map.Entry<String, FormField> entry : actualForm.getFields().entrySet()) { FormField actualFormField = entry.getValue(); final KeyValuePair expectedFormField = expectedPage.getKeyValuePairs().get(i++); assertEquals(expectedFormField.getConfidence(), actualFormField.getConfidence()); assertEquals(expectedFormField.getKey().getText(), actualFormField.getLabelData().getText()); validateBoundingBoxData(expectedFormField.getKey().getBoundingBox(), actualFormField.getLabelData().getBoundingBox()); if (includeFieldElements) { validateReferenceElementsData(expectedFormField.getKey().getElements(), actualFormField.getLabelData().getFieldElements(), readResults); validateReferenceElementsData(expectedFormField.getValue().getElements(), actualFormField.getValueData().getFieldElements(), readResults); } assertEquals(expectedFormField.getValue().getText(), actualFormField.getValueData().getText()); validateBoundingBoxData(expectedFormField.getValue().getBoundingBox(), actualFormField.getValueData().getBoundingBox()); } } private void validateLabeledData(RecognizedForm actualForm, boolean includeFieldElements, List<ReadResult> readResults, DocumentResult documentResult) { assertEquals(documentResult.getPageRange().get(0), actualForm.getPageRange().getFirstPageNumber()); assertEquals(documentResult.getPageRange().get(1), actualForm.getPageRange().getLastPageNumber()); assertEquals(documentResult.getFields().keySet(), actualForm.getFields().keySet()); documentResult.getFields().forEach((label, expectedFieldValue) -> { final FormField actualFormField = actualForm.getFields().get(label); assertEquals(label, actualFormField.getName()); if (expectedFieldValue != null) { if (expectedFieldValue.getConfidence() != null) { assertEquals(expectedFieldValue.getConfidence(), actualFormField.getConfidence()); } else { assertEquals(1.0f, actualFormField.getConfidence()); } validateFieldValueTransforms(expectedFieldValue, actualFormField, readResults, includeFieldElements); } }); } static void validateMultiPageDataUnlabeled(List<RecognizedForm> actualRecognizedFormsList) { actualRecognizedFormsList.forEach(recognizedForm -> { assertNotNull(recognizedForm.getFormType()); assertEquals(1, (long) recognizedForm.getPages().size()); recognizedForm.getFields().forEach((label, formField) -> { assertNotNull(formField.getName()); assertNotNull(formField.getValue()); assertNotNull(formField.getValueData().getText()); assertNotNull(formField.getLabelData().getText()); }); }); } static void validateMultipageReceiptData(List<RecognizedForm> recognizedReceipts) { assertEquals(3, recognizedReceipts.size()); RecognizedForm receiptPage1 = recognizedReceipts.get(0); RecognizedForm receiptPage2 = recognizedReceipts.get(1); RecognizedForm receiptPage3 = recognizedReceipts.get(2); assertEquals(1, receiptPage1.getPageRange().getFirstPageNumber()); assertEquals(1, receiptPage1.getPageRange().getLastPageNumber()); Map<String, FormField> receiptPage1Fields = receiptPage1.getFields(); assertEquals(EXPECTED_MULTIPAGE_ADDRESS_VALUE, receiptPage1Fields.get("MerchantAddress") .getValue().asString()); assertEquals("Bilbo Baggins", receiptPage1Fields.get("MerchantName") .getValue().asString()); assertEquals(EXPECTED_MULTIPAGE_PHONE_NUMBER_VALUE, receiptPage1Fields.get("MerchantPhoneNumber") .getValue().asPhoneNumber()); assertNotNull(receiptPage1Fields.get("Total").getValue().asFloat()); assertNotNull(receiptPage1.getPages()); assertEquals(ITEMIZED_RECEIPT_VALUE, receiptPage1Fields.get("ReceiptType").getValue().asString()); assertEquals(0, receiptPage2.getFields().size()); List<FormPage> receipt2Pages = receiptPage2.getPages(); assertEquals(1, receipt2Pages.size()); assertEquals(0, receipt2Pages.stream().findFirst().get().getTables().size()); assertEquals(0, receipt2Pages.stream().findFirst().get().getLines().size()); assertEquals(2, receiptPage2.getPageRange().getFirstPageNumber()); assertEquals(2, receiptPage2.getPageRange().getLastPageNumber()); assertEquals(3, receiptPage3.getPageRange().getFirstPageNumber()); assertEquals(3, receiptPage3.getPageRange().getLastPageNumber()); Map<String, FormField> receiptPage3Fields = receiptPage3.getFields(); assertEquals(EXPECTED_MULTIPAGE_ADDRESS_VALUE, receiptPage3Fields.get("MerchantAddress").getValue().asString()); assertEquals("Frodo Baggins", receiptPage3Fields.get("MerchantName").getValue().asString()); assertEquals(EXPECTED_MULTIPAGE_PHONE_NUMBER_VALUE, receiptPage3Fields.get("MerchantPhoneNumber").getValue().asPhoneNumber()); assertNotNull(receiptPage3Fields.get("Total").getValue().asFloat()); assertEquals(3000.0f, receiptPage3Fields.get("Subtotal").getValue().asFloat()); assertEquals(ITEMIZED_RECEIPT_VALUE, receiptPage3Fields.get("ReceiptType").getValue().asString()); } protected String getEndpoint() { return interceptorManager.isPlaybackMode() ? "https: : Configuration.getGlobalConfiguration().get(AZURE_FORM_RECOGNIZER_ENDPOINT); } /** * Get the training data set SAS Url value based on the test running mode. * * @return the training data set Url */ private String getTrainingSasUri() { if (interceptorManager.isPlaybackMode()) { return "https: } else { return Configuration.getGlobalConfiguration().get(FORM_RECOGNIZER_TRAINING_BLOB_CONTAINER_SAS_URL); } } /** * Get the training data set SAS Url value based on the test running mode. * * @return the training data set Url */ private String getMultipageTrainingSasUri() { if (interceptorManager.isPlaybackMode()) { return "https: } else { return Configuration.getGlobalConfiguration() .get(FORM_RECOGNIZER_MULTIPAGE_TRAINING_BLOB_CONTAINER_SAS_URL); } } /** * Get the testing data set SAS Url value based on the test running mode. * * @return the testing data set Url */ private String getTestingSasUri() { if (interceptorManager.isPlaybackMode()) { return "https: } else { return Configuration.getGlobalConfiguration().get("FORM_RECOGNIZER_TESTING_BLOB_CONTAINER_SAS_URL"); } } /** * Prepare the file url from the testing data set SAS Url value. * * @return the testing data specific file Url */ private String getStorageTestingFileUrl(String fileName) { if (interceptorManager.isPlaybackMode()) { return "https: } else { final String[] urlParts = getTestingSasUri().split("\\?"); return urlParts[0] + "/" + fileName + "?" + urlParts[1]; } } /** * Prepare the expected test data from service raw response. * * @return the {@code AnalyzeOperationResult} test data */ private AnalyzeOperationResult getAnalyzeRawResponse() { final SerializerAdapter serializerAdapter = getSerializerAdapter(); final NetworkCallRecord networkCallRecord = interceptorManager.getRecordedData().findFirstAndRemoveNetworkCall(record -> { AnalyzeOperationResult rawModelResponse = deserializeRawResponse(serializerAdapter, record, AnalyzeOperationResult.class); return rawModelResponse != null && rawModelResponse.getStatus() == OperationStatus.SUCCEEDED; }); interceptorManager.getRecordedData().addNetworkCall(networkCallRecord); return deserializeRawResponse(serializerAdapter, networkCallRecord, AnalyzeOperationResult.class); } }
In response to [this](https://github.com/Azure/azure-sdk-for-java/pull/15829/files/4ca941908e952d64df5b77759742a12796075610#r504325546) Could do something like, ```java businessCardsFields.forEach(eachField -> validateFieldValueTransforms(expectedReceiptFields.get(eachField), actualRecognizedBusinessCardFields.get(eachField), readResults, includeFieldElements)) ``` where businessCards = List.of("ContactNames", "MobilePhones") So you just have one constant related to business card fields rather than 10/12 loose ones!
void validateBusinessCardDataFields(Map<String, FormField> actualRecognizedBusinessCardFields, boolean includeFieldElements) { final AnalyzeResult analyzeResult = getAnalyzeRawResponse().getAnalyzeResult(); List<ReadResult> readResults = analyzeResult.getReadResults(); DocumentResult documentResult = analyzeResult.getDocumentResults().get(0); Map<String, FieldValue> expectedReceiptFields = documentResult.getFields(); validateFieldValueTransforms(expectedReceiptFields.get(CONTACT_NAMES), actualRecognizedBusinessCardFields.get(CONTACT_NAMES), readResults, includeFieldElements); validateFieldValueTransforms(expectedReceiptFields.get(JOB_TITLES), actualRecognizedBusinessCardFields.get(JOB_TITLES), readResults, includeFieldElements); validateFieldValueTransforms(expectedReceiptFields.get(DEPARTMENTS), actualRecognizedBusinessCardFields.get(DEPARTMENTS), readResults, includeFieldElements); validateFieldValueTransforms(expectedReceiptFields.get(EMAILS), actualRecognizedBusinessCardFields.get(EMAILS), readResults, includeFieldElements); validateFieldValueTransforms(expectedReceiptFields.get(WEBSITES), actualRecognizedBusinessCardFields.get(WEBSITES), readResults, includeFieldElements); validateFieldValueTransforms(expectedReceiptFields.get(MOBILE_PHONES), actualRecognizedBusinessCardFields.get(MOBILE_PHONES), readResults, includeFieldElements); validateFieldValueTransforms(expectedReceiptFields.get(OTHER_PHONES), actualRecognizedBusinessCardFields.get(OTHER_PHONES), readResults, includeFieldElements); validateFieldValueTransforms(expectedReceiptFields.get(FAXES), actualRecognizedBusinessCardFields.get(FAXES), readResults, includeFieldElements); validateFieldValueTransforms(expectedReceiptFields.get(ADDRESSES), actualRecognizedBusinessCardFields.get(ADDRESSES), readResults, includeFieldElements); validateFieldValueTransforms(expectedReceiptFields.get(COMPANY_NAMES), actualRecognizedBusinessCardFields.get(COMPANY_NAMES), readResults, includeFieldElements); }
validateFieldValueTransforms(expectedReceiptFields.get(CONTACT_NAMES),
void validateBusinessCardDataFields(Map<String, FormField> actualRecognizedBusinessCardFields, boolean includeFieldElements) { final AnalyzeResult analyzeResult = getAnalyzeRawResponse().getAnalyzeResult(); List<ReadResult> readResults = analyzeResult.getReadResults(); DocumentResult documentResult = analyzeResult.getDocumentResults().get(0); Map<String, FieldValue> expectedReceiptFields = documentResult.getFields(); BUSINESS_CARD_FIELDS.forEach(businessCardField -> validateFieldValueTransforms(expectedReceiptFields.get(businessCardField), actualRecognizedBusinessCardFields.get(businessCardField), readResults, includeFieldElements)); }
class FormRecognizerClientTestBase extends TestBase { private static final Pattern NON_DIGIT_PATTERN = Pattern.compile("[^0-9]+"); private static final String EXPECTED_MULTIPAGE_ADDRESS_VALUE = "123 Hobbit Lane 567 Main St. Redmond, WA Redmond," + " WA"; private static final String EXPECTED_MULTIPAGE_PHONE_NUMBER_VALUE = "+15555555555"; private static final String ITEMIZED_RECEIPT_VALUE = "Itemized"; static final String RECEIPT_CONTOSO_JPG = "contoso-allinone.jpg"; static final String RECEIPT_CONTOSO_PNG = "contoso-receipt.png"; static final String INVOICE_6_PDF = "Invoice_6.pdf"; static final String MULTIPAGE_INVOICE_PDF = "multipage_invoice1.pdf"; static final String BUSINESS_CARD_JPG = "businessCard.jpg"; static final String BUSINESS_CARD_PNG = "businessCard.png"; static final String BAD_ARGUMENT_CODE = "BadArgument"; static final String INVALID_IMAGE_ERROR_CODE = "InvalidImage"; static final String INVALID_MODEL_ID_ERROR_CODE = "1001"; static final String MODEL_ID_NOT_FOUND_ERROR_CODE = "1022"; static final String URL_BADLY_FORMATTED_ERROR_CODE = "2001"; static final String UNABLE_TO_READ_FILE_ERROR_CODE = "2005"; static final String HTTPS_EXCEPTION_MESSAGE = "Max retries 3 times exceeded. Error Details: Key credentials require HTTPS to prevent leaking the key."; static final String INVALID_UUID_EXCEPTION_MESSAGE = "Invalid UUID string: "; static final String MODEL_ID_IS_REQUIRED_EXCEPTION_MESSAGE = "'modelId' is required and cannot be null."; static final String INVALID_ENDPOINT = "https: static final String LOCAL_FILE_PATH = "src/test/resources/sample_files/Test/"; static final String ENCODED_EMPTY_SPACE = "{\"source\":\"https: static final String CONTACT_NAMES = "ContactNames"; static final String JOB_TITLES = "JobTitles"; static final String DEPARTMENTS = "Departments"; static final String EMAILS = "Emails"; static final String WEBSITES = "Websites"; static final String MOBILE_PHONES = "MobilePhones"; static final String OTHER_PHONES = "OtherPhones"; static final String FAXES = "Faxes"; static final String ADDRESSES = "Addresses"; static final String COMPANY_NAMES = "CompanyNames"; Duration durationTestMode; /** * Use duration of nearly zero value for PLAYBACK test mode, otherwise, use default duration value for LIVE mode. */ @Override protected void beforeTest() { if (interceptorManager.isPlaybackMode()) { durationTestMode = ONE_NANO_DURATION; } else { durationTestMode = DEFAULT_DURATION; } } FormRecognizerClientBuilder getFormRecognizerClientBuilder(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { FormRecognizerClientBuilder builder = new FormRecognizerClientBuilder() .endpoint(getEndpoint()) .httpClient(httpClient == null ? interceptorManager.getPlaybackClient() : httpClient) .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)) .serviceVersion(serviceVersion) .addPolicy(interceptorManager.getRecordPolicy()); if (getTestMode() == TestMode.PLAYBACK) { builder.credential(new AzureKeyCredential(INVALID_KEY)); } else { builder.credential(new AzureKeyCredential( Configuration.getGlobalConfiguration().get(AZURE_FORM_RECOGNIZER_API_KEY))); } return builder; } FormTrainingClientBuilder getFormTrainingClientBuilder(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { FormTrainingClientBuilder builder = new FormTrainingClientBuilder() .endpoint(getEndpoint()) .httpClient(httpClient == null ? interceptorManager.getPlaybackClient() : httpClient) .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)) .serviceVersion(serviceVersion) .addPolicy(interceptorManager.getRecordPolicy()); if (getTestMode() == TestMode.PLAYBACK) { builder.credential(new AzureKeyCredential(INVALID_KEY)); } else { builder.credential(new AzureKeyCredential( Configuration.getGlobalConfiguration().get(AZURE_FORM_RECOGNIZER_API_KEY))); } return builder; } private static void validateReferenceElementsData(List<String> expectedElements, List<FormElement> actualFormElementList, List<ReadResult> readResults) { if (expectedElements != null && actualFormElementList != null) { assertEquals(expectedElements.size(), actualFormElementList.size()); for (int i = 0; i < actualFormElementList.size(); i++) { String[] indices = NON_DIGIT_PATTERN.matcher(expectedElements.get(i)).replaceAll(" ").trim().split(" "); if (indices.length < 2) { return; } int readResultIndex = Integer.parseInt(indices[0]); int lineIndex = Integer.parseInt(indices[1]); if (indices.length == 3) { int wordIndex = Integer.parseInt(indices[2]); TextWord expectedTextWord = readResults.get(readResultIndex).getLines().get(lineIndex).getWords().get(wordIndex); TextLine expectedTextLine = readResults.get(readResultIndex).getLines().get(lineIndex); if (actualFormElementList.get(i) instanceof FormLine) { FormLine actualFormLine = (FormLine) actualFormElementList.get(i); validateFormWordData(expectedTextLine.getWords(), actualFormLine.getWords()); } FormWord actualFormWord = (FormWord) actualFormElementList.get(i); assertEquals(expectedTextWord.getText(), actualFormWord.getText()); if (expectedTextWord.getConfidence() != null) { assertEquals(expectedTextWord.getConfidence(), actualFormWord.getConfidence()); } else { assertEquals(1.0f, actualFormWord.getConfidence()); } validateBoundingBoxData(expectedTextWord.getBoundingBox(), actualFormWord.getBoundingBox()); } } } } private static void validateFormTableData(List<DataTable> expectedFormTables, List<FormTable> actualFormTable, List<ReadResult> readResults, boolean includeFieldElements, int pageNumber) { assertEquals(expectedFormTables.size(), actualFormTable.size()); for (int i = 0; i < actualFormTable.size(); i++) { DataTable expectedTable = expectedFormTables.get(i); FormTable actualTable = actualFormTable.get(i); assertEquals(pageNumber, actualTable.getPageNumber()); assertEquals(expectedTable.getColumns(), actualTable.getColumnCount()); validateCellData(expectedTable.getCells(), actualTable.getCells(), readResults, includeFieldElements); assertEquals(expectedTable.getRows(), actualTable.getRowCount()); } } private static void validateCellData(List<DataTableCell> expectedTableCells, List<FormTableCell> actualTableCellList, List<ReadResult> readResults, boolean includeFieldElements) { assertEquals(expectedTableCells.size(), actualTableCellList.size()); for (int i = 0; i < actualTableCellList.size(); i++) { DataTableCell expectedTableCell = expectedTableCells.get(i); FormTableCell actualTableCell = actualTableCellList.get(i); assertEquals(expectedTableCell.getColumnIndex(), actualTableCell.getColumnIndex()); if (expectedTableCell.getColumnSpan() != null) { assertEquals(expectedTableCell.getColumnSpan(), actualTableCell.getColumnSpan()); } assertNotNull(actualTableCell.getColumnSpan()); assertEquals(expectedTableCell.getRowIndex(), actualTableCell.getRowIndex()); if (expectedTableCell.getRowSpan() != null) { assertEquals(expectedTableCell.getRowSpan(), actualTableCell.getRowSpan()); } assertNotNull(actualTableCell.getRowSpan()); validateBoundingBoxData(expectedTableCell.getBoundingBox(), actualTableCell.getBoundingBox()); if (includeFieldElements) { validateReferenceElementsData(expectedTableCell.getElements(), actualTableCell.getFieldElements(), readResults); } } } private static void validateFormLineData(List<TextLine> expectedLines, List<FormLine> actualLineList) { assertEquals(expectedLines.size(), actualLineList.size()); for (int i = 0; i < actualLineList.size(); i++) { TextLine expectedLine = expectedLines.get(i); FormLine actualLine = actualLineList.get(i); assertEquals(expectedLine.getText(), actualLine.getText()); validateBoundingBoxData(expectedLine.getBoundingBox(), actualLine.getBoundingBox()); validateFormWordData(expectedLine.getWords(), actualLine.getWords()); } } private static void validateFormWordData(List<TextWord> expectedFormWords, List<FormWord> actualFormWordList) { assertEquals(expectedFormWords.size(), actualFormWordList.size()); for (int i = 0; i < actualFormWordList.size(); i++) { TextWord expectedWord = expectedFormWords.get(i); FormWord actualWord = actualFormWordList.get(i); assertEquals(expectedWord.getText(), actualWord.getText()); validateBoundingBoxData(expectedWord.getBoundingBox(), actualWord.getBoundingBox()); if (expectedWord.getConfidence() != null) { assertEquals(expectedWord.getConfidence(), actualWord.getConfidence()); } else { assertEquals(1.0f, actualWord.getConfidence()); } } } private static void validateBoundingBoxData(List<Float> expectedBoundingBox, FieldBoundingBox actualFieldBoundingBox) { if (actualFieldBoundingBox != null && actualFieldBoundingBox.getPoints() != null) { int i = 0; for (Point point : actualFieldBoundingBox.getPoints()) { assertEquals(expectedBoundingBox.get(i), point.getX()); assertEquals(expectedBoundingBox.get(++i), point.getY()); i++; } } } @SuppressWarnings("unchecked") private static void validateFieldValueTransforms(FieldValue expectedFieldValue, FormField actualFormField, List<ReadResult> readResults, boolean includeFieldElements) { if (expectedFieldValue != null) { if (expectedFieldValue.getBoundingBox() != null) { validateBoundingBoxData(expectedFieldValue.getBoundingBox(), actualFormField.getValueData().getBoundingBox()); } if (includeFieldElements && expectedFieldValue.getElements() != null) { validateReferenceElementsData(expectedFieldValue.getElements(), actualFormField.getValueData().getFieldElements(), readResults); } switch (expectedFieldValue.getType()) { case NUMBER: if (expectedFieldValue.getValueNumber() != null) { assertEquals(expectedFieldValue.getValueNumber(), actualFormField.getValue().asFloat()); } break; case DATE: assertEquals(expectedFieldValue.getValueDate(), actualFormField.getValue().asDate()); break; case TIME: assertEquals(LocalTime.parse(expectedFieldValue.getValueTime(), DateTimeFormatter.ofPattern("HH:mm:ss")), actualFormField.getValue().asTime()); break; case STRING: if (actualFormField.getName() != "ReceiptType") { assertEquals(expectedFieldValue.getValueString(), actualFormField.getValue().asString()); } break; case INTEGER: assertEquals(expectedFieldValue.getValueInteger(), actualFormField.getValue().asLong()); break; case PHONE_NUMBER: assertEquals(expectedFieldValue.getValuePhoneNumber(), actualFormField.getValue().asPhoneNumber()); break; case OBJECT: expectedFieldValue.getValueObject().forEach((key, formField) -> { FormField actualFormFieldValue = actualFormField.getValue().asMap().get(key); validateFieldValueTransforms(formField, actualFormFieldValue, readResults, includeFieldElements); }); break; case ARRAY: assertEquals(expectedFieldValue.getValueArray().size(), actualFormField.getValue().asList().size()); for (int i = 0; i < expectedFieldValue.getValueArray().size(); i++) { FieldValue expectedReceiptItem = expectedFieldValue.getValueArray().get(i); FormField actualReceiptItem = actualFormField.getValue().asList().get(i); validateFieldValueTransforms(expectedReceiptItem, actualReceiptItem, readResults, includeFieldElements); } break; default: assertFalse(false, "Field type not supported."); } } } private static void validatePageRangeData(int expectedPageInfo, FormPageRange actualPageInfo) { assertEquals(expectedPageInfo, actualPageInfo.getFirstPageNumber()); assertEquals(expectedPageInfo, actualPageInfo.getLastPageNumber()); } @Test abstract void recognizeReceiptData(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeReceiptDataNullData(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeReceiptDataWithContentTypeAutoDetection(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeReceiptDataIncludeFieldElements(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeReceiptDataWithPngFile(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeReceiptDataWithBlankPdf(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeReceiptFromDataMultiPage(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeReceiptSourceUrl(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeReceiptInvalidSourceUrl(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeReceiptFromUrlIncludeFieldElements(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeReceiptSourceUrlWithPngFile(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeReceiptFromUrlMultiPage(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeContent(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeContentResultWithNullData(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeContentResultWithContentTypeAutoDetection(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeContentResultWithBlankPdf(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeContentFromDataMultiPage(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeContentFromUrl(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeContentFromUrlWithPdf(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeContentInvalidSourceUrl(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeContentFromUrlMultiPage(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormLabeledData(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormLabeledDataWithJpgContentType(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormLabeledDataWithBlankPdfContentType(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormLabeledDataExcludeFieldElements(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormLabeledDataWithNullFormData(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormLabeledDataWithNullModelId(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormLabeledDataWithEmptyModelId(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormInvalidStatus(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormLabeledDataWithContentTypeAutoDetection(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormMultiPageLabeled(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormUnlabeledData(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormUnlabeledDataIncludeFieldElements(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormMultiPageUnlabeled(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormUnlabeledDataWithJpgContentType(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormUnlabeledDataWithBlankPdfContentType(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormUrlUnlabeledData(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormUrlUnlabeledDataIncludeFieldElements(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormUrlMultiPageUnlabeled(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormInvalidSourceUrl(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormFromUrlLabeledDataWithNullModelId(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormFromUrlLabeledDataWithEmptyModelId(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormUrlLabeledData(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormUrlLabeledDataIncludeFieldElements(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormUrlMultiPageLabeled(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeBusinessCardData(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeBusinessCardDataNullData(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeBusinessCardDataWithContentTypeAutoDetection(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeBusinessCardDataIncludeFieldElements(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeBusinessCardDataWithPngFile(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeBusinessCardDataWithBlankPdf(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeBusinessCardFromDamagedPdf(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeBusinessCardSourceUrl(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeBusinessCardFromUrlWithEncodedBlankSpaceSourceUrl(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeBusinessCardInvalidSourceUrl(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeBusinessCardFromUrlIncludeFieldElements(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeBusinessCardSourceUrlWithPngFile(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); void validateReceiptDataFields(Map<String, FormField> actualRecognizedReceiptFields, boolean includeFieldElements) { final AnalyzeResult analyzeResult = getAnalyzeRawResponse().getAnalyzeResult(); List<ReadResult> readResults = analyzeResult.getReadResults(); DocumentResult documentResult = analyzeResult.getDocumentResults().get(0); Map<String, FieldValue> expectedReceiptFields = documentResult.getFields(); assertEquals(expectedReceiptFields.get("ReceiptType").getValueString(), actualRecognizedReceiptFields.get("ReceiptType").getValue().asString()); assertEquals(expectedReceiptFields.get("ReceiptType").getConfidence(), actualRecognizedReceiptFields.get("ReceiptType").getConfidence()); validateFieldValueTransforms(expectedReceiptFields.get("MerchantName"), actualRecognizedReceiptFields.get("MerchantName"), readResults, includeFieldElements); validateFieldValueTransforms(expectedReceiptFields.get("MerchantPhoneNumber"), actualRecognizedReceiptFields.get("MerchantPhoneNumber"), readResults, includeFieldElements); validateFieldValueTransforms(expectedReceiptFields.get("MerchantAddress"), actualRecognizedReceiptFields.get("MerchantAddress"), readResults, includeFieldElements); validateFieldValueTransforms(expectedReceiptFields.get("Total"), actualRecognizedReceiptFields.get("Total"), readResults, includeFieldElements); validateFieldValueTransforms(expectedReceiptFields.get("Subtotal"), actualRecognizedReceiptFields.get("Subtotal"), readResults, includeFieldElements); validateFieldValueTransforms(expectedReceiptFields.get("Tax"), actualRecognizedReceiptFields.get("Tax"), readResults, includeFieldElements); validateFieldValueTransforms(expectedReceiptFields.get("TransactionDate"), actualRecognizedReceiptFields.get("TransactionDate"), readResults, includeFieldElements); validateFieldValueTransforms(expectedReceiptFields.get("TransactionTime"), actualRecognizedReceiptFields.get("TransactionTime"), readResults, includeFieldElements); validateFieldValueTransforms(expectedReceiptFields.get("Items"), actualRecognizedReceiptFields.get("Items"), readResults, includeFieldElements); } void validateContentResultData(List<FormPage> actualFormPageList, boolean includeFieldElements) { AnalyzeResult analyzeResult = getAnalyzeRawResponse().getAnalyzeResult(); final List<PageResult> pageResults = analyzeResult.getPageResults(); final List<ReadResult> readResults = analyzeResult.getReadResults(); for (int i = 0; i < actualFormPageList.size(); i++) { FormPage actualFormPage = actualFormPageList.get(i); ReadResult readResult = readResults.get(i); if (readResult.getAngle() > 180) { assertEquals(readResult.getAngle() - 360, actualFormPage.getTextAngle()); } else { assertEquals(readResult.getAngle(), actualFormPage.getTextAngle()); } assertEquals(readResult.getWidth(), actualFormPage.getWidth()); assertEquals(readResult.getHeight(), actualFormPage.getHeight()); assertEquals(readResult.getUnit().toString(), actualFormPage.getUnit().toString()); assertEquals(readResult.getPage(), actualFormPage.getPageNumber()); if (includeFieldElements) { validateFormLineData(readResult.getLines(), actualFormPage.getLines()); } if (pageResults != null) { validateFormTableData(pageResults.get(i).getTables(), actualFormPage.getTables(), readResults, includeFieldElements, pageResults.get(i).getPage()); } } } void validateReceiptResultData(List<RecognizedForm> actualReceiptList, boolean includeFieldElements) { final AnalyzeResult rawResponse = getAnalyzeRawResponse().getAnalyzeResult(); for (int i = 0; i < actualReceiptList.size(); i++) { final RecognizedForm actualReceipt = actualReceiptList.get(i); validateLabeledData(actualReceipt, includeFieldElements, rawResponse.getReadResults(), rawResponse.getDocumentResults().get(i)); validateReceiptDataFields(actualReceipt.getFields(), includeFieldElements); } } void validateBlankPdfResultData(List<RecognizedForm> actualReceiptList) { assertEquals(1, actualReceiptList.size()); final RecognizedForm actualReceipt = actualReceiptList.get(0); assertTrue(actualReceipt.getFields().isEmpty()); } void validateRecognizedResult(List<RecognizedForm> actualFormList, boolean includeFieldElements, boolean isLabeled) { final AnalyzeResult rawResponse = getAnalyzeRawResponse().getAnalyzeResult(); List<ReadResult> readResults = rawResponse.getReadResults(); List<PageResult> pageResults = rawResponse.getPageResults(); List<DocumentResult> documentResults = rawResponse.getDocumentResults(); for (int i = 0; i < actualFormList.size(); i++) { validateContentResultData(actualFormList.get(i).getPages(), includeFieldElements); if (isLabeled) { validateLabeledData(actualFormList.get(i), includeFieldElements, readResults, documentResults.get(i)); } else { validateUnLabeledResult(actualFormList.get(i), includeFieldElements, readResults, pageResults.get(i)); } } } void validateBusinessCardResultData(List<RecognizedForm> actualBusinessCardList, boolean includeFieldElements) { final AnalyzeResult rawResponse = getAnalyzeRawResponse().getAnalyzeResult(); for (int i = 0; i < actualBusinessCardList.size(); i++) { final RecognizedForm actualBusinessCard = actualBusinessCardList.get(i); validateLabeledData(actualBusinessCard, includeFieldElements, rawResponse.getReadResults(), rawResponse.getDocumentResults().get(i)); validateBusinessCardDataFields(actualBusinessCard.getFields(), includeFieldElements); } } void invalidSourceUrlRunner(Consumer<String> testRunner) { testRunner.accept(TestUtils.INVALID_RECEIPT_URL); } void encodedBlankSpaceSourceUrlRunner(Consumer<String> testRunner) { testRunner.accept(FAKE_ENCODED_EMPTY_SPACE_URL); } void urlRunner(Consumer<String> testRunner, String fileName) { testRunner.accept(URL_TEST_FILE_FORMAT + fileName); } void storageUrlRunner(Consumer<String> testRunner, String fileName) { testRunner.accept(getStorageTestingFileUrl(fileName)); } void urlPdfUnlabeledRunner(Consumer<String> testRunner) { testRunner.accept(getStorageTestingFileUrl(MULTIPAGE_INVOICE_PDF)); } void dataRunner(BiConsumer<InputStream, Long> testRunner, String fileName) { final long fileLength = new File(LOCAL_FILE_PATH + fileName).length(); if (interceptorManager.isPlaybackMode()) { testRunner.accept(new ByteArrayInputStream(TEST_DATA_PNG.getBytes(StandardCharsets.UTF_8)), fileLength); } else { try { testRunner.accept(new FileInputStream(LOCAL_FILE_PATH + fileName), fileLength); } catch (FileNotFoundException e) { throw new RuntimeException("Local file not found.", e); } } } void localFilePathRunner(BiConsumer<String, Long> testRunner, String fileName) { final long fileLength = new File(LOCAL_FILE_PATH + fileName).length(); testRunner.accept(LOCAL_FILE_PATH + fileName, fileLength); } void damagedPdfDataRunner(BiConsumer<InputStream, Integer> testRunner) { testRunner.accept(new ByteArrayInputStream(new byte[]{0x25, 0x50, 0x44, 0x46, 0x55, 0x55, 0x55}), 7); } void beginTrainingUnlabeledRunner(BiConsumer<String, Boolean> testRunner) { testRunner.accept(getTrainingSasUri(), false); } void beginTrainingLabeledRunner(BiConsumer<String, Boolean> testRunner) { testRunner.accept(getTrainingSasUri(), true); } void beginTrainingMultipageRunner(Consumer<String> testRunner) { testRunner.accept(getMultipageTrainingSasUri()); } private void validateUnLabeledResult(RecognizedForm actualForm, boolean includeFieldElements, List<ReadResult> readResults, PageResult expectedPage) { validatePageRangeData(expectedPage.getPage(), actualForm.getPageRange()); int i = 0; for (Map.Entry<String, FormField> entry : actualForm.getFields().entrySet()) { FormField actualFormField = entry.getValue(); final KeyValuePair expectedFormField = expectedPage.getKeyValuePairs().get(i++); assertEquals(expectedFormField.getConfidence(), actualFormField.getConfidence()); assertEquals(expectedFormField.getKey().getText(), actualFormField.getLabelData().getText()); validateBoundingBoxData(expectedFormField.getKey().getBoundingBox(), actualFormField.getLabelData().getBoundingBox()); if (includeFieldElements) { validateReferenceElementsData(expectedFormField.getKey().getElements(), actualFormField.getLabelData().getFieldElements(), readResults); validateReferenceElementsData(expectedFormField.getValue().getElements(), actualFormField.getValueData().getFieldElements(), readResults); } assertEquals(expectedFormField.getValue().getText(), actualFormField.getValueData().getText()); validateBoundingBoxData(expectedFormField.getValue().getBoundingBox(), actualFormField.getValueData().getBoundingBox()); } } private void validateLabeledData(RecognizedForm actualForm, boolean includeFieldElements, List<ReadResult> readResults, DocumentResult documentResult) { assertEquals(documentResult.getPageRange().get(0), actualForm.getPageRange().getFirstPageNumber()); assertEquals(documentResult.getPageRange().get(1), actualForm.getPageRange().getLastPageNumber()); assertEquals(documentResult.getFields().keySet(), actualForm.getFields().keySet()); documentResult.getFields().forEach((label, expectedFieldValue) -> { final FormField actualFormField = actualForm.getFields().get(label); assertEquals(label, actualFormField.getName()); if (expectedFieldValue != null) { if (expectedFieldValue.getConfidence() != null) { assertEquals(expectedFieldValue.getConfidence(), actualFormField.getConfidence()); } else { assertEquals(1.0f, actualFormField.getConfidence()); } validateFieldValueTransforms(expectedFieldValue, actualFormField, readResults, includeFieldElements); } }); } static void validateMultiPageDataLabeled(List<RecognizedForm> actualRecognizedFormsList) { actualRecognizedFormsList.forEach(recognizedForm -> { assertEquals(1, recognizedForm.getPageRange().getFirstPageNumber()); assertEquals(3, recognizedForm.getPageRange().getLastPageNumber()); assertEquals(3, recognizedForm.getPages().size()); recognizedForm.getFields().forEach((label, formField) -> { assertNotNull(formField.getName()); assertNotNull(formField.getValue()); assertNotNull(formField.getValueData().getText()); }); }); } static void validateMultiPageDataUnlabeled(List<RecognizedForm> actualRecognizedFormsList) { actualRecognizedFormsList.forEach(recognizedForm -> { assertNotNull(recognizedForm.getFormType()); assertEquals(1, (long) recognizedForm.getPages().size()); recognizedForm.getFields().forEach((label, formField) -> { assertNotNull(formField.getName()); assertNotNull(formField.getValue()); assertNotNull(formField.getValueData().getText()); assertNotNull(formField.getLabelData().getText()); }); }); } static void validateMultipageReceiptData(List<RecognizedForm> recognizedReceipts) { assertEquals(3, recognizedReceipts.size()); RecognizedForm receiptPage1 = recognizedReceipts.get(0); RecognizedForm receiptPage2 = recognizedReceipts.get(1); RecognizedForm receiptPage3 = recognizedReceipts.get(2); assertEquals(1, receiptPage1.getPageRange().getFirstPageNumber()); assertEquals(1, receiptPage1.getPageRange().getLastPageNumber()); Map<String, FormField> receiptPage1Fields = receiptPage1.getFields(); assertEquals(EXPECTED_MULTIPAGE_ADDRESS_VALUE, receiptPage1Fields.get("MerchantAddress") .getValue().asString()); assertEquals("Bilbo Baggins", receiptPage1Fields.get("MerchantName") .getValue().asString()); assertEquals(EXPECTED_MULTIPAGE_PHONE_NUMBER_VALUE, receiptPage1Fields.get("MerchantPhoneNumber") .getValue().asPhoneNumber()); assertNotNull(receiptPage1Fields.get("Total").getValue().asFloat()); assertNotNull(receiptPage1.getPages()); assertEquals(ITEMIZED_RECEIPT_VALUE, receiptPage1Fields.get("ReceiptType").getValue().asString()); assertEquals(0, receiptPage2.getFields().size()); List<FormPage> receipt2Pages = receiptPage2.getPages(); assertEquals(1, receipt2Pages.size()); assertEquals(0, receipt2Pages.stream().findFirst().get().getTables().size()); assertEquals(0, receipt2Pages.stream().findFirst().get().getLines().size()); assertEquals(2, receiptPage2.getPageRange().getFirstPageNumber()); assertEquals(2, receiptPage2.getPageRange().getLastPageNumber()); assertEquals(3, receiptPage3.getPageRange().getFirstPageNumber()); assertEquals(3, receiptPage3.getPageRange().getLastPageNumber()); Map<String, FormField> receiptPage3Fields = receiptPage3.getFields(); assertEquals(EXPECTED_MULTIPAGE_ADDRESS_VALUE, receiptPage3Fields.get("MerchantAddress").getValue().asString()); assertEquals("Frodo Baggins", receiptPage3Fields.get("MerchantName").getValue().asString()); assertEquals(EXPECTED_MULTIPAGE_PHONE_NUMBER_VALUE, receiptPage3Fields.get("MerchantPhoneNumber").getValue().asPhoneNumber()); assertNotNull(receiptPage3Fields.get("Total").getValue().asFloat()); assertEquals(3000.0f, receiptPage3Fields.get("Subtotal").getValue().asFloat()); assertEquals(ITEMIZED_RECEIPT_VALUE, receiptPage3Fields.get("ReceiptType").getValue().asString()); } protected String getEndpoint() { return interceptorManager.isPlaybackMode() ? "https: : Configuration.getGlobalConfiguration().get(AZURE_FORM_RECOGNIZER_ENDPOINT); } /** * Get the training data set SAS Url value based on the test running mode. * * @return the training data set Url */ private String getTrainingSasUri() { if (interceptorManager.isPlaybackMode()) { return "https: } else { return Configuration.getGlobalConfiguration().get(FORM_RECOGNIZER_TRAINING_BLOB_CONTAINER_SAS_URL); } } /** * Get the training data set SAS Url value based on the test running mode. * * @return the training data set Url */ private String getMultipageTrainingSasUri() { if (interceptorManager.isPlaybackMode()) { return "https: } else { return Configuration.getGlobalConfiguration() .get(FORM_RECOGNIZER_MULTIPAGE_TRAINING_BLOB_CONTAINER_SAS_URL); } } /** * Get the testing data set SAS Url value based on the test running mode. * * @return the testing data set Url */ private String getTestingSasUri() { if (interceptorManager.isPlaybackMode()) { return "https: } else { return Configuration.getGlobalConfiguration().get("FORM_RECOGNIZER_TESTING_BLOB_CONTAINER_SAS_URL"); } } /** * Prepare the file url from the testing data set SAS Url value. * * @return the testing data specific file Url */ private String getStorageTestingFileUrl(String fileName) { if (interceptorManager.isPlaybackMode()) { return "https: } else { final String[] urlParts = getTestingSasUri().split("\\?"); return urlParts[0] + "/" + fileName + "?" + urlParts[1]; } } /** * Prepare the expected test data from service raw response. * * @return the {@code AnalyzeOperationResult} test data */ private AnalyzeOperationResult getAnalyzeRawResponse() { final SerializerAdapter serializerAdapter = getSerializerAdapter(); final NetworkCallRecord networkCallRecord = interceptorManager.getRecordedData().findFirstAndRemoveNetworkCall(record -> { AnalyzeOperationResult rawModelResponse = deserializeRawResponse(serializerAdapter, record, AnalyzeOperationResult.class); return rawModelResponse != null && rawModelResponse.getStatus() == OperationStatus.SUCCEEDED; }); interceptorManager.getRecordedData().addNetworkCall(networkCallRecord); return deserializeRawResponse(serializerAdapter, networkCallRecord, AnalyzeOperationResult.class); } }
class FormRecognizerClientTestBase extends TestBase { private static final Pattern NON_DIGIT_PATTERN = Pattern.compile("[^0-9]+"); private static final String EXPECTED_MULTIPAGE_ADDRESS_VALUE = "123 Hobbit Lane 567 Main St. Redmond, WA Redmond," + " WA"; private static final String EXPECTED_MULTIPAGE_PHONE_NUMBER_VALUE = "+15555555555"; private static final String ITEMIZED_RECEIPT_VALUE = "Itemized"; static final String RECEIPT_CONTOSO_JPG = "contoso-allinone.jpg"; static final String RECEIPT_CONTOSO_PNG = "contoso-receipt.png"; static final String INVOICE_6_PDF = "Invoice_6.pdf"; static final String MULTIPAGE_INVOICE_PDF = "multipage_invoice1.pdf"; static final String BUSINESS_CARD_JPG = "businessCard.jpg"; static final String BUSINESS_CARD_PNG = "businessCard.png"; static final String BAD_ARGUMENT_CODE = "BadArgument"; static final String INVALID_IMAGE_ERROR_CODE = "InvalidImage"; static final String INVALID_MODEL_ID_ERROR_CODE = "1001"; static final String MODEL_ID_NOT_FOUND_ERROR_CODE = "1022"; static final String URL_BADLY_FORMATTED_ERROR_CODE = "2001"; static final String UNABLE_TO_READ_FILE_ERROR_CODE = "2005"; static final String HTTPS_EXCEPTION_MESSAGE = "Max retries 3 times exceeded. Error Details: Key credentials require HTTPS to prevent leaking the key."; static final String INVALID_UUID_EXCEPTION_MESSAGE = "Invalid UUID string: "; static final String MODEL_ID_IS_REQUIRED_EXCEPTION_MESSAGE = "'modelId' is required and cannot be null."; static final String INVALID_ENDPOINT = "https: static final String LOCAL_FILE_PATH = "src/test/resources/sample_files/Test/"; static final String ENCODED_EMPTY_SPACE = "{\"source\":\"https: static final List<String> BUSINESS_CARD_FIELDS = Arrays.asList("ContactNames", "JobTitles", "Departments", "Emails", "Websites", "MobilePhones", "OtherPhones", "Faxes", "Addresses", "CompanyNames"); Duration durationTestMode; /** * Use duration of nearly zero value for PLAYBACK test mode, otherwise, use default duration value for LIVE mode. */ @Override protected void beforeTest() { if (interceptorManager.isPlaybackMode()) { durationTestMode = ONE_NANO_DURATION; } else { durationTestMode = DEFAULT_DURATION; } } FormRecognizerClientBuilder getFormRecognizerClientBuilder(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { FormRecognizerClientBuilder builder = new FormRecognizerClientBuilder() .endpoint(getEndpoint()) .httpClient(httpClient == null ? interceptorManager.getPlaybackClient() : httpClient) .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)) .serviceVersion(serviceVersion) .addPolicy(interceptorManager.getRecordPolicy()); if (getTestMode() == TestMode.PLAYBACK) { builder.credential(new AzureKeyCredential(INVALID_KEY)); } else { builder.credential(new DefaultAzureCredentialBuilder().build()); } return builder; } FormTrainingClientBuilder getFormTrainingClientBuilder(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { FormTrainingClientBuilder builder = new FormTrainingClientBuilder() .endpoint(getEndpoint()) .httpClient(httpClient == null ? interceptorManager.getPlaybackClient() : httpClient) .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)) .serviceVersion(serviceVersion) .addPolicy(interceptorManager.getRecordPolicy()); if (getTestMode() == TestMode.PLAYBACK) { builder.credential(new AzureKeyCredential(INVALID_KEY)); } else { builder.credential(new AzureKeyCredential(Configuration.getGlobalConfiguration().get(AZURE_FORM_RECOGNIZER_API_KEY))); } return builder; } private static void validateReferenceElementsData(List<String> expectedElements, List<FormElement> actualFormElementList, List<ReadResult> readResults) { if (expectedElements != null && actualFormElementList != null) { assertEquals(expectedElements.size(), actualFormElementList.size()); for (int i = 0; i < actualFormElementList.size(); i++) { String[] indices = NON_DIGIT_PATTERN.matcher(expectedElements.get(i)).replaceAll(" ").trim().split(" "); if (indices.length < 2) { return; } int readResultIndex = Integer.parseInt(indices[0]); int lineIndex = Integer.parseInt(indices[1]); if (indices.length == 3) { int wordIndex = Integer.parseInt(indices[2]); TextWord expectedTextWord = readResults.get(readResultIndex).getLines().get(lineIndex).getWords().get(wordIndex); TextLine expectedTextLine = readResults.get(readResultIndex).getLines().get(lineIndex); if (actualFormElementList.get(i) instanceof FormLine) { FormLine actualFormLine = (FormLine) actualFormElementList.get(i); validateFormWordData(expectedTextLine.getWords(), actualFormLine.getWords()); } FormWord actualFormWord = (FormWord) actualFormElementList.get(i); assertEquals(expectedTextWord.getText(), actualFormWord.getText()); if (expectedTextWord.getConfidence() != null) { assertEquals(expectedTextWord.getConfidence(), actualFormWord.getConfidence()); } else { assertEquals(1.0f, actualFormWord.getConfidence()); } validateBoundingBoxData(expectedTextWord.getBoundingBox(), actualFormWord.getBoundingBox()); } } } } private static void validateFormTableData(List<DataTable> expectedFormTables, List<FormTable> actualFormTable, List<ReadResult> readResults, boolean includeFieldElements, int pageNumber) { assertEquals(expectedFormTables.size(), actualFormTable.size()); for (int i = 0; i < actualFormTable.size(); i++) { DataTable expectedTable = expectedFormTables.get(i); FormTable actualTable = actualFormTable.get(i); assertEquals(pageNumber, actualTable.getPageNumber()); assertEquals(expectedTable.getColumns(), actualTable.getColumnCount()); validateCellData(expectedTable.getCells(), actualTable.getCells(), readResults, includeFieldElements); assertEquals(expectedTable.getRows(), actualTable.getRowCount()); } } private static void validateCellData(List<DataTableCell> expectedTableCells, List<FormTableCell> actualTableCellList, List<ReadResult> readResults, boolean includeFieldElements) { assertEquals(expectedTableCells.size(), actualTableCellList.size()); for (int i = 0; i < actualTableCellList.size(); i++) { DataTableCell expectedTableCell = expectedTableCells.get(i); FormTableCell actualTableCell = actualTableCellList.get(i); assertEquals(expectedTableCell.getColumnIndex(), actualTableCell.getColumnIndex()); if (expectedTableCell.getColumnSpan() != null) { assertEquals(expectedTableCell.getColumnSpan(), actualTableCell.getColumnSpan()); } assertNotNull(actualTableCell.getColumnSpan()); assertEquals(expectedTableCell.getRowIndex(), actualTableCell.getRowIndex()); if (expectedTableCell.getRowSpan() != null) { assertEquals(expectedTableCell.getRowSpan(), actualTableCell.getRowSpan()); } assertNotNull(actualTableCell.getRowSpan()); validateBoundingBoxData(expectedTableCell.getBoundingBox(), actualTableCell.getBoundingBox()); if (includeFieldElements) { validateReferenceElementsData(expectedTableCell.getElements(), actualTableCell.getFieldElements(), readResults); } } } private static void validateFormLineData(List<TextLine> expectedLines, List<FormLine> actualLineList) { assertEquals(expectedLines.size(), actualLineList.size()); for (int i = 0; i < actualLineList.size(); i++) { TextLine expectedLine = expectedLines.get(i); FormLine actualLine = actualLineList.get(i); assertEquals(expectedLine.getText(), actualLine.getText()); validateBoundingBoxData(expectedLine.getBoundingBox(), actualLine.getBoundingBox()); validateFormWordData(expectedLine.getWords(), actualLine.getWords()); } } private static void validateFormWordData(List<TextWord> expectedFormWords, List<FormWord> actualFormWordList) { assertEquals(expectedFormWords.size(), actualFormWordList.size()); for (int i = 0; i < actualFormWordList.size(); i++) { TextWord expectedWord = expectedFormWords.get(i); FormWord actualWord = actualFormWordList.get(i); assertEquals(expectedWord.getText(), actualWord.getText()); validateBoundingBoxData(expectedWord.getBoundingBox(), actualWord.getBoundingBox()); if (expectedWord.getConfidence() != null) { assertEquals(expectedWord.getConfidence(), actualWord.getConfidence()); } else { assertEquals(1.0f, actualWord.getConfidence()); } } } private static void validateBoundingBoxData(List<Float> expectedBoundingBox, FieldBoundingBox actualFieldBoundingBox) { if (actualFieldBoundingBox != null && actualFieldBoundingBox.getPoints() != null) { int i = 0; for (Point point : actualFieldBoundingBox.getPoints()) { assertEquals(expectedBoundingBox.get(i), point.getX()); assertEquals(expectedBoundingBox.get(++i), point.getY()); i++; } } } @SuppressWarnings("unchecked") private static void validateFieldValueTransforms(FieldValue expectedFieldValue, FormField actualFormField, List<ReadResult> readResults, boolean includeFieldElements) { if (expectedFieldValue != null) { if (expectedFieldValue.getBoundingBox() != null) { validateBoundingBoxData(expectedFieldValue.getBoundingBox(), actualFormField.getValueData().getBoundingBox()); } if (includeFieldElements && expectedFieldValue.getElements() != null) { validateReferenceElementsData(expectedFieldValue.getElements(), actualFormField.getValueData().getFieldElements(), readResults); } switch (expectedFieldValue.getType()) { case NUMBER: if (expectedFieldValue.getValueNumber() != null) { assertEquals(expectedFieldValue.getValueNumber(), actualFormField.getValue().asFloat()); } break; case DATE: assertEquals(expectedFieldValue.getValueDate(), actualFormField.getValue().asDate()); break; case TIME: assertEquals(LocalTime.parse(expectedFieldValue.getValueTime(), DateTimeFormatter.ofPattern("HH:mm:ss")), actualFormField.getValue().asTime()); break; case STRING: if (actualFormField.getName() != "ReceiptType") { assertEquals(expectedFieldValue.getValueString(), actualFormField.getValue().asString()); } break; case INTEGER: assertEquals(expectedFieldValue.getValueInteger(), actualFormField.getValue().asLong()); break; case PHONE_NUMBER: assertEquals(expectedFieldValue.getValuePhoneNumber(), actualFormField.getValue().asPhoneNumber()); break; case OBJECT: expectedFieldValue.getValueObject().forEach((key, formField) -> { FormField actualFormFieldValue = actualFormField.getValue().asMap().get(key); validateFieldValueTransforms(formField, actualFormFieldValue, readResults, includeFieldElements); }); break; case ARRAY: assertEquals(expectedFieldValue.getValueArray().size(), actualFormField.getValue().asList().size()); for (int i = 0; i < expectedFieldValue.getValueArray().size(); i++) { FieldValue expectedReceiptItem = expectedFieldValue.getValueArray().get(i); FormField actualReceiptItem = actualFormField.getValue().asList().get(i); validateFieldValueTransforms(expectedReceiptItem, actualReceiptItem, readResults, includeFieldElements); } break; default: assertFalse(false, "Field type not supported."); } } } private static void validatePageRangeData(int expectedPageInfo, FormPageRange actualPageInfo) { assertEquals(expectedPageInfo, actualPageInfo.getFirstPageNumber()); assertEquals(expectedPageInfo, actualPageInfo.getLastPageNumber()); } @Test abstract void recognizeReceiptData(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeReceiptDataNullData(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeReceiptDataWithContentTypeAutoDetection(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeReceiptDataIncludeFieldElements(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeReceiptDataWithPngFile(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeReceiptDataWithBlankPdf(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeReceiptFromDataMultiPage(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeReceiptSourceUrl(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeReceiptInvalidSourceUrl(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeReceiptFromUrlIncludeFieldElements(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeReceiptSourceUrlWithPngFile(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeReceiptFromUrlMultiPage(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeContent(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeContentResultWithNullData(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeContentResultWithContentTypeAutoDetection(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeContentResultWithBlankPdf(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeContentFromDataMultiPage(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeContentFromUrl(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeContentFromUrlWithPdf(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeContentInvalidSourceUrl(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeContentFromUrlMultiPage(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormLabeledData(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormLabeledDataWithJpgContentType(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormLabeledDataWithBlankPdfContentType(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormLabeledDataExcludeFieldElements(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormLabeledDataWithNullFormData(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormLabeledDataWithNullModelId(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormLabeledDataWithEmptyModelId(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormInvalidStatus(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormLabeledDataWithContentTypeAutoDetection(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormMultiPageLabeled(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormUnlabeledData(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormUnlabeledDataIncludeFieldElements(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormMultiPageUnlabeled(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormUnlabeledDataWithJpgContentType(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormUnlabeledDataWithBlankPdfContentType(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormUrlUnlabeledData(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormUrlUnlabeledDataIncludeFieldElements(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormUrlMultiPageUnlabeled(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormInvalidSourceUrl(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormFromUrlLabeledDataWithNullModelId(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormFromUrlLabeledDataWithEmptyModelId(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormUrlLabeledData(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormUrlLabeledDataIncludeFieldElements(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormUrlMultiPageLabeled(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeBusinessCardData(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeBusinessCardDataNullData(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeBusinessCardDataWithContentTypeAutoDetection(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeBusinessCardDataIncludeFieldElements(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeBusinessCardDataWithPngFile(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeBusinessCardDataWithBlankPdf(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeBusinessCardFromDamagedPdf(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeBusinessCardSourceUrl(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeBusinessCardFromUrlWithEncodedBlankSpaceSourceUrl(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeBusinessCardInvalidSourceUrl(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeBusinessCardFromUrlIncludeFieldElements(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeBusinessCardSourceUrlWithPngFile(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); void validateReceiptDataFields(Map<String, FormField> actualRecognizedReceiptFields, boolean includeFieldElements) { final AnalyzeResult analyzeResult = getAnalyzeRawResponse().getAnalyzeResult(); List<ReadResult> readResults = analyzeResult.getReadResults(); DocumentResult documentResult = analyzeResult.getDocumentResults().get(0); Map<String, FieldValue> expectedReceiptFields = documentResult.getFields(); assertEquals(expectedReceiptFields.get("ReceiptType").getValueString(), actualRecognizedReceiptFields.get("ReceiptType").getValue().asString()); assertEquals(expectedReceiptFields.get("ReceiptType").getConfidence(), actualRecognizedReceiptFields.get("ReceiptType").getConfidence()); validateFieldValueTransforms(expectedReceiptFields.get("MerchantName"), actualRecognizedReceiptFields.get("MerchantName"), readResults, includeFieldElements); validateFieldValueTransforms(expectedReceiptFields.get("MerchantPhoneNumber"), actualRecognizedReceiptFields.get("MerchantPhoneNumber"), readResults, includeFieldElements); validateFieldValueTransforms(expectedReceiptFields.get("MerchantAddress"), actualRecognizedReceiptFields.get("MerchantAddress"), readResults, includeFieldElements); validateFieldValueTransforms(expectedReceiptFields.get("Total"), actualRecognizedReceiptFields.get("Total"), readResults, includeFieldElements); validateFieldValueTransforms(expectedReceiptFields.get("Subtotal"), actualRecognizedReceiptFields.get("Subtotal"), readResults, includeFieldElements); validateFieldValueTransforms(expectedReceiptFields.get("Tax"), actualRecognizedReceiptFields.get("Tax"), readResults, includeFieldElements); validateFieldValueTransforms(expectedReceiptFields.get("TransactionDate"), actualRecognizedReceiptFields.get("TransactionDate"), readResults, includeFieldElements); validateFieldValueTransforms(expectedReceiptFields.get("TransactionTime"), actualRecognizedReceiptFields.get("TransactionTime"), readResults, includeFieldElements); validateFieldValueTransforms(expectedReceiptFields.get("Items"), actualRecognizedReceiptFields.get("Items"), readResults, includeFieldElements); } void validateContentResultData(List<FormPage> actualFormPageList, boolean includeFieldElements) { AnalyzeResult analyzeResult = getAnalyzeRawResponse().getAnalyzeResult(); final List<PageResult> pageResults = analyzeResult.getPageResults(); final List<ReadResult> readResults = analyzeResult.getReadResults(); for (int i = 0; i < actualFormPageList.size(); i++) { FormPage actualFormPage = actualFormPageList.get(i); ReadResult readResult = readResults.get(i); if (readResult.getAngle() > 180) { assertEquals(readResult.getAngle() - 360, actualFormPage.getTextAngle()); } else { assertEquals(readResult.getAngle(), actualFormPage.getTextAngle()); } assertEquals(readResult.getWidth(), actualFormPage.getWidth()); assertEquals(readResult.getHeight(), actualFormPage.getHeight()); assertEquals(readResult.getUnit().toString(), actualFormPage.getUnit().toString()); assertEquals(readResult.getPage(), actualFormPage.getPageNumber()); if (includeFieldElements) { validateFormLineData(readResult.getLines(), actualFormPage.getLines()); } if (pageResults != null) { validateFormTableData(pageResults.get(i).getTables(), actualFormPage.getTables(), readResults, includeFieldElements, pageResults.get(i).getPage()); } } } void validateReceiptResultData(List<RecognizedForm> actualReceiptList, boolean includeFieldElements) { final AnalyzeResult rawResponse = getAnalyzeRawResponse().getAnalyzeResult(); for (int i = 0; i < actualReceiptList.size(); i++) { final RecognizedForm actualReceipt = actualReceiptList.get(i); validateLabeledData(actualReceipt, includeFieldElements, rawResponse.getReadResults(), rawResponse.getDocumentResults().get(i)); validateReceiptDataFields(actualReceipt.getFields(), includeFieldElements); } } void validateBlankPdfResultData(List<RecognizedForm> actualReceiptList) { assertEquals(1, actualReceiptList.size()); final RecognizedForm actualReceipt = actualReceiptList.get(0); assertTrue(actualReceipt.getFields().isEmpty()); } void validateRecognizedResult(List<RecognizedForm> actualFormList, boolean includeFieldElements, boolean isLabeled) { final AnalyzeResult rawResponse = getAnalyzeRawResponse().getAnalyzeResult(); List<ReadResult> readResults = rawResponse.getReadResults(); List<PageResult> pageResults = rawResponse.getPageResults(); List<DocumentResult> documentResults = rawResponse.getDocumentResults(); for (int i = 0; i < actualFormList.size(); i++) { validateContentResultData(actualFormList.get(i).getPages(), includeFieldElements); if (isLabeled) { validateLabeledData(actualFormList.get(i), includeFieldElements, readResults, documentResults.get(i)); } else { validateUnLabeledResult(actualFormList.get(i), includeFieldElements, readResults, pageResults.get(i)); } } } void validateBusinessCardResultData(List<RecognizedForm> actualBusinessCardList, boolean includeFieldElements) { final AnalyzeResult rawResponse = getAnalyzeRawResponse().getAnalyzeResult(); for (int i = 0; i < actualBusinessCardList.size(); i++) { final RecognizedForm actualBusinessCard = actualBusinessCardList.get(i); validateLabeledData(actualBusinessCard, includeFieldElements, rawResponse.getReadResults(), rawResponse.getDocumentResults().get(i)); validateBusinessCardDataFields(actualBusinessCard.getFields(), includeFieldElements); } } void invalidSourceUrlRunner(Consumer<String> testRunner) { testRunner.accept(TestUtils.INVALID_RECEIPT_URL); } void encodedBlankSpaceSourceUrlRunner(Consumer<String> testRunner) { testRunner.accept(FAKE_ENCODED_EMPTY_SPACE_URL); } void urlRunner(Consumer<String> testRunner, String fileName) { testRunner.accept(URL_TEST_FILE_FORMAT + fileName); } void storageUrlRunner(Consumer<String> testRunner, String fileName) { testRunner.accept(getStorageTestingFileUrl(fileName)); } void urlPdfUnlabeledRunner(Consumer<String> testRunner) { testRunner.accept(getStorageTestingFileUrl(MULTIPAGE_INVOICE_PDF)); } void dataRunner(BiConsumer<InputStream, Long> testRunner, String fileName) { final long fileLength = new File(LOCAL_FILE_PATH + fileName).length(); if (interceptorManager.isPlaybackMode()) { testRunner.accept(new ByteArrayInputStream(TEST_DATA_PNG.getBytes(StandardCharsets.UTF_8)), fileLength); } else { try { testRunner.accept(new FileInputStream(LOCAL_FILE_PATH + fileName), fileLength); } catch (FileNotFoundException e) { throw new RuntimeException("Local file not found.", e); } } } void localFilePathRunner(BiConsumer<String, Long> testRunner, String fileName) { final long fileLength = new File(LOCAL_FILE_PATH + fileName).length(); testRunner.accept(LOCAL_FILE_PATH + fileName, fileLength); } void damagedPdfDataRunner(BiConsumer<InputStream, Integer> testRunner) { testRunner.accept(new ByteArrayInputStream(new byte[]{0x25, 0x50, 0x44, 0x46, 0x55, 0x55, 0x55}), 7); } void beginTrainingUnlabeledRunner(BiConsumer<String, Boolean> testRunner) { testRunner.accept(getTrainingSasUri(), false); } void beginTrainingLabeledRunner(BiConsumer<String, Boolean> testRunner) { testRunner.accept(getTrainingSasUri(), true); } void beginTrainingMultipageRunner(Consumer<String> testRunner) { testRunner.accept(getMultipageTrainingSasUri()); } private void validateUnLabeledResult(RecognizedForm actualForm, boolean includeFieldElements, List<ReadResult> readResults, PageResult expectedPage) { validatePageRangeData(expectedPage.getPage(), actualForm.getPageRange()); int i = 0; for (Map.Entry<String, FormField> entry : actualForm.getFields().entrySet()) { FormField actualFormField = entry.getValue(); final KeyValuePair expectedFormField = expectedPage.getKeyValuePairs().get(i++); assertEquals(expectedFormField.getConfidence(), actualFormField.getConfidence()); assertEquals(expectedFormField.getKey().getText(), actualFormField.getLabelData().getText()); validateBoundingBoxData(expectedFormField.getKey().getBoundingBox(), actualFormField.getLabelData().getBoundingBox()); if (includeFieldElements) { validateReferenceElementsData(expectedFormField.getKey().getElements(), actualFormField.getLabelData().getFieldElements(), readResults); validateReferenceElementsData(expectedFormField.getValue().getElements(), actualFormField.getValueData().getFieldElements(), readResults); } assertEquals(expectedFormField.getValue().getText(), actualFormField.getValueData().getText()); validateBoundingBoxData(expectedFormField.getValue().getBoundingBox(), actualFormField.getValueData().getBoundingBox()); } } private void validateLabeledData(RecognizedForm actualForm, boolean includeFieldElements, List<ReadResult> readResults, DocumentResult documentResult) { assertEquals(documentResult.getPageRange().get(0), actualForm.getPageRange().getFirstPageNumber()); assertEquals(documentResult.getPageRange().get(1), actualForm.getPageRange().getLastPageNumber()); assertEquals(documentResult.getFields().keySet(), actualForm.getFields().keySet()); documentResult.getFields().forEach((label, expectedFieldValue) -> { final FormField actualFormField = actualForm.getFields().get(label); assertEquals(label, actualFormField.getName()); if (expectedFieldValue != null) { if (expectedFieldValue.getConfidence() != null) { assertEquals(expectedFieldValue.getConfidence(), actualFormField.getConfidence()); } else { assertEquals(1.0f, actualFormField.getConfidence()); } validateFieldValueTransforms(expectedFieldValue, actualFormField, readResults, includeFieldElements); } }); } static void validateMultiPageDataLabeled(List<RecognizedForm> actualRecognizedFormsList) { actualRecognizedFormsList.forEach(recognizedForm -> { assertEquals(1, recognizedForm.getPageRange().getFirstPageNumber()); assertEquals(3, recognizedForm.getPageRange().getLastPageNumber()); assertEquals(3, recognizedForm.getPages().size()); recognizedForm.getFields().forEach((label, formField) -> { assertNotNull(formField.getName()); assertNotNull(formField.getValue()); assertNotNull(formField.getValueData().getText()); assertNull(formField.getLabelData()); }); }); } static void validateMultiPageDataUnlabeled(List<RecognizedForm> actualRecognizedFormsList) { actualRecognizedFormsList.forEach(recognizedForm -> { assertNotNull(recognizedForm.getFormType()); assertEquals(1, (long) recognizedForm.getPages().size()); recognizedForm.getFields().forEach((label, formField) -> { assertNotNull(formField.getName()); assertNotNull(formField.getValue()); assertNotNull(formField.getValueData().getText()); assertNotNull(formField.getLabelData().getText()); }); }); } static void validateMultipageReceiptData(List<RecognizedForm> recognizedReceipts) { assertEquals(3, recognizedReceipts.size()); RecognizedForm receiptPage1 = recognizedReceipts.get(0); RecognizedForm receiptPage2 = recognizedReceipts.get(1); RecognizedForm receiptPage3 = recognizedReceipts.get(2); assertEquals(1, receiptPage1.getPageRange().getFirstPageNumber()); assertEquals(1, receiptPage1.getPageRange().getLastPageNumber()); Map<String, FormField> receiptPage1Fields = receiptPage1.getFields(); assertEquals(EXPECTED_MULTIPAGE_ADDRESS_VALUE, receiptPage1Fields.get("MerchantAddress") .getValue().asString()); assertEquals("Bilbo Baggins", receiptPage1Fields.get("MerchantName") .getValue().asString()); assertEquals(EXPECTED_MULTIPAGE_PHONE_NUMBER_VALUE, receiptPage1Fields.get("MerchantPhoneNumber") .getValue().asPhoneNumber()); assertNotNull(receiptPage1Fields.get("Total").getValue().asFloat()); assertNotNull(receiptPage1.getPages()); assertEquals(ITEMIZED_RECEIPT_VALUE, receiptPage1Fields.get("ReceiptType").getValue().asString()); assertEquals(0, receiptPage2.getFields().size()); List<FormPage> receipt2Pages = receiptPage2.getPages(); assertEquals(1, receipt2Pages.size()); assertEquals(0, receipt2Pages.stream().findFirst().get().getTables().size()); assertEquals(0, receipt2Pages.stream().findFirst().get().getLines().size()); assertEquals(2, receiptPage2.getPageRange().getFirstPageNumber()); assertEquals(2, receiptPage2.getPageRange().getLastPageNumber()); assertEquals(3, receiptPage3.getPageRange().getFirstPageNumber()); assertEquals(3, receiptPage3.getPageRange().getLastPageNumber()); Map<String, FormField> receiptPage3Fields = receiptPage3.getFields(); assertEquals(EXPECTED_MULTIPAGE_ADDRESS_VALUE, receiptPage3Fields.get("MerchantAddress").getValue().asString()); assertEquals("Frodo Baggins", receiptPage3Fields.get("MerchantName").getValue().asString()); assertEquals(EXPECTED_MULTIPAGE_PHONE_NUMBER_VALUE, receiptPage3Fields.get("MerchantPhoneNumber").getValue().asPhoneNumber()); assertNotNull(receiptPage3Fields.get("Total").getValue().asFloat()); assertEquals(3000.0f, receiptPage3Fields.get("Subtotal").getValue().asFloat()); assertEquals(ITEMIZED_RECEIPT_VALUE, receiptPage3Fields.get("ReceiptType").getValue().asString()); } protected String getEndpoint() { return interceptorManager.isPlaybackMode() ? "https: : Configuration.getGlobalConfiguration().get(AZURE_FORM_RECOGNIZER_ENDPOINT); } /** * Get the training data set SAS Url value based on the test running mode. * * @return the training data set Url */ private String getTrainingSasUri() { if (interceptorManager.isPlaybackMode()) { return "https: } else { return Configuration.getGlobalConfiguration().get(FORM_RECOGNIZER_TRAINING_BLOB_CONTAINER_SAS_URL); } } /** * Get the training data set SAS Url value based on the test running mode. * * @return the training data set Url */ private String getMultipageTrainingSasUri() { if (interceptorManager.isPlaybackMode()) { return "https: } else { return Configuration.getGlobalConfiguration() .get(FORM_RECOGNIZER_MULTIPAGE_TRAINING_BLOB_CONTAINER_SAS_URL); } } /** * Get the testing data set SAS Url value based on the test running mode. * * @return the testing data set Url */ private String getTestingSasUri() { if (interceptorManager.isPlaybackMode()) { return "https: } else { return Configuration.getGlobalConfiguration().get("FORM_RECOGNIZER_TESTING_BLOB_CONTAINER_SAS_URL"); } } /** * Prepare the file url from the testing data set SAS Url value. * * @return the testing data specific file Url */ private String getStorageTestingFileUrl(String fileName) { if (interceptorManager.isPlaybackMode()) { return "https: } else { final String[] urlParts = getTestingSasUri().split("\\?"); return urlParts[0] + "/" + fileName + "?" + urlParts[1]; } } /** * Prepare the expected test data from service raw response. * * @return the {@code AnalyzeOperationResult} test data */ private AnalyzeOperationResult getAnalyzeRawResponse() { final SerializerAdapter serializerAdapter = getSerializerAdapter(); final NetworkCallRecord networkCallRecord = interceptorManager.getRecordedData().findFirstAndRemoveNetworkCall(record -> { AnalyzeOperationResult rawModelResponse = deserializeRawResponse(serializerAdapter, record, AnalyzeOperationResult.class); return rawModelResponse != null && rawModelResponse.getStatus() == OperationStatus.SUCCEEDED; }); interceptorManager.getRecordedData().addNetworkCall(networkCallRecord); return deserializeRawResponse(serializerAdapter, networkCallRecord, AnalyzeOperationResult.class); } }
Clarified offline, this is not updating the request headers.
static String replaceTracingPlaceHolder(HttpRequest request, StringBuilder bodyStringBuilder) { final int traceParentPlaceHolderIndex = bodyStringBuilder.indexOf(Constants.TRACE_PARENT_PLACEHOLDER); if (traceParentPlaceHolderIndex >= 0) { final HttpHeader traceparentHeader = request.getHeaders().get(Constants.TRACE_PARENT); bodyStringBuilder.replace(traceParentPlaceHolderIndex, Constants.TRACE_PARENT_PLACEHOLDER.length() + traceParentPlaceHolderIndex, traceparentHeader != null ? String.format(",\"%s\":\"%s\"", Constants.TRACE_PARENT, traceparentHeader.getValue()) : ""); } final int traceStatePlaceHolderIndex = bodyStringBuilder.indexOf(Constants.TRACE_STATE_PLACEHOLDER); if (traceStatePlaceHolderIndex >= 0) { final HttpHeader tracestateHeader = request.getHeaders().get(Constants.TRACE_STATE); bodyStringBuilder.replace(traceStatePlaceHolderIndex, Constants.TRACE_STATE_PLACEHOLDER.length() + traceStatePlaceHolderIndex, tracestateHeader != null ? String.format(",\"%s\":\"%s\"", Constants.TRACE_STATE, tracestateHeader.getValue()) : ""); } String newBodyString = bodyStringBuilder.toString(); request.setHeader(Constants.CONTENT_LENGTH, String.valueOf(newBodyString.length())); request.setBody(newBodyString); return newBodyString; }
: "");
static String replaceTracingPlaceHolder(HttpRequest request, StringBuilder bodyStringBuilder) { final int traceParentPlaceHolderIndex = bodyStringBuilder.indexOf(Constants.TRACE_PARENT_PLACEHOLDER); if (traceParentPlaceHolderIndex >= 0) { final HttpHeader traceparentHeader = request.getHeaders().get(Constants.TRACE_PARENT); bodyStringBuilder.replace(traceParentPlaceHolderIndex, Constants.TRACE_PARENT_PLACEHOLDER.length() + traceParentPlaceHolderIndex, traceparentHeader != null ? String.format(",\"%s\":\"%s\"", Constants.TRACE_PARENT, traceparentHeader.getValue()) : ""); } final int traceStatePlaceHolderIndex = bodyStringBuilder.indexOf(Constants.TRACE_STATE_PLACEHOLDER); if (traceStatePlaceHolderIndex >= 0) { final HttpHeader tracestateHeader = request.getHeaders().get(Constants.TRACE_STATE); bodyStringBuilder.replace(traceStatePlaceHolderIndex, Constants.TRACE_STATE_PLACEHOLDER.length() + traceStatePlaceHolderIndex, tracestateHeader != null ? String.format(",\"%s\":\"%s\"", Constants.TRACE_STATE, tracestateHeader.getValue()) : ""); } String newBodyString = bodyStringBuilder.toString(); request.setHeader(Constants.CONTENT_LENGTH, String.valueOf(newBodyString.length())); request.setBody(newBodyString); return newBodyString; }
class CloudEventTracingPipelinePolicy implements HttpPipelinePolicy { @Override public Mono<HttpResponse> process(HttpPipelineCallContext context, HttpPipelineNextPolicy next) { final HttpRequest request = context.getHttpRequest(); final HttpHeader contentType = request.getHeaders().get(Constants.CONTENT_TYPE); StringBuilder bodyStringBuilder = new StringBuilder(); if (TracerProxy.isTracingEnabled() && contentType != null && Constants.CLOUD_EVENT_CONTENT_TYPE.equals(contentType.getValue())) { return request.getBody().map(byteBuffer -> bodyStringBuilder.append(new String(byteBuffer.array(), StandardCharsets.UTF_8))) .then(Mono.fromCallable(() -> replaceTracingPlaceHolder(request, bodyStringBuilder))) .then(next.process()); } else { return next.process(); } } /** * * @param request The {@link HttpRequest}, whose body will be mutated by replacing traceparent and tracestate * placeholders. * @param bodyStringBuilder The {@link StringBuilder} that contains the full HttpRequest body string. * @return The new body string with the place holders replaced (if header has tracing) * or removed (if header no tracing). */ }
class CloudEventTracingPipelinePolicy implements HttpPipelinePolicy { @Override public Mono<HttpResponse> process(HttpPipelineCallContext context, HttpPipelineNextPolicy next) { final HttpRequest request = context.getHttpRequest(); final HttpHeader contentType = request.getHeaders().get(Constants.CONTENT_TYPE); StringBuilder bodyStringBuilder = new StringBuilder(); if (TracerProxy.isTracingEnabled() && contentType != null && Constants.CLOUD_EVENT_CONTENT_TYPE.equals(contentType.getValue())) { return request.getBody().map(byteBuffer -> bodyStringBuilder.append(new String(byteBuffer.array(), StandardCharsets.UTF_8))) .then(Mono.fromCallable(() -> replaceTracingPlaceHolder(request, bodyStringBuilder))) .then(next.process()); } else { return next.process(); } } /** * * @param request The {@link HttpRequest}, whose body will be mutated by replacing traceparent and tracestate * placeholders. * @param bodyStringBuilder The {@link StringBuilder} that contains the full HttpRequest body string. * @return The new body string with the place holders replaced (if header has tracing) * or removed (if header no tracing). */ }
:)
void validateBusinessCardDataFields(Map<String, FormField> actualRecognizedBusinessCardFields, boolean includeFieldElements) { final AnalyzeResult analyzeResult = getAnalyzeRawResponse().getAnalyzeResult(); List<ReadResult> readResults = analyzeResult.getReadResults(); DocumentResult documentResult = analyzeResult.getDocumentResults().get(0); Map<String, FieldValue> expectedReceiptFields = documentResult.getFields(); BUSINESS_CARD_FIELDS.forEach(businessCardField -> validateFieldValueTransforms(expectedReceiptFields.get(businessCardField), actualRecognizedBusinessCardFields.get(businessCardField), readResults, includeFieldElements)); }
BUSINESS_CARD_FIELDS.forEach(businessCardField ->
void validateBusinessCardDataFields(Map<String, FormField> actualRecognizedBusinessCardFields, boolean includeFieldElements) { final AnalyzeResult analyzeResult = getAnalyzeRawResponse().getAnalyzeResult(); List<ReadResult> readResults = analyzeResult.getReadResults(); DocumentResult documentResult = analyzeResult.getDocumentResults().get(0); Map<String, FieldValue> expectedReceiptFields = documentResult.getFields(); BUSINESS_CARD_FIELDS.forEach(businessCardField -> validateFieldValueTransforms(expectedReceiptFields.get(businessCardField), actualRecognizedBusinessCardFields.get(businessCardField), readResults, includeFieldElements)); }
class FormRecognizerClientTestBase extends TestBase { private static final Pattern NON_DIGIT_PATTERN = Pattern.compile("[^0-9]+"); private static final String EXPECTED_MULTIPAGE_ADDRESS_VALUE = "123 Hobbit Lane 567 Main St. Redmond, WA Redmond," + " WA"; private static final String EXPECTED_MULTIPAGE_PHONE_NUMBER_VALUE = "+15555555555"; private static final String ITEMIZED_RECEIPT_VALUE = "Itemized"; static final String RECEIPT_CONTOSO_JPG = "contoso-allinone.jpg"; static final String RECEIPT_CONTOSO_PNG = "contoso-receipt.png"; static final String INVOICE_6_PDF = "Invoice_6.pdf"; static final String MULTIPAGE_INVOICE_PDF = "multipage_invoice1.pdf"; static final String BUSINESS_CARD_JPG = "businessCard.jpg"; static final String BUSINESS_CARD_PNG = "businessCard.png"; static final String BAD_ARGUMENT_CODE = "BadArgument"; static final String INVALID_IMAGE_ERROR_CODE = "InvalidImage"; static final String INVALID_MODEL_ID_ERROR_CODE = "1001"; static final String MODEL_ID_NOT_FOUND_ERROR_CODE = "1022"; static final String URL_BADLY_FORMATTED_ERROR_CODE = "2001"; static final String UNABLE_TO_READ_FILE_ERROR_CODE = "2005"; static final String HTTPS_EXCEPTION_MESSAGE = "Max retries 3 times exceeded. Error Details: Key credentials require HTTPS to prevent leaking the key."; static final String INVALID_UUID_EXCEPTION_MESSAGE = "Invalid UUID string: "; static final String MODEL_ID_IS_REQUIRED_EXCEPTION_MESSAGE = "'modelId' is required and cannot be null."; static final String INVALID_ENDPOINT = "https: static final String LOCAL_FILE_PATH = "src/test/resources/sample_files/Test/"; static final String ENCODED_EMPTY_SPACE = "{\"source\":\"https: static final List<String> BUSINESS_CARD_FIELDS = Arrays.asList("ContactNames", "JobTitles", "Departments", "Emails", "Websites", "MobilePhones", "OtherPhones", "Faxes", "Addresses", "CompanyNames"); Duration durationTestMode; /** * Use duration of nearly zero value for PLAYBACK test mode, otherwise, use default duration value for LIVE mode. */ @Override protected void beforeTest() { if (interceptorManager.isPlaybackMode()) { durationTestMode = ONE_NANO_DURATION; } else { durationTestMode = DEFAULT_DURATION; } } FormRecognizerClientBuilder getFormRecognizerClientBuilder(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { FormRecognizerClientBuilder builder = new FormRecognizerClientBuilder() .endpoint(getEndpoint()) .httpClient(httpClient == null ? interceptorManager.getPlaybackClient() : httpClient) .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)) .serviceVersion(serviceVersion) .addPolicy(interceptorManager.getRecordPolicy()); if (getTestMode() == TestMode.PLAYBACK) { builder.credential(new AzureKeyCredential(INVALID_KEY)); } else { builder.credential(new DefaultAzureCredentialBuilder().build()); } return builder; } FormTrainingClientBuilder getFormTrainingClientBuilder(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { FormTrainingClientBuilder builder = new FormTrainingClientBuilder() .endpoint(getEndpoint()) .httpClient(httpClient == null ? interceptorManager.getPlaybackClient() : httpClient) .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)) .serviceVersion(serviceVersion) .addPolicy(interceptorManager.getRecordPolicy()); if (getTestMode() == TestMode.PLAYBACK) { builder.credential(new AzureKeyCredential(INVALID_KEY)); } else { builder.credential(new DefaultAzureCredentialBuilder().build()); } return builder; } private static void validateReferenceElementsData(List<String> expectedElements, List<FormElement> actualFormElementList, List<ReadResult> readResults) { if (expectedElements != null && actualFormElementList != null) { assertEquals(expectedElements.size(), actualFormElementList.size()); for (int i = 0; i < actualFormElementList.size(); i++) { String[] indices = NON_DIGIT_PATTERN.matcher(expectedElements.get(i)).replaceAll(" ").trim().split(" "); if (indices.length < 2) { return; } int readResultIndex = Integer.parseInt(indices[0]); int lineIndex = Integer.parseInt(indices[1]); if (indices.length == 3) { int wordIndex = Integer.parseInt(indices[2]); TextWord expectedTextWord = readResults.get(readResultIndex).getLines().get(lineIndex).getWords().get(wordIndex); TextLine expectedTextLine = readResults.get(readResultIndex).getLines().get(lineIndex); if (actualFormElementList.get(i) instanceof FormLine) { FormLine actualFormLine = (FormLine) actualFormElementList.get(i); validateFormWordData(expectedTextLine.getWords(), actualFormLine.getWords()); } FormWord actualFormWord = (FormWord) actualFormElementList.get(i); assertEquals(expectedTextWord.getText(), actualFormWord.getText()); if (expectedTextWord.getConfidence() != null) { assertEquals(expectedTextWord.getConfidence(), actualFormWord.getConfidence()); } else { assertEquals(1.0f, actualFormWord.getConfidence()); } validateBoundingBoxData(expectedTextWord.getBoundingBox(), actualFormWord.getBoundingBox()); } } } } private static void validateFormTableData(List<DataTable> expectedFormTables, List<FormTable> actualFormTable, List<ReadResult> readResults, boolean includeFieldElements, int pageNumber) { assertEquals(expectedFormTables.size(), actualFormTable.size()); for (int i = 0; i < actualFormTable.size(); i++) { DataTable expectedTable = expectedFormTables.get(i); FormTable actualTable = actualFormTable.get(i); assertEquals(pageNumber, actualTable.getPageNumber()); assertEquals(expectedTable.getColumns(), actualTable.getColumnCount()); validateCellData(expectedTable.getCells(), actualTable.getCells(), readResults, includeFieldElements); assertEquals(expectedTable.getRows(), actualTable.getRowCount()); } } private static void validateCellData(List<DataTableCell> expectedTableCells, List<FormTableCell> actualTableCellList, List<ReadResult> readResults, boolean includeFieldElements) { assertEquals(expectedTableCells.size(), actualTableCellList.size()); for (int i = 0; i < actualTableCellList.size(); i++) { DataTableCell expectedTableCell = expectedTableCells.get(i); FormTableCell actualTableCell = actualTableCellList.get(i); assertEquals(expectedTableCell.getColumnIndex(), actualTableCell.getColumnIndex()); if (expectedTableCell.getColumnSpan() != null) { assertEquals(expectedTableCell.getColumnSpan(), actualTableCell.getColumnSpan()); } assertNotNull(actualTableCell.getColumnSpan()); assertEquals(expectedTableCell.getRowIndex(), actualTableCell.getRowIndex()); if (expectedTableCell.getRowSpan() != null) { assertEquals(expectedTableCell.getRowSpan(), actualTableCell.getRowSpan()); } assertNotNull(actualTableCell.getRowSpan()); validateBoundingBoxData(expectedTableCell.getBoundingBox(), actualTableCell.getBoundingBox()); if (includeFieldElements) { validateReferenceElementsData(expectedTableCell.getElements(), actualTableCell.getFieldElements(), readResults); } } } private static void validateFormLineData(List<TextLine> expectedLines, List<FormLine> actualLineList) { assertEquals(expectedLines.size(), actualLineList.size()); for (int i = 0; i < actualLineList.size(); i++) { TextLine expectedLine = expectedLines.get(i); FormLine actualLine = actualLineList.get(i); assertEquals(expectedLine.getText(), actualLine.getText()); validateBoundingBoxData(expectedLine.getBoundingBox(), actualLine.getBoundingBox()); validateFormWordData(expectedLine.getWords(), actualLine.getWords()); } } private static void validateFormWordData(List<TextWord> expectedFormWords, List<FormWord> actualFormWordList) { assertEquals(expectedFormWords.size(), actualFormWordList.size()); for (int i = 0; i < actualFormWordList.size(); i++) { TextWord expectedWord = expectedFormWords.get(i); FormWord actualWord = actualFormWordList.get(i); assertEquals(expectedWord.getText(), actualWord.getText()); validateBoundingBoxData(expectedWord.getBoundingBox(), actualWord.getBoundingBox()); if (expectedWord.getConfidence() != null) { assertEquals(expectedWord.getConfidence(), actualWord.getConfidence()); } else { assertEquals(1.0f, actualWord.getConfidence()); } } } private static void validateBoundingBoxData(List<Float> expectedBoundingBox, FieldBoundingBox actualFieldBoundingBox) { if (actualFieldBoundingBox != null && actualFieldBoundingBox.getPoints() != null) { int i = 0; for (Point point : actualFieldBoundingBox.getPoints()) { assertEquals(expectedBoundingBox.get(i), point.getX()); assertEquals(expectedBoundingBox.get(++i), point.getY()); i++; } } } @SuppressWarnings("unchecked") private static void validateFieldValueTransforms(FieldValue expectedFieldValue, FormField actualFormField, List<ReadResult> readResults, boolean includeFieldElements) { if (expectedFieldValue != null) { if (expectedFieldValue.getBoundingBox() != null) { validateBoundingBoxData(expectedFieldValue.getBoundingBox(), actualFormField.getValueData().getBoundingBox()); } if (includeFieldElements && expectedFieldValue.getElements() != null) { validateReferenceElementsData(expectedFieldValue.getElements(), actualFormField.getValueData().getFieldElements(), readResults); } switch (expectedFieldValue.getType()) { case NUMBER: if (expectedFieldValue.getValueNumber() != null) { assertEquals(expectedFieldValue.getValueNumber(), actualFormField.getValue().asFloat()); } break; case DATE: assertEquals(expectedFieldValue.getValueDate(), actualFormField.getValue().asDate()); break; case TIME: assertEquals(LocalTime.parse(expectedFieldValue.getValueTime(), DateTimeFormatter.ofPattern("HH:mm:ss")), actualFormField.getValue().asTime()); break; case STRING: if (actualFormField.getName() != "ReceiptType") { assertEquals(expectedFieldValue.getValueString(), actualFormField.getValue().asString()); } break; case INTEGER: assertEquals(expectedFieldValue.getValueInteger(), actualFormField.getValue().asLong()); break; case PHONE_NUMBER: assertEquals(expectedFieldValue.getValuePhoneNumber(), actualFormField.getValue().asPhoneNumber()); break; case OBJECT: expectedFieldValue.getValueObject().forEach((key, formField) -> { FormField actualFormFieldValue = actualFormField.getValue().asMap().get(key); validateFieldValueTransforms(formField, actualFormFieldValue, readResults, includeFieldElements); }); break; case ARRAY: assertEquals(expectedFieldValue.getValueArray().size(), actualFormField.getValue().asList().size()); for (int i = 0; i < expectedFieldValue.getValueArray().size(); i++) { FieldValue expectedReceiptItem = expectedFieldValue.getValueArray().get(i); FormField actualReceiptItem = actualFormField.getValue().asList().get(i); validateFieldValueTransforms(expectedReceiptItem, actualReceiptItem, readResults, includeFieldElements); } break; default: assertFalse(false, "Field type not supported."); } } } private static void validatePageRangeData(int expectedPageInfo, FormPageRange actualPageInfo) { assertEquals(expectedPageInfo, actualPageInfo.getFirstPageNumber()); assertEquals(expectedPageInfo, actualPageInfo.getLastPageNumber()); } @Test abstract void recognizeReceiptData(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeReceiptDataNullData(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeReceiptDataWithContentTypeAutoDetection(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeReceiptDataIncludeFieldElements(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeReceiptDataWithPngFile(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeReceiptDataWithBlankPdf(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeReceiptFromDataMultiPage(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeReceiptSourceUrl(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeReceiptInvalidSourceUrl(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeReceiptFromUrlIncludeFieldElements(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeReceiptSourceUrlWithPngFile(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeReceiptFromUrlMultiPage(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeContent(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeContentResultWithNullData(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeContentResultWithContentTypeAutoDetection(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeContentResultWithBlankPdf(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeContentFromDataMultiPage(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeContentFromUrl(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeContentFromUrlWithPdf(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeContentInvalidSourceUrl(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeContentFromUrlMultiPage(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormLabeledData(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormLabeledDataWithJpgContentType(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormLabeledDataWithBlankPdfContentType(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormLabeledDataExcludeFieldElements(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormLabeledDataWithNullFormData(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormLabeledDataWithNullModelId(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormLabeledDataWithEmptyModelId(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormInvalidStatus(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormLabeledDataWithContentTypeAutoDetection(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormMultiPageLabeled(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormUnlabeledData(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormUnlabeledDataIncludeFieldElements(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormMultiPageUnlabeled(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormUnlabeledDataWithJpgContentType(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormUnlabeledDataWithBlankPdfContentType(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormUrlUnlabeledData(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormUrlUnlabeledDataIncludeFieldElements(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormUrlMultiPageUnlabeled(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormInvalidSourceUrl(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormFromUrlLabeledDataWithNullModelId(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormFromUrlLabeledDataWithEmptyModelId(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormUrlLabeledData(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormUrlLabeledDataIncludeFieldElements(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormUrlMultiPageLabeled(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeBusinessCardData(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeBusinessCardDataNullData(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeBusinessCardDataWithContentTypeAutoDetection(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeBusinessCardDataIncludeFieldElements(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeBusinessCardDataWithPngFile(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeBusinessCardDataWithBlankPdf(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeBusinessCardFromDamagedPdf(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeBusinessCardSourceUrl(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeBusinessCardFromUrlWithEncodedBlankSpaceSourceUrl(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeBusinessCardInvalidSourceUrl(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeBusinessCardFromUrlIncludeFieldElements(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeBusinessCardSourceUrlWithPngFile(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); void validateReceiptDataFields(Map<String, FormField> actualRecognizedReceiptFields, boolean includeFieldElements) { final AnalyzeResult analyzeResult = getAnalyzeRawResponse().getAnalyzeResult(); List<ReadResult> readResults = analyzeResult.getReadResults(); DocumentResult documentResult = analyzeResult.getDocumentResults().get(0); Map<String, FieldValue> expectedReceiptFields = documentResult.getFields(); assertEquals(expectedReceiptFields.get("ReceiptType").getValueString(), actualRecognizedReceiptFields.get("ReceiptType").getValue().asString()); assertEquals(expectedReceiptFields.get("ReceiptType").getConfidence(), actualRecognizedReceiptFields.get("ReceiptType").getConfidence()); validateFieldValueTransforms(expectedReceiptFields.get("MerchantName"), actualRecognizedReceiptFields.get("MerchantName"), readResults, includeFieldElements); validateFieldValueTransforms(expectedReceiptFields.get("MerchantPhoneNumber"), actualRecognizedReceiptFields.get("MerchantPhoneNumber"), readResults, includeFieldElements); validateFieldValueTransforms(expectedReceiptFields.get("MerchantAddress"), actualRecognizedReceiptFields.get("MerchantAddress"), readResults, includeFieldElements); validateFieldValueTransforms(expectedReceiptFields.get("Total"), actualRecognizedReceiptFields.get("Total"), readResults, includeFieldElements); validateFieldValueTransforms(expectedReceiptFields.get("Subtotal"), actualRecognizedReceiptFields.get("Subtotal"), readResults, includeFieldElements); validateFieldValueTransforms(expectedReceiptFields.get("Tax"), actualRecognizedReceiptFields.get("Tax"), readResults, includeFieldElements); validateFieldValueTransforms(expectedReceiptFields.get("TransactionDate"), actualRecognizedReceiptFields.get("TransactionDate"), readResults, includeFieldElements); validateFieldValueTransforms(expectedReceiptFields.get("TransactionTime"), actualRecognizedReceiptFields.get("TransactionTime"), readResults, includeFieldElements); validateFieldValueTransforms(expectedReceiptFields.get("Items"), actualRecognizedReceiptFields.get("Items"), readResults, includeFieldElements); } void validateContentResultData(List<FormPage> actualFormPageList, boolean includeFieldElements) { AnalyzeResult analyzeResult = getAnalyzeRawResponse().getAnalyzeResult(); final List<PageResult> pageResults = analyzeResult.getPageResults(); final List<ReadResult> readResults = analyzeResult.getReadResults(); for (int i = 0; i < actualFormPageList.size(); i++) { FormPage actualFormPage = actualFormPageList.get(i); ReadResult readResult = readResults.get(i); if (readResult.getAngle() > 180) { assertEquals(readResult.getAngle() - 360, actualFormPage.getTextAngle()); } else { assertEquals(readResult.getAngle(), actualFormPage.getTextAngle()); } assertEquals(readResult.getWidth(), actualFormPage.getWidth()); assertEquals(readResult.getHeight(), actualFormPage.getHeight()); assertEquals(readResult.getUnit().toString(), actualFormPage.getUnit().toString()); assertEquals(readResult.getPage(), actualFormPage.getPageNumber()); if (includeFieldElements) { validateFormLineData(readResult.getLines(), actualFormPage.getLines()); } if (pageResults != null) { validateFormTableData(pageResults.get(i).getTables(), actualFormPage.getTables(), readResults, includeFieldElements, pageResults.get(i).getPage()); } } } void validateReceiptResultData(List<RecognizedForm> actualReceiptList, boolean includeFieldElements) { final AnalyzeResult rawResponse = getAnalyzeRawResponse().getAnalyzeResult(); for (int i = 0; i < actualReceiptList.size(); i++) { final RecognizedForm actualReceipt = actualReceiptList.get(i); validateLabeledData(actualReceipt, includeFieldElements, rawResponse.getReadResults(), rawResponse.getDocumentResults().get(i)); validateReceiptDataFields(actualReceipt.getFields(), includeFieldElements); } } void validateBlankPdfResultData(List<RecognizedForm> actualReceiptList) { assertEquals(1, actualReceiptList.size()); final RecognizedForm actualReceipt = actualReceiptList.get(0); assertTrue(actualReceipt.getFields().isEmpty()); } void validateRecognizedResult(List<RecognizedForm> actualFormList, boolean includeFieldElements, boolean isLabeled) { final AnalyzeResult rawResponse = getAnalyzeRawResponse().getAnalyzeResult(); List<ReadResult> readResults = rawResponse.getReadResults(); List<PageResult> pageResults = rawResponse.getPageResults(); List<DocumentResult> documentResults = rawResponse.getDocumentResults(); for (int i = 0; i < actualFormList.size(); i++) { validateContentResultData(actualFormList.get(i).getPages(), includeFieldElements); if (isLabeled) { validateLabeledData(actualFormList.get(i), includeFieldElements, readResults, documentResults.get(i)); } else { validateUnLabeledResult(actualFormList.get(i), includeFieldElements, readResults, pageResults.get(i)); } } } void validateBusinessCardResultData(List<RecognizedForm> actualBusinessCardList, boolean includeFieldElements) { final AnalyzeResult rawResponse = getAnalyzeRawResponse().getAnalyzeResult(); for (int i = 0; i < actualBusinessCardList.size(); i++) { final RecognizedForm actualBusinessCard = actualBusinessCardList.get(i); validateLabeledData(actualBusinessCard, includeFieldElements, rawResponse.getReadResults(), rawResponse.getDocumentResults().get(i)); validateBusinessCardDataFields(actualBusinessCard.getFields(), includeFieldElements); } } void invalidSourceUrlRunner(Consumer<String> testRunner) { testRunner.accept(TestUtils.INVALID_RECEIPT_URL); } void encodedBlankSpaceSourceUrlRunner(Consumer<String> testRunner) { testRunner.accept(FAKE_ENCODED_EMPTY_SPACE_URL); } void urlRunner(Consumer<String> testRunner, String fileName) { testRunner.accept(URL_TEST_FILE_FORMAT + fileName); } void storageUrlRunner(Consumer<String> testRunner, String fileName) { testRunner.accept(getStorageTestingFileUrl(fileName)); } void urlPdfUnlabeledRunner(Consumer<String> testRunner) { testRunner.accept(getStorageTestingFileUrl(MULTIPAGE_INVOICE_PDF)); } void dataRunner(BiConsumer<InputStream, Long> testRunner, String fileName) { final long fileLength = new File(LOCAL_FILE_PATH + fileName).length(); if (interceptorManager.isPlaybackMode()) { testRunner.accept(new ByteArrayInputStream(TEST_DATA_PNG.getBytes(StandardCharsets.UTF_8)), fileLength); } else { try { testRunner.accept(new FileInputStream(LOCAL_FILE_PATH + fileName), fileLength); } catch (FileNotFoundException e) { throw new RuntimeException("Local file not found.", e); } } } void localFilePathRunner(BiConsumer<String, Long> testRunner, String fileName) { final long fileLength = new File(LOCAL_FILE_PATH + fileName).length(); testRunner.accept(LOCAL_FILE_PATH + fileName, fileLength); } void damagedPdfDataRunner(BiConsumer<InputStream, Integer> testRunner) { testRunner.accept(new ByteArrayInputStream(new byte[]{0x25, 0x50, 0x44, 0x46, 0x55, 0x55, 0x55}), 7); } void beginTrainingUnlabeledRunner(BiConsumer<String, Boolean> testRunner) { testRunner.accept(getTrainingSasUri(), false); } void beginTrainingLabeledRunner(BiConsumer<String, Boolean> testRunner) { testRunner.accept(getTrainingSasUri(), true); } void beginTrainingMultipageRunner(Consumer<String> testRunner) { testRunner.accept(getMultipageTrainingSasUri()); } private void validateUnLabeledResult(RecognizedForm actualForm, boolean includeFieldElements, List<ReadResult> readResults, PageResult expectedPage) { validatePageRangeData(expectedPage.getPage(), actualForm.getPageRange()); int i = 0; for (Map.Entry<String, FormField> entry : actualForm.getFields().entrySet()) { FormField actualFormField = entry.getValue(); final KeyValuePair expectedFormField = expectedPage.getKeyValuePairs().get(i++); assertEquals(expectedFormField.getConfidence(), actualFormField.getConfidence()); assertEquals(expectedFormField.getKey().getText(), actualFormField.getLabelData().getText()); validateBoundingBoxData(expectedFormField.getKey().getBoundingBox(), actualFormField.getLabelData().getBoundingBox()); if (includeFieldElements) { validateReferenceElementsData(expectedFormField.getKey().getElements(), actualFormField.getLabelData().getFieldElements(), readResults); validateReferenceElementsData(expectedFormField.getValue().getElements(), actualFormField.getValueData().getFieldElements(), readResults); } assertEquals(expectedFormField.getValue().getText(), actualFormField.getValueData().getText()); validateBoundingBoxData(expectedFormField.getValue().getBoundingBox(), actualFormField.getValueData().getBoundingBox()); } } private void validateLabeledData(RecognizedForm actualForm, boolean includeFieldElements, List<ReadResult> readResults, DocumentResult documentResult) { assertEquals(documentResult.getPageRange().get(0), actualForm.getPageRange().getFirstPageNumber()); assertEquals(documentResult.getPageRange().get(1), actualForm.getPageRange().getLastPageNumber()); assertEquals(documentResult.getFields().keySet(), actualForm.getFields().keySet()); documentResult.getFields().forEach((label, expectedFieldValue) -> { final FormField actualFormField = actualForm.getFields().get(label); assertEquals(label, actualFormField.getName()); if (expectedFieldValue != null) { if (expectedFieldValue.getConfidence() != null) { assertEquals(expectedFieldValue.getConfidence(), actualFormField.getConfidence()); } else { assertEquals(1.0f, actualFormField.getConfidence()); } validateFieldValueTransforms(expectedFieldValue, actualFormField, readResults, includeFieldElements); } }); } static void validateMultiPageDataLabeled(List<RecognizedForm> actualRecognizedFormsList) { actualRecognizedFormsList.forEach(recognizedForm -> { assertEquals(1, recognizedForm.getPageRange().getFirstPageNumber()); assertEquals(3, recognizedForm.getPageRange().getLastPageNumber()); assertEquals(3, recognizedForm.getPages().size()); recognizedForm.getFields().forEach((label, formField) -> { assertNotNull(formField.getName()); assertNotNull(formField.getValue()); assertNotNull(formField.getValueData().getText()); assertNull(formField.getLabelData()); }); }); } static void validateMultiPageDataUnlabeled(List<RecognizedForm> actualRecognizedFormsList) { actualRecognizedFormsList.forEach(recognizedForm -> { assertNotNull(recognizedForm.getFormType()); assertEquals(1, (long) recognizedForm.getPages().size()); recognizedForm.getFields().forEach((label, formField) -> { assertNotNull(formField.getName()); assertNotNull(formField.getValue()); assertNotNull(formField.getValueData().getText()); assertNotNull(formField.getLabelData().getText()); }); }); } static void validateMultipageReceiptData(List<RecognizedForm> recognizedReceipts) { assertEquals(3, recognizedReceipts.size()); RecognizedForm receiptPage1 = recognizedReceipts.get(0); RecognizedForm receiptPage2 = recognizedReceipts.get(1); RecognizedForm receiptPage3 = recognizedReceipts.get(2); assertEquals(1, receiptPage1.getPageRange().getFirstPageNumber()); assertEquals(1, receiptPage1.getPageRange().getLastPageNumber()); Map<String, FormField> receiptPage1Fields = receiptPage1.getFields(); assertEquals(EXPECTED_MULTIPAGE_ADDRESS_VALUE, receiptPage1Fields.get("MerchantAddress") .getValue().asString()); assertEquals("Bilbo Baggins", receiptPage1Fields.get("MerchantName") .getValue().asString()); assertEquals(EXPECTED_MULTIPAGE_PHONE_NUMBER_VALUE, receiptPage1Fields.get("MerchantPhoneNumber") .getValue().asPhoneNumber()); assertNotNull(receiptPage1Fields.get("Total").getValue().asFloat()); assertNotNull(receiptPage1.getPages()); assertEquals(ITEMIZED_RECEIPT_VALUE, receiptPage1Fields.get("ReceiptType").getValue().asString()); assertEquals(0, receiptPage2.getFields().size()); List<FormPage> receipt2Pages = receiptPage2.getPages(); assertEquals(1, receipt2Pages.size()); assertEquals(0, receipt2Pages.stream().findFirst().get().getTables().size()); assertEquals(0, receipt2Pages.stream().findFirst().get().getLines().size()); assertEquals(2, receiptPage2.getPageRange().getFirstPageNumber()); assertEquals(2, receiptPage2.getPageRange().getLastPageNumber()); assertEquals(3, receiptPage3.getPageRange().getFirstPageNumber()); assertEquals(3, receiptPage3.getPageRange().getLastPageNumber()); Map<String, FormField> receiptPage3Fields = receiptPage3.getFields(); assertEquals(EXPECTED_MULTIPAGE_ADDRESS_VALUE, receiptPage3Fields.get("MerchantAddress").getValue().asString()); assertEquals("Frodo Baggins", receiptPage3Fields.get("MerchantName").getValue().asString()); assertEquals(EXPECTED_MULTIPAGE_PHONE_NUMBER_VALUE, receiptPage3Fields.get("MerchantPhoneNumber").getValue().asPhoneNumber()); assertNotNull(receiptPage3Fields.get("Total").getValue().asFloat()); assertEquals(3000.0f, receiptPage3Fields.get("Subtotal").getValue().asFloat()); assertEquals(ITEMIZED_RECEIPT_VALUE, receiptPage3Fields.get("ReceiptType").getValue().asString()); } protected String getEndpoint() { return interceptorManager.isPlaybackMode() ? "https: : Configuration.getGlobalConfiguration().get(AZURE_FORM_RECOGNIZER_ENDPOINT); } /** * Get the training data set SAS Url value based on the test running mode. * * @return the training data set Url */ private String getTrainingSasUri() { if (interceptorManager.isPlaybackMode()) { return "https: } else { return Configuration.getGlobalConfiguration().get(FORM_RECOGNIZER_TRAINING_BLOB_CONTAINER_SAS_URL); } } /** * Get the training data set SAS Url value based on the test running mode. * * @return the training data set Url */ private String getMultipageTrainingSasUri() { if (interceptorManager.isPlaybackMode()) { return "https: } else { return Configuration.getGlobalConfiguration() .get(FORM_RECOGNIZER_MULTIPAGE_TRAINING_BLOB_CONTAINER_SAS_URL); } } /** * Get the testing data set SAS Url value based on the test running mode. * * @return the testing data set Url */ private String getTestingSasUri() { if (interceptorManager.isPlaybackMode()) { return "https: } else { return Configuration.getGlobalConfiguration().get("FORM_RECOGNIZER_TESTING_BLOB_CONTAINER_SAS_URL"); } } /** * Prepare the file url from the testing data set SAS Url value. * * @return the testing data specific file Url */ private String getStorageTestingFileUrl(String fileName) { if (interceptorManager.isPlaybackMode()) { return "https: } else { final String[] urlParts = getTestingSasUri().split("\\?"); return urlParts[0] + "/" + fileName + "?" + urlParts[1]; } } /** * Prepare the expected test data from service raw response. * * @return the {@code AnalyzeOperationResult} test data */ private AnalyzeOperationResult getAnalyzeRawResponse() { final SerializerAdapter serializerAdapter = getSerializerAdapter(); final NetworkCallRecord networkCallRecord = interceptorManager.getRecordedData().findFirstAndRemoveNetworkCall(record -> { AnalyzeOperationResult rawModelResponse = deserializeRawResponse(serializerAdapter, record, AnalyzeOperationResult.class); return rawModelResponse != null && rawModelResponse.getStatus() == OperationStatus.SUCCEEDED; }); interceptorManager.getRecordedData().addNetworkCall(networkCallRecord); return deserializeRawResponse(serializerAdapter, networkCallRecord, AnalyzeOperationResult.class); } }
class FormRecognizerClientTestBase extends TestBase { private static final Pattern NON_DIGIT_PATTERN = Pattern.compile("[^0-9]+"); private static final String EXPECTED_MULTIPAGE_ADDRESS_VALUE = "123 Hobbit Lane 567 Main St. Redmond, WA Redmond," + " WA"; private static final String EXPECTED_MULTIPAGE_PHONE_NUMBER_VALUE = "+15555555555"; private static final String ITEMIZED_RECEIPT_VALUE = "Itemized"; static final String RECEIPT_CONTOSO_JPG = "contoso-allinone.jpg"; static final String RECEIPT_CONTOSO_PNG = "contoso-receipt.png"; static final String INVOICE_6_PDF = "Invoice_6.pdf"; static final String MULTIPAGE_INVOICE_PDF = "multipage_invoice1.pdf"; static final String BUSINESS_CARD_JPG = "businessCard.jpg"; static final String BUSINESS_CARD_PNG = "businessCard.png"; static final String BAD_ARGUMENT_CODE = "BadArgument"; static final String INVALID_IMAGE_ERROR_CODE = "InvalidImage"; static final String INVALID_MODEL_ID_ERROR_CODE = "1001"; static final String MODEL_ID_NOT_FOUND_ERROR_CODE = "1022"; static final String URL_BADLY_FORMATTED_ERROR_CODE = "2001"; static final String UNABLE_TO_READ_FILE_ERROR_CODE = "2005"; static final String HTTPS_EXCEPTION_MESSAGE = "Max retries 3 times exceeded. Error Details: Key credentials require HTTPS to prevent leaking the key."; static final String INVALID_UUID_EXCEPTION_MESSAGE = "Invalid UUID string: "; static final String MODEL_ID_IS_REQUIRED_EXCEPTION_MESSAGE = "'modelId' is required and cannot be null."; static final String INVALID_ENDPOINT = "https: static final String LOCAL_FILE_PATH = "src/test/resources/sample_files/Test/"; static final String ENCODED_EMPTY_SPACE = "{\"source\":\"https: static final List<String> BUSINESS_CARD_FIELDS = Arrays.asList("ContactNames", "JobTitles", "Departments", "Emails", "Websites", "MobilePhones", "OtherPhones", "Faxes", "Addresses", "CompanyNames"); Duration durationTestMode; /** * Use duration of nearly zero value for PLAYBACK test mode, otherwise, use default duration value for LIVE mode. */ @Override protected void beforeTest() { if (interceptorManager.isPlaybackMode()) { durationTestMode = ONE_NANO_DURATION; } else { durationTestMode = DEFAULT_DURATION; } } FormRecognizerClientBuilder getFormRecognizerClientBuilder(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { FormRecognizerClientBuilder builder = new FormRecognizerClientBuilder() .endpoint(getEndpoint()) .httpClient(httpClient == null ? interceptorManager.getPlaybackClient() : httpClient) .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)) .serviceVersion(serviceVersion) .addPolicy(interceptorManager.getRecordPolicy()); if (getTestMode() == TestMode.PLAYBACK) { builder.credential(new AzureKeyCredential(INVALID_KEY)); } else { builder.credential(new DefaultAzureCredentialBuilder().build()); } return builder; } FormTrainingClientBuilder getFormTrainingClientBuilder(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) { FormTrainingClientBuilder builder = new FormTrainingClientBuilder() .endpoint(getEndpoint()) .httpClient(httpClient == null ? interceptorManager.getPlaybackClient() : httpClient) .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)) .serviceVersion(serviceVersion) .addPolicy(interceptorManager.getRecordPolicy()); if (getTestMode() == TestMode.PLAYBACK) { builder.credential(new AzureKeyCredential(INVALID_KEY)); } else { builder.credential(new AzureKeyCredential(Configuration.getGlobalConfiguration().get(AZURE_FORM_RECOGNIZER_API_KEY))); } return builder; } private static void validateReferenceElementsData(List<String> expectedElements, List<FormElement> actualFormElementList, List<ReadResult> readResults) { if (expectedElements != null && actualFormElementList != null) { assertEquals(expectedElements.size(), actualFormElementList.size()); for (int i = 0; i < actualFormElementList.size(); i++) { String[] indices = NON_DIGIT_PATTERN.matcher(expectedElements.get(i)).replaceAll(" ").trim().split(" "); if (indices.length < 2) { return; } int readResultIndex = Integer.parseInt(indices[0]); int lineIndex = Integer.parseInt(indices[1]); if (indices.length == 3) { int wordIndex = Integer.parseInt(indices[2]); TextWord expectedTextWord = readResults.get(readResultIndex).getLines().get(lineIndex).getWords().get(wordIndex); TextLine expectedTextLine = readResults.get(readResultIndex).getLines().get(lineIndex); if (actualFormElementList.get(i) instanceof FormLine) { FormLine actualFormLine = (FormLine) actualFormElementList.get(i); validateFormWordData(expectedTextLine.getWords(), actualFormLine.getWords()); } FormWord actualFormWord = (FormWord) actualFormElementList.get(i); assertEquals(expectedTextWord.getText(), actualFormWord.getText()); if (expectedTextWord.getConfidence() != null) { assertEquals(expectedTextWord.getConfidence(), actualFormWord.getConfidence()); } else { assertEquals(1.0f, actualFormWord.getConfidence()); } validateBoundingBoxData(expectedTextWord.getBoundingBox(), actualFormWord.getBoundingBox()); } } } } private static void validateFormTableData(List<DataTable> expectedFormTables, List<FormTable> actualFormTable, List<ReadResult> readResults, boolean includeFieldElements, int pageNumber) { assertEquals(expectedFormTables.size(), actualFormTable.size()); for (int i = 0; i < actualFormTable.size(); i++) { DataTable expectedTable = expectedFormTables.get(i); FormTable actualTable = actualFormTable.get(i); assertEquals(pageNumber, actualTable.getPageNumber()); assertEquals(expectedTable.getColumns(), actualTable.getColumnCount()); validateCellData(expectedTable.getCells(), actualTable.getCells(), readResults, includeFieldElements); assertEquals(expectedTable.getRows(), actualTable.getRowCount()); } } private static void validateCellData(List<DataTableCell> expectedTableCells, List<FormTableCell> actualTableCellList, List<ReadResult> readResults, boolean includeFieldElements) { assertEquals(expectedTableCells.size(), actualTableCellList.size()); for (int i = 0; i < actualTableCellList.size(); i++) { DataTableCell expectedTableCell = expectedTableCells.get(i); FormTableCell actualTableCell = actualTableCellList.get(i); assertEquals(expectedTableCell.getColumnIndex(), actualTableCell.getColumnIndex()); if (expectedTableCell.getColumnSpan() != null) { assertEquals(expectedTableCell.getColumnSpan(), actualTableCell.getColumnSpan()); } assertNotNull(actualTableCell.getColumnSpan()); assertEquals(expectedTableCell.getRowIndex(), actualTableCell.getRowIndex()); if (expectedTableCell.getRowSpan() != null) { assertEquals(expectedTableCell.getRowSpan(), actualTableCell.getRowSpan()); } assertNotNull(actualTableCell.getRowSpan()); validateBoundingBoxData(expectedTableCell.getBoundingBox(), actualTableCell.getBoundingBox()); if (includeFieldElements) { validateReferenceElementsData(expectedTableCell.getElements(), actualTableCell.getFieldElements(), readResults); } } } private static void validateFormLineData(List<TextLine> expectedLines, List<FormLine> actualLineList) { assertEquals(expectedLines.size(), actualLineList.size()); for (int i = 0; i < actualLineList.size(); i++) { TextLine expectedLine = expectedLines.get(i); FormLine actualLine = actualLineList.get(i); assertEquals(expectedLine.getText(), actualLine.getText()); validateBoundingBoxData(expectedLine.getBoundingBox(), actualLine.getBoundingBox()); validateFormWordData(expectedLine.getWords(), actualLine.getWords()); } } private static void validateFormWordData(List<TextWord> expectedFormWords, List<FormWord> actualFormWordList) { assertEquals(expectedFormWords.size(), actualFormWordList.size()); for (int i = 0; i < actualFormWordList.size(); i++) { TextWord expectedWord = expectedFormWords.get(i); FormWord actualWord = actualFormWordList.get(i); assertEquals(expectedWord.getText(), actualWord.getText()); validateBoundingBoxData(expectedWord.getBoundingBox(), actualWord.getBoundingBox()); if (expectedWord.getConfidence() != null) { assertEquals(expectedWord.getConfidence(), actualWord.getConfidence()); } else { assertEquals(1.0f, actualWord.getConfidence()); } } } private static void validateBoundingBoxData(List<Float> expectedBoundingBox, FieldBoundingBox actualFieldBoundingBox) { if (actualFieldBoundingBox != null && actualFieldBoundingBox.getPoints() != null) { int i = 0; for (Point point : actualFieldBoundingBox.getPoints()) { assertEquals(expectedBoundingBox.get(i), point.getX()); assertEquals(expectedBoundingBox.get(++i), point.getY()); i++; } } } @SuppressWarnings("unchecked") private static void validateFieldValueTransforms(FieldValue expectedFieldValue, FormField actualFormField, List<ReadResult> readResults, boolean includeFieldElements) { if (expectedFieldValue != null) { if (expectedFieldValue.getBoundingBox() != null) { validateBoundingBoxData(expectedFieldValue.getBoundingBox(), actualFormField.getValueData().getBoundingBox()); } if (includeFieldElements && expectedFieldValue.getElements() != null) { validateReferenceElementsData(expectedFieldValue.getElements(), actualFormField.getValueData().getFieldElements(), readResults); } switch (expectedFieldValue.getType()) { case NUMBER: if (expectedFieldValue.getValueNumber() != null) { assertEquals(expectedFieldValue.getValueNumber(), actualFormField.getValue().asFloat()); } break; case DATE: assertEquals(expectedFieldValue.getValueDate(), actualFormField.getValue().asDate()); break; case TIME: assertEquals(LocalTime.parse(expectedFieldValue.getValueTime(), DateTimeFormatter.ofPattern("HH:mm:ss")), actualFormField.getValue().asTime()); break; case STRING: if (actualFormField.getName() != "ReceiptType") { assertEquals(expectedFieldValue.getValueString(), actualFormField.getValue().asString()); } break; case INTEGER: assertEquals(expectedFieldValue.getValueInteger(), actualFormField.getValue().asLong()); break; case PHONE_NUMBER: assertEquals(expectedFieldValue.getValuePhoneNumber(), actualFormField.getValue().asPhoneNumber()); break; case OBJECT: expectedFieldValue.getValueObject().forEach((key, formField) -> { FormField actualFormFieldValue = actualFormField.getValue().asMap().get(key); validateFieldValueTransforms(formField, actualFormFieldValue, readResults, includeFieldElements); }); break; case ARRAY: assertEquals(expectedFieldValue.getValueArray().size(), actualFormField.getValue().asList().size()); for (int i = 0; i < expectedFieldValue.getValueArray().size(); i++) { FieldValue expectedReceiptItem = expectedFieldValue.getValueArray().get(i); FormField actualReceiptItem = actualFormField.getValue().asList().get(i); validateFieldValueTransforms(expectedReceiptItem, actualReceiptItem, readResults, includeFieldElements); } break; default: assertFalse(false, "Field type not supported."); } } } private static void validatePageRangeData(int expectedPageInfo, FormPageRange actualPageInfo) { assertEquals(expectedPageInfo, actualPageInfo.getFirstPageNumber()); assertEquals(expectedPageInfo, actualPageInfo.getLastPageNumber()); } @Test abstract void recognizeReceiptData(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeReceiptDataNullData(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeReceiptDataWithContentTypeAutoDetection(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeReceiptDataIncludeFieldElements(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeReceiptDataWithPngFile(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeReceiptDataWithBlankPdf(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeReceiptFromDataMultiPage(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeReceiptSourceUrl(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeReceiptInvalidSourceUrl(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeReceiptFromUrlIncludeFieldElements(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeReceiptSourceUrlWithPngFile(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeReceiptFromUrlMultiPage(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeContent(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeContentResultWithNullData(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeContentResultWithContentTypeAutoDetection(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeContentResultWithBlankPdf(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeContentFromDataMultiPage(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeContentFromUrl(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeContentFromUrlWithPdf(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeContentInvalidSourceUrl(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeContentFromUrlMultiPage(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormLabeledData(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormLabeledDataWithJpgContentType(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormLabeledDataWithBlankPdfContentType(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormLabeledDataExcludeFieldElements(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormLabeledDataWithNullFormData(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormLabeledDataWithNullModelId(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormLabeledDataWithEmptyModelId(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormInvalidStatus(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormLabeledDataWithContentTypeAutoDetection(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormMultiPageLabeled(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormUnlabeledData(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormUnlabeledDataIncludeFieldElements(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormMultiPageUnlabeled(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormUnlabeledDataWithJpgContentType(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormUnlabeledDataWithBlankPdfContentType(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormUrlUnlabeledData(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormUrlUnlabeledDataIncludeFieldElements(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormUrlMultiPageUnlabeled(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormInvalidSourceUrl(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormFromUrlLabeledDataWithNullModelId(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormFromUrlLabeledDataWithEmptyModelId(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormUrlLabeledData(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormUrlLabeledDataIncludeFieldElements(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeCustomFormUrlMultiPageLabeled(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeBusinessCardData(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeBusinessCardDataNullData(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeBusinessCardDataWithContentTypeAutoDetection(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeBusinessCardDataIncludeFieldElements(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeBusinessCardDataWithPngFile(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeBusinessCardDataWithBlankPdf(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeBusinessCardFromDamagedPdf(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeBusinessCardSourceUrl(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeBusinessCardFromUrlWithEncodedBlankSpaceSourceUrl(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeBusinessCardInvalidSourceUrl(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeBusinessCardFromUrlIncludeFieldElements(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); @Test abstract void recognizeBusinessCardSourceUrlWithPngFile(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion); void validateReceiptDataFields(Map<String, FormField> actualRecognizedReceiptFields, boolean includeFieldElements) { final AnalyzeResult analyzeResult = getAnalyzeRawResponse().getAnalyzeResult(); List<ReadResult> readResults = analyzeResult.getReadResults(); DocumentResult documentResult = analyzeResult.getDocumentResults().get(0); Map<String, FieldValue> expectedReceiptFields = documentResult.getFields(); assertEquals(expectedReceiptFields.get("ReceiptType").getValueString(), actualRecognizedReceiptFields.get("ReceiptType").getValue().asString()); assertEquals(expectedReceiptFields.get("ReceiptType").getConfidence(), actualRecognizedReceiptFields.get("ReceiptType").getConfidence()); validateFieldValueTransforms(expectedReceiptFields.get("MerchantName"), actualRecognizedReceiptFields.get("MerchantName"), readResults, includeFieldElements); validateFieldValueTransforms(expectedReceiptFields.get("MerchantPhoneNumber"), actualRecognizedReceiptFields.get("MerchantPhoneNumber"), readResults, includeFieldElements); validateFieldValueTransforms(expectedReceiptFields.get("MerchantAddress"), actualRecognizedReceiptFields.get("MerchantAddress"), readResults, includeFieldElements); validateFieldValueTransforms(expectedReceiptFields.get("Total"), actualRecognizedReceiptFields.get("Total"), readResults, includeFieldElements); validateFieldValueTransforms(expectedReceiptFields.get("Subtotal"), actualRecognizedReceiptFields.get("Subtotal"), readResults, includeFieldElements); validateFieldValueTransforms(expectedReceiptFields.get("Tax"), actualRecognizedReceiptFields.get("Tax"), readResults, includeFieldElements); validateFieldValueTransforms(expectedReceiptFields.get("TransactionDate"), actualRecognizedReceiptFields.get("TransactionDate"), readResults, includeFieldElements); validateFieldValueTransforms(expectedReceiptFields.get("TransactionTime"), actualRecognizedReceiptFields.get("TransactionTime"), readResults, includeFieldElements); validateFieldValueTransforms(expectedReceiptFields.get("Items"), actualRecognizedReceiptFields.get("Items"), readResults, includeFieldElements); } void validateContentResultData(List<FormPage> actualFormPageList, boolean includeFieldElements) { AnalyzeResult analyzeResult = getAnalyzeRawResponse().getAnalyzeResult(); final List<PageResult> pageResults = analyzeResult.getPageResults(); final List<ReadResult> readResults = analyzeResult.getReadResults(); for (int i = 0; i < actualFormPageList.size(); i++) { FormPage actualFormPage = actualFormPageList.get(i); ReadResult readResult = readResults.get(i); if (readResult.getAngle() > 180) { assertEquals(readResult.getAngle() - 360, actualFormPage.getTextAngle()); } else { assertEquals(readResult.getAngle(), actualFormPage.getTextAngle()); } assertEquals(readResult.getWidth(), actualFormPage.getWidth()); assertEquals(readResult.getHeight(), actualFormPage.getHeight()); assertEquals(readResult.getUnit().toString(), actualFormPage.getUnit().toString()); assertEquals(readResult.getPage(), actualFormPage.getPageNumber()); if (includeFieldElements) { validateFormLineData(readResult.getLines(), actualFormPage.getLines()); } if (pageResults != null) { validateFormTableData(pageResults.get(i).getTables(), actualFormPage.getTables(), readResults, includeFieldElements, pageResults.get(i).getPage()); } } } void validateReceiptResultData(List<RecognizedForm> actualReceiptList, boolean includeFieldElements) { final AnalyzeResult rawResponse = getAnalyzeRawResponse().getAnalyzeResult(); for (int i = 0; i < actualReceiptList.size(); i++) { final RecognizedForm actualReceipt = actualReceiptList.get(i); validateLabeledData(actualReceipt, includeFieldElements, rawResponse.getReadResults(), rawResponse.getDocumentResults().get(i)); validateReceiptDataFields(actualReceipt.getFields(), includeFieldElements); } } void validateBlankPdfResultData(List<RecognizedForm> actualReceiptList) { assertEquals(1, actualReceiptList.size()); final RecognizedForm actualReceipt = actualReceiptList.get(0); assertTrue(actualReceipt.getFields().isEmpty()); } void validateRecognizedResult(List<RecognizedForm> actualFormList, boolean includeFieldElements, boolean isLabeled) { final AnalyzeResult rawResponse = getAnalyzeRawResponse().getAnalyzeResult(); List<ReadResult> readResults = rawResponse.getReadResults(); List<PageResult> pageResults = rawResponse.getPageResults(); List<DocumentResult> documentResults = rawResponse.getDocumentResults(); for (int i = 0; i < actualFormList.size(); i++) { validateContentResultData(actualFormList.get(i).getPages(), includeFieldElements); if (isLabeled) { validateLabeledData(actualFormList.get(i), includeFieldElements, readResults, documentResults.get(i)); } else { validateUnLabeledResult(actualFormList.get(i), includeFieldElements, readResults, pageResults.get(i)); } } } void validateBusinessCardResultData(List<RecognizedForm> actualBusinessCardList, boolean includeFieldElements) { final AnalyzeResult rawResponse = getAnalyzeRawResponse().getAnalyzeResult(); for (int i = 0; i < actualBusinessCardList.size(); i++) { final RecognizedForm actualBusinessCard = actualBusinessCardList.get(i); validateLabeledData(actualBusinessCard, includeFieldElements, rawResponse.getReadResults(), rawResponse.getDocumentResults().get(i)); validateBusinessCardDataFields(actualBusinessCard.getFields(), includeFieldElements); } } void invalidSourceUrlRunner(Consumer<String> testRunner) { testRunner.accept(TestUtils.INVALID_RECEIPT_URL); } void encodedBlankSpaceSourceUrlRunner(Consumer<String> testRunner) { testRunner.accept(FAKE_ENCODED_EMPTY_SPACE_URL); } void urlRunner(Consumer<String> testRunner, String fileName) { testRunner.accept(URL_TEST_FILE_FORMAT + fileName); } void storageUrlRunner(Consumer<String> testRunner, String fileName) { testRunner.accept(getStorageTestingFileUrl(fileName)); } void urlPdfUnlabeledRunner(Consumer<String> testRunner) { testRunner.accept(getStorageTestingFileUrl(MULTIPAGE_INVOICE_PDF)); } void dataRunner(BiConsumer<InputStream, Long> testRunner, String fileName) { final long fileLength = new File(LOCAL_FILE_PATH + fileName).length(); if (interceptorManager.isPlaybackMode()) { testRunner.accept(new ByteArrayInputStream(TEST_DATA_PNG.getBytes(StandardCharsets.UTF_8)), fileLength); } else { try { testRunner.accept(new FileInputStream(LOCAL_FILE_PATH + fileName), fileLength); } catch (FileNotFoundException e) { throw new RuntimeException("Local file not found.", e); } } } void localFilePathRunner(BiConsumer<String, Long> testRunner, String fileName) { final long fileLength = new File(LOCAL_FILE_PATH + fileName).length(); testRunner.accept(LOCAL_FILE_PATH + fileName, fileLength); } void damagedPdfDataRunner(BiConsumer<InputStream, Integer> testRunner) { testRunner.accept(new ByteArrayInputStream(new byte[]{0x25, 0x50, 0x44, 0x46, 0x55, 0x55, 0x55}), 7); } void beginTrainingUnlabeledRunner(BiConsumer<String, Boolean> testRunner) { testRunner.accept(getTrainingSasUri(), false); } void beginTrainingLabeledRunner(BiConsumer<String, Boolean> testRunner) { testRunner.accept(getTrainingSasUri(), true); } void beginTrainingMultipageRunner(Consumer<String> testRunner) { testRunner.accept(getMultipageTrainingSasUri()); } private void validateUnLabeledResult(RecognizedForm actualForm, boolean includeFieldElements, List<ReadResult> readResults, PageResult expectedPage) { validatePageRangeData(expectedPage.getPage(), actualForm.getPageRange()); int i = 0; for (Map.Entry<String, FormField> entry : actualForm.getFields().entrySet()) { FormField actualFormField = entry.getValue(); final KeyValuePair expectedFormField = expectedPage.getKeyValuePairs().get(i++); assertEquals(expectedFormField.getConfidence(), actualFormField.getConfidence()); assertEquals(expectedFormField.getKey().getText(), actualFormField.getLabelData().getText()); validateBoundingBoxData(expectedFormField.getKey().getBoundingBox(), actualFormField.getLabelData().getBoundingBox()); if (includeFieldElements) { validateReferenceElementsData(expectedFormField.getKey().getElements(), actualFormField.getLabelData().getFieldElements(), readResults); validateReferenceElementsData(expectedFormField.getValue().getElements(), actualFormField.getValueData().getFieldElements(), readResults); } assertEquals(expectedFormField.getValue().getText(), actualFormField.getValueData().getText()); validateBoundingBoxData(expectedFormField.getValue().getBoundingBox(), actualFormField.getValueData().getBoundingBox()); } } private void validateLabeledData(RecognizedForm actualForm, boolean includeFieldElements, List<ReadResult> readResults, DocumentResult documentResult) { assertEquals(documentResult.getPageRange().get(0), actualForm.getPageRange().getFirstPageNumber()); assertEquals(documentResult.getPageRange().get(1), actualForm.getPageRange().getLastPageNumber()); assertEquals(documentResult.getFields().keySet(), actualForm.getFields().keySet()); documentResult.getFields().forEach((label, expectedFieldValue) -> { final FormField actualFormField = actualForm.getFields().get(label); assertEquals(label, actualFormField.getName()); if (expectedFieldValue != null) { if (expectedFieldValue.getConfidence() != null) { assertEquals(expectedFieldValue.getConfidence(), actualFormField.getConfidence()); } else { assertEquals(1.0f, actualFormField.getConfidence()); } validateFieldValueTransforms(expectedFieldValue, actualFormField, readResults, includeFieldElements); } }); } static void validateMultiPageDataLabeled(List<RecognizedForm> actualRecognizedFormsList) { actualRecognizedFormsList.forEach(recognizedForm -> { assertEquals(1, recognizedForm.getPageRange().getFirstPageNumber()); assertEquals(3, recognizedForm.getPageRange().getLastPageNumber()); assertEquals(3, recognizedForm.getPages().size()); recognizedForm.getFields().forEach((label, formField) -> { assertNotNull(formField.getName()); assertNotNull(formField.getValue()); assertNotNull(formField.getValueData().getText()); assertNull(formField.getLabelData()); }); }); } static void validateMultiPageDataUnlabeled(List<RecognizedForm> actualRecognizedFormsList) { actualRecognizedFormsList.forEach(recognizedForm -> { assertNotNull(recognizedForm.getFormType()); assertEquals(1, (long) recognizedForm.getPages().size()); recognizedForm.getFields().forEach((label, formField) -> { assertNotNull(formField.getName()); assertNotNull(formField.getValue()); assertNotNull(formField.getValueData().getText()); assertNotNull(formField.getLabelData().getText()); }); }); } static void validateMultipageReceiptData(List<RecognizedForm> recognizedReceipts) { assertEquals(3, recognizedReceipts.size()); RecognizedForm receiptPage1 = recognizedReceipts.get(0); RecognizedForm receiptPage2 = recognizedReceipts.get(1); RecognizedForm receiptPage3 = recognizedReceipts.get(2); assertEquals(1, receiptPage1.getPageRange().getFirstPageNumber()); assertEquals(1, receiptPage1.getPageRange().getLastPageNumber()); Map<String, FormField> receiptPage1Fields = receiptPage1.getFields(); assertEquals(EXPECTED_MULTIPAGE_ADDRESS_VALUE, receiptPage1Fields.get("MerchantAddress") .getValue().asString()); assertEquals("Bilbo Baggins", receiptPage1Fields.get("MerchantName") .getValue().asString()); assertEquals(EXPECTED_MULTIPAGE_PHONE_NUMBER_VALUE, receiptPage1Fields.get("MerchantPhoneNumber") .getValue().asPhoneNumber()); assertNotNull(receiptPage1Fields.get("Total").getValue().asFloat()); assertNotNull(receiptPage1.getPages()); assertEquals(ITEMIZED_RECEIPT_VALUE, receiptPage1Fields.get("ReceiptType").getValue().asString()); assertEquals(0, receiptPage2.getFields().size()); List<FormPage> receipt2Pages = receiptPage2.getPages(); assertEquals(1, receipt2Pages.size()); assertEquals(0, receipt2Pages.stream().findFirst().get().getTables().size()); assertEquals(0, receipt2Pages.stream().findFirst().get().getLines().size()); assertEquals(2, receiptPage2.getPageRange().getFirstPageNumber()); assertEquals(2, receiptPage2.getPageRange().getLastPageNumber()); assertEquals(3, receiptPage3.getPageRange().getFirstPageNumber()); assertEquals(3, receiptPage3.getPageRange().getLastPageNumber()); Map<String, FormField> receiptPage3Fields = receiptPage3.getFields(); assertEquals(EXPECTED_MULTIPAGE_ADDRESS_VALUE, receiptPage3Fields.get("MerchantAddress").getValue().asString()); assertEquals("Frodo Baggins", receiptPage3Fields.get("MerchantName").getValue().asString()); assertEquals(EXPECTED_MULTIPAGE_PHONE_NUMBER_VALUE, receiptPage3Fields.get("MerchantPhoneNumber").getValue().asPhoneNumber()); assertNotNull(receiptPage3Fields.get("Total").getValue().asFloat()); assertEquals(3000.0f, receiptPage3Fields.get("Subtotal").getValue().asFloat()); assertEquals(ITEMIZED_RECEIPT_VALUE, receiptPage3Fields.get("ReceiptType").getValue().asString()); } protected String getEndpoint() { return interceptorManager.isPlaybackMode() ? "https: : Configuration.getGlobalConfiguration().get(AZURE_FORM_RECOGNIZER_ENDPOINT); } /** * Get the training data set SAS Url value based on the test running mode. * * @return the training data set Url */ private String getTrainingSasUri() { if (interceptorManager.isPlaybackMode()) { return "https: } else { return Configuration.getGlobalConfiguration().get(FORM_RECOGNIZER_TRAINING_BLOB_CONTAINER_SAS_URL); } } /** * Get the training data set SAS Url value based on the test running mode. * * @return the training data set Url */ private String getMultipageTrainingSasUri() { if (interceptorManager.isPlaybackMode()) { return "https: } else { return Configuration.getGlobalConfiguration() .get(FORM_RECOGNIZER_MULTIPAGE_TRAINING_BLOB_CONTAINER_SAS_URL); } } /** * Get the testing data set SAS Url value based on the test running mode. * * @return the testing data set Url */ private String getTestingSasUri() { if (interceptorManager.isPlaybackMode()) { return "https: } else { return Configuration.getGlobalConfiguration().get("FORM_RECOGNIZER_TESTING_BLOB_CONTAINER_SAS_URL"); } } /** * Prepare the file url from the testing data set SAS Url value. * * @return the testing data specific file Url */ private String getStorageTestingFileUrl(String fileName) { if (interceptorManager.isPlaybackMode()) { return "https: } else { final String[] urlParts = getTestingSasUri().split("\\?"); return urlParts[0] + "/" + fileName + "?" + urlParts[1]; } } /** * Prepare the expected test data from service raw response. * * @return the {@code AnalyzeOperationResult} test data */ private AnalyzeOperationResult getAnalyzeRawResponse() { final SerializerAdapter serializerAdapter = getSerializerAdapter(); final NetworkCallRecord networkCallRecord = interceptorManager.getRecordedData().findFirstAndRemoveNetworkCall(record -> { AnalyzeOperationResult rawModelResponse = deserializeRawResponse(serializerAdapter, record, AnalyzeOperationResult.class); return rawModelResponse != null && rawModelResponse.getStatus() == OperationStatus.SUCCEEDED; }); interceptorManager.getRecordedData().addNetworkCall(networkCallRecord); return deserializeRawResponse(serializerAdapter, networkCallRecord, AnalyzeOperationResult.class); } }
Do we want the request headers to have the keys of `tracestate` and `traceparent` with empty values ? >traceparentHeader != null ? String.format(",\"%s\":\"%s\"", Constants.TRACE_PARENT, traceparentHeader.getValue()) : "") I think we should skip updating the key value if `traceparentHeader == null`.
static String replaceTracingPlaceHolder(HttpRequest request, StringBuilder bodyStringBuilder) { final int traceParentPlaceHolderIndex = bodyStringBuilder.indexOf(Constants.TRACE_PARENT_PLACEHOLDER); if (traceParentPlaceHolderIndex >= 0) { final HttpHeader traceparentHeader = request.getHeaders().get(Constants.TRACE_PARENT); bodyStringBuilder.replace(traceParentPlaceHolderIndex, Constants.TRACE_PARENT_PLACEHOLDER.length() + traceParentPlaceHolderIndex, traceparentHeader != null ? String.format(",\"%s\":\"%s\"", Constants.TRACE_PARENT, traceparentHeader.getValue()) : ""); } final int traceStatePlaceHolderIndex = bodyStringBuilder.indexOf(Constants.TRACE_STATE_PLACEHOLDER); if (traceStatePlaceHolderIndex >= 0) { final HttpHeader tracestateHeader = request.getHeaders().get(Constants.TRACE_STATE); bodyStringBuilder.replace(traceStatePlaceHolderIndex, Constants.TRACE_STATE_PLACEHOLDER.length() + traceStatePlaceHolderIndex, tracestateHeader != null ? String.format(",\"%s\":\"%s\"", Constants.TRACE_STATE, tracestateHeader.getValue()) : ""); } String newBodyString = bodyStringBuilder.toString(); request.setHeader(Constants.CONTENT_LENGTH, String.valueOf(newBodyString.length())); request.setBody(newBodyString); return newBodyString; }
: "");
static String replaceTracingPlaceHolder(HttpRequest request, StringBuilder bodyStringBuilder) { final int traceParentPlaceHolderIndex = bodyStringBuilder.indexOf(Constants.TRACE_PARENT_PLACEHOLDER); if (traceParentPlaceHolderIndex >= 0) { final HttpHeader traceparentHeader = request.getHeaders().get(Constants.TRACE_PARENT); bodyStringBuilder.replace(traceParentPlaceHolderIndex, Constants.TRACE_PARENT_PLACEHOLDER.length() + traceParentPlaceHolderIndex, traceparentHeader != null ? String.format(",\"%s\":\"%s\"", Constants.TRACE_PARENT, traceparentHeader.getValue()) : ""); } final int traceStatePlaceHolderIndex = bodyStringBuilder.indexOf(Constants.TRACE_STATE_PLACEHOLDER); if (traceStatePlaceHolderIndex >= 0) { final HttpHeader tracestateHeader = request.getHeaders().get(Constants.TRACE_STATE); bodyStringBuilder.replace(traceStatePlaceHolderIndex, Constants.TRACE_STATE_PLACEHOLDER.length() + traceStatePlaceHolderIndex, tracestateHeader != null ? String.format(",\"%s\":\"%s\"", Constants.TRACE_STATE, tracestateHeader.getValue()) : ""); } String newBodyString = bodyStringBuilder.toString(); request.setHeader(Constants.CONTENT_LENGTH, String.valueOf(newBodyString.length())); request.setBody(newBodyString); return newBodyString; }
class CloudEventTracingPipelinePolicy implements HttpPipelinePolicy { @Override public Mono<HttpResponse> process(HttpPipelineCallContext context, HttpPipelineNextPolicy next) { final HttpRequest request = context.getHttpRequest(); final HttpHeader contentType = request.getHeaders().get(Constants.CONTENT_TYPE); StringBuilder bodyStringBuilder = new StringBuilder(); if (TracerProxy.isTracingEnabled() && contentType != null && Constants.CLOUD_EVENT_CONTENT_TYPE.equals(contentType.getValue())) { return request.getBody().map(byteBuffer -> bodyStringBuilder.append(new String(byteBuffer.array(), StandardCharsets.UTF_8))) .then(Mono.fromCallable(() -> replaceTracingPlaceHolder(request, bodyStringBuilder))) .then(next.process()); } else { return next.process(); } } /** * * @param request The {@link HttpRequest}, whose body will be mutated by replacing traceparent and tracestate * placeholders. * @param bodyStringBuilder The {@link StringBuilder} that contains the full HttpRequest body string. * @return The new body string with the place holders replaced (if header has tracing) * or removed (if header no tracing). */ }
class CloudEventTracingPipelinePolicy implements HttpPipelinePolicy { @Override public Mono<HttpResponse> process(HttpPipelineCallContext context, HttpPipelineNextPolicy next) { final HttpRequest request = context.getHttpRequest(); final HttpHeader contentType = request.getHeaders().get(Constants.CONTENT_TYPE); StringBuilder bodyStringBuilder = new StringBuilder(); if (TracerProxy.isTracingEnabled() && contentType != null && Constants.CLOUD_EVENT_CONTENT_TYPE.equals(contentType.getValue())) { return request.getBody().map(byteBuffer -> bodyStringBuilder.append(new String(byteBuffer.array(), StandardCharsets.UTF_8))) .then(Mono.fromCallable(() -> replaceTracingPlaceHolder(request, bodyStringBuilder))) .then(next.process()); } else { return next.process(); } } /** * * @param request The {@link HttpRequest}, whose body will be mutated by replacing traceparent and tracestate * placeholders. * @param bodyStringBuilder The {@link StringBuilder} that contains the full HttpRequest body string. * @return The new body string with the place holders replaced (if header has tracing) * or removed (if header no tracing). */ }
It is better to catch the MalformedURLException and wrap it with IllegalArgumentException with a custom message and attach the MalformedURLException as a cause.
public static KeyVaultCertificateIdentifier parse(String certificateId) throws IllegalArgumentException, MalformedURLException { if (certificateId == null) { throw new IllegalArgumentException("certificateId cannot be null"); } URL url = new URL(certificateId); String[] pathSegments = url.getPath().split("/"); if ((pathSegments.length != 3 && pathSegments.length != 4) || !"https".equals(url.getProtocol()) || (!"certificates".equals(pathSegments[1]) && !"deletedcertificates".equals(pathSegments[1])) || ("deletedcertificates".equals(pathSegments[1]) && pathSegments.length == 4)) { throw new IllegalArgumentException("certificateId is not a valid Key Vault Certificate identifier"); } return new KeyVaultCertificateIdentifier(certificateId, url.getProtocol() + ": pathSegments[2], pathSegments.length == 4 ? pathSegments[3] : null); }
URL url = new URL(certificateId);
public static KeyVaultCertificateIdentifier parse(String certificateId) throws IllegalArgumentException { if (certificateId == null) { throw new IllegalArgumentException("certificateId cannot be null"); } try { final URL url = new URL(certificateId); final String[] pathSegments = url.getPath().split("/"); if ((pathSegments.length != 3 && pathSegments.length != 4) || !"https".equals(url.getProtocol()) || (!"certificates".equals(pathSegments[1]) && !"deletedcertificates".equals(pathSegments[1])) || ("deletedcertificates".equals(pathSegments[1]) && pathSegments.length == 4)) { throw new IllegalArgumentException("certificateId is not a valid Key Vault Certificate identifier"); } final String vaultUrl = String.format("%s: final String certificateName = pathSegments[2]; final String certificateVersion = pathSegments.length == 4 ? pathSegments[3] : null; return new KeyVaultCertificateIdentifier(certificateId, vaultUrl, certificateName, certificateVersion); } catch (MalformedURLException e) { throw new IllegalArgumentException("Could not parse certificateId", e); } }
class KeyVaultCertificateIdentifier { private final String certificateId, vaultUrl, name, version; private KeyVaultCertificateIdentifier(String certificateId, String vaultUrl, String name, String version) { this.certificateId = certificateId; this.vaultUrl = vaultUrl; this.name = name; this.version = version; } /** * Gets the key identifier used to create this object * * @return The certificate identifier. */ public String getCertificateId() { return certificateId; } /** * Gets the URL of the Key Vault. * * @return The Key Vault URL. */ public String getVaultUrl() { return vaultUrl; } /** * Gets the name of the certificate. * * @return The certificate name. */ public String getName() { return name; } /** * Gets the optional version of the certificate. * * @return The certificate version. */ public String getVersion() { return version; } /** * Create a new {@link KeyVaultCertificateIdentifier} from a given certificate identifier. * * <p>Valid examples are: * * <ul> * <li>https: * <li>https: * <li>https: * <li>https: * </ul> * * @param certificateId The certificate identifier to extract information from. * @return a new instance of {@link KeyVaultCertificateIdentifier}. * @throws IllegalArgumentException if the given identifier is {@code null}. * @throws MalformedURLException if the given identifier is not a valid Key Vault Certificate identifier */ }
class KeyVaultCertificateIdentifier { private final String certificateId, vaultUrl, name, version; private KeyVaultCertificateIdentifier(String certificateId, String vaultUrl, String name, String version) { this.certificateId = certificateId; this.vaultUrl = vaultUrl; this.name = name; this.version = version; } /** * Gets the key identifier used to create this object * * @return The certificate identifier. */ public String getCertificateId() { return certificateId; } /** * Gets the URL of the Key Vault. * * @return The Key Vault URL. */ public String getVaultUrl() { return vaultUrl; } /** * Gets the name of the certificate. * * @return The certificate name. */ public String getName() { return name; } /** * Gets the optional version of the certificate. * * @return The certificate version. */ public String getVersion() { return version; } /** * Create a new {@link KeyVaultCertificateIdentifier} from a given certificate identifier. * * <p>Valid examples are: * * <ul> * <li>https: * <li>https: * <li>https: * <li>https: * </ul> * * @param certificateId The certificate identifier to extract information from. * @return a new instance of {@link KeyVaultCertificateIdentifier}. * @throws IllegalArgumentException if the given identifier is {@code null} or an invalid Key Vault Certificate * identifier. */ }
this can be refactored and made readable with String.format command.
public static KeyVaultCertificateIdentifier parse(String certificateId) throws IllegalArgumentException, MalformedURLException { if (certificateId == null) { throw new IllegalArgumentException("certificateId cannot be null"); } URL url = new URL(certificateId); String[] pathSegments = url.getPath().split("/"); if ((pathSegments.length != 3 && pathSegments.length != 4) || !"https".equals(url.getProtocol()) || (!"certificates".equals(pathSegments[1]) && !"deletedcertificates".equals(pathSegments[1])) || ("deletedcertificates".equals(pathSegments[1]) && pathSegments.length == 4)) { throw new IllegalArgumentException("certificateId is not a valid Key Vault Certificate identifier"); } return new KeyVaultCertificateIdentifier(certificateId, url.getProtocol() + ": pathSegments[2], pathSegments.length == 4 ? pathSegments[3] : null); }
return new KeyVaultCertificateIdentifier(certificateId, url.getProtocol() + ":
public static KeyVaultCertificateIdentifier parse(String certificateId) throws IllegalArgumentException { if (certificateId == null) { throw new IllegalArgumentException("certificateId cannot be null"); } try { final URL url = new URL(certificateId); final String[] pathSegments = url.getPath().split("/"); if ((pathSegments.length != 3 && pathSegments.length != 4) || !"https".equals(url.getProtocol()) || (!"certificates".equals(pathSegments[1]) && !"deletedcertificates".equals(pathSegments[1])) || ("deletedcertificates".equals(pathSegments[1]) && pathSegments.length == 4)) { throw new IllegalArgumentException("certificateId is not a valid Key Vault Certificate identifier"); } final String vaultUrl = String.format("%s: final String certificateName = pathSegments[2]; final String certificateVersion = pathSegments.length == 4 ? pathSegments[3] : null; return new KeyVaultCertificateIdentifier(certificateId, vaultUrl, certificateName, certificateVersion); } catch (MalformedURLException e) { throw new IllegalArgumentException("Could not parse certificateId", e); } }
class KeyVaultCertificateIdentifier { private final String certificateId, vaultUrl, name, version; private KeyVaultCertificateIdentifier(String certificateId, String vaultUrl, String name, String version) { this.certificateId = certificateId; this.vaultUrl = vaultUrl; this.name = name; this.version = version; } /** * Gets the key identifier used to create this object * * @return The certificate identifier. */ public String getCertificateId() { return certificateId; } /** * Gets the URL of the Key Vault. * * @return The Key Vault URL. */ public String getVaultUrl() { return vaultUrl; } /** * Gets the name of the certificate. * * @return The certificate name. */ public String getName() { return name; } /** * Gets the optional version of the certificate. * * @return The certificate version. */ public String getVersion() { return version; } /** * Create a new {@link KeyVaultCertificateIdentifier} from a given certificate identifier. * * <p>Valid examples are: * * <ul> * <li>https: * <li>https: * <li>https: * <li>https: * </ul> * * @param certificateId The certificate identifier to extract information from. * @return a new instance of {@link KeyVaultCertificateIdentifier}. * @throws IllegalArgumentException if the given identifier is {@code null}. * @throws MalformedURLException if the given identifier is not a valid Key Vault Certificate identifier */ }
class KeyVaultCertificateIdentifier { private final String certificateId, vaultUrl, name, version; private KeyVaultCertificateIdentifier(String certificateId, String vaultUrl, String name, String version) { this.certificateId = certificateId; this.vaultUrl = vaultUrl; this.name = name; this.version = version; } /** * Gets the key identifier used to create this object * * @return The certificate identifier. */ public String getCertificateId() { return certificateId; } /** * Gets the URL of the Key Vault. * * @return The Key Vault URL. */ public String getVaultUrl() { return vaultUrl; } /** * Gets the name of the certificate. * * @return The certificate name. */ public String getName() { return name; } /** * Gets the optional version of the certificate. * * @return The certificate version. */ public String getVersion() { return version; } /** * Create a new {@link KeyVaultCertificateIdentifier} from a given certificate identifier. * * <p>Valid examples are: * * <ul> * <li>https: * <li>https: * <li>https: * <li>https: * </ul> * * @param certificateId The certificate identifier to extract information from. * @return a new instance of {@link KeyVaultCertificateIdentifier}. * @throws IllegalArgumentException if the given identifier is {@code null} or an invalid Key Vault Certificate * identifier. */ }
same feedback as certs.
public static KeyVaultKeyIdentifier parse(String keyId) throws IllegalArgumentException, MalformedURLException { if (keyId == null) { throw new IllegalArgumentException("keyId cannot be null"); } URL url = new URL(keyId); String[] pathSegments = url.getPath().split("/"); if ((pathSegments.length != 3 && pathSegments.length != 4) || !"https".equals(url.getProtocol()) || (!"keys".equals(pathSegments[1]) && !"deletedkeys".equals(pathSegments[1])) || ("deletedkeys".equals(pathSegments[1]) && pathSegments.length == 4)) { throw new IllegalArgumentException("keyId is not a valid Key Vault Key identifier"); } return new KeyVaultKeyIdentifier(keyId, url.getProtocol() + ": pathSegments.length == 4 ? pathSegments[3] : null); }
URL url = new URL(keyId);
public static KeyVaultKeyIdentifier parse(String keyId) throws IllegalArgumentException { if (keyId == null) { throw new IllegalArgumentException("keyId cannot be null"); } try { final URL url = new URL(keyId); final String[] pathSegments = url.getPath().split("/"); if ((pathSegments.length != 3 && pathSegments.length != 4) || !"https".equals(url.getProtocol()) || (!"keys".equals(pathSegments[1]) && !"deletedkeys".equals(pathSegments[1])) || ("deletedkeys".equals(pathSegments[1]) && pathSegments.length == 4)) { throw new IllegalArgumentException("keyId is not a valid Key Vault Key identifier"); } final String vaultUrl = String.format("%s: final String keyName = pathSegments[2]; final String keyVersion = pathSegments.length == 4 ? pathSegments[3] : null; return new KeyVaultKeyIdentifier(keyId, vaultUrl, keyName, keyVersion); } catch (MalformedURLException e) { throw new IllegalArgumentException("Could not parse keyId", e); } }
class KeyVaultKeyIdentifier { private final String keyId, vaultUrl, name, version; private KeyVaultKeyIdentifier(String keyId, String vaultUrl, String name, String version) { this.keyId = keyId; this.vaultUrl = vaultUrl; this.name = name; this.version = version; } /** * Gets the key identifier used to create this object. * * @return The key identifier. */ public String getKeyId() { return keyId; } /** * Gets the URL of the Key Vault. * * @return The Key Vault URL. */ public String getVaultUrl() { return vaultUrl; } /** * Gets the name of the key. * * @return The key name. */ public String getName() { return name; } /** * Gets the optional version of the key. * * @return The key version. */ public String getVersion() { return version; } /** * Create a new {@link KeyVaultKeyIdentifier} from a given key identifier. * * <p>Valid examples are: * * <ul> * <li>https: * <li>https: * <li>https: * <li>https: * </ul> * * @param keyId The key identifier to extract information from. * @return a new instance of {@link KeyVaultKeyIdentifier}. * @throws IllegalArgumentException if the given identifier is {@code null}. * @throws MalformedURLException if the given identifier is not a valid Key Vault Key identifier */ }
class KeyVaultKeyIdentifier { private final String keyId, vaultUrl, name, version; private KeyVaultKeyIdentifier(String keyId, String vaultUrl, String name, String version) { this.keyId = keyId; this.vaultUrl = vaultUrl; this.name = name; this.version = version; } /** * Gets the key identifier used to create this object. * * @return The key identifier. */ public String getKeyId() { return keyId; } /** * Gets the URL of the Key Vault. * * @return The Key Vault URL. */ public String getVaultUrl() { return vaultUrl; } /** * Gets the name of the key. * * @return The key name. */ public String getName() { return name; } /** * Gets the optional version of the key. * * @return The key version. */ public String getVersion() { return version; } /** * Create a new {@link KeyVaultKeyIdentifier} from a given key identifier. * * <p>Valid examples are: * * <ul> * <li>https: * <li>https: * <li>https: * <li>https: * </ul> * * @param keyId The key identifier to extract information from. * @return a new instance of {@link KeyVaultKeyIdentifier}. * @throws IllegalArgumentException if the given identifier is {@code null} or an invalid Key Vault Key identifier. */ }
same feedback as certs.
public static KeyVaultKeyIdentifier parse(String keyId) throws IllegalArgumentException, MalformedURLException { if (keyId == null) { throw new IllegalArgumentException("keyId cannot be null"); } URL url = new URL(keyId); String[] pathSegments = url.getPath().split("/"); if ((pathSegments.length != 3 && pathSegments.length != 4) || !"https".equals(url.getProtocol()) || (!"keys".equals(pathSegments[1]) && !"deletedkeys".equals(pathSegments[1])) || ("deletedkeys".equals(pathSegments[1]) && pathSegments.length == 4)) { throw new IllegalArgumentException("keyId is not a valid Key Vault Key identifier"); } return new KeyVaultKeyIdentifier(keyId, url.getProtocol() + ": pathSegments.length == 4 ? pathSegments[3] : null); }
return new KeyVaultKeyIdentifier(keyId, url.getProtocol() + ":
public static KeyVaultKeyIdentifier parse(String keyId) throws IllegalArgumentException { if (keyId == null) { throw new IllegalArgumentException("keyId cannot be null"); } try { final URL url = new URL(keyId); final String[] pathSegments = url.getPath().split("/"); if ((pathSegments.length != 3 && pathSegments.length != 4) || !"https".equals(url.getProtocol()) || (!"keys".equals(pathSegments[1]) && !"deletedkeys".equals(pathSegments[1])) || ("deletedkeys".equals(pathSegments[1]) && pathSegments.length == 4)) { throw new IllegalArgumentException("keyId is not a valid Key Vault Key identifier"); } final String vaultUrl = String.format("%s: final String keyName = pathSegments[2]; final String keyVersion = pathSegments.length == 4 ? pathSegments[3] : null; return new KeyVaultKeyIdentifier(keyId, vaultUrl, keyName, keyVersion); } catch (MalformedURLException e) { throw new IllegalArgumentException("Could not parse keyId", e); } }
class KeyVaultKeyIdentifier { private final String keyId, vaultUrl, name, version; private KeyVaultKeyIdentifier(String keyId, String vaultUrl, String name, String version) { this.keyId = keyId; this.vaultUrl = vaultUrl; this.name = name; this.version = version; } /** * Gets the key identifier used to create this object. * * @return The key identifier. */ public String getKeyId() { return keyId; } /** * Gets the URL of the Key Vault. * * @return The Key Vault URL. */ public String getVaultUrl() { return vaultUrl; } /** * Gets the name of the key. * * @return The key name. */ public String getName() { return name; } /** * Gets the optional version of the key. * * @return The key version. */ public String getVersion() { return version; } /** * Create a new {@link KeyVaultKeyIdentifier} from a given key identifier. * * <p>Valid examples are: * * <ul> * <li>https: * <li>https: * <li>https: * <li>https: * </ul> * * @param keyId The key identifier to extract information from. * @return a new instance of {@link KeyVaultKeyIdentifier}. * @throws IllegalArgumentException if the given identifier is {@code null}. * @throws MalformedURLException if the given identifier is not a valid Key Vault Key identifier */ }
class KeyVaultKeyIdentifier { private final String keyId, vaultUrl, name, version; private KeyVaultKeyIdentifier(String keyId, String vaultUrl, String name, String version) { this.keyId = keyId; this.vaultUrl = vaultUrl; this.name = name; this.version = version; } /** * Gets the key identifier used to create this object. * * @return The key identifier. */ public String getKeyId() { return keyId; } /** * Gets the URL of the Key Vault. * * @return The Key Vault URL. */ public String getVaultUrl() { return vaultUrl; } /** * Gets the name of the key. * * @return The key name. */ public String getName() { return name; } /** * Gets the optional version of the key. * * @return The key version. */ public String getVersion() { return version; } /** * Create a new {@link KeyVaultKeyIdentifier} from a given key identifier. * * <p>Valid examples are: * * <ul> * <li>https: * <li>https: * <li>https: * <li>https: * </ul> * * @param keyId The key identifier to extract information from. * @return a new instance of {@link KeyVaultKeyIdentifier}. * @throws IllegalArgumentException if the given identifier is {@code null} or an invalid Key Vault Key identifier. */ }
same feedback.
public static KeyVaultSecretIdentifier parse(String secretId) throws IllegalArgumentException, MalformedURLException { if (secretId == null) { throw new IllegalArgumentException("secretId cannot be null"); } URL url = new URL(secretId); String[] pathSegments = url.getPath().split("/"); if ((pathSegments.length != 3 && pathSegments.length != 4) || !"https".equals(url.getProtocol()) || (!"secrets".equals(pathSegments[1]) && !"deletedsecrets".equals(pathSegments[1])) || ("deletedsecrets".equals(pathSegments[1]) && pathSegments.length == 4)) { throw new IllegalArgumentException("secretId is not a valid Key Vault Secret identifier"); } return new KeyVaultSecretIdentifier(secretId, url.getProtocol() + ": pathSegments.length == 4 ? pathSegments[3] : null); }
URL url = new URL(secretId);
public static KeyVaultSecretIdentifier parse(String secretId) throws IllegalArgumentException { if (secretId == null) { throw new IllegalArgumentException("secretId cannot be null"); } try { final URL url = new URL(secretId); final String[] pathSegments = url.getPath().split("/"); if ((pathSegments.length != 3 && pathSegments.length != 4) || !"https".equals(url.getProtocol()) || (!"secrets".equals(pathSegments[1]) && !"deletedsecrets".equals(pathSegments[1])) || ("deletedsecrets".equals(pathSegments[1]) && pathSegments.length == 4)) { throw new IllegalArgumentException("secretId is not a valid Key Vault Secret identifier"); } final String vaultUrl = String.format("%s: final String secretName = pathSegments[2]; final String secretVersion = pathSegments.length == 4 ? pathSegments[3] : null; return new KeyVaultSecretIdentifier(secretId, vaultUrl, secretName, secretVersion); } catch (MalformedURLException e) { throw new IllegalArgumentException("Could not parse secretId", e); } }
class KeyVaultSecretIdentifier { private final String secretId, vaultUrl, name, version; private KeyVaultSecretIdentifier(String secretId, String vaultUrl, String name, String version) { this.secretId = secretId; this.vaultUrl = vaultUrl; this.name = name; this.version = version; } /** * Gets the key identifier used to create this object * * @return The secret identifier. */ public String getSecretId() { return secretId; } /** * Gets the URL of the Key Vault. * * @return The Key Vault URL. */ public String getVaultUrl() { return vaultUrl; } /** * Gets the name of the secret. * * @return The secret name. */ public String getName() { return name; } /** * Gets the optional version of the secret. * * @return The secret version. */ public String getVersion() { return version; } /** * Create a new {@link KeyVaultSecretIdentifier} from a given secret identifier. * * <p>Valid examples are: * * <ul> * <li>https: * <li>https: * <li>https: * <li>https: * </ul> * * @param secretId The secret identifier to extract information from. * @return a new instance of {@link KeyVaultSecretIdentifier}. * @throws IllegalArgumentException if the given identifier is {@code null}. * @throws MalformedURLException if the given identifier is not a valid Key Vault Secret identifier */ }
class KeyVaultSecretIdentifier { private final String secretId, vaultUrl, name, version; private KeyVaultSecretIdentifier(String secretId, String vaultUrl, String name, String version) { this.secretId = secretId; this.vaultUrl = vaultUrl; this.name = name; this.version = version; } /** * Gets the key identifier used to create this object * * @return The secret identifier. */ public String getSecretId() { return secretId; } /** * Gets the URL of the Key Vault. * * @return The Key Vault URL. */ public String getVaultUrl() { return vaultUrl; } /** * Gets the name of the secret. * * @return The secret name. */ public String getName() { return name; } /** * Gets the optional version of the secret. * * @return The secret version. */ public String getVersion() { return version; } /** * Create a new {@link KeyVaultSecretIdentifier} from a given secret identifier. * * <p>Valid examples are: * * <ul> * <li>https: * <li>https: * <li>https: * <li>https: * </ul> * * @param secretId The secret identifier to extract information from. * @return a new instance of {@link KeyVaultSecretIdentifier}. * @throws IllegalArgumentException if the given identifier is {@code null} or an invalid Key Vault Secret * identifier. */ }
same feedback.
public static KeyVaultSecretIdentifier parse(String secretId) throws IllegalArgumentException, MalformedURLException { if (secretId == null) { throw new IllegalArgumentException("secretId cannot be null"); } URL url = new URL(secretId); String[] pathSegments = url.getPath().split("/"); if ((pathSegments.length != 3 && pathSegments.length != 4) || !"https".equals(url.getProtocol()) || (!"secrets".equals(pathSegments[1]) && !"deletedsecrets".equals(pathSegments[1])) || ("deletedsecrets".equals(pathSegments[1]) && pathSegments.length == 4)) { throw new IllegalArgumentException("secretId is not a valid Key Vault Secret identifier"); } return new KeyVaultSecretIdentifier(secretId, url.getProtocol() + ": pathSegments.length == 4 ? pathSegments[3] : null); }
return new KeyVaultSecretIdentifier(secretId, url.getProtocol() + ":
public static KeyVaultSecretIdentifier parse(String secretId) throws IllegalArgumentException { if (secretId == null) { throw new IllegalArgumentException("secretId cannot be null"); } try { final URL url = new URL(secretId); final String[] pathSegments = url.getPath().split("/"); if ((pathSegments.length != 3 && pathSegments.length != 4) || !"https".equals(url.getProtocol()) || (!"secrets".equals(pathSegments[1]) && !"deletedsecrets".equals(pathSegments[1])) || ("deletedsecrets".equals(pathSegments[1]) && pathSegments.length == 4)) { throw new IllegalArgumentException("secretId is not a valid Key Vault Secret identifier"); } final String vaultUrl = String.format("%s: final String secretName = pathSegments[2]; final String secretVersion = pathSegments.length == 4 ? pathSegments[3] : null; return new KeyVaultSecretIdentifier(secretId, vaultUrl, secretName, secretVersion); } catch (MalformedURLException e) { throw new IllegalArgumentException("Could not parse secretId", e); } }
class KeyVaultSecretIdentifier { private final String secretId, vaultUrl, name, version; private KeyVaultSecretIdentifier(String secretId, String vaultUrl, String name, String version) { this.secretId = secretId; this.vaultUrl = vaultUrl; this.name = name; this.version = version; } /** * Gets the key identifier used to create this object * * @return The secret identifier. */ public String getSecretId() { return secretId; } /** * Gets the URL of the Key Vault. * * @return The Key Vault URL. */ public String getVaultUrl() { return vaultUrl; } /** * Gets the name of the secret. * * @return The secret name. */ public String getName() { return name; } /** * Gets the optional version of the secret. * * @return The secret version. */ public String getVersion() { return version; } /** * Create a new {@link KeyVaultSecretIdentifier} from a given secret identifier. * * <p>Valid examples are: * * <ul> * <li>https: * <li>https: * <li>https: * <li>https: * </ul> * * @param secretId The secret identifier to extract information from. * @return a new instance of {@link KeyVaultSecretIdentifier}. * @throws IllegalArgumentException if the given identifier is {@code null}. * @throws MalformedURLException if the given identifier is not a valid Key Vault Secret identifier */ }
class KeyVaultSecretIdentifier { private final String secretId, vaultUrl, name, version; private KeyVaultSecretIdentifier(String secretId, String vaultUrl, String name, String version) { this.secretId = secretId; this.vaultUrl = vaultUrl; this.name = name; this.version = version; } /** * Gets the key identifier used to create this object * * @return The secret identifier. */ public String getSecretId() { return secretId; } /** * Gets the URL of the Key Vault. * * @return The Key Vault URL. */ public String getVaultUrl() { return vaultUrl; } /** * Gets the name of the secret. * * @return The secret name. */ public String getName() { return name; } /** * Gets the optional version of the secret. * * @return The secret version. */ public String getVersion() { return version; } /** * Create a new {@link KeyVaultSecretIdentifier} from a given secret identifier. * * <p>Valid examples are: * * <ul> * <li>https: * <li>https: * <li>https: * <li>https: * </ul> * * @param secretId The secret identifier to extract information from. * @return a new instance of {@link KeyVaultSecretIdentifier}. * @throws IllegalArgumentException if the given identifier is {@code null} or an invalid Key Vault Secret * identifier. */ }
You can remove this line. This target id was accidentally added to the request object exposed to the user.
public void configurePhoneNumber() { PhoneNumber phoneNumber = new PhoneNumber("PHONENUMBER_TO_CONFIGURE"); PstnConfiguration pstnConfiguration = new PstnConfiguration(); pstnConfiguration.setApplicationId("APPLICATION_ID"); pstnConfiguration.setAzurePstnTargetId("AZURE_PSTN_TARGET_ID"); pstnConfiguration.setCallbackUrl("CALLBACK_URL"); try { PhoneNumberClient phoneNumberClient = createPhoneNumberClient(); phoneNumberClient.configureNumber(phoneNumber, pstnConfiguration); } catch (Exception e) { e.printStackTrace(); } }
pstnConfiguration.setAzurePstnTargetId("AZURE_PSTN_TARGET_ID");
public void configurePhoneNumber() { PhoneNumber phoneNumber = new PhoneNumber("PHONENUMBER_TO_CONFIGURE"); PstnConfiguration pstnConfiguration = new PstnConfiguration(); pstnConfiguration.setApplicationId("APPLICATION_ID"); pstnConfiguration.setCallbackUrl("CALLBACK_URL"); try { PhoneNumberClient phoneNumberClient = createPhoneNumberClient(); phoneNumberClient.configureNumber(phoneNumber, pstnConfiguration); } catch (Exception e) { e.printStackTrace(); } }
class ReadmeSamples { /** * Sample code for creating a sync Communication Identity Client. * * @return the Communication Identity Client. * @throws NoSuchAlgorithmException if Communication Client Credential HMAC not available * @throws InvalidKeyException if Communication Client Credential access key is not valid */ public CommunicationIdentityClient createCommunicationIdentityClient() throws InvalidKeyException, NoSuchAlgorithmException { String endpoint = "https: String accessToken = "SECRET"; HttpClient httpClient = new NettyAsyncHttpClientBuilder().build(); CommunicationIdentityClient communicationIdentityClient = new CommunicationIdentityClientBuilder() .endpoint(endpoint) .credential(new CommunicationClientCredential(accessToken)) .httpClient(httpClient) .buildClient(); return communicationIdentityClient; } /** * Sample code for creating a user * * @return the created user */ public CommunicationUser createNewUser() { try { CommunicationIdentityClient communicationIdentityClient = createCommunicationIdentityClient(); CommunicationUser user = communicationIdentityClient.createUser(); System.out.println("User id: " + user.getId()); return user; } catch (Exception e) { e.printStackTrace(); } return null; } /** * Sample code for issuing a user token * * @return the issued user token */ public CommunicationUserToken issueUserToken() { try { CommunicationIdentityClient communicationIdentityClient = createCommunicationIdentityClient(); CommunicationUser user = communicationIdentityClient.createUser(); List<String> scopes = new ArrayList<>(Arrays.asList("chat")); CommunicationUserToken userToken = communicationIdentityClient.issueToken(user, scopes); System.out.println("Token: " + userToken.getToken()); System.out.println("Expires On: " + userToken.getExpiresOn()); return userToken; } catch (Exception e) { e.printStackTrace(); } return null; } /** * Sample code for revoking user token */ public void revokeUserToken() { try { CommunicationIdentityClient communicationIdentityClient = createCommunicationIdentityClient(); CommunicationUser user = createNewUser(); List<String> scopes = new ArrayList<>(Arrays.asList("chat")); communicationIdentityClient.issueToken(user, scopes); communicationIdentityClient.revokeTokens(user, OffsetDateTime.now()); } catch (Exception e) { e.printStackTrace(); } } /** * Sample code for deleting user */ public void deleteUser() { try { CommunicationIdentityClient communicationIdentityClient = createCommunicationIdentityClient(); CommunicationUser user = communicationIdentityClient.createUser(); communicationIdentityClient.deleteUser(user); } catch (Exception e) { e.printStackTrace(); } } /** * Sample code for creating a sync Phone Number Client. * * @return the Phone Number Client. * @throws NoSuchAlgorithmException if Communication Client Credential HMAC not available * @throws InvalidKeyException if Communication Client Credential access key is not valid */ public PhoneNumberClient createPhoneNumberClient() throws NoSuchAlgorithmException, InvalidKeyException { String endpoint = "https: String accessToken = "SECRET"; HttpClient httpClient = new NettyAsyncHttpClientBuilder().build(); PhoneNumberClient phoneNumberClient = new PhoneNumberClientBuilder() .endpoint(endpoint) .credential(new CommunicationClientCredential(accessToken)) .httpClient(httpClient) .buildClient(); return phoneNumberClient; } /** * Sample code to get all supported countries * * @return supported countries */ public PagedIterable<PhoneNumberCountry> getSupportedCountries() { String locale = "en-us"; try { PhoneNumberClient phoneNumberClient = createPhoneNumberClient(); PagedIterable<PhoneNumberCountry> phoneNumberCountries = phoneNumberClient .listAllSupportedCountries(locale); for (PhoneNumberCountry phoneNumberCountry : phoneNumberCountries) { System.out.println("Phone Number Country Code: " + phoneNumberCountry.getCountryCode()); System.out.println("Phone Number Country Name: " + phoneNumberCountry.getLocalizedName()); } return phoneNumberCountries; } catch (Exception e) { e.printStackTrace(); } return null; } /** * Sample code to get a list of all acquired phone numbers * * @return the acquired phone numbers */ public PagedIterable<AcquiredPhoneNumber> getAcquiredPhoneNumbers() { String locale = "en-us"; try { PhoneNumberClient phoneNumberClient = createPhoneNumberClient(); PagedIterable<AcquiredPhoneNumber> acquiredPhoneNumbers = phoneNumberClient .listAllPhoneNumbers(locale); for (AcquiredPhoneNumber acquiredPhoneNumber : acquiredPhoneNumbers) { System.out.println("Acquired Phone Number: " + acquiredPhoneNumber.getPhoneNumber()); } return acquiredPhoneNumbers; } catch (Exception e) { e.printStackTrace(); } return null; } /** * Sample code to get a list of all phone plan groups * * @return phone plans groups */ public PagedIterable<PhonePlanGroup> getPhonePlanGroups() { String countryCode = "US"; String locale = "en-us"; try { PhoneNumberClient phoneNumberClient = createPhoneNumberClient(); PagedIterable<PhonePlanGroup> phonePlanGroups = phoneNumberClient .listPhonePlanGroups(countryCode, locale, true); for (PhonePlanGroup phonePlanGroup : phonePlanGroups) { System.out.println("Phone Plan GroupId: " + phonePlanGroup.getPhonePlanGroupId()); System.out.println("Phone Plan NumberType: " + phonePlanGroup.getPhoneNumberType()); } return phonePlanGroups; } catch (Exception e) { e.printStackTrace(); } return null; } /** * Sample code to get a list of all phone plan instances in a group * * @return phone plans */ public PagedIterable<PhonePlan> getPhonePlansInGroup() { String countryCode = "US"; String locale = "en-us"; String phonePlanGroupId = "PHONE_PLAN_GROUP_ID"; try { PhoneNumberClient phoneNumberClient = createPhoneNumberClient(); PagedIterable<PhonePlan> phonePlans = phoneNumberClient .listPhonePlans(countryCode, phonePlanGroupId, locale); for (PhonePlan phonePlan : phonePlans) { System.out.println("Phone Plan Id: " + phonePlan.getPhonePlanId()); System.out.println("Phone Plan Name: " + phonePlan.getLocalizedName()); System.out.println("Phone Plan Capabilities: " + phonePlan.getCapabilities()); System.out.println("Phone Plan Area Codes: " + phonePlan.getAreaCodes()); } return phonePlans; } catch (Exception e) { e.printStackTrace(); } return null; } /** * Sample code to get the location options for a phone plan * * @return Location Options for a phone plan */ public LocationOptions getPhonePlanLocationOptions() { String countryCode = "US"; String locale = "en-us"; String phonePlanGroupId = "PHONE_PLAN_GROUP_ID"; String phonePlanId = "PHONE_PLAN_ID"; try { PhoneNumberClient phoneNumberClient = createPhoneNumberClient(); LocationOptions locationOptions = phoneNumberClient .getPhonePlanLocationOptions(countryCode, phonePlanGroupId, phonePlanId, locale) .getLocationOptions(); System.out.println("Getting LocationOptions for: " + locationOptions.getLabelId()); for (LocationOptionsDetails locationOptionsDetails : locationOptions.getOptions()) { System.out.println(locationOptionsDetails.getValue()); for (LocationOptions locationOptions1 : locationOptionsDetails.getLocationOptions()) { System.out.println("Getting LocationOptions for: " + locationOptions1.getLabelId()); for (LocationOptionsDetails locationOptionsDetails1 : locationOptions1.getOptions()) { System.out.println(locationOptionsDetails1.getValue()); } } } return locationOptions; } catch (Exception e) { e.printStackTrace(); } return null; } /** * Sample code to get the area codes for a location * * @return Area Codes for a location */ public AreaCodes getAreaCodes() { String countryCode = "US"; String phonePlanId = "PHONE_PLAN_ID"; List<LocationOptionsQuery> locationOptions = new ArrayList<>(); LocationOptionsQuery query = new LocationOptionsQuery(); query.setLabelId("state"); query.setOptionsValue("LOCATION_OPTION_STATE"); locationOptions.add(query); query = new LocationOptionsQuery(); query.setLabelId("city"); query.setOptionsValue("LOCATION_OPTION_CITY"); locationOptions.add(query); try { PhoneNumberClient phoneNumberClient = createPhoneNumberClient(); AreaCodes areaCodes = phoneNumberClient .getAllAreaCodes("selection", countryCode, phonePlanId, locationOptions); for (String areaCode : areaCodes.getPrimaryAreaCodes()) { System.out.println(areaCode); } return areaCodes; } catch (Exception e) { e.printStackTrace(); } return null; } /** * Sample code to create a phone number search * * @return PhoneNumberSearch for the phone plan */ public PhoneNumberSearch createPhoneNumberSearch() { String phonePlanId = "PHONE_PLAN_ID"; List<String> phonePlanIds = new ArrayList<>(); phonePlanIds.add(phonePlanId); CreateSearchOptions createSearchOptions = new CreateSearchOptions(); createSearchOptions .setAreaCode("AREA_CODE_FOR_SEARCH") .setDescription("DESCRIPTION_FOR_SEARCH") .setDisplayName("NAME_FOR_SEARCH") .setPhonePlanIds(phonePlanIds) .setQuantity(2); try { PhoneNumberClient phoneNumberClient = createPhoneNumberClient(); CreateSearchResponse createSearchResponse = phoneNumberClient.createSearch(createSearchOptions); System.out.println("SearchId: " + createSearchResponse.getSearchId()); PhoneNumberSearch phoneNumberSearch = phoneNumberClient.getSearchById(createSearchResponse.getSearchId()); for (String phoneNumber : phoneNumberSearch.getPhoneNumbers()) { System.out.println("Phone Number: " + phoneNumber); } return phoneNumberSearch; } catch (Exception e) { e.printStackTrace(); } return null; } /** * Sample code to purchase a phone number search */ public void purchasePhoneNumberSearch() { String phoneNumberSearchId = "SEARCH_ID_TO_PURCHASE"; try { PhoneNumberClient phoneNumberClient = createPhoneNumberClient(); phoneNumberClient.purchaseSearch(phoneNumberSearchId); } catch (Exception e) { e.printStackTrace(); } } /** * Sample code to configure a phone number */ }
class ReadmeSamples { /** * Sample code for creating a sync Communication Identity Client. * * @return the Communication Identity Client. * @throws NoSuchAlgorithmException if Communication Client Credential HMAC not available * @throws InvalidKeyException if Communication Client Credential access key is not valid */ public CommunicationIdentityClient createCommunicationIdentityClient() throws InvalidKeyException, NoSuchAlgorithmException { String endpoint = "https: String accessToken = "SECRET"; HttpClient httpClient = new NettyAsyncHttpClientBuilder().build(); CommunicationIdentityClient communicationIdentityClient = new CommunicationIdentityClientBuilder() .endpoint(endpoint) .credential(new CommunicationClientCredential(accessToken)) .httpClient(httpClient) .buildClient(); return communicationIdentityClient; } /** * Sample code for creating a user * * @return the created user */ public CommunicationUser createNewUser() { try { CommunicationIdentityClient communicationIdentityClient = createCommunicationIdentityClient(); CommunicationUser user = communicationIdentityClient.createUser(); System.out.println("User id: " + user.getId()); return user; } catch (Exception e) { e.printStackTrace(); } return null; } /** * Sample code for issuing a user token * * @return the issued user token */ public CommunicationUserToken issueUserToken() { try { CommunicationIdentityClient communicationIdentityClient = createCommunicationIdentityClient(); CommunicationUser user = communicationIdentityClient.createUser(); List<String> scopes = new ArrayList<>(Arrays.asList("chat")); CommunicationUserToken userToken = communicationIdentityClient.issueToken(user, scopes); System.out.println("Token: " + userToken.getToken()); System.out.println("Expires On: " + userToken.getExpiresOn()); return userToken; } catch (Exception e) { e.printStackTrace(); } return null; } /** * Sample code for revoking user token */ public void revokeUserToken() { try { CommunicationIdentityClient communicationIdentityClient = createCommunicationIdentityClient(); CommunicationUser user = createNewUser(); List<String> scopes = new ArrayList<>(Arrays.asList("chat")); communicationIdentityClient.issueToken(user, scopes); communicationIdentityClient.revokeTokens(user, OffsetDateTime.now()); } catch (Exception e) { e.printStackTrace(); } } /** * Sample code for deleting user */ public void deleteUser() { try { CommunicationIdentityClient communicationIdentityClient = createCommunicationIdentityClient(); CommunicationUser user = communicationIdentityClient.createUser(); communicationIdentityClient.deleteUser(user); } catch (Exception e) { e.printStackTrace(); } } /** * Sample code for creating a sync Phone Number Client. * * @return the Phone Number Client. * @throws NoSuchAlgorithmException if Communication Client Credential HMAC not available * @throws InvalidKeyException if Communication Client Credential access key is not valid */ public PhoneNumberClient createPhoneNumberClient() throws NoSuchAlgorithmException, InvalidKeyException { String endpoint = "https: String accessToken = "SECRET"; HttpClient httpClient = new NettyAsyncHttpClientBuilder().build(); PhoneNumberClient phoneNumberClient = new PhoneNumberClientBuilder() .endpoint(endpoint) .credential(new CommunicationClientCredential(accessToken)) .httpClient(httpClient) .buildClient(); return phoneNumberClient; } /** * Sample code to get all supported countries * * @return supported countries */ public PagedIterable<PhoneNumberCountry> getSupportedCountries() { String locale = "en-us"; try { PhoneNumberClient phoneNumberClient = createPhoneNumberClient(); PagedIterable<PhoneNumberCountry> phoneNumberCountries = phoneNumberClient .listAllSupportedCountries(locale); for (PhoneNumberCountry phoneNumberCountry : phoneNumberCountries) { System.out.println("Phone Number Country Code: " + phoneNumberCountry.getCountryCode()); System.out.println("Phone Number Country Name: " + phoneNumberCountry.getLocalizedName()); } return phoneNumberCountries; } catch (Exception e) { e.printStackTrace(); } return null; } /** * Sample code to get a list of all acquired phone numbers * * @return the acquired phone numbers */ public PagedIterable<AcquiredPhoneNumber> getAcquiredPhoneNumbers() { String locale = "en-us"; try { PhoneNumberClient phoneNumberClient = createPhoneNumberClient(); PagedIterable<AcquiredPhoneNumber> acquiredPhoneNumbers = phoneNumberClient .listAllPhoneNumbers(locale); for (AcquiredPhoneNumber acquiredPhoneNumber : acquiredPhoneNumbers) { System.out.println("Acquired Phone Number: " + acquiredPhoneNumber.getPhoneNumber()); } return acquiredPhoneNumbers; } catch (Exception e) { e.printStackTrace(); } return null; } /** * Sample code to get a list of all phone plan groups * * @return phone plans groups */ public PagedIterable<PhonePlanGroup> getPhonePlanGroups() { String countryCode = "US"; String locale = "en-us"; try { PhoneNumberClient phoneNumberClient = createPhoneNumberClient(); PagedIterable<PhonePlanGroup> phonePlanGroups = phoneNumberClient .listPhonePlanGroups(countryCode, locale, true); for (PhonePlanGroup phonePlanGroup : phonePlanGroups) { System.out.println("Phone Plan GroupId: " + phonePlanGroup.getPhonePlanGroupId()); System.out.println("Phone Plan NumberType: " + phonePlanGroup.getPhoneNumberType()); } return phonePlanGroups; } catch (Exception e) { e.printStackTrace(); } return null; } /** * Sample code to get a list of all phone plan instances in a group * * @return phone plans */ public PagedIterable<PhonePlan> getPhonePlansInGroup() { String countryCode = "US"; String locale = "en-us"; String phonePlanGroupId = "PHONE_PLAN_GROUP_ID"; try { PhoneNumberClient phoneNumberClient = createPhoneNumberClient(); PagedIterable<PhonePlan> phonePlans = phoneNumberClient .listPhonePlans(countryCode, phonePlanGroupId, locale); for (PhonePlan phonePlan : phonePlans) { System.out.println("Phone Plan Id: " + phonePlan.getPhonePlanId()); System.out.println("Phone Plan Name: " + phonePlan.getLocalizedName()); System.out.println("Phone Plan Capabilities: " + phonePlan.getCapabilities()); System.out.println("Phone Plan Area Codes: " + phonePlan.getAreaCodes()); } return phonePlans; } catch (Exception e) { e.printStackTrace(); } return null; } /** * Sample code to get the location options for a phone plan * * @return Location Options for a phone plan */ public LocationOptions getPhonePlanLocationOptions() { String countryCode = "US"; String locale = "en-us"; String phonePlanGroupId = "PHONE_PLAN_GROUP_ID"; String phonePlanId = "PHONE_PLAN_ID"; try { PhoneNumberClient phoneNumberClient = createPhoneNumberClient(); LocationOptions locationOptions = phoneNumberClient .getPhonePlanLocationOptions(countryCode, phonePlanGroupId, phonePlanId, locale) .getLocationOptions(); System.out.println("Getting LocationOptions for: " + locationOptions.getLabelId()); for (LocationOptionsDetails locationOptionsDetails : locationOptions.getOptions()) { System.out.println(locationOptionsDetails.getValue()); for (LocationOptions locationOptions1 : locationOptionsDetails.getLocationOptions()) { System.out.println("Getting LocationOptions for: " + locationOptions1.getLabelId()); for (LocationOptionsDetails locationOptionsDetails1 : locationOptions1.getOptions()) { System.out.println(locationOptionsDetails1.getValue()); } } } return locationOptions; } catch (Exception e) { e.printStackTrace(); } return null; } /** * Sample code to get the area codes for a location * * @return Area Codes for a location */ public AreaCodes getAreaCodes() { String countryCode = "US"; String phonePlanId = "PHONE_PLAN_ID"; List<LocationOptionsQuery> locationOptions = new ArrayList<>(); LocationOptionsQuery query = new LocationOptionsQuery(); query.setLabelId("state"); query.setOptionsValue("LOCATION_OPTION_STATE"); locationOptions.add(query); query = new LocationOptionsQuery(); query.setLabelId("city"); query.setOptionsValue("LOCATION_OPTION_CITY"); locationOptions.add(query); try { PhoneNumberClient phoneNumberClient = createPhoneNumberClient(); AreaCodes areaCodes = phoneNumberClient .getAllAreaCodes("selection", countryCode, phonePlanId, locationOptions); for (String areaCode : areaCodes.getPrimaryAreaCodes()) { System.out.println(areaCode); } return areaCodes; } catch (Exception e) { e.printStackTrace(); } return null; } /** * Sample code to create a phone number search * * @return PhoneNumberSearch for the phone plan */ public PhoneNumberSearch createPhoneNumberSearch() { String phonePlanId = "PHONE_PLAN_ID"; List<String> phonePlanIds = new ArrayList<>(); phonePlanIds.add(phonePlanId); CreateSearchOptions createSearchOptions = new CreateSearchOptions(); createSearchOptions .setAreaCode("AREA_CODE_FOR_SEARCH") .setDescription("DESCRIPTION_FOR_SEARCH") .setDisplayName("NAME_FOR_SEARCH") .setPhonePlanIds(phonePlanIds) .setQuantity(2); try { PhoneNumberClient phoneNumberClient = createPhoneNumberClient(); CreateSearchResponse createSearchResponse = phoneNumberClient.createSearch(createSearchOptions); System.out.println("SearchId: " + createSearchResponse.getSearchId()); PhoneNumberSearch phoneNumberSearch = phoneNumberClient.getSearchById(createSearchResponse.getSearchId()); for (String phoneNumber : phoneNumberSearch.getPhoneNumbers()) { System.out.println("Phone Number: " + phoneNumber); } return phoneNumberSearch; } catch (Exception e) { e.printStackTrace(); } return null; } /** * Sample code to purchase a phone number search */ public void purchasePhoneNumberSearch() { String phoneNumberSearchId = "SEARCH_ID_TO_PURCHASE"; try { PhoneNumberClient phoneNumberClient = createPhoneNumberClient(); phoneNumberClient.purchaseSearch(phoneNumberSearchId); } catch (Exception e) { e.printStackTrace(); } } /** * Sample code to configure a phone number */ }