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 |
|---|---|---|---|---|---|
So the end result from both of these transformed APIs will be the `.getValue()` items directly. | public Mono<String> getComponent(String digitalTwinId, String componentPath) {
return getComponentWithResponse(digitalTwinId, componentPath)
.flatMap(response -> Mono.justOrEmpty(response.getValue()));
} | .flatMap(response -> Mono.justOrEmpty(response.getValue())); | public Mono<String> getComponent(String digitalTwinId, String componentPath) {
return getComponentWithResponse(digitalTwinId, componentPath)
.map(DigitalTwinsResponse::getValue);
} | class to convert the relationship to.
* @param <T> The generic type to convert the relationship to.
* @return A {@link PagedFlux} | class to convert the relationship to.
* @param <T> The generic type to convert the relationship to.
* @return A {@link PagedFlux} |
We've been following the format where the async APIs call the async overloads, and the max overload API calls the PL. Similarly, the sync APIs call the sync overloads, and the max overload sync API calls the async API. | public String getComponent(String digitalTwinId, String componentPath) {
return digitalTwinsAsyncClient.getComponent(digitalTwinId, componentPath).block();
} | return digitalTwinsAsyncClient.getComponent(digitalTwinId, componentPath).block(); | public String getComponent(String digitalTwinId, String componentPath) {
return getComponentWithResponse(digitalTwinId, componentPath, Context.NONE).getValue();
} | class to convert the relationship to.
* @param <T> The generic type to convert the relationship to.
* @param context Additional context that is passed through the Http pipeline during the service call.
* @return A {@link PagedIterable} | class to convert the relationship to.
* @param <T> The generic type to convert the relationship to.
* @param context Additional context that is passed through the Http pipeline during the service call.
* @return A {@link PagedIterable} |
nit: this can be replaced by a method reference `.map(DigitalTwinsResponse::getValue)`. | public Mono<String> getComponent(String digitalTwinId, String componentPath) {
return getComponentWithResponse(digitalTwinId, componentPath)
.map(response -> response.getValue());
} | .map(response -> response.getValue()); | public Mono<String> getComponent(String digitalTwinId, String componentPath) {
return getComponentWithResponse(digitalTwinId, componentPath)
.map(DigitalTwinsResponse::getValue);
} | class to convert the relationship to.
* @param <T> The generic type to convert the relationship to.
* @return A {@link PagedFlux} | class to convert the relationship to.
* @param <T> The generic type to convert the relationship to.
* @return A {@link PagedFlux} |
Ha, too slow. I just figured this out while looking at another PR | public Mono<String> getComponent(String digitalTwinId, String componentPath) {
return getComponentWithResponse(digitalTwinId, componentPath)
.map(response -> response.getValue());
} | .map(response -> response.getValue()); | public Mono<String> getComponent(String digitalTwinId, String componentPath) {
return getComponentWithResponse(digitalTwinId, componentPath)
.map(DigitalTwinsResponse::getValue);
} | class to convert the relationship to.
* @param <T> The generic type to convert the relationship to.
* @return A {@link PagedFlux} | class to convert the relationship to.
* @param <T> The generic type to convert the relationship to.
* @return A {@link PagedFlux} |
So I made this change already | public Mono<String> getComponent(String digitalTwinId, String componentPath) {
return getComponentWithResponse(digitalTwinId, componentPath)
.map(response -> response.getValue());
} | .map(response -> response.getValue()); | public Mono<String> getComponent(String digitalTwinId, String componentPath) {
return getComponentWithResponse(digitalTwinId, componentPath)
.map(DigitalTwinsResponse::getValue);
} | class to convert the relationship to.
* @param <T> The generic type to convert the relationship to.
* @return A {@link PagedFlux} | class to convert the relationship to.
* @param <T> The generic type to convert the relationship to.
* @return A {@link PagedFlux} |
Gotcha, I can chain it that way instead | public String getComponent(String digitalTwinId, String componentPath) {
return digitalTwinsAsyncClient.getComponent(digitalTwinId, componentPath).block();
} | return digitalTwinsAsyncClient.getComponent(digitalTwinId, componentPath).block(); | public String getComponent(String digitalTwinId, String componentPath) {
return getComponentWithResponse(digitalTwinId, componentPath, Context.NONE).getValue();
} | class to convert the relationship to.
* @param <T> The generic type to convert the relationship to.
* @param context Additional context that is passed through the Http pipeline during the service call.
* @return A {@link PagedIterable} | class to convert the relationship to.
* @param <T> The generic type to convert the relationship to.
* @param context Additional context that is passed through the Http pipeline during the service call.
* @return A {@link PagedIterable} |
Fiyi - for default context you can use `Context.NONE`. | public String getComponent(String digitalTwinId, String componentPath) {
return digitalTwinsAsyncClient.getComponent(digitalTwinId, componentPath).block();
} | return digitalTwinsAsyncClient.getComponent(digitalTwinId, componentPath).block(); | public String getComponent(String digitalTwinId, String componentPath) {
return getComponentWithResponse(digitalTwinId, componentPath, Context.NONE).getValue();
} | class to convert the relationship to.
* @param <T> The generic type to convert the relationship to.
* @param context Additional context that is passed through the Http pipeline during the service call.
* @return A {@link PagedIterable} | class to convert the relationship to.
* @param <T> The generic type to convert the relationship to.
* @param context Additional context that is passed through the Http pipeline during the service call.
* @return A {@link PagedIterable} |
can be replaced with method reference: ```java .map(Response::getValue); ``` | public Mono<ModelData> getModel(String modelId) {
return getModelWithResponse(modelId)
.map(response -> response.getValue());
} | .map(response -> response.getValue()); | public Mono<ModelData> getModel(String modelId) {
return getModelWithResponse(modelId)
.map(Response::getValue);
} | class to convert the relationship to.
* @param <T> The generic type to convert the relationship to.
* @return A {@link PagedFlux} | class to convert the relationship to.
* @param <T> The generic type to convert the relationship to.
* @return A {@link PagedFlux} |
same here as well :) | public Mono<Void> deleteModel(String modelId) {
return deleteModelWithResponse(modelId)
.map(response -> response.getValue());
} | .map(response -> response.getValue()); | public Mono<Void> deleteModel(String modelId) {
return deleteModelWithResponse(modelId)
.map(Response::getValue);
} | class to convert the relationship to.
* @param <T> The generic type to convert the relationship to.
* @return A {@link PagedFlux} | class to convert the relationship to.
* @param <T> The generic type to convert the relationship to.
* @return A {@link PagedFlux} |
you fancy | public Mono<ModelData> getModel(String modelId) {
return getModelWithResponse(modelId)
.map(response -> response.getValue());
} | .map(response -> response.getValue()); | public Mono<ModelData> getModel(String modelId) {
return getModelWithResponse(modelId)
.map(Response::getValue);
} | class to convert the relationship to.
* @param <T> The generic type to convert the relationship to.
* @return A {@link PagedFlux} | class to convert the relationship to.
* @param <T> The generic type to convert the relationship to.
* @return A {@link PagedFlux} |
Doesn't look like there exists a test where we settle with a sessionId. | void settleWithNullTransaction(DispositionStatus dispositionStatus) {
ServiceBusTransactionContext nullTransaction = null;
when(connection.getManagementNode(ENTITY_PATH, ENTITY_TYPE)).thenReturn(Mono.just(managementNode));
when(managementNode.updateDisposition(any(), eq(dispositionStatus), isNull(), isNull(), isNull(),
isNull(), isNull(), isNull()))
.thenReturn(Mono.delay(Duration.ofMillis(250)).then());
when(receivedMessage.getLockToken()).thenReturn("mylockToken");
final Mono<Void> operation;
switch (dispositionStatus) {
case DEFERRED:
operation = receiver.defer(receivedMessage, null, nullTransaction);
break;
case ABANDONED:
operation = receiver.abandon(receivedMessage, null, nullTransaction);
break;
case COMPLETED:
operation = receiver.complete(receivedMessage, nullTransaction);
break;
case SUSPENDED:
operation = receiver.deadLetter(receivedMessage, new DeadLetterOptions(), nullTransaction);
break;
default:
throw new IllegalArgumentException("Unrecognized operation: " + dispositionStatus);
}
StepVerifier.create(operation)
.expectError(NullPointerException.class)
.verify();
verify(managementNode, never()).updateDisposition(any(), eq(dispositionStatus), isNull(), isNull(),
isNull(), isNull(), isNull(), isNull());
} | final Mono<Void> operation; | void settleWithNullTransaction(DispositionStatus dispositionStatus) {
ServiceBusTransactionContext nullTransaction = null;
when(connection.getManagementNode(ENTITY_PATH, ENTITY_TYPE)).thenReturn(Mono.just(managementNode));
when(managementNode.updateDisposition(any(), eq(dispositionStatus), isNull(), isNull(), isNull(),
isNull(), isNull(), isNull()))
.thenReturn(Mono.delay(Duration.ofMillis(250)).then());
when(receivedMessage.getLockToken()).thenReturn("mylockToken");
final Mono<Void> operation;
switch (dispositionStatus) {
case DEFERRED:
operation = receiver.defer(receivedMessage, null, nullTransaction);
break;
case ABANDONED:
operation = receiver.abandon(receivedMessage, null, nullTransaction);
break;
case COMPLETED:
operation = receiver.complete(receivedMessage, nullTransaction);
break;
case SUSPENDED:
operation = receiver.deadLetter(receivedMessage, new DeadLetterOptions(), nullTransaction);
break;
default:
throw new IllegalArgumentException("Unrecognized operation: " + dispositionStatus);
}
StepVerifier.create(operation)
.expectError(NullPointerException.class)
.verify();
verify(managementNode, never()).updateDisposition(any(), eq(dispositionStatus), isNull(), isNull(),
isNull(), isNull(), isNull(), isNull());
} | class ServiceBusReceiverAsyncClientTest {
private static final String PAYLOAD = "hello";
private static final byte[] PAYLOAD_BYTES = PAYLOAD.getBytes(UTF_8);
private static final int PREFETCH = 5;
private static final String NAMESPACE = "my-namespace-foo.net";
private static final String ENTITY_PATH = "queue-name";
private static final MessagingEntityType ENTITY_TYPE = MessagingEntityType.QUEUE;
private static final String NAMESPACE_CONNECTION_STRING = String.format(
"Endpoint=sb:
NAMESPACE, "some-name", "something-else");
private static final Duration CLEANUP_INTERVAL = Duration.ofSeconds(10);
private static final String SESSION_ID = "my-session-id";
private final ClientLogger logger = new ClientLogger(ServiceBusReceiverAsyncClientTest.class);
private final String messageTrackingUUID = UUID.randomUUID().toString();
private final ReplayProcessor<AmqpEndpointState> endpointProcessor = ReplayProcessor.cacheLast();
private final FluxSink<AmqpEndpointState> endpointSink = endpointProcessor.sink(FluxSink.OverflowStrategy.BUFFER);
private final DirectProcessor<Message> messageProcessor = DirectProcessor.create();
private final FluxSink<Message> messageSink = messageProcessor.sink(FluxSink.OverflowStrategy.BUFFER);
private ServiceBusConnectionProcessor connectionProcessor;
private ServiceBusReceiverAsyncClient receiver;
private ServiceBusReceiverAsyncClient sessionReceiver;
private Duration maxAutoLockRenewalDuration;
@Mock
private ServiceBusReactorReceiver amqpReceiveLink;
@Mock
private ServiceBusReactorReceiver sessionReceiveLink;
@Mock
private ServiceBusAmqpConnection connection;
@Mock
private TokenCredential tokenCredential;
@Mock
private MessageSerializer messageSerializer;
@Mock
private TracerProvider tracerProvider;
@Mock
private ServiceBusManagementNode managementNode;
@Mock
private ServiceBusReceivedMessage receivedMessage;
@Mock
private ServiceBusReceivedMessage receivedMessage2;
@Mock
private Runnable onClientClose;
@Mock
private Function<String, Mono<OffsetDateTime>> renewalOperation;
@BeforeAll
static void beforeAll() {
StepVerifier.setDefaultTimeout(Duration.ofSeconds(100));
}
@AfterAll
static void afterAll() {
StepVerifier.resetDefaultTimeout();
}
@BeforeEach
void setup(TestInfo testInfo) {
logger.info("[{}] Setting up.", testInfo.getDisplayName());
MockitoAnnotations.initMocks(this);
when(amqpReceiveLink.receive()).thenReturn(messageProcessor.publishOn(Schedulers.single()));
when(amqpReceiveLink.getEndpointStates()).thenReturn(endpointProcessor);
ConnectionOptions connectionOptions = new ConnectionOptions(NAMESPACE, tokenCredential,
CbsAuthorizationType.SHARED_ACCESS_SIGNATURE, AmqpTransportType.AMQP, new AmqpRetryOptions(),
ProxyOptions.SYSTEM_DEFAULTS, Schedulers.boundedElastic());
when(connection.getEndpointStates()).thenReturn(endpointProcessor);
endpointSink.next(AmqpEndpointState.ACTIVE);
when(connection.getManagementNode(ENTITY_PATH, ENTITY_TYPE))
.thenReturn(Mono.just(managementNode));
when(connection.createReceiveLink(anyString(), anyString(), any(ReceiveMode.class), any(),
any(MessagingEntityType.class))).thenReturn(Mono.just(amqpReceiveLink));
when(connection.createReceiveLink(anyString(), anyString(), any(ReceiveMode.class), any(),
any(MessagingEntityType.class), anyString())).thenReturn(Mono.just(sessionReceiveLink));
connectionProcessor =
Flux.<ServiceBusAmqpConnection>create(sink -> sink.next(connection))
.subscribeWith(new ServiceBusConnectionProcessor(connectionOptions.getFullyQualifiedNamespace(),
connectionOptions.getRetry()));
receiver = new ServiceBusReceiverAsyncClient(NAMESPACE, ENTITY_PATH, MessagingEntityType.QUEUE,
new ReceiverOptions(ReceiveMode.PEEK_LOCK, PREFETCH), connectionProcessor, CLEANUP_INTERVAL,
tracerProvider, messageSerializer, onClientClose);
sessionReceiver = new ServiceBusReceiverAsyncClient(NAMESPACE, ENTITY_PATH, MessagingEntityType.QUEUE,
new ReceiverOptions(ReceiveMode.PEEK_LOCK, PREFETCH, "Some-Session", false, null),
connectionProcessor, CLEANUP_INTERVAL, tracerProvider, messageSerializer, onClientClose);
}
@AfterEach
void teardown(TestInfo testInfo) {
logger.info("[{}] Tearing down.", testInfo.getDisplayName());
receiver.close();
Mockito.framework().clearInlineMocks();
}
/**
* Verifies that when user calls peek more than one time, It returns different object.
*/
@SuppressWarnings("unchecked")
@Test
void peekTwoMessages() {
final long sequence1 = 10;
final long sequence2 = 12;
final ArgumentCaptor<Long> captor = ArgumentCaptor.forClass(Long.class);
when(receivedMessage.getSequenceNumber()).thenReturn(sequence1);
when(receivedMessage2.getSequenceNumber()).thenReturn(sequence2);
when(managementNode.peek(anyLong(), isNull(), isNull()))
.thenReturn(Mono.just(receivedMessage), Mono.just(receivedMessage2));
StepVerifier.create(receiver.peekMessage())
.expectNext(receivedMessage)
.verifyComplete();
StepVerifier.create(receiver.peekMessage())
.expectNext(receivedMessage2)
.verifyComplete();
verify(managementNode, times(2)).peek(captor.capture(), isNull(), isNull());
final List<Long> allValues = captor.getAllValues();
Assertions.assertEquals(2, allValues.size());
Assertions.assertTrue(allValues.contains(0L));
Assertions.assertTrue(allValues.contains(11L));
}
/**
* Verifies that this peek one messages from a sequence Number.
*/
@Test
void peekWithSequenceOneMessage() {
final int fromSequenceNumber = 10;
final ServiceBusReceivedMessage receivedMessage = mock(ServiceBusReceivedMessage.class);
when(managementNode.peek(fromSequenceNumber, null, null)).thenReturn(Mono.just(receivedMessage));
StepVerifier.create(receiver.peekMessageAt(fromSequenceNumber))
.expectNext(receivedMessage)
.verifyComplete();
}
/**
* Verifies that this receives a number of messages. Verifies that the initial credits we add are equal to the
* prefetch value.
*/
@Test
void receivesNumberOfEvents() {
final int numberOfEvents = 1;
final List<Message> messages = getMessages(10);
ServiceBusReceivedMessage receivedMessage = mock(ServiceBusReceivedMessage.class);
when(receivedMessage.getLockToken()).thenReturn(UUID.randomUUID().toString());
when(messageSerializer.deserialize(any(Message.class), eq(ServiceBusReceivedMessage.class)))
.thenReturn(receivedMessage);
StepVerifier.create(receiver.receiveMessages().take(numberOfEvents))
.then(() -> messages.forEach(m -> messageSink.next(m)))
.expectNextCount(numberOfEvents)
.verifyComplete();
verify(amqpReceiveLink).addCredits(PREFETCH);
}
/**
* Verifies that we error if we try to settle a message with null transaction.
*/
@ParameterizedTest
@EnumSource(DispositionStatus.class)
/**
* Verifies that we error if we try to settle a message with null transaction-id.
*/
@ParameterizedTest
@EnumSource(DispositionStatus.class)
void settleWithNullTransactionId(DispositionStatus dispositionStatus) {
ServiceBusTransactionContext nullTransactionId = new ServiceBusTransactionContext(null);
when(connection.getManagementNode(ENTITY_PATH, ENTITY_TYPE)).thenReturn(Mono.just(managementNode));
when(managementNode.updateDisposition(any(), eq(dispositionStatus), isNull(), isNull(), isNull(),
isNull(), isNull(), isNull()))
.thenReturn(Mono.delay(Duration.ofMillis(250)).then());
when(receivedMessage.getLockToken()).thenReturn("mylockToken");
final Mono<Void> operation;
switch (dispositionStatus) {
case DEFERRED:
operation = receiver.defer(receivedMessage, null, nullTransactionId);
break;
case ABANDONED:
operation = receiver.abandon(receivedMessage, null, nullTransactionId);
break;
case COMPLETED:
operation = receiver.complete(receivedMessage, nullTransactionId);
break;
case SUSPENDED:
operation = receiver.deadLetter(receivedMessage, new DeadLetterOptions(), nullTransactionId);
break;
default:
throw new IllegalArgumentException("Unrecognized operation: " + dispositionStatus);
}
StepVerifier.create(operation)
.expectError(NullPointerException.class)
.verify();
verify(managementNode, never()).updateDisposition(any(), eq(dispositionStatus), isNull(), isNull(),
isNull(), isNull(), isNull(), isNull());
}
/**
* Verifies that we error if we try to complete a message with null value.
*/
@Test
void completeNullLockToken() {
when(connection.getManagementNode(ENTITY_PATH, ENTITY_TYPE)).thenReturn(Mono.just(managementNode));
when(managementNode.updateDisposition(any(), eq(DispositionStatus.COMPLETED), isNull(), isNull(), isNull(),
isNull(), isNull(), isNull()))
.thenReturn(Mono.delay(Duration.ofMillis(250)).then());
StepVerifier.create(receiver.complete(null))
.expectError(NullPointerException.class)
.verify();
verify(managementNode, never()).updateDisposition(any(), eq(DispositionStatus.COMPLETED), isNull(), isNull(),
isNull(), isNull(), isNull(), isNull());
}
/**
* Verifies that we error if we try to complete a null message.
*/
@Test
void completeNullMessage() {
StepVerifier.create(receiver.complete(null)).expectError(NullPointerException.class).verify();
}
/**
* Verifies that we error if we complete in RECEIVE_AND_DELETE mode.
*/
@Test
void completeInReceiveAndDeleteMode() {
final ReceiverOptions options = new ReceiverOptions(ReceiveMode.RECEIVE_AND_DELETE, PREFETCH);
ServiceBusReceiverAsyncClient client = new ServiceBusReceiverAsyncClient(NAMESPACE, ENTITY_PATH,
MessagingEntityType.QUEUE, options, connectionProcessor, CLEANUP_INTERVAL, tracerProvider,
messageSerializer, onClientClose);
final String lockToken1 = UUID.randomUUID().toString();
when(receivedMessage.getLockToken()).thenReturn(lockToken1);
try {
StepVerifier.create(client.complete(receivedMessage))
.expectError(UnsupportedOperationException.class)
.verify();
} finally {
client.close();
}
}
/**
* Verifies that this peek batch of messages.
*/
@Test
void peekBatchMessages() {
final int numberOfEvents = 2;
when(managementNode.peek(0, null, null, numberOfEvents))
.thenReturn(Flux.fromArray(new ServiceBusReceivedMessage[]{receivedMessage, receivedMessage2}));
StepVerifier.create(receiver.peekMessages(numberOfEvents))
.expectNextCount(numberOfEvents)
.verifyComplete();
}
/**
* Verifies that this peek batch of messages from a sequence Number.
*/
@Test
void peekBatchWithSequenceNumberMessages() {
final int numberOfEvents = 2;
final int fromSequenceNumber = 10;
when(managementNode.peek(fromSequenceNumber, null, null, numberOfEvents))
.thenReturn(Flux.fromArray(new ServiceBusReceivedMessage[]{receivedMessage, receivedMessage2}));
StepVerifier.create(receiver.peekMessagesAt(numberOfEvents, fromSequenceNumber))
.expectNext(receivedMessage, receivedMessage2)
.verifyComplete();
}
/**
* Verifies that we can deadletter a message with an error and description.
*/
@Test
void deadLetterWithDescription() {
final String lockToken1 = UUID.randomUUID().toString();
final String description = "some-dead-letter-description";
final String reason = "dead-letter-reason";
final Map<String, Object> propertiesToModify = new HashMap<>();
propertiesToModify.put("something", true);
final DeadLetterOptions deadLetterOptions = new DeadLetterOptions().setDeadLetterReason(reason)
.setDeadLetterErrorDescription(description)
.setPropertiesToModify(propertiesToModify);
final OffsetDateTime expiration = OffsetDateTime.now().plus(Duration.ofMinutes(5));
final MessageWithLockToken message = mock(MessageWithLockToken.class);
when(messageSerializer.deserialize(message, ServiceBusReceivedMessage.class)).thenReturn(receivedMessage);
when(receivedMessage.getLockToken()).thenReturn(lockToken1);
when(receivedMessage.getLockedUntil()).thenReturn(expiration);
when(amqpReceiveLink.updateDisposition(eq(lockToken1), argThat(e -> e.getType() == DeliveryStateType.Rejected))).thenReturn(Mono.empty());
StepVerifier.create(receiver.receiveMessages()
.take(1)
.flatMap(context -> receiver.deadLetter(context.getMessage(), deadLetterOptions)))
.then(() -> messageSink.next(message))
.expectNext()
.verifyComplete();
verify(amqpReceiveLink).updateDisposition(eq(lockToken1), isA(Rejected.class));
}
/**
* Verifies that the user can complete settlement methods on received message.
*/
@ParameterizedTest
@EnumSource(DispositionStatus.class)
void settleMessageOnManagement(DispositionStatus dispositionStatus) {
final String lockToken1 = UUID.randomUUID().toString();
final String lockToken2 = UUID.randomUUID().toString();
final OffsetDateTime expiration = OffsetDateTime.now().plus(Duration.ofMinutes(5));
final long sequenceNumber = 10L;
final long sequenceNumber2 = 15L;
final MessageWithLockToken message = mock(MessageWithLockToken.class);
final MessageWithLockToken message2 = mock(MessageWithLockToken.class);
when(messageSerializer.deserialize(message, ServiceBusReceivedMessage.class)).thenReturn(receivedMessage);
when(messageSerializer.deserialize(message2, ServiceBusReceivedMessage.class)).thenReturn(receivedMessage2);
when(receivedMessage.getLockToken()).thenReturn(lockToken1);
when(receivedMessage.getLockedUntil()).thenReturn(expiration);
when(receivedMessage2.getLockToken()).thenReturn(lockToken2);
when(receivedMessage2.getLockedUntil()).thenReturn(expiration);
when(connection.getManagementNode(eq(ENTITY_PATH), eq(ENTITY_TYPE)))
.thenReturn(Mono.just(managementNode));
when(managementNode.receiveDeferredMessages(eq(ReceiveMode.PEEK_LOCK), isNull(), isNull(), argThat(arg -> {
boolean foundFirst = false;
boolean foundSecond = false;
for (Long seq : arg) {
if (!foundFirst && sequenceNumber == seq) {
foundFirst = true;
} else if (!foundSecond && sequenceNumber2 == seq) {
foundSecond = true;
}
}
return foundFirst && foundSecond;
})))
.thenReturn(Flux.just(receivedMessage, receivedMessage2));
when(managementNode.updateDisposition(lockToken1, dispositionStatus, null, null, null, null, null, null))
.thenReturn(Mono.empty());
when(managementNode.updateDisposition(lockToken2, dispositionStatus, null, null, null, null, null, null))
.thenReturn(Mono.empty());
StepVerifier.create(receiver.receiveDeferredMessages(Arrays.asList(sequenceNumber, sequenceNumber2)))
.expectNext(receivedMessage, receivedMessage2)
.verifyComplete();
final Mono<Void> operation;
switch (dispositionStatus) {
case DEFERRED:
operation = receiver.defer(receivedMessage);
break;
case ABANDONED:
operation = receiver.abandon(receivedMessage);
break;
case COMPLETED:
operation = receiver.complete(receivedMessage);
break;
case SUSPENDED:
operation = receiver.deadLetter(receivedMessage);
break;
default:
throw new IllegalArgumentException("Unrecognized operation: " + dispositionStatus);
}
StepVerifier.create(operation)
.verifyComplete();
verify(managementNode).updateDisposition(lockToken1, dispositionStatus, null, null, null, null, null, null);
verify(managementNode, never()).updateDisposition(lockToken2, dispositionStatus, null, null, null, null, null, null);
}
/**
* Verifies that this receive deferred one messages from a sequence Number.
*/
@Test
void receiveDeferredWithSequenceOneMessage() {
final int fromSequenceNumber = 10;
final ServiceBusReceivedMessage receivedMessage = mock(ServiceBusReceivedMessage.class);
when(managementNode.receiveDeferredMessages(any(), any(), any(), any())).thenReturn(Flux.just(receivedMessage));
StepVerifier.create(receiver.receiveDeferredMessage(fromSequenceNumber))
.expectNext(receivedMessage)
.verifyComplete();
}
/**
* Verifies that this receive deferred messages from a sequence Number.
*/
@Test
void receiveDeferredBatchFromSequenceNumber() {
final long fromSequenceNumber1 = 10;
final long fromSequenceNumber2 = 11;
when(managementNode.receiveDeferredMessages(any(), any(), any(), any()))
.thenReturn(Flux.fromArray(new ServiceBusReceivedMessage[]{receivedMessage, receivedMessage2}));
StepVerifier.create(receiver.receiveDeferredMessages(Arrays.asList(fromSequenceNumber1, fromSequenceNumber2)))
.expectNext(receivedMessage)
.expectNext(receivedMessage2)
.verifyComplete();
}
/**
* Verifies that the onClientClose is called.
*/
@Test
void callsClientClose() {
receiver.close();
verify(onClientClose).run();
}
/**
* Verifies that the onClientClose is only called once.
*/
@Test
void callsClientCloseOnce() {
receiver.close();
receiver.close();
verify(onClientClose).run();
}
/**
* Tests that invalid options throws and null options.
*/
@Test
void receiveIllegalOptions() {
ServiceBusReceiverClientBuilder builder = new ServiceBusClientBuilder()
.connectionString(NAMESPACE_CONNECTION_STRING)
.receiver()
.topicName("baz").subscriptionName("bar").prefetchCount(-1)
.receiveMode(ReceiveMode.PEEK_LOCK);
Assertions.assertThrows(IllegalArgumentException.class, () -> builder.buildAsyncClient());
}
@Test
void topicCorrectEntityPath() {
final String topicName = "foo";
final String subscriptionName = "bar";
final String entityPath = String.join("/", topicName, "subscriptions", subscriptionName);
final ServiceBusReceiverAsyncClient receiver = new ServiceBusClientBuilder()
.connectionString(NAMESPACE_CONNECTION_STRING)
.receiver()
.topicName(topicName)
.subscriptionName(subscriptionName)
.receiveMode(ReceiveMode.PEEK_LOCK)
.buildAsyncClient();
final String actual = receiver.getEntityPath();
final String actualNamespace = receiver.getFullyQualifiedNamespace();
Assertions.assertEquals(entityPath, actual);
Assertions.assertEquals(NAMESPACE, actualNamespace);
}
/**
* Cannot get session state for non-session receiver.
*/
@Test
void cannotPerformGetSessionState() {
final String sessionId = "a-session-id";
StepVerifier.create(receiver.getSessionState(sessionId))
.expectError(IllegalStateException.class)
.verify();
}
/**
* Cannot get session state for non-session receiver.
*/
@Test
void cannotPerformSetSessionState() {
final String sessionId = "a-session-id";
final byte[] sessionState = new byte[]{10, 11, 8};
StepVerifier.create(receiver.setSessionState(sessionId, sessionState))
.expectError(IllegalStateException.class)
.verify();
}
/**
* Cannot get session state for non-session receiver.
*/
@Test
void cannotPerformRenewSessionLock() {
final String sessionId = "a-session-id";
StepVerifier.create(receiver.renewSessionLock(sessionId))
.expectError(IllegalStateException.class)
.verify();
}
/**
* Verifies that we can get a session state.
*/
@SuppressWarnings("unchecked")
@Test
void getSessionState() {
final byte[] bytes = new byte[]{95, 11, 54, 10};
when(managementNode.getSessionState(SESSION_ID, null))
.thenReturn(Mono.just(bytes), Mono.empty());
StepVerifier.create(sessionReceiver.getSessionState(SESSION_ID))
.expectNext(bytes)
.expectComplete()
.verify();
}
/**
* Verifies that we can set a session state.
*/
@Test
void setSessionState() {
final byte[] bytes = new byte[]{95, 11, 54, 10};
when(managementNode.setSessionState(SESSION_ID, bytes, null)).thenReturn(Mono.empty());
StepVerifier.create(sessionReceiver.setSessionState(SESSION_ID, bytes))
.expectComplete()
.verify();
}
/**
* Verifies that we can renew a session state.
*/
@Test
void renewSessionLock() {
final Instant expiry = Instant.ofEpochSecond(1588011761L);
when(managementNode.renewSessionLock(SESSION_ID, null)).thenReturn(Mono.just(expiry));
StepVerifier.create(sessionReceiver.renewSessionLock(SESSION_ID))
.expectNext(expiry.atOffset(ZoneOffset.UTC))
.expectComplete()
.verify();
}
/**
* Verifies that we cannot renew a message lock when using a session receiver.
*/
@Test
void cannotRenewMessageLockInSession() {
final String lockToken = UUID.randomUUID().toString();
StepVerifier.create(sessionReceiver.renewMessageLock(lockToken))
.expectError(IllegalStateException.class)
.verify();
}
/**
* Verifies that we can auto-renew a message lock.
*/
@Test
void autoRenewMessageLock() throws InterruptedException {
final Duration maxDuration = Duration.ofSeconds(8);
final Duration renewalPeriod = Duration.ofSeconds(3);
final String lockToken = "some-token";
final OffsetDateTime startTime = OffsetDateTime.now();
final int atMost = 5;
final Duration totalSleepPeriod = maxDuration.plusMillis(500);
when(managementNode.renewMessageLock(lockToken, null))
.thenReturn(Mono.fromCallable(() -> Instant.now().plus(renewalPeriod)));
final LockRenewalOperation operation = receiver.getAutoRenewMessageLock(lockToken, maxDuration);
Thread.sleep(totalSleepPeriod.toMillis());
logger.info("Finished renewals for first sleep.");
assertEquals(LockRenewalStatus.COMPLETE, operation.getStatus());
assertNull(operation.getThrowable());
assertTrue(startTime.isBefore(operation.getLockedUntil()), String.format(
"initial lockedUntil[%s] is not before lockedUntil[%s]", startTime, operation.getLockedUntil()));
verify(managementNode, Mockito.atMost(atMost)).renewMessageLock(lockToken, null);
}
/**
* Verifies that we can auto-renew a message lock.
*/
@Test
void autoRenewSessionLock() throws InterruptedException {
final Duration maxDuration = Duration.ofSeconds(8);
final Duration renewalPeriod = Duration.ofSeconds(3);
final String sessionId = "some-token";
final OffsetDateTime startTime = OffsetDateTime.now();
final int atMost = 5;
final Duration totalSleepPeriod = maxDuration.plusMillis(500);
when(managementNode.renewSessionLock(sessionId, null))
.thenReturn(Mono.fromCallable(() -> Instant.now().plus(renewalPeriod)));
final LockRenewalOperation operation = sessionReceiver.getAutoRenewSessionLock(sessionId, maxDuration);
Thread.sleep(totalSleepPeriod.toMillis());
logger.info("Finished renewals for first sleep.");
assertEquals(LockRenewalStatus.COMPLETE, operation.getStatus());
assertNull(operation.getThrowable());
assertTrue(startTime.isBefore(operation.getLockedUntil()), String.format(
"initial lockedUntil[%s] is not before lockedUntil[%s]", startTime, operation.getLockedUntil()));
verify(managementNode, Mockito.atMost(atMost)).renewSessionLock(sessionId, null);
}
private List<Message> getMessages(int numberOfEvents) {
final Map<String, String> map = Collections.singletonMap("SAMPLE_HEADER", "foo");
return IntStream.range(0, numberOfEvents)
.mapToObj(index -> getMessage(PAYLOAD_BYTES, messageTrackingUUID, map))
.collect(Collectors.toList());
}
} | class ServiceBusReceiverAsyncClientTest {
private static final String PAYLOAD = "hello";
private static final byte[] PAYLOAD_BYTES = PAYLOAD.getBytes(UTF_8);
private static final int PREFETCH = 5;
private static final String NAMESPACE = "my-namespace-foo.net";
private static final String ENTITY_PATH = "queue-name";
private static final MessagingEntityType ENTITY_TYPE = MessagingEntityType.QUEUE;
private static final String NAMESPACE_CONNECTION_STRING = String.format(
"Endpoint=sb:
NAMESPACE, "some-name", "something-else");
private static final Duration CLEANUP_INTERVAL = Duration.ofSeconds(10);
private static final String SESSION_ID = "my-session-id";
private final ClientLogger logger = new ClientLogger(ServiceBusReceiverAsyncClientTest.class);
private final String messageTrackingUUID = UUID.randomUUID().toString();
private final ReplayProcessor<AmqpEndpointState> endpointProcessor = ReplayProcessor.cacheLast();
private final FluxSink<AmqpEndpointState> endpointSink = endpointProcessor.sink(FluxSink.OverflowStrategy.BUFFER);
private final DirectProcessor<Message> messageProcessor = DirectProcessor.create();
private final FluxSink<Message> messageSink = messageProcessor.sink(FluxSink.OverflowStrategy.BUFFER);
private ServiceBusConnectionProcessor connectionProcessor;
private ServiceBusReceiverAsyncClient receiver;
private ServiceBusReceiverAsyncClient sessionReceiver;
private Duration maxAutoLockRenewalDuration;
@Mock
private ServiceBusReactorReceiver amqpReceiveLink;
@Mock
private ServiceBusReactorReceiver sessionReceiveLink;
@Mock
private ServiceBusAmqpConnection connection;
@Mock
private TokenCredential tokenCredential;
@Mock
private MessageSerializer messageSerializer;
@Mock
private TracerProvider tracerProvider;
@Mock
private ServiceBusManagementNode managementNode;
@Mock
private ServiceBusReceivedMessage receivedMessage;
@Mock
private ServiceBusReceivedMessage receivedMessage2;
@Mock
private Runnable onClientClose;
@Mock
private Function<String, Mono<OffsetDateTime>> renewalOperation;
@BeforeAll
static void beforeAll() {
StepVerifier.setDefaultTimeout(Duration.ofSeconds(100));
}
@AfterAll
static void afterAll() {
StepVerifier.resetDefaultTimeout();
}
@BeforeEach
void setup(TestInfo testInfo) {
logger.info("[{}] Setting up.", testInfo.getDisplayName());
MockitoAnnotations.initMocks(this);
when(amqpReceiveLink.receive()).thenReturn(messageProcessor.publishOn(Schedulers.single()));
when(amqpReceiveLink.getEndpointStates()).thenReturn(endpointProcessor);
ConnectionOptions connectionOptions = new ConnectionOptions(NAMESPACE, tokenCredential,
CbsAuthorizationType.SHARED_ACCESS_SIGNATURE, AmqpTransportType.AMQP, new AmqpRetryOptions(),
ProxyOptions.SYSTEM_DEFAULTS, Schedulers.boundedElastic());
when(connection.getEndpointStates()).thenReturn(endpointProcessor);
endpointSink.next(AmqpEndpointState.ACTIVE);
when(connection.getManagementNode(ENTITY_PATH, ENTITY_TYPE))
.thenReturn(Mono.just(managementNode));
when(connection.createReceiveLink(anyString(), anyString(), any(ReceiveMode.class), any(),
any(MessagingEntityType.class))).thenReturn(Mono.just(amqpReceiveLink));
when(connection.createReceiveLink(anyString(), anyString(), any(ReceiveMode.class), any(),
any(MessagingEntityType.class), anyString())).thenReturn(Mono.just(sessionReceiveLink));
connectionProcessor =
Flux.<ServiceBusAmqpConnection>create(sink -> sink.next(connection))
.subscribeWith(new ServiceBusConnectionProcessor(connectionOptions.getFullyQualifiedNamespace(),
connectionOptions.getRetry()));
receiver = new ServiceBusReceiverAsyncClient(NAMESPACE, ENTITY_PATH, MessagingEntityType.QUEUE,
new ReceiverOptions(ReceiveMode.PEEK_LOCK, PREFETCH), connectionProcessor, CLEANUP_INTERVAL,
tracerProvider, messageSerializer, onClientClose);
sessionReceiver = new ServiceBusReceiverAsyncClient(NAMESPACE, ENTITY_PATH, MessagingEntityType.QUEUE,
new ReceiverOptions(ReceiveMode.PEEK_LOCK, PREFETCH, "Some-Session", false, null),
connectionProcessor, CLEANUP_INTERVAL, tracerProvider, messageSerializer, onClientClose);
}
@AfterEach
void teardown(TestInfo testInfo) {
logger.info("[{}] Tearing down.", testInfo.getDisplayName());
receiver.close();
Mockito.framework().clearInlineMocks();
}
/**
* Verifies that when user calls peek more than one time, It returns different object.
*/
@SuppressWarnings("unchecked")
@Test
void peekTwoMessages() {
final long sequence1 = 10;
final long sequence2 = 12;
final ArgumentCaptor<Long> captor = ArgumentCaptor.forClass(Long.class);
when(receivedMessage.getSequenceNumber()).thenReturn(sequence1);
when(receivedMessage2.getSequenceNumber()).thenReturn(sequence2);
when(managementNode.peek(anyLong(), isNull(), isNull()))
.thenReturn(Mono.just(receivedMessage), Mono.just(receivedMessage2));
StepVerifier.create(receiver.peekMessage())
.expectNext(receivedMessage)
.verifyComplete();
StepVerifier.create(receiver.peekMessage())
.expectNext(receivedMessage2)
.verifyComplete();
verify(managementNode, times(2)).peek(captor.capture(), isNull(), isNull());
final List<Long> allValues = captor.getAllValues();
Assertions.assertEquals(2, allValues.size());
Assertions.assertTrue(allValues.contains(0L));
Assertions.assertTrue(allValues.contains(11L));
}
/**
* Verifies that this peek one messages from a sequence Number.
*/
@Test
void peekWithSequenceOneMessage() {
final int fromSequenceNumber = 10;
final ServiceBusReceivedMessage receivedMessage = mock(ServiceBusReceivedMessage.class);
when(managementNode.peek(fromSequenceNumber, null, null)).thenReturn(Mono.just(receivedMessage));
StepVerifier.create(receiver.peekMessageAt(fromSequenceNumber))
.expectNext(receivedMessage)
.verifyComplete();
}
/**
* Verifies that this receives a number of messages. Verifies that the initial credits we add are equal to the
* prefetch value.
*/
@Test
void receivesNumberOfEvents() {
final int numberOfEvents = 1;
final List<Message> messages = getMessages(10);
ServiceBusReceivedMessage receivedMessage = mock(ServiceBusReceivedMessage.class);
when(receivedMessage.getLockToken()).thenReturn(UUID.randomUUID().toString());
when(messageSerializer.deserialize(any(Message.class), eq(ServiceBusReceivedMessage.class)))
.thenReturn(receivedMessage);
StepVerifier.create(receiver.receiveMessages().take(numberOfEvents))
.then(() -> messages.forEach(m -> messageSink.next(m)))
.expectNextCount(numberOfEvents)
.verifyComplete();
verify(amqpReceiveLink).addCredits(PREFETCH);
}
/**
* Verifies that we error if we try to settle a message with null transaction.
*/
@ParameterizedTest
@EnumSource(DispositionStatus.class)
/**
* Verifies that we error if we try to settle a message with null transaction-id.
*/
@ParameterizedTest
@EnumSource(DispositionStatus.class)
void settleWithNullTransactionId(DispositionStatus dispositionStatus) {
ServiceBusTransactionContext nullTransactionId = new ServiceBusTransactionContext(null);
when(connection.getManagementNode(ENTITY_PATH, ENTITY_TYPE)).thenReturn(Mono.just(managementNode));
when(managementNode.updateDisposition(any(), eq(dispositionStatus), isNull(), isNull(), isNull(),
isNull(), isNull(), isNull()))
.thenReturn(Mono.delay(Duration.ofMillis(250)).then());
when(receivedMessage.getLockToken()).thenReturn("mylockToken");
final Mono<Void> operation;
switch (dispositionStatus) {
case DEFERRED:
operation = receiver.defer(receivedMessage, null, nullTransactionId);
break;
case ABANDONED:
operation = receiver.abandon(receivedMessage, null, nullTransactionId);
break;
case COMPLETED:
operation = receiver.complete(receivedMessage, nullTransactionId);
break;
case SUSPENDED:
operation = receiver.deadLetter(receivedMessage, new DeadLetterOptions(), nullTransactionId);
break;
default:
throw new IllegalArgumentException("Unrecognized operation: " + dispositionStatus);
}
StepVerifier.create(operation)
.expectError(NullPointerException.class)
.verify();
verify(managementNode, never()).updateDisposition(any(), eq(dispositionStatus), isNull(), isNull(),
isNull(), isNull(), isNull(), isNull());
}
/**
* Verifies that we error if we try to complete a null message.
*/
@Test
void completeNullMessage() {
StepVerifier.create(receiver.complete(null)).expectError(NullPointerException.class).verify();
}
/**
* Verifies that we error if we complete in RECEIVE_AND_DELETE mode.
*/
@Test
void completeInReceiveAndDeleteMode() {
final ReceiverOptions options = new ReceiverOptions(ReceiveMode.RECEIVE_AND_DELETE, PREFETCH);
ServiceBusReceiverAsyncClient client = new ServiceBusReceiverAsyncClient(NAMESPACE, ENTITY_PATH,
MessagingEntityType.QUEUE, options, connectionProcessor, CLEANUP_INTERVAL, tracerProvider,
messageSerializer, onClientClose);
final String lockToken1 = UUID.randomUUID().toString();
when(receivedMessage.getLockToken()).thenReturn(lockToken1);
try {
StepVerifier.create(client.complete(receivedMessage))
.expectError(UnsupportedOperationException.class)
.verify();
} finally {
client.close();
}
}
/**
* Verifies that this peek batch of messages.
*/
@Test
void peekBatchMessages() {
final int numberOfEvents = 2;
when(managementNode.peek(0, null, null, numberOfEvents))
.thenReturn(Flux.fromArray(new ServiceBusReceivedMessage[]{receivedMessage, receivedMessage2}));
StepVerifier.create(receiver.peekMessages(numberOfEvents))
.expectNextCount(numberOfEvents)
.verifyComplete();
}
/**
* Verifies that this peek batch of messages from a sequence Number.
*/
@Test
void peekBatchWithSequenceNumberMessages() {
final int numberOfEvents = 2;
final int fromSequenceNumber = 10;
when(managementNode.peek(fromSequenceNumber, null, null, numberOfEvents))
.thenReturn(Flux.fromArray(new ServiceBusReceivedMessage[]{receivedMessage, receivedMessage2}));
StepVerifier.create(receiver.peekMessagesAt(numberOfEvents, fromSequenceNumber))
.expectNext(receivedMessage, receivedMessage2)
.verifyComplete();
}
/**
* Verifies that we can deadletter a message with an error and description.
*/
@Test
void deadLetterWithDescription() {
final String lockToken1 = UUID.randomUUID().toString();
final String description = "some-dead-letter-description";
final String reason = "dead-letter-reason";
final Map<String, Object> propertiesToModify = new HashMap<>();
propertiesToModify.put("something", true);
final DeadLetterOptions deadLetterOptions = new DeadLetterOptions().setDeadLetterReason(reason)
.setDeadLetterErrorDescription(description)
.setPropertiesToModify(propertiesToModify);
final OffsetDateTime expiration = OffsetDateTime.now().plus(Duration.ofMinutes(5));
final MessageWithLockToken message = mock(MessageWithLockToken.class);
when(messageSerializer.deserialize(message, ServiceBusReceivedMessage.class)).thenReturn(receivedMessage);
when(receivedMessage.getLockToken()).thenReturn(lockToken1);
when(receivedMessage.getLockedUntil()).thenReturn(expiration);
when(amqpReceiveLink.updateDisposition(eq(lockToken1), argThat(e -> e.getType() == DeliveryStateType.Rejected))).thenReturn(Mono.empty());
StepVerifier.create(receiver.receiveMessages()
.take(1)
.flatMap(context -> receiver.deadLetter(context.getMessage(), deadLetterOptions)))
.then(() -> messageSink.next(message))
.expectNext()
.verifyComplete();
verify(amqpReceiveLink).updateDisposition(eq(lockToken1), isA(Rejected.class));
}
/**
* Verifies that the user can complete settlement methods on received message.
*/
@ParameterizedTest
@EnumSource(DispositionStatus.class)
void settleMessageOnManagement(DispositionStatus dispositionStatus) {
final String lockToken1 = UUID.randomUUID().toString();
final String lockToken2 = UUID.randomUUID().toString();
final OffsetDateTime expiration = OffsetDateTime.now().plus(Duration.ofMinutes(5));
final long sequenceNumber = 10L;
final long sequenceNumber2 = 15L;
final MessageWithLockToken message = mock(MessageWithLockToken.class);
final MessageWithLockToken message2 = mock(MessageWithLockToken.class);
when(messageSerializer.deserialize(message, ServiceBusReceivedMessage.class)).thenReturn(receivedMessage);
when(messageSerializer.deserialize(message2, ServiceBusReceivedMessage.class)).thenReturn(receivedMessage2);
when(receivedMessage.getLockToken()).thenReturn(lockToken1);
when(receivedMessage.getLockedUntil()).thenReturn(expiration);
when(receivedMessage2.getLockToken()).thenReturn(lockToken2);
when(receivedMessage2.getLockedUntil()).thenReturn(expiration);
when(connection.getManagementNode(eq(ENTITY_PATH), eq(ENTITY_TYPE)))
.thenReturn(Mono.just(managementNode));
when(managementNode.receiveDeferredMessages(eq(ReceiveMode.PEEK_LOCK), isNull(), isNull(), argThat(arg -> {
boolean foundFirst = false;
boolean foundSecond = false;
for (Long seq : arg) {
if (!foundFirst && sequenceNumber == seq) {
foundFirst = true;
} else if (!foundSecond && sequenceNumber2 == seq) {
foundSecond = true;
}
}
return foundFirst && foundSecond;
})))
.thenReturn(Flux.just(receivedMessage, receivedMessage2));
when(managementNode.updateDisposition(lockToken1, dispositionStatus, null, null, null, null, null, null))
.thenReturn(Mono.empty());
when(managementNode.updateDisposition(lockToken2, dispositionStatus, null, null, null, null, null, null))
.thenReturn(Mono.empty());
StepVerifier.create(receiver.receiveDeferredMessages(Arrays.asList(sequenceNumber, sequenceNumber2)))
.expectNext(receivedMessage, receivedMessage2)
.verifyComplete();
final Mono<Void> operation;
switch (dispositionStatus) {
case DEFERRED:
operation = receiver.defer(receivedMessage);
break;
case ABANDONED:
operation = receiver.abandon(receivedMessage);
break;
case COMPLETED:
operation = receiver.complete(receivedMessage);
break;
case SUSPENDED:
operation = receiver.deadLetter(receivedMessage);
break;
default:
throw new IllegalArgumentException("Unrecognized operation: " + dispositionStatus);
}
StepVerifier.create(operation)
.verifyComplete();
verify(managementNode).updateDisposition(lockToken1, dispositionStatus, null, null, null, null, null, null);
verify(managementNode, never()).updateDisposition(lockToken2, dispositionStatus, null, null, null, null, null, null);
}
/**
* Verifies that this receive deferred one messages from a sequence Number.
*/
@Test
void receiveDeferredWithSequenceOneMessage() {
final int fromSequenceNumber = 10;
final ServiceBusReceivedMessage receivedMessage = mock(ServiceBusReceivedMessage.class);
when(managementNode.receiveDeferredMessages(any(), any(), any(), any())).thenReturn(Flux.just(receivedMessage));
StepVerifier.create(receiver.receiveDeferredMessage(fromSequenceNumber))
.expectNext(receivedMessage)
.verifyComplete();
}
/**
* Verifies that this receive deferred messages from a sequence Number.
*/
@Test
void receiveDeferredBatchFromSequenceNumber() {
final long fromSequenceNumber1 = 10;
final long fromSequenceNumber2 = 11;
when(managementNode.receiveDeferredMessages(any(), any(), any(), any()))
.thenReturn(Flux.fromArray(new ServiceBusReceivedMessage[]{receivedMessage, receivedMessage2}));
StepVerifier.create(receiver.receiveDeferredMessages(Arrays.asList(fromSequenceNumber1, fromSequenceNumber2)))
.expectNext(receivedMessage)
.expectNext(receivedMessage2)
.verifyComplete();
}
/**
* Verifies that the onClientClose is called.
*/
@Test
void callsClientClose() {
receiver.close();
verify(onClientClose).run();
}
/**
* Verifies that the onClientClose is only called once.
*/
@Test
void callsClientCloseOnce() {
receiver.close();
receiver.close();
verify(onClientClose).run();
}
/**
* Tests that invalid options throws and null options.
*/
@Test
void receiveIllegalOptions() {
ServiceBusReceiverClientBuilder builder = new ServiceBusClientBuilder()
.connectionString(NAMESPACE_CONNECTION_STRING)
.receiver()
.topicName("baz").subscriptionName("bar").prefetchCount(-1)
.receiveMode(ReceiveMode.PEEK_LOCK);
Assertions.assertThrows(IllegalArgumentException.class, () -> builder.buildAsyncClient());
}
@Test
void topicCorrectEntityPath() {
final String topicName = "foo";
final String subscriptionName = "bar";
final String entityPath = String.join("/", topicName, "subscriptions", subscriptionName);
final ServiceBusReceiverAsyncClient receiver = new ServiceBusClientBuilder()
.connectionString(NAMESPACE_CONNECTION_STRING)
.receiver()
.topicName(topicName)
.subscriptionName(subscriptionName)
.receiveMode(ReceiveMode.PEEK_LOCK)
.buildAsyncClient();
final String actual = receiver.getEntityPath();
final String actualNamespace = receiver.getFullyQualifiedNamespace();
Assertions.assertEquals(entityPath, actual);
Assertions.assertEquals(NAMESPACE, actualNamespace);
}
/**
* Cannot get session state for non-session receiver.
*/
@Test
void cannotPerformGetSessionState() {
final String sessionId = "a-session-id";
StepVerifier.create(receiver.getSessionState(sessionId))
.expectError(IllegalStateException.class)
.verify();
}
/**
* Cannot get session state for non-session receiver.
*/
@Test
void cannotPerformSetSessionState() {
final String sessionId = "a-session-id";
final byte[] sessionState = new byte[]{10, 11, 8};
StepVerifier.create(receiver.setSessionState(sessionId, sessionState))
.expectError(IllegalStateException.class)
.verify();
}
/**
* Cannot get session state for non-session receiver.
*/
@Test
void cannotPerformRenewSessionLock() {
final String sessionId = "a-session-id";
StepVerifier.create(receiver.renewSessionLock(sessionId))
.expectError(IllegalStateException.class)
.verify();
}
/**
* Verifies that we can get a session state.
*/
@SuppressWarnings("unchecked")
@Test
void getSessionState() {
final byte[] bytes = new byte[]{95, 11, 54, 10};
when(managementNode.getSessionState(SESSION_ID, null))
.thenReturn(Mono.just(bytes), Mono.empty());
StepVerifier.create(sessionReceiver.getSessionState(SESSION_ID))
.expectNext(bytes)
.expectComplete()
.verify();
}
/**
* Verifies that we can set a session state.
*/
@Test
void setSessionState() {
final byte[] bytes = new byte[]{95, 11, 54, 10};
when(managementNode.setSessionState(SESSION_ID, bytes, null)).thenReturn(Mono.empty());
StepVerifier.create(sessionReceiver.setSessionState(SESSION_ID, bytes))
.expectComplete()
.verify();
}
/**
* Verifies that we can renew a session state.
*/
@Test
void renewSessionLock() {
final Instant expiry = Instant.ofEpochSecond(1588011761L);
when(managementNode.renewSessionLock(SESSION_ID, null)).thenReturn(Mono.just(expiry));
StepVerifier.create(sessionReceiver.renewSessionLock(SESSION_ID))
.expectNext(expiry.atOffset(ZoneOffset.UTC))
.expectComplete()
.verify();
}
/**
* Verifies that we cannot renew a message lock when using a session receiver.
*/
@Test
void cannotRenewMessageLockInSession() {
final String lockToken = UUID.randomUUID().toString();
StepVerifier.create(sessionReceiver.renewMessageLock(lockToken))
.expectError(IllegalStateException.class)
.verify();
}
/**
* Verifies that we can auto-renew a message lock.
*/
@Test
void autoRenewMessageLock() throws InterruptedException {
final Duration maxDuration = Duration.ofSeconds(8);
final Duration renewalPeriod = Duration.ofSeconds(3);
final String lockToken = "some-token";
final OffsetDateTime startTime = OffsetDateTime.now();
final int atMost = 5;
final Duration totalSleepPeriod = maxDuration.plusMillis(500);
when(managementNode.renewMessageLock(lockToken, null))
.thenReturn(Mono.fromCallable(() -> Instant.now().plus(renewalPeriod)));
final LockRenewalOperation operation = receiver.getAutoRenewMessageLock(lockToken, maxDuration);
Thread.sleep(totalSleepPeriod.toMillis());
logger.info("Finished renewals for first sleep.");
assertEquals(LockRenewalStatus.COMPLETE, operation.getStatus());
assertNull(operation.getThrowable());
assertTrue(startTime.isBefore(operation.getLockedUntil()), String.format(
"initial lockedUntil[%s] is not before lockedUntil[%s]", startTime, operation.getLockedUntil()));
verify(managementNode, Mockito.atMost(atMost)).renewMessageLock(lockToken, null);
}
/**
* Verifies that we can auto-renew a message lock.
*/
@Test
void autoRenewSessionLock() throws InterruptedException {
final Duration maxDuration = Duration.ofSeconds(8);
final Duration renewalPeriod = Duration.ofSeconds(3);
final String sessionId = "some-token";
final OffsetDateTime startTime = OffsetDateTime.now();
final int atMost = 5;
final Duration totalSleepPeriod = maxDuration.plusMillis(500);
when(managementNode.renewSessionLock(sessionId, null))
.thenReturn(Mono.fromCallable(() -> Instant.now().plus(renewalPeriod)));
final LockRenewalOperation operation = sessionReceiver.getAutoRenewSessionLock(sessionId, maxDuration);
Thread.sleep(totalSleepPeriod.toMillis());
logger.info("Finished renewals for first sleep.");
assertEquals(LockRenewalStatus.COMPLETE, operation.getStatus());
assertNull(operation.getThrowable());
assertTrue(startTime.isBefore(operation.getLockedUntil()), String.format(
"initial lockedUntil[%s] is not before lockedUntil[%s]", startTime, operation.getLockedUntil()));
verify(managementNode, Mockito.atMost(atMost)).renewSessionLock(sessionId, null);
}
private List<Message> getMessages(int numberOfEvents) {
final Map<String, String> map = Collections.singletonMap("SAMPLE_HEADER", "foo");
return IntStream.range(0, numberOfEvents)
.mapToObj(index -> getMessage(PAYLOAD_BYTES, messageTrackingUUID, map))
.collect(Collectors.toList());
}
} |
method reference here as well -> anywhere we are calling a static method can be replaced by a method reference | Mono<PagedResponse<ModelData>> listModelsSinglePageAsync(ListModelOptions listModelOptions, Context context){
return protocolLayer.getDigitalTwinModels().listSinglePageAsync(
listModelOptions.getDependenciesFor(),
listModelOptions.getIncludeModelDefinition(),
new DigitalTwinModelsListOptions().setMaxItemCount(listModelOptions.getMaxItemCount()),
context)
.map(
objectPagedResponse -> {
List<ModelData> convertedList = objectPagedResponse.getValue().stream()
.map(object -> ModelDataConverter.map(object))
.filter(Objects::nonNull)
.collect(Collectors.toList());
return new PagedResponseBase<>(
objectPagedResponse.getRequest(),
objectPagedResponse.getStatusCode(),
objectPagedResponse.getHeaders(),
convertedList,
null,
((PagedResponseBase) objectPagedResponse).getDeserializedHeaders());
}
);
} | .map(object -> ModelDataConverter.map(object)) | new DigitalTwinModelsListOptions().setMaxItemCount(listModelOptions.getMaxItemCount()),
context)
.map(
objectPagedResponse -> {
List<ModelData> convertedList = objectPagedResponse.getValue().stream()
.map(ModelDataConverter::map)
.filter(Objects::nonNull)
.collect(Collectors.toList());
return new PagedResponseBase<>(
objectPagedResponse.getRequest(),
objectPagedResponse.getStatusCode(),
objectPagedResponse.getHeaders(),
convertedList,
null,
((PagedResponseBase) objectPagedResponse).getDeserializedHeaders());
} | class to convert the relationship to.
* @param <T> The generic type to convert the relationship to.
* @return A {@link PagedFlux} | class to convert the relationship to.
* @param <T> The generic type to convert the relationship to.
* @return A {@link PagedFlux} |
https://docs.oracle.com/javase/tutorial/java/javaOO/methodreferences.html | Mono<PagedResponse<ModelData>> listModelsSinglePageAsync(ListModelOptions listModelOptions, Context context){
return protocolLayer.getDigitalTwinModels().listSinglePageAsync(
listModelOptions.getDependenciesFor(),
listModelOptions.getIncludeModelDefinition(),
new DigitalTwinModelsListOptions().setMaxItemCount(listModelOptions.getMaxItemCount()),
context)
.map(
objectPagedResponse -> {
List<ModelData> convertedList = objectPagedResponse.getValue().stream()
.map(object -> ModelDataConverter.map(object))
.filter(Objects::nonNull)
.collect(Collectors.toList());
return new PagedResponseBase<>(
objectPagedResponse.getRequest(),
objectPagedResponse.getStatusCode(),
objectPagedResponse.getHeaders(),
convertedList,
null,
((PagedResponseBase) objectPagedResponse).getDeserializedHeaders());
}
);
} | .map(object -> ModelDataConverter.map(object)) | new DigitalTwinModelsListOptions().setMaxItemCount(listModelOptions.getMaxItemCount()),
context)
.map(
objectPagedResponse -> {
List<ModelData> convertedList = objectPagedResponse.getValue().stream()
.map(ModelDataConverter::map)
.filter(Objects::nonNull)
.collect(Collectors.toList());
return new PagedResponseBase<>(
objectPagedResponse.getRequest(),
objectPagedResponse.getStatusCode(),
objectPagedResponse.getHeaders(),
convertedList,
null,
((PagedResponseBase) objectPagedResponse).getDeserializedHeaders());
} | class to convert the relationship to.
* @param <T> The generic type to convert the relationship to.
* @return A {@link PagedFlux} | class to convert the relationship to.
* @param <T> The generic type to convert the relationship to.
* @return A {@link PagedFlux} |
How to access response status code? `ErrorResponse.getValue().getError().getCode()` is string. | public static void deleteTwins() throws IOException, InterruptedException {
System.out.println("DELETE DIGITAL TWINS");
Map<String, String> twins = FileHelper.loadAllFilesInPath(TwinsPath);
final Semaphore deleteTwinsSemaphore = new Semaphore(0);
twins
.forEach((twinId, twinContent) -> client.deleteDigitalTwin(twinId)
.subscribe(
aVoid -> { },
throwable -> {
if (!(throwable instanceof ErrorResponseException) || !((ErrorResponseException) throwable).getValue().getError().getCode().equals("DigitalTwinNotFound")) {
throw new RuntimeException(throwable);
}
},
() -> {
System.out.println("Deleted digital twin: " + twinId);
deleteTwinsSemaphore.release();
}));
boolean created = deleteTwinsSemaphore.tryAcquire(twins.size(), MaxTimeForTwinOperationsInSeconds, TimeUnit.SECONDS);
System.out.println("Twins deleted: " + created);
} | if (!(throwable instanceof ErrorResponseException) || !((ErrorResponseException) throwable).getValue().getError().getCode().equals("DigitalTwinNotFound")) { | public static void deleteTwins() throws IOException, InterruptedException {
System.out.println("DELETE DIGITAL TWINS");
Map<String, String> twins = FileHelper.loadAllFilesInPath(TwinsPath);
final Semaphore deleteTwinsSemaphore = new Semaphore(0);
twins
.forEach((twinId, twinContent) -> client.deleteDigitalTwin(twinId)
.doOnSuccess(aVoid -> System.out.println("Deleted digital twin: " + twinId))
.doOnError(throwable -> {
if (!(throwable instanceof ErrorResponseException) || !((ErrorResponseException) throwable).getValue().getError().getCode().equals("DigitalTwinNotFound")) {
System.err.println("Could not delete digital twin " + twinId + " due to " + throwable);
}
})
.doOnTerminate(deleteTwinsSemaphore::release)
.subscribe());
boolean created = deleteTwinsSemaphore.tryAcquire(twins.size(), MaxWaitTimeAsyncOperationsInSeconds, TimeUnit.SECONDS);
System.out.println("Twins deleted: " + created);
} | class DigitalTwinsLifecycleSample {
private static final ClientLogger logger = new ClientLogger(DigitalTwinsLifecycleSample.class);
private static final String tenantId = System.getenv("TENANT_ID");
private static final String clientId = System.getenv("CLIENT_ID");
private static final String clientSecret = System.getenv("CLIENT_SECRET");
private static final String endpoint = System.getenv("DIGITAL_TWINS_ENDPOINT");
private static final int MaxTimeForTwinOperationsInSeconds = 10;
private static final URL DtdlDirectoryUrl = DigitalTwinsLifecycleSample.class.getClassLoader().getResource("DTDL");
private static final Path DtDlDirectoryPath;
private static final Path TwinsPath;
private static final Path ModelsPath;
private static final Path RelationshipsPath;
private static final DigitalTwinsAsyncClient client;
static {
try {
assert DtdlDirectoryUrl != null;
DtDlDirectoryPath = Paths.get(DtdlDirectoryUrl.toURI());
} catch (URISyntaxException e) {
logger.error("Unable to convert the DTDL directory URL to URI: ", e);
throw new RuntimeException(e);
}
TwinsPath = Paths.get(DtDlDirectoryPath.toString(), "DigitalTwins");
ModelsPath = Paths.get(DtDlDirectoryPath.toString(), "Models");
RelationshipsPath = Paths.get(DtDlDirectoryPath.toString(), "Relationships");
client = new DigitalTwinsClientBuilder()
.tokenCredential(
new ClientSecretCredentialBuilder()
.tenantId(tenantId)
.clientId(clientId)
.clientSecret(clientSecret)
.build()
)
.endpoint(endpoint)
.httpLogOptions(
new HttpLogOptions()
.setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS))
.buildAsyncClient();
}
public static void main(String[] args) throws IOException, InterruptedException {
deleteTwins();
createTwins();
}
public static void createTwins() throws IOException, InterruptedException {
System.out.println("CREATE DIGITAL TWINS");
Map<String, String> twins = FileHelper.loadAllFilesInPath(TwinsPath);
final Semaphore createTwinsSemaphore = new Semaphore(0);
twins
.forEach(
(twinId, twinContent) -> client.createDigitalTwinWithResponse(twinId, twinContent)
.subscribe(
stringDigitalTwinsResponse -> {
System.out.println("Created digital twin: " + twinId);
System.out.println("\t Body: " + stringDigitalTwinsResponse.getValue());
},
throwable -> System.err.println("Could not create digital twin " + twinId + " due to " + throwable),
createTwinsSemaphore::release));
boolean created = createTwinsSemaphore.tryAcquire(twins.size(), MaxTimeForTwinOperationsInSeconds, TimeUnit.SECONDS);
System.out.println("Twins created: " + created);
}
} | class DigitalTwinsLifecycleSample {
private static final String tenantId = System.getenv("TENANT_ID");
private static final String clientId = System.getenv("CLIENT_ID");
private static final String clientSecret = System.getenv("CLIENT_SECRET");
private static final String endpoint = System.getenv("DIGITAL_TWINS_ENDPOINT");
private static final int MaxWaitTimeAsyncOperationsInSeconds = 10;
private static final URL DtdlDirectoryUrl = DigitalTwinsLifecycleSample.class.getClassLoader().getResource("DTDL");
private static final Path DtDlDirectoryPath;
private static final Path TwinsPath;
private static final Path ModelsPath;
private static final Path RelationshipsPath;
private static final DigitalTwinsAsyncClient client;
static {
try {
assert DtdlDirectoryUrl != null;
DtDlDirectoryPath = Paths.get(DtdlDirectoryUrl.toURI());
} catch (URISyntaxException e) {
System.err.println("Unable to convert the DTDL directory URL to URI: " + e);
throw new RuntimeException(e);
}
TwinsPath = Paths.get(DtDlDirectoryPath.toString(), "DigitalTwins");
ModelsPath = Paths.get(DtDlDirectoryPath.toString(), "Models");
RelationshipsPath = Paths.get(DtDlDirectoryPath.toString(), "Relationships");
client = new DigitalTwinsClientBuilder()
.tokenCredential(
new ClientSecretCredentialBuilder()
.tenantId(tenantId)
.clientId(clientId)
.clientSecret(clientSecret)
.build()
)
.endpoint(endpoint)
.httpLogOptions(
new HttpLogOptions()
.setLogLevel(HttpLogDetailLevel.NONE))
.buildAsyncClient();
}
public static void main(String[] args) throws IOException, InterruptedException {
deleteTwins();
createTwins();
}
public static void createTwins() throws IOException, InterruptedException {
System.out.println("CREATE DIGITAL TWINS");
Map<String, String> twins = FileHelper.loadAllFilesInPath(TwinsPath);
final Semaphore createTwinsSemaphore = new Semaphore(0);
twins
.forEach((twinId, twinContent) -> client.createDigitalTwinWithResponse(twinId, twinContent)
.doOnSuccess(response -> System.out.println("Created digital twin: " + twinId + "\n\t Body: " + response.getValue()))
.doOnError(throwable -> System.err.println("Could not create digital twin " + twinId + " due to " + throwable))
.doOnTerminate(createTwinsSemaphore::release)
.subscribe());
boolean created = createTwinsSemaphore.tryAcquire(twins.size(), MaxWaitTimeAsyncOperationsInSeconds, TimeUnit.SECONDS);
System.out.println("Twins created: " + created);
}
} |
Can you add a test for domain filter where a returned entity gets filtered out? [Here](https://github.com/Azure/azure-sdk-for-python/blob/master/sdk/textanalytics/azure-ai-textanalytics/tests/test_recognize_pii_entities.py#L599) is a python test for taht | public void recognizePiiEntitiesWithRecognizePiiEntityOptions() {
textAnalyticsClient.recognizePiiEntities("My SSN is 859-98-0987", "en",
new RecognizePiiEntityOptions().setDomainFilter(PiiEntityDomainType.PROTECTED_HEALTH_INFORMATION))
.forEach(entity -> System.out.printf(
"Recognized Personally Identifiable Information entity: %s, entity category: %s,"
+ " entity subcategory: %s, confidence score: %f.%n",
entity.getText(), entity.getCategory(), entity.getSubcategory(), entity.getConfidenceScore()));
} | public void recognizePiiEntitiesWithRecognizePiiEntityOptions() {
PiiEntityCollection piiEntityCollection = textAnalyticsClient.recognizePiiEntities(
"My SSN is 859-98-0987", "en",
new RecognizePiiEntityOptions().setDomainFilter(PiiEntityDomainType.PROTECTED_HEALTH_INFORMATION));
System.out.printf("Redacted Text: %s%n", piiEntityCollection.getRedactedText());
piiEntityCollection.forEach(entity -> System.out.printf(
"Recognized Personally Identifiable Information entity: %s, entity category: %s,"
+ " entity subcategory: %s, confidence score: %f.%n",
entity.getText(), entity.getCategory(), entity.getSubcategory(), entity.getConfidenceScore()));
} | class TextAnalyticsClientJavaDocCodeSnippets {
private TextAnalyticsClient textAnalyticsClient = new TextAnalyticsClientBuilder().buildClient();
/**
* Code snippet for creating a {@link TextAnalyticsClient} with pipeline
*/
public void createTextAnalyticsClientWithPipeline() {
HttpPipeline pipeline = new HttpPipelineBuilder()
.policies(/* add policies */)
.build();
TextAnalyticsClient textAnalyticsClient = new TextAnalyticsClientBuilder()
.credential(new AzureKeyCredential("{key}"))
.endpoint("{endpoint}")
.pipeline(pipeline)
.buildClient();
}
/**
* Code snippet for creating a {@link TextAnalyticsClient}
*/
public void createTextAnalyticsClient() {
TextAnalyticsClient textAnalyticsClient = new TextAnalyticsClientBuilder()
.credential(new AzureKeyCredential("{key}"))
.endpoint("{endpoint}")
.buildClient();
}
/**
* Code snippet for {@link TextAnalyticsClient
*/
public void detectLanguage() {
DetectedLanguage detectedLanguage = textAnalyticsClient.detectLanguage("Bonjour tout le monde");
System.out.printf("Detected language name: %s, ISO 6391 name: %s, confidence score: %f.%n",
detectedLanguage.getName(), detectedLanguage.getIso6391Name(), detectedLanguage.getConfidenceScore());
}
/**
* Code snippet for {@link TextAnalyticsClient
*/
public void detectLanguageWithCountryHint() {
DetectedLanguage detectedLanguage = textAnalyticsClient.detectLanguage(
"This text is in English", "US");
System.out.printf("Detected language name: %s, ISO 6391 name: %s, confidence score: %f.%n",
detectedLanguage.getName(), detectedLanguage.getIso6391Name(), detectedLanguage.getConfidenceScore());
}
/**
* Code snippet for {@link TextAnalyticsClient
*/
public void detectLanguageStringListWithOptions() {
List<String> documents = Arrays.asList(
"This is written in English",
"Este es un documento escrito en Español."
);
DetectLanguageResultCollection resultCollection =
textAnalyticsClient.detectLanguageBatch(documents, "US", null);
TextDocumentBatchStatistics batchStatistics = resultCollection.getStatistics();
System.out.printf("A batch of documents statistics, transaction count: %s, valid document count: %s.%n",
batchStatistics.getTransactionCount(), batchStatistics.getValidDocumentCount());
resultCollection.forEach(detectLanguageResult -> {
System.out.printf("Document ID: %s%n", detectLanguageResult.getId());
DetectedLanguage detectedLanguage = detectLanguageResult.getPrimaryLanguage();
System.out.printf("Primary language name: %s, ISO 6391 name: %s, confidence score: %f.%n",
detectedLanguage.getName(), detectedLanguage.getIso6391Name(),
detectedLanguage.getConfidenceScore());
});
}
/**
* Code snippet for {@link TextAnalyticsClient
*/
public void detectBatchLanguagesMaxOverload() {
List<DetectLanguageInput> detectLanguageInputs = Arrays.asList(
new DetectLanguageInput("1", "This is written in English.", "US"),
new DetectLanguageInput("2", "Este es un documento escrito en Español.", "es")
);
Response<DetectLanguageResultCollection> response =
textAnalyticsClient.detectLanguageBatchWithResponse(detectLanguageInputs,
new TextAnalyticsRequestOptions().setIncludeStatistics(true), Context.NONE);
System.out.printf("Status code of request response: %d%n", response.getStatusCode());
DetectLanguageResultCollection detectedLanguageResultCollection = response.getValue();
TextDocumentBatchStatistics batchStatistics = detectedLanguageResultCollection.getStatistics();
System.out.printf(
"Documents statistics: document count = %s, erroneous document count = %s, transaction count = %s,"
+ " valid document count = %s.%n",
batchStatistics.getDocumentCount(), batchStatistics.getInvalidDocumentCount(),
batchStatistics.getTransactionCount(), batchStatistics.getValidDocumentCount());
detectedLanguageResultCollection.forEach(detectLanguageResult -> {
System.out.printf("Document ID: %s%n", detectLanguageResult.getId());
DetectedLanguage detectedLanguage = detectLanguageResult.getPrimaryLanguage();
System.out.printf("Primary language name: %s, ISO 6391 name: %s, confidence score: %f.%n",
detectedLanguage.getName(), detectedLanguage.getIso6391Name(),
detectedLanguage.getConfidenceScore());
});
}
/**
* Code snippet for {@link TextAnalyticsClient
*/
public void recognizeEntities() {
final CategorizedEntityCollection recognizeEntitiesResult =
textAnalyticsClient.recognizeEntities("Satya Nadella is the CEO of Microsoft");
for (CategorizedEntity entity : recognizeEntitiesResult) {
System.out.printf("Recognized entity: %s, entity category: %s, confidence score: %f.%n",
entity.getText(), entity.getCategory(), entity.getConfidenceScore());
}
}
/**
* Code snippet for {@link TextAnalyticsClient
*/
public void recognizeEntitiesWithLanguage() {
final CategorizedEntityCollection recognizeEntitiesResult =
textAnalyticsClient.recognizeEntities("Satya Nadella is the CEO of Microsoft", "en");
for (CategorizedEntity entity : recognizeEntitiesResult) {
System.out.printf("Recognized entity: %s, entity category: %s, confidence score: %f.%n",
entity.getText(), entity.getCategory(), entity.getConfidenceScore());
}
}
/**
* Code snippet for {@link TextAnalyticsClient
*/
public void recognizeEntitiesStringListWithOptions() {
List<String> documents = Arrays.asList(
"I had a wonderful trip to Seattle last week.",
"I work at Microsoft.");
RecognizeEntitiesResultCollection resultCollection =
textAnalyticsClient.recognizeEntitiesBatch(documents, "en", null);
TextDocumentBatchStatistics batchStatistics = resultCollection.getStatistics();
System.out.printf(
"A batch of documents statistics, transaction count: %s, valid document count: %s.%n",
batchStatistics.getTransactionCount(), batchStatistics.getValidDocumentCount());
resultCollection.forEach(recognizeEntitiesResult ->
recognizeEntitiesResult.getEntities().forEach(entity ->
System.out.printf("Recognized entity: %s, entity category: %s, confidence score: %f.%n",
entity.getText(), entity.getCategory(), entity.getConfidenceScore())));
}
/**
* Code snippet for {@link TextAnalyticsClient
*/
public void recognizeBatchEntitiesMaxOverload() {
List<TextDocumentInput> textDocumentInputs = Arrays.asList(
new TextDocumentInput("0", "I had a wonderful trip to Seattle last week.").setLanguage("en"),
new TextDocumentInput("1", "I work at Microsoft.").setLanguage("en")
);
Response<RecognizeEntitiesResultCollection> response =
textAnalyticsClient.recognizeEntitiesBatchWithResponse(textDocumentInputs,
new TextAnalyticsRequestOptions().setIncludeStatistics(true), Context.NONE);
System.out.printf("Status code of request response: %d%n", response.getStatusCode());
RecognizeEntitiesResultCollection recognizeEntitiesResultCollection = response.getValue();
TextDocumentBatchStatistics batchStatistics = recognizeEntitiesResultCollection.getStatistics();
System.out.printf(
"A batch of documents statistics, transaction count: %s, valid document count: %s.%n",
batchStatistics.getTransactionCount(), batchStatistics.getValidDocumentCount());
recognizeEntitiesResultCollection.forEach(recognizeEntitiesResult ->
recognizeEntitiesResult.getEntities().forEach(entity ->
System.out.printf("Recognized entity: %s, entity category: %s, confidence score: %f.%n",
entity.getText(), entity.getCategory(), entity.getConfidenceScore())));
}
/**
* Code snippet for {@link TextAnalyticsClient
*/
public void recognizePiiEntities() {
for (PiiEntity entity : textAnalyticsClient.recognizePiiEntities("My SSN is 859-98-0987")) {
System.out.printf(
"Recognized Personally Identifiable Information entity: %s, entity category: %s,"
+ " entity subcategory: %s, confidence score: %f.%n",
entity.getText(), entity.getCategory(), entity.getSubcategory(), entity.getConfidenceScore());
}
}
/**
* Code snippet for {@link TextAnalyticsClient
*/
public void recognizePiiEntitiesWithLanguage() {
textAnalyticsClient.recognizePiiEntities("My SSN is 859-98-0987", "en")
.forEach(entity -> System.out.printf(
"Recognized Personally Identifiable Information entity: %s, entity category: %s,"
+ " entity subcategory: %s, confidence score: %f.%n",
entity.getText(), entity.getCategory(), entity.getSubcategory(), entity.getConfidenceScore()));
}
/**
* Code snippet for {@link TextAnalyticsClient
*/
/**
* Code snippet for {@link TextAnalyticsClient
*/
public void recognizePiiEntitiesStringListWithOptions() {
List<String> documents = Arrays.asList(
"My SSN is 859-98-0987",
"Visa card 4111 1111 1111 1111"
);
RecognizePiiEntitiesResultCollection resultCollection = textAnalyticsClient.recognizePiiEntitiesBatch(
documents, "en", new RecognizePiiEntityOptions().setIncludeStatistics(true));
TextDocumentBatchStatistics batchStatistics = resultCollection.getStatistics();
System.out.printf("A batch of documents statistics, transaction count: %s, valid document count: %s.%n",
batchStatistics.getTransactionCount(), batchStatistics.getValidDocumentCount());
resultCollection.forEach(recognizePiiEntitiesResult ->
recognizePiiEntitiesResult.getEntities().forEach(entity -> System.out.printf(
"Recognized Personally Identifiable Information entity: %s, entity category: %s,"
+ " entity subcategory: %s, confidence score: %f.%n",
entity.getText(), entity.getCategory(), entity.getSubcategory(), entity.getConfidenceScore())));
}
/**
* Code snippet for {@link TextAnalyticsClient
*/
public void recognizeBatchPiiEntitiesMaxOverload() {
List<TextDocumentInput> textDocumentInputs = Arrays.asList(
new TextDocumentInput("0", "My SSN is 859-98-0987"),
new TextDocumentInput("1", "Visa card 4111 1111 1111 1111")
);
Response<RecognizePiiEntitiesResultCollection> response =
textAnalyticsClient.recognizePiiEntitiesBatchWithResponse(textDocumentInputs,
new RecognizePiiEntityOptions().setIncludeStatistics(true), Context.NONE);
RecognizePiiEntitiesResultCollection resultCollection = response.getValue();
TextDocumentBatchStatistics batchStatistics = resultCollection.getStatistics();
System.out.printf("A batch of documents statistics, transaction count: %s, valid document count: %s.%n",
batchStatistics.getTransactionCount(), batchStatistics.getValidDocumentCount());
resultCollection.forEach(recognizePiiEntitiesResult ->
recognizePiiEntitiesResult.getEntities().forEach(entity -> System.out.printf(
"Recognized Personally Identifiable Information entity: %s, entity category: %s,"
+ " entity subcategory: %s, confidence score: %f.%n",
entity.getText(), entity.getCategory(), entity.getSubcategory(), entity.getConfidenceScore())));
}
/**
* Code snippet for {@link TextAnalyticsClient
*/
public void recognizeLinkedEntities() {
final String document = "Old Faithful is a geyser at Yellowstone Park.";
System.out.println("Linked Entities:");
textAnalyticsClient.recognizeLinkedEntities(document).forEach(linkedEntity -> {
System.out.printf("Name: %s, entity ID in data source: %s, URL: %s, data source: %s.%n",
linkedEntity.getName(), linkedEntity.getDataSourceEntityId(), linkedEntity.getUrl(),
linkedEntity.getDataSource());
linkedEntity.getMatches().forEach(entityMatch -> System.out.printf(
"Matched entity: %s, confidence score: %f.%n",
entityMatch.getText(), entityMatch.getConfidenceScore()));
});
}
/**
* Code snippet for {@link TextAnalyticsClient
*/
public void recognizeLinkedEntitiesWithLanguage() {
String document = "Old Faithful is a geyser at Yellowstone Park.";
textAnalyticsClient.recognizeLinkedEntities(document, "en").forEach(linkedEntity -> {
System.out.printf("Name: %s, entity ID in data source: %s, URL: %s, data source: %s.%n",
linkedEntity.getName(), linkedEntity.getDataSourceEntityId(), linkedEntity.getUrl(),
linkedEntity.getDataSource());
linkedEntity.getMatches().forEach(entityMatch -> System.out.printf(
"Matched entity: %s, confidence score: %f.%n",
entityMatch.getText(), entityMatch.getConfidenceScore()));
});
}
/**
* Code snippet for {@link TextAnalyticsClient
*/
public void recognizeLinkedEntitiesStringListWithOptions() {
List<String> documents = Arrays.asList(
"Old Faithful is a geyser at Yellowstone Park.",
"Mount Shasta has lenticular clouds."
);
RecognizeLinkedEntitiesResultCollection resultCollection =
textAnalyticsClient.recognizeLinkedEntitiesBatch(documents, "en", null);
TextDocumentBatchStatistics batchStatistics = resultCollection.getStatistics();
System.out.printf("A batch of documents statistics, transaction count: %s, valid document count: %s.%n",
batchStatistics.getTransactionCount(), batchStatistics.getValidDocumentCount());
resultCollection.forEach(recognizeLinkedEntitiesResult ->
recognizeLinkedEntitiesResult.getEntities().forEach(linkedEntity -> {
System.out.println("Linked Entities:");
System.out.printf("Name: %s, entity ID in data source: %s, URL: %s, data source: %s.%n",
linkedEntity.getName(), linkedEntity.getDataSourceEntityId(), linkedEntity.getUrl(),
linkedEntity.getDataSource());
linkedEntity.getMatches().forEach(entityMatch -> System.out.printf(
"Matched entity: %s, confidence score: %f.%n",
entityMatch.getText(), entityMatch.getConfidenceScore()));
}));
}
/**
* Code snippet for {@link TextAnalyticsClient
*/
public void recognizeLinkedEntitiesBatchMaxOverload() {
List<TextDocumentInput> textDocumentInputs = Arrays.asList(
new TextDocumentInput("1", "Old Faithful is a geyser at Yellowstone Park.").setLanguage("en"),
new TextDocumentInput("2", "Mount Shasta has lenticular clouds.").setLanguage("en")
);
Response<RecognizeLinkedEntitiesResultCollection> response =
textAnalyticsClient.recognizeLinkedEntitiesBatchWithResponse(textDocumentInputs,
new TextAnalyticsRequestOptions().setIncludeStatistics(true), Context.NONE);
System.out.printf("Status code of request response: %d%n", response.getStatusCode());
RecognizeLinkedEntitiesResultCollection resultCollection = response.getValue();
TextDocumentBatchStatistics batchStatistics = resultCollection.getStatistics();
System.out.printf(
"A batch of documents statistics, transaction count: %s, valid document count: %s.%n",
batchStatistics.getTransactionCount(), batchStatistics.getValidDocumentCount());
resultCollection.forEach(recognizeLinkedEntitiesResult ->
recognizeLinkedEntitiesResult.getEntities().forEach(linkedEntity -> {
System.out.println("Linked Entities:");
System.out.printf("Name: %s, entity ID in data source: %s, URL: %s, data source: %s.%n",
linkedEntity.getName(), linkedEntity.getDataSourceEntityId(), linkedEntity.getUrl(),
linkedEntity.getDataSource());
linkedEntity.getMatches().forEach(entityMatch -> System.out.printf(
"Matched entity: %s, confidence score: %.2f.%n",
entityMatch.getText(), entityMatch.getConfidenceScore()));
}));
}
/**
* Code snippet for {@link TextAnalyticsClient
*/
public void extractKeyPhrases() {
System.out.println("Extracted phrases:");
for (String keyPhrase : textAnalyticsClient.extractKeyPhrases("My cat might need to see a veterinarian.")) {
System.out.printf("%s.%n", keyPhrase);
}
}
/**
* Code snippet for {@link TextAnalyticsClient
*/
public void extractKeyPhrasesWithLanguage() {
System.out.println("Extracted phrases:");
textAnalyticsClient.extractKeyPhrases("My cat might need to see a veterinarian.", "en")
.forEach(kegPhrase -> System.out.printf("%s.%n", kegPhrase));
}
/**
* Code snippet for {@link TextAnalyticsClient
*/
public void extractKeyPhrasesStringListWithOptions() {
List<String> documents = Arrays.asList(
"My cat might need to see a veterinarian.",
"The pitot tube is used to measure airspeed."
);
ExtractKeyPhrasesResultCollection resultCollection =
textAnalyticsClient.extractKeyPhrasesBatch(documents, "en", null);
TextDocumentBatchStatistics batchStatistics = resultCollection.getStatistics();
System.out.printf(
"A batch of documents statistics, transaction count: %s, valid document count: %s.%n",
batchStatistics.getTransactionCount(), batchStatistics.getValidDocumentCount());
resultCollection.forEach(extractKeyPhraseResult -> {
System.out.printf("Document ID: %s%n", extractKeyPhraseResult.getId());
System.out.println("Extracted phrases:");
extractKeyPhraseResult.getKeyPhrases().forEach(keyPhrase -> System.out.printf("%s.%n", keyPhrase));
});
}
/**
* Code snippet for {@link TextAnalyticsClient
*/
public void extractBatchKeyPhrasesMaxOverload() {
List<TextDocumentInput> textDocumentInputs = Arrays.asList(
new TextDocumentInput("1", "My cat might need to see a veterinarian.").setLanguage("en"),
new TextDocumentInput("2", "The pitot tube is used to measure airspeed.").setLanguage("en")
);
Response<ExtractKeyPhrasesResultCollection> response =
textAnalyticsClient.extractKeyPhrasesBatchWithResponse(textDocumentInputs,
new TextAnalyticsRequestOptions().setIncludeStatistics(true), Context.NONE);
System.out.printf("Status code of request response: %d%n", response.getStatusCode());
ExtractKeyPhrasesResultCollection resultCollection = response.getValue();
TextDocumentBatchStatistics batchStatistics = resultCollection.getStatistics();
System.out.printf(
"A batch of documents statistics, transaction count: %s, valid document count: %s.%n",
batchStatistics.getTransactionCount(), batchStatistics.getValidDocumentCount());
resultCollection.forEach(extractKeyPhraseResult -> {
System.out.printf("Document ID: %s%n", extractKeyPhraseResult.getId());
System.out.println("Extracted phrases:");
extractKeyPhraseResult.getKeyPhrases().forEach(keyPhrase ->
System.out.printf("%s.%n", keyPhrase));
});
}
/**
* Code snippet for {@link TextAnalyticsClient
*/
public void analyzeSentiment() {
final DocumentSentiment documentSentiment =
textAnalyticsClient.analyzeSentiment("The hotel was dark and unclean.");
System.out.printf(
"Recognized sentiment: %s, positive score: %.2f, neutral score: %.2f, negative score: %.2f.%n",
documentSentiment.getSentiment(),
documentSentiment.getConfidenceScores().getPositive(),
documentSentiment.getConfidenceScores().getNeutral(),
documentSentiment.getConfidenceScores().getNegative());
for (SentenceSentiment sentenceSentiment : documentSentiment.getSentences()) {
System.out.printf(
"Recognized sentence sentiment: %s, positive score: %.2f, neutral score: %.2f, negative score: %.2f.%n",
sentenceSentiment.getSentiment(),
sentenceSentiment.getConfidenceScores().getPositive(),
sentenceSentiment.getConfidenceScores().getNeutral(),
sentenceSentiment.getConfidenceScores().getNegative());
}
}
/**
* Code snippet for {@link TextAnalyticsClient
*/
public void analyzeSentimentWithLanguage() {
final DocumentSentiment documentSentiment = textAnalyticsClient.analyzeSentiment(
"The hotel was dark and unclean.", "en");
System.out.printf(
"Recognized sentiment: %s, positive score: %.2f, neutral score: %.2f, negative score: %.2f.%n",
documentSentiment.getSentiment(),
documentSentiment.getConfidenceScores().getPositive(),
documentSentiment.getConfidenceScores().getNeutral(),
documentSentiment.getConfidenceScores().getNegative());
for (SentenceSentiment sentenceSentiment : documentSentiment.getSentences()) {
System.out.printf(
"Recognized sentence sentiment: %s, positive score: %.2f, neutral score: %.2f, negative score: %.2f.%n",
sentenceSentiment.getSentiment(),
sentenceSentiment.getConfidenceScores().getPositive(),
sentenceSentiment.getConfidenceScores().getNeutral(),
sentenceSentiment.getConfidenceScores().getNegative());
}
}
/**
* Code snippet for {@link TextAnalyticsClient
*/
public void analyzeSentimentWithLanguageWithOpinionMining() {
final DocumentSentiment documentSentiment = textAnalyticsClient.analyzeSentiment(
"The hotel was dark and unclean.", "en",
new AnalyzeSentimentOptions().setIncludeOpinionMining(true));
for (SentenceSentiment sentenceSentiment : documentSentiment.getSentences()) {
System.out.printf("\tSentence sentiment: %s%n", sentenceSentiment.getSentiment());
sentenceSentiment.getMinedOpinions().forEach(minedOpinions -> {
AspectSentiment aspectSentiment = minedOpinions.getAspect();
System.out.printf("\tAspect sentiment: %s, aspect text: %s%n", aspectSentiment.getSentiment(),
aspectSentiment.getText());
for (OpinionSentiment opinionSentiment : minedOpinions.getOpinions()) {
System.out.printf("\t\t'%s' sentiment because of \"%s\". Is the opinion negated: %s.%n",
opinionSentiment.getSentiment(), opinionSentiment.getText(), opinionSentiment.isNegated());
}
});
}
}
/**
* Code snippet for {@link TextAnalyticsClient
*/
public void analyzeSentimentStringListWithOptions() {
List<String> documents = Arrays.asList(
"The hotel was dark and unclean. The restaurant had amazing gnocchi.",
"The restaurant had amazing gnocchi. The hotel was dark and unclean."
);
AnalyzeSentimentResultCollection resultCollection = textAnalyticsClient.analyzeSentimentBatch(
documents, "en", new TextAnalyticsRequestOptions().setIncludeStatistics(true));
TextDocumentBatchStatistics batchStatistics = resultCollection.getStatistics();
System.out.printf("A batch of documents statistics, transaction count: %s, valid document count: %s.%n",
batchStatistics.getTransactionCount(), batchStatistics.getValidDocumentCount());
resultCollection.forEach(analyzeSentimentResult -> {
System.out.printf("Document ID: %s%n", analyzeSentimentResult.getId());
DocumentSentiment documentSentiment = analyzeSentimentResult.getDocumentSentiment();
System.out.printf(
"Recognized document sentiment: %s, positive score: %.2f, neutral score: %.2f,"
+ " negative score: %.2f.%n",
documentSentiment.getSentiment(),
documentSentiment.getConfidenceScores().getPositive(),
documentSentiment.getConfidenceScores().getNeutral(),
documentSentiment.getConfidenceScores().getNegative());
documentSentiment.getSentences().forEach(sentenceSentiment -> System.out.printf(
"Recognized sentence sentiment: %s, positive score: %.2f, neutral score: %.2f,"
+ " negative score: %.2f.%n",
sentenceSentiment.getSentiment(),
sentenceSentiment.getConfidenceScores().getPositive(),
sentenceSentiment.getConfidenceScores().getNeutral(),
sentenceSentiment.getConfidenceScores().getNegative()));
});
}
/**
* Code snippet for {@link TextAnalyticsClient
*/
public void analyzeSentimentStringListWithOptionsAndOpinionMining() {
List<String> documents = Arrays.asList(
"The hotel was dark and unclean. The restaurant had amazing gnocchi.",
"The restaurant had amazing gnocchi. The hotel was dark and unclean."
);
AnalyzeSentimentResultCollection resultCollection = textAnalyticsClient.analyzeSentimentBatch(
documents, "en", new AnalyzeSentimentOptions().setIncludeOpinionMining(true));
resultCollection.forEach(analyzeSentimentResult -> {
System.out.printf("Document ID: %s%n", analyzeSentimentResult.getId());
DocumentSentiment documentSentiment = analyzeSentimentResult.getDocumentSentiment();
documentSentiment.getSentences().forEach(sentenceSentiment -> {
System.out.printf("\tSentence sentiment: %s%n", sentenceSentiment.getSentiment());
sentenceSentiment.getMinedOpinions().forEach(minedOpinions -> {
AspectSentiment aspectSentiment = minedOpinions.getAspect();
System.out.printf("\tAspect sentiment: %s, aspect text: %s%n", aspectSentiment.getSentiment(),
aspectSentiment.getText());
for (OpinionSentiment opinionSentiment : minedOpinions.getOpinions()) {
System.out.printf("\t\t'%s' sentiment because of \"%s\". Is the opinion negated: %s.%n",
opinionSentiment.getSentiment(), opinionSentiment.getText(), opinionSentiment.isNegated());
}
});
});
});
}
/**
* Code snippet for {@link TextAnalyticsClient
*/
public void analyzeBatchSentimentMaxOverload() {
List<TextDocumentInput> textDocumentInputs = Arrays.asList(
new TextDocumentInput("1", "The hotel was dark and unclean. The restaurant had amazing gnocchi.")
.setLanguage("en"),
new TextDocumentInput("2", "The restaurant had amazing gnocchi. The hotel was dark and unclean.")
.setLanguage("en")
);
Response<AnalyzeSentimentResultCollection> response =
textAnalyticsClient.analyzeSentimentBatchWithResponse(textDocumentInputs,
new TextAnalyticsRequestOptions().setIncludeStatistics(true), Context.NONE);
System.out.printf("Status code of request response: %d%n", response.getStatusCode());
AnalyzeSentimentResultCollection resultCollection = response.getValue();
TextDocumentBatchStatistics batchStatistics = resultCollection.getStatistics();
System.out.printf("A batch of documents statistics, transaction count: %s, valid document count: %s.%n",
batchStatistics.getTransactionCount(), batchStatistics.getValidDocumentCount());
resultCollection.forEach(analyzeSentimentResult -> {
System.out.printf("Document ID: %s%n", analyzeSentimentResult.getId());
DocumentSentiment documentSentiment = analyzeSentimentResult.getDocumentSentiment();
System.out.printf(
"Recognized document sentiment: %s, positive score: %.2f, neutral score: %.2f, "
+ "negative score: %.2f.%n",
documentSentiment.getSentiment(),
documentSentiment.getConfidenceScores().getPositive(),
documentSentiment.getConfidenceScores().getNeutral(),
documentSentiment.getConfidenceScores().getNegative());
documentSentiment.getSentences().forEach(sentenceSentiment -> {
System.out.printf(
"Recognized sentence sentiment: %s, positive score: %.2f, neutral score: %.2f,"
+ " negative score: %.2f.%n",
sentenceSentiment.getSentiment(),
sentenceSentiment.getConfidenceScores().getPositive(),
sentenceSentiment.getConfidenceScores().getNeutral(),
sentenceSentiment.getConfidenceScores().getNegative());
});
});
}
/**
* Code snippet for {@link TextAnalyticsClient
*/
public void analyzeBatchSentimentMaxOverloadWithOpinionMining() {
List<TextDocumentInput> textDocumentInputs = Arrays.asList(
new TextDocumentInput("1", "The hotel was dark and unclean. The restaurant had amazing gnocchi.")
.setLanguage("en"),
new TextDocumentInput("2", "The restaurant had amazing gnocchi. The hotel was dark and unclean.")
.setLanguage("en")
);
AnalyzeSentimentOptions options = new AnalyzeSentimentOptions().setIncludeOpinionMining(true)
.setIncludeStatistics(true);
Response<AnalyzeSentimentResultCollection> response =
textAnalyticsClient.analyzeSentimentBatchWithResponse(textDocumentInputs, options, Context.NONE);
System.out.printf("Status code of request response: %d%n", response.getStatusCode());
AnalyzeSentimentResultCollection resultCollection = response.getValue();
TextDocumentBatchStatistics batchStatistics = resultCollection.getStatistics();
System.out.printf("A batch of documents statistics, transaction count: %s, valid document count: %s.%n",
batchStatistics.getTransactionCount(), batchStatistics.getValidDocumentCount());
resultCollection.forEach(analyzeSentimentResult -> {
System.out.printf("Document ID: %s%n", analyzeSentimentResult.getId());
DocumentSentiment documentSentiment = analyzeSentimentResult.getDocumentSentiment();
documentSentiment.getSentences().forEach(sentenceSentiment -> {
System.out.printf("\tSentence sentiment: %s%n", sentenceSentiment.getSentiment());
sentenceSentiment.getMinedOpinions().forEach(minedOpinions -> {
AspectSentiment aspectSentiment = minedOpinions.getAspect();
System.out.printf("\tAspect sentiment: %s, aspect text: %s%n", aspectSentiment.getSentiment(),
aspectSentiment.getText());
for (OpinionSentiment opinionSentiment : minedOpinions.getOpinions()) {
System.out.printf("\t\t'%s' sentiment because of \"%s\". Is the opinion negated: %s.%n",
opinionSentiment.getSentiment(), opinionSentiment.getText(), opinionSentiment.isNegated());
}
});
});
});
}
} | class TextAnalyticsClientJavaDocCodeSnippets {
private TextAnalyticsClient textAnalyticsClient = new TextAnalyticsClientBuilder().buildClient();
/**
* Code snippet for creating a {@link TextAnalyticsClient} with pipeline
*/
public void createTextAnalyticsClientWithPipeline() {
HttpPipeline pipeline = new HttpPipelineBuilder()
.policies(/* add policies */)
.build();
TextAnalyticsClient textAnalyticsClient = new TextAnalyticsClientBuilder()
.credential(new AzureKeyCredential("{key}"))
.endpoint("{endpoint}")
.pipeline(pipeline)
.buildClient();
}
/**
* Code snippet for creating a {@link TextAnalyticsClient}
*/
public void createTextAnalyticsClient() {
TextAnalyticsClient textAnalyticsClient = new TextAnalyticsClientBuilder()
.credential(new AzureKeyCredential("{key}"))
.endpoint("{endpoint}")
.buildClient();
}
/**
* Code snippet for {@link TextAnalyticsClient
*/
public void detectLanguage() {
DetectedLanguage detectedLanguage = textAnalyticsClient.detectLanguage("Bonjour tout le monde");
System.out.printf("Detected language name: %s, ISO 6391 name: %s, confidence score: %f.%n",
detectedLanguage.getName(), detectedLanguage.getIso6391Name(), detectedLanguage.getConfidenceScore());
}
/**
* Code snippet for {@link TextAnalyticsClient
*/
public void detectLanguageWithCountryHint() {
DetectedLanguage detectedLanguage = textAnalyticsClient.detectLanguage(
"This text is in English", "US");
System.out.printf("Detected language name: %s, ISO 6391 name: %s, confidence score: %f.%n",
detectedLanguage.getName(), detectedLanguage.getIso6391Name(), detectedLanguage.getConfidenceScore());
}
/**
* Code snippet for {@link TextAnalyticsClient
*/
public void detectLanguageStringListWithOptions() {
List<String> documents = Arrays.asList(
"This is written in English",
"Este es un documento escrito en Español."
);
DetectLanguageResultCollection resultCollection =
textAnalyticsClient.detectLanguageBatch(documents, "US", null);
TextDocumentBatchStatistics batchStatistics = resultCollection.getStatistics();
System.out.printf("A batch of documents statistics, transaction count: %s, valid document count: %s.%n",
batchStatistics.getTransactionCount(), batchStatistics.getValidDocumentCount());
resultCollection.forEach(detectLanguageResult -> {
System.out.printf("Document ID: %s%n", detectLanguageResult.getId());
DetectedLanguage detectedLanguage = detectLanguageResult.getPrimaryLanguage();
System.out.printf("Primary language name: %s, ISO 6391 name: %s, confidence score: %f.%n",
detectedLanguage.getName(), detectedLanguage.getIso6391Name(),
detectedLanguage.getConfidenceScore());
});
}
/**
* Code snippet for {@link TextAnalyticsClient
*/
public void detectBatchLanguagesMaxOverload() {
List<DetectLanguageInput> detectLanguageInputs = Arrays.asList(
new DetectLanguageInput("1", "This is written in English.", "US"),
new DetectLanguageInput("2", "Este es un documento escrito en Español.", "es")
);
Response<DetectLanguageResultCollection> response =
textAnalyticsClient.detectLanguageBatchWithResponse(detectLanguageInputs,
new TextAnalyticsRequestOptions().setIncludeStatistics(true), Context.NONE);
System.out.printf("Status code of request response: %d%n", response.getStatusCode());
DetectLanguageResultCollection detectedLanguageResultCollection = response.getValue();
TextDocumentBatchStatistics batchStatistics = detectedLanguageResultCollection.getStatistics();
System.out.printf(
"Documents statistics: document count = %s, erroneous document count = %s, transaction count = %s,"
+ " valid document count = %s.%n",
batchStatistics.getDocumentCount(), batchStatistics.getInvalidDocumentCount(),
batchStatistics.getTransactionCount(), batchStatistics.getValidDocumentCount());
detectedLanguageResultCollection.forEach(detectLanguageResult -> {
System.out.printf("Document ID: %s%n", detectLanguageResult.getId());
DetectedLanguage detectedLanguage = detectLanguageResult.getPrimaryLanguage();
System.out.printf("Primary language name: %s, ISO 6391 name: %s, confidence score: %f.%n",
detectedLanguage.getName(), detectedLanguage.getIso6391Name(),
detectedLanguage.getConfidenceScore());
});
}
/**
* Code snippet for {@link TextAnalyticsClient
*/
public void recognizeEntities() {
final CategorizedEntityCollection recognizeEntitiesResult =
textAnalyticsClient.recognizeEntities("Satya Nadella is the CEO of Microsoft");
for (CategorizedEntity entity : recognizeEntitiesResult) {
System.out.printf("Recognized entity: %s, entity category: %s, confidence score: %f.%n",
entity.getText(), entity.getCategory(), entity.getConfidenceScore());
}
}
/**
* Code snippet for {@link TextAnalyticsClient
*/
public void recognizeEntitiesWithLanguage() {
final CategorizedEntityCollection recognizeEntitiesResult =
textAnalyticsClient.recognizeEntities("Satya Nadella is the CEO of Microsoft", "en");
for (CategorizedEntity entity : recognizeEntitiesResult) {
System.out.printf("Recognized entity: %s, entity category: %s, confidence score: %f.%n",
entity.getText(), entity.getCategory(), entity.getConfidenceScore());
}
}
/**
* Code snippet for {@link TextAnalyticsClient
*/
public void recognizeEntitiesStringListWithOptions() {
List<String> documents = Arrays.asList(
"I had a wonderful trip to Seattle last week.",
"I work at Microsoft.");
RecognizeEntitiesResultCollection resultCollection =
textAnalyticsClient.recognizeEntitiesBatch(documents, "en", null);
TextDocumentBatchStatistics batchStatistics = resultCollection.getStatistics();
System.out.printf(
"A batch of documents statistics, transaction count: %s, valid document count: %s.%n",
batchStatistics.getTransactionCount(), batchStatistics.getValidDocumentCount());
resultCollection.forEach(recognizeEntitiesResult ->
recognizeEntitiesResult.getEntities().forEach(entity ->
System.out.printf("Recognized entity: %s, entity category: %s, confidence score: %f.%n",
entity.getText(), entity.getCategory(), entity.getConfidenceScore())));
}
/**
* Code snippet for {@link TextAnalyticsClient
*/
public void recognizeBatchEntitiesMaxOverload() {
List<TextDocumentInput> textDocumentInputs = Arrays.asList(
new TextDocumentInput("0", "I had a wonderful trip to Seattle last week.").setLanguage("en"),
new TextDocumentInput("1", "I work at Microsoft.").setLanguage("en")
);
Response<RecognizeEntitiesResultCollection> response =
textAnalyticsClient.recognizeEntitiesBatchWithResponse(textDocumentInputs,
new TextAnalyticsRequestOptions().setIncludeStatistics(true), Context.NONE);
System.out.printf("Status code of request response: %d%n", response.getStatusCode());
RecognizeEntitiesResultCollection recognizeEntitiesResultCollection = response.getValue();
TextDocumentBatchStatistics batchStatistics = recognizeEntitiesResultCollection.getStatistics();
System.out.printf(
"A batch of documents statistics, transaction count: %s, valid document count: %s.%n",
batchStatistics.getTransactionCount(), batchStatistics.getValidDocumentCount());
recognizeEntitiesResultCollection.forEach(recognizeEntitiesResult ->
recognizeEntitiesResult.getEntities().forEach(entity ->
System.out.printf("Recognized entity: %s, entity category: %s, confidence score: %f.%n",
entity.getText(), entity.getCategory(), entity.getConfidenceScore())));
}
/**
* Code snippet for {@link TextAnalyticsClient
*/
public void recognizePiiEntities() {
PiiEntityCollection piiEntityCollection = textAnalyticsClient.recognizePiiEntities("My SSN is 859-98-0987");
System.out.printf("Redacted Text: %s%n", piiEntityCollection.getRedactedText());
for (PiiEntity entity : piiEntityCollection) {
System.out.printf(
"Recognized Personally Identifiable Information entity: %s, entity category: %s,"
+ " entity subcategory: %s, confidence score: %f.%n",
entity.getText(), entity.getCategory(), entity.getSubcategory(), entity.getConfidenceScore());
}
}
/**
* Code snippet for {@link TextAnalyticsClient
*/
public void recognizePiiEntitiesWithLanguage() {
PiiEntityCollection piiEntityCollection = textAnalyticsClient.recognizePiiEntities(
"My SSN is 859-98-0987", "en");
System.out.printf("Redacted Text: %s%n", piiEntityCollection.getRedactedText());
piiEntityCollection.forEach(entity -> System.out.printf(
"Recognized Personally Identifiable Information entity: %s, entity category: %s,"
+ " entity subcategory: %s, confidence score: %f.%n",
entity.getText(), entity.getCategory(), entity.getSubcategory(), entity.getConfidenceScore()));
}
/**
* Code snippet for {@link TextAnalyticsClient
*/
/**
* Code snippet for {@link TextAnalyticsClient
*/
public void recognizePiiEntitiesStringListWithOptions() {
List<String> documents = Arrays.asList(
"My SSN is 859-98-0987",
"Visa card 4111 1111 1111 1111"
);
RecognizePiiEntitiesResultCollection resultCollection = textAnalyticsClient.recognizePiiEntitiesBatch(
documents, "en", new RecognizePiiEntityOptions().setIncludeStatistics(true));
TextDocumentBatchStatistics batchStatistics = resultCollection.getStatistics();
System.out.printf("A batch of documents statistics, transaction count: %s, valid document count: %s.%n",
batchStatistics.getTransactionCount(), batchStatistics.getValidDocumentCount());
resultCollection.forEach(recognizePiiEntitiesResult -> {
PiiEntityCollection piiEntityCollection = recognizePiiEntitiesResult.getEntities();
System.out.printf("Redacted Text: %s%n", piiEntityCollection.getRedactedText());
piiEntityCollection.forEach(entity -> System.out.printf(
"Recognized Personally Identifiable Information entity: %s, entity category: %s,"
+ " entity subcategory: %s, confidence score: %f.%n",
entity.getText(), entity.getCategory(), entity.getSubcategory(), entity.getConfidenceScore()));
});
}
/**
* Code snippet for {@link TextAnalyticsClient
*/
public void recognizeBatchPiiEntitiesMaxOverload() {
List<TextDocumentInput> textDocumentInputs = Arrays.asList(
new TextDocumentInput("0", "My SSN is 859-98-0987"),
new TextDocumentInput("1", "Visa card 4111 1111 1111 1111")
);
Response<RecognizePiiEntitiesResultCollection> response =
textAnalyticsClient.recognizePiiEntitiesBatchWithResponse(textDocumentInputs,
new RecognizePiiEntityOptions().setIncludeStatistics(true), Context.NONE);
RecognizePiiEntitiesResultCollection resultCollection = response.getValue();
TextDocumentBatchStatistics batchStatistics = resultCollection.getStatistics();
System.out.printf("A batch of documents statistics, transaction count: %s, valid document count: %s.%n",
batchStatistics.getTransactionCount(), batchStatistics.getValidDocumentCount());
resultCollection.forEach(recognizePiiEntitiesResult -> {
PiiEntityCollection piiEntityCollection = recognizePiiEntitiesResult.getEntities();
System.out.printf("Redacted Text: %s%n", piiEntityCollection.getRedactedText());
piiEntityCollection.forEach(entity -> System.out.printf(
"Recognized Personally Identifiable Information entity: %s, entity category: %s,"
+ " entity subcategory: %s, confidence score: %f.%n",
entity.getText(), entity.getCategory(), entity.getSubcategory(), entity.getConfidenceScore()));
});
}
/**
* Code snippet for {@link TextAnalyticsClient
*/
public void recognizeLinkedEntities() {
final String document = "Old Faithful is a geyser at Yellowstone Park.";
System.out.println("Linked Entities:");
textAnalyticsClient.recognizeLinkedEntities(document).forEach(linkedEntity -> {
System.out.printf("Name: %s, entity ID in data source: %s, URL: %s, data source: %s.%n",
linkedEntity.getName(), linkedEntity.getDataSourceEntityId(), linkedEntity.getUrl(),
linkedEntity.getDataSource());
linkedEntity.getMatches().forEach(entityMatch -> System.out.printf(
"Matched entity: %s, confidence score: %f.%n",
entityMatch.getText(), entityMatch.getConfidenceScore()));
});
}
/**
* Code snippet for {@link TextAnalyticsClient
*/
public void recognizeLinkedEntitiesWithLanguage() {
String document = "Old Faithful is a geyser at Yellowstone Park.";
textAnalyticsClient.recognizeLinkedEntities(document, "en").forEach(linkedEntity -> {
System.out.printf("Name: %s, entity ID in data source: %s, URL: %s, data source: %s.%n",
linkedEntity.getName(), linkedEntity.getDataSourceEntityId(), linkedEntity.getUrl(),
linkedEntity.getDataSource());
linkedEntity.getMatches().forEach(entityMatch -> System.out.printf(
"Matched entity: %s, confidence score: %f.%n",
entityMatch.getText(), entityMatch.getConfidenceScore()));
});
}
/**
* Code snippet for {@link TextAnalyticsClient
*/
public void recognizeLinkedEntitiesStringListWithOptions() {
List<String> documents = Arrays.asList(
"Old Faithful is a geyser at Yellowstone Park.",
"Mount Shasta has lenticular clouds."
);
RecognizeLinkedEntitiesResultCollection resultCollection =
textAnalyticsClient.recognizeLinkedEntitiesBatch(documents, "en", null);
TextDocumentBatchStatistics batchStatistics = resultCollection.getStatistics();
System.out.printf("A batch of documents statistics, transaction count: %s, valid document count: %s.%n",
batchStatistics.getTransactionCount(), batchStatistics.getValidDocumentCount());
resultCollection.forEach(recognizeLinkedEntitiesResult ->
recognizeLinkedEntitiesResult.getEntities().forEach(linkedEntity -> {
System.out.println("Linked Entities:");
System.out.printf("Name: %s, entity ID in data source: %s, URL: %s, data source: %s.%n",
linkedEntity.getName(), linkedEntity.getDataSourceEntityId(), linkedEntity.getUrl(),
linkedEntity.getDataSource());
linkedEntity.getMatches().forEach(entityMatch -> System.out.printf(
"Matched entity: %s, confidence score: %f.%n",
entityMatch.getText(), entityMatch.getConfidenceScore()));
}));
}
/**
* Code snippet for {@link TextAnalyticsClient
*/
public void recognizeLinkedEntitiesBatchMaxOverload() {
List<TextDocumentInput> textDocumentInputs = Arrays.asList(
new TextDocumentInput("1", "Old Faithful is a geyser at Yellowstone Park.").setLanguage("en"),
new TextDocumentInput("2", "Mount Shasta has lenticular clouds.").setLanguage("en")
);
Response<RecognizeLinkedEntitiesResultCollection> response =
textAnalyticsClient.recognizeLinkedEntitiesBatchWithResponse(textDocumentInputs,
new TextAnalyticsRequestOptions().setIncludeStatistics(true), Context.NONE);
System.out.printf("Status code of request response: %d%n", response.getStatusCode());
RecognizeLinkedEntitiesResultCollection resultCollection = response.getValue();
TextDocumentBatchStatistics batchStatistics = resultCollection.getStatistics();
System.out.printf(
"A batch of documents statistics, transaction count: %s, valid document count: %s.%n",
batchStatistics.getTransactionCount(), batchStatistics.getValidDocumentCount());
resultCollection.forEach(recognizeLinkedEntitiesResult ->
recognizeLinkedEntitiesResult.getEntities().forEach(linkedEntity -> {
System.out.println("Linked Entities:");
System.out.printf("Name: %s, entity ID in data source: %s, URL: %s, data source: %s.%n",
linkedEntity.getName(), linkedEntity.getDataSourceEntityId(), linkedEntity.getUrl(),
linkedEntity.getDataSource());
linkedEntity.getMatches().forEach(entityMatch -> System.out.printf(
"Matched entity: %s, confidence score: %.2f.%n",
entityMatch.getText(), entityMatch.getConfidenceScore()));
}));
}
/**
* Code snippet for {@link TextAnalyticsClient
*/
public void extractKeyPhrases() {
System.out.println("Extracted phrases:");
for (String keyPhrase : textAnalyticsClient.extractKeyPhrases("My cat might need to see a veterinarian.")) {
System.out.printf("%s.%n", keyPhrase);
}
}
/**
* Code snippet for {@link TextAnalyticsClient
*/
public void extractKeyPhrasesWithLanguage() {
System.out.println("Extracted phrases:");
textAnalyticsClient.extractKeyPhrases("My cat might need to see a veterinarian.", "en")
.forEach(kegPhrase -> System.out.printf("%s.%n", kegPhrase));
}
/**
* Code snippet for {@link TextAnalyticsClient
*/
public void extractKeyPhrasesStringListWithOptions() {
List<String> documents = Arrays.asList(
"My cat might need to see a veterinarian.",
"The pitot tube is used to measure airspeed."
);
ExtractKeyPhrasesResultCollection resultCollection =
textAnalyticsClient.extractKeyPhrasesBatch(documents, "en", null);
TextDocumentBatchStatistics batchStatistics = resultCollection.getStatistics();
System.out.printf(
"A batch of documents statistics, transaction count: %s, valid document count: %s.%n",
batchStatistics.getTransactionCount(), batchStatistics.getValidDocumentCount());
resultCollection.forEach(extractKeyPhraseResult -> {
System.out.printf("Document ID: %s%n", extractKeyPhraseResult.getId());
System.out.println("Extracted phrases:");
extractKeyPhraseResult.getKeyPhrases().forEach(keyPhrase -> System.out.printf("%s.%n", keyPhrase));
});
}
/**
* Code snippet for {@link TextAnalyticsClient
*/
public void extractBatchKeyPhrasesMaxOverload() {
List<TextDocumentInput> textDocumentInputs = Arrays.asList(
new TextDocumentInput("1", "My cat might need to see a veterinarian.").setLanguage("en"),
new TextDocumentInput("2", "The pitot tube is used to measure airspeed.").setLanguage("en")
);
Response<ExtractKeyPhrasesResultCollection> response =
textAnalyticsClient.extractKeyPhrasesBatchWithResponse(textDocumentInputs,
new TextAnalyticsRequestOptions().setIncludeStatistics(true), Context.NONE);
System.out.printf("Status code of request response: %d%n", response.getStatusCode());
ExtractKeyPhrasesResultCollection resultCollection = response.getValue();
TextDocumentBatchStatistics batchStatistics = resultCollection.getStatistics();
System.out.printf(
"A batch of documents statistics, transaction count: %s, valid document count: %s.%n",
batchStatistics.getTransactionCount(), batchStatistics.getValidDocumentCount());
resultCollection.forEach(extractKeyPhraseResult -> {
System.out.printf("Document ID: %s%n", extractKeyPhraseResult.getId());
System.out.println("Extracted phrases:");
extractKeyPhraseResult.getKeyPhrases().forEach(keyPhrase ->
System.out.printf("%s.%n", keyPhrase));
});
}
/**
* Code snippet for {@link TextAnalyticsClient
*/
public void analyzeSentiment() {
final DocumentSentiment documentSentiment =
textAnalyticsClient.analyzeSentiment("The hotel was dark and unclean.");
System.out.printf(
"Recognized sentiment: %s, positive score: %.2f, neutral score: %.2f, negative score: %.2f.%n",
documentSentiment.getSentiment(),
documentSentiment.getConfidenceScores().getPositive(),
documentSentiment.getConfidenceScores().getNeutral(),
documentSentiment.getConfidenceScores().getNegative());
for (SentenceSentiment sentenceSentiment : documentSentiment.getSentences()) {
System.out.printf(
"Recognized sentence sentiment: %s, positive score: %.2f, neutral score: %.2f, negative score: %.2f.%n",
sentenceSentiment.getSentiment(),
sentenceSentiment.getConfidenceScores().getPositive(),
sentenceSentiment.getConfidenceScores().getNeutral(),
sentenceSentiment.getConfidenceScores().getNegative());
}
}
/**
* Code snippet for {@link TextAnalyticsClient
*/
public void analyzeSentimentWithLanguage() {
final DocumentSentiment documentSentiment = textAnalyticsClient.analyzeSentiment(
"The hotel was dark and unclean.", "en");
System.out.printf(
"Recognized sentiment: %s, positive score: %.2f, neutral score: %.2f, negative score: %.2f.%n",
documentSentiment.getSentiment(),
documentSentiment.getConfidenceScores().getPositive(),
documentSentiment.getConfidenceScores().getNeutral(),
documentSentiment.getConfidenceScores().getNegative());
for (SentenceSentiment sentenceSentiment : documentSentiment.getSentences()) {
System.out.printf(
"Recognized sentence sentiment: %s, positive score: %.2f, neutral score: %.2f, negative score: %.2f.%n",
sentenceSentiment.getSentiment(),
sentenceSentiment.getConfidenceScores().getPositive(),
sentenceSentiment.getConfidenceScores().getNeutral(),
sentenceSentiment.getConfidenceScores().getNegative());
}
}
/**
* Code snippet for {@link TextAnalyticsClient
*/
public void analyzeSentimentWithLanguageWithOpinionMining() {
final DocumentSentiment documentSentiment = textAnalyticsClient.analyzeSentiment(
"The hotel was dark and unclean.", "en",
new AnalyzeSentimentOptions().setIncludeOpinionMining(true));
for (SentenceSentiment sentenceSentiment : documentSentiment.getSentences()) {
System.out.printf("\tSentence sentiment: %s%n", sentenceSentiment.getSentiment());
sentenceSentiment.getMinedOpinions().forEach(minedOpinions -> {
AspectSentiment aspectSentiment = minedOpinions.getAspect();
System.out.printf("\tAspect sentiment: %s, aspect text: %s%n", aspectSentiment.getSentiment(),
aspectSentiment.getText());
for (OpinionSentiment opinionSentiment : minedOpinions.getOpinions()) {
System.out.printf("\t\t'%s' sentiment because of \"%s\". Is the opinion negated: %s.%n",
opinionSentiment.getSentiment(), opinionSentiment.getText(), opinionSentiment.isNegated());
}
});
}
}
/**
* Code snippet for {@link TextAnalyticsClient
*/
public void analyzeSentimentStringListWithOptions() {
List<String> documents = Arrays.asList(
"The hotel was dark and unclean. The restaurant had amazing gnocchi.",
"The restaurant had amazing gnocchi. The hotel was dark and unclean."
);
AnalyzeSentimentResultCollection resultCollection = textAnalyticsClient.analyzeSentimentBatch(
documents, "en", new TextAnalyticsRequestOptions().setIncludeStatistics(true));
TextDocumentBatchStatistics batchStatistics = resultCollection.getStatistics();
System.out.printf("A batch of documents statistics, transaction count: %s, valid document count: %s.%n",
batchStatistics.getTransactionCount(), batchStatistics.getValidDocumentCount());
resultCollection.forEach(analyzeSentimentResult -> {
System.out.printf("Document ID: %s%n", analyzeSentimentResult.getId());
DocumentSentiment documentSentiment = analyzeSentimentResult.getDocumentSentiment();
System.out.printf(
"Recognized document sentiment: %s, positive score: %.2f, neutral score: %.2f,"
+ " negative score: %.2f.%n",
documentSentiment.getSentiment(),
documentSentiment.getConfidenceScores().getPositive(),
documentSentiment.getConfidenceScores().getNeutral(),
documentSentiment.getConfidenceScores().getNegative());
documentSentiment.getSentences().forEach(sentenceSentiment -> System.out.printf(
"Recognized sentence sentiment: %s, positive score: %.2f, neutral score: %.2f,"
+ " negative score: %.2f.%n",
sentenceSentiment.getSentiment(),
sentenceSentiment.getConfidenceScores().getPositive(),
sentenceSentiment.getConfidenceScores().getNeutral(),
sentenceSentiment.getConfidenceScores().getNegative()));
});
}
/**
* Code snippet for {@link TextAnalyticsClient
*/
public void analyzeSentimentStringListWithOptionsAndOpinionMining() {
List<String> documents = Arrays.asList(
"The hotel was dark and unclean. The restaurant had amazing gnocchi.",
"The restaurant had amazing gnocchi. The hotel was dark and unclean."
);
AnalyzeSentimentResultCollection resultCollection = textAnalyticsClient.analyzeSentimentBatch(
documents, "en", new AnalyzeSentimentOptions().setIncludeOpinionMining(true));
resultCollection.forEach(analyzeSentimentResult -> {
System.out.printf("Document ID: %s%n", analyzeSentimentResult.getId());
DocumentSentiment documentSentiment = analyzeSentimentResult.getDocumentSentiment();
documentSentiment.getSentences().forEach(sentenceSentiment -> {
System.out.printf("\tSentence sentiment: %s%n", sentenceSentiment.getSentiment());
sentenceSentiment.getMinedOpinions().forEach(minedOpinions -> {
AspectSentiment aspectSentiment = minedOpinions.getAspect();
System.out.printf("\tAspect sentiment: %s, aspect text: %s%n", aspectSentiment.getSentiment(),
aspectSentiment.getText());
for (OpinionSentiment opinionSentiment : minedOpinions.getOpinions()) {
System.out.printf("\t\t'%s' sentiment because of \"%s\". Is the opinion negated: %s.%n",
opinionSentiment.getSentiment(), opinionSentiment.getText(), opinionSentiment.isNegated());
}
});
});
});
}
/**
* Code snippet for {@link TextAnalyticsClient
*/
public void analyzeBatchSentimentMaxOverload() {
List<TextDocumentInput> textDocumentInputs = Arrays.asList(
new TextDocumentInput("1", "The hotel was dark and unclean. The restaurant had amazing gnocchi.")
.setLanguage("en"),
new TextDocumentInput("2", "The restaurant had amazing gnocchi. The hotel was dark and unclean.")
.setLanguage("en")
);
Response<AnalyzeSentimentResultCollection> response =
textAnalyticsClient.analyzeSentimentBatchWithResponse(textDocumentInputs,
new TextAnalyticsRequestOptions().setIncludeStatistics(true), Context.NONE);
System.out.printf("Status code of request response: %d%n", response.getStatusCode());
AnalyzeSentimentResultCollection resultCollection = response.getValue();
TextDocumentBatchStatistics batchStatistics = resultCollection.getStatistics();
System.out.printf("A batch of documents statistics, transaction count: %s, valid document count: %s.%n",
batchStatistics.getTransactionCount(), batchStatistics.getValidDocumentCount());
resultCollection.forEach(analyzeSentimentResult -> {
System.out.printf("Document ID: %s%n", analyzeSentimentResult.getId());
DocumentSentiment documentSentiment = analyzeSentimentResult.getDocumentSentiment();
System.out.printf(
"Recognized document sentiment: %s, positive score: %.2f, neutral score: %.2f, "
+ "negative score: %.2f.%n",
documentSentiment.getSentiment(),
documentSentiment.getConfidenceScores().getPositive(),
documentSentiment.getConfidenceScores().getNeutral(),
documentSentiment.getConfidenceScores().getNegative());
documentSentiment.getSentences().forEach(sentenceSentiment -> {
System.out.printf(
"Recognized sentence sentiment: %s, positive score: %.2f, neutral score: %.2f,"
+ " negative score: %.2f.%n",
sentenceSentiment.getSentiment(),
sentenceSentiment.getConfidenceScores().getPositive(),
sentenceSentiment.getConfidenceScores().getNeutral(),
sentenceSentiment.getConfidenceScores().getNegative());
});
});
}
/**
* Code snippet for {@link TextAnalyticsClient
*/
public void analyzeBatchSentimentMaxOverloadWithOpinionMining() {
List<TextDocumentInput> textDocumentInputs = Arrays.asList(
new TextDocumentInput("1", "The hotel was dark and unclean. The restaurant had amazing gnocchi.")
.setLanguage("en"),
new TextDocumentInput("2", "The restaurant had amazing gnocchi. The hotel was dark and unclean.")
.setLanguage("en")
);
AnalyzeSentimentOptions options = new AnalyzeSentimentOptions().setIncludeOpinionMining(true)
.setIncludeStatistics(true);
Response<AnalyzeSentimentResultCollection> response =
textAnalyticsClient.analyzeSentimentBatchWithResponse(textDocumentInputs, options, Context.NONE);
System.out.printf("Status code of request response: %d%n", response.getStatusCode());
AnalyzeSentimentResultCollection resultCollection = response.getValue();
TextDocumentBatchStatistics batchStatistics = resultCollection.getStatistics();
System.out.printf("A batch of documents statistics, transaction count: %s, valid document count: %s.%n",
batchStatistics.getTransactionCount(), batchStatistics.getValidDocumentCount());
resultCollection.forEach(analyzeSentimentResult -> {
System.out.printf("Document ID: %s%n", analyzeSentimentResult.getId());
DocumentSentiment documentSentiment = analyzeSentimentResult.getDocumentSentiment();
documentSentiment.getSentences().forEach(sentenceSentiment -> {
System.out.printf("\tSentence sentiment: %s%n", sentenceSentiment.getSentiment());
sentenceSentiment.getMinedOpinions().forEach(minedOpinions -> {
AspectSentiment aspectSentiment = minedOpinions.getAspect();
System.out.printf("\tAspect sentiment: %s, aspect text: %s%n", aspectSentiment.getSentiment(),
aspectSentiment.getText());
for (OpinionSentiment opinionSentiment : minedOpinions.getOpinions()) {
System.out.printf("\t\t'%s' sentiment because of \"%s\". Is the opinion negated: %s.%n",
opinionSentiment.getSentiment(), opinionSentiment.getText(), opinionSentiment.isNegated());
}
});
});
});
}
} | |
There are a few tests for domain filter already in the PR. You are looking at the codesnippet section. https://github.com/Azure/azure-sdk-for-java/pull/14714/files#diff-9df5b3d7d96dd8e2313b619beb609285R509 | public void recognizePiiEntitiesWithRecognizePiiEntityOptions() {
textAnalyticsClient.recognizePiiEntities("My SSN is 859-98-0987", "en",
new RecognizePiiEntityOptions().setDomainFilter(PiiEntityDomainType.PROTECTED_HEALTH_INFORMATION))
.forEach(entity -> System.out.printf(
"Recognized Personally Identifiable Information entity: %s, entity category: %s,"
+ " entity subcategory: %s, confidence score: %f.%n",
entity.getText(), entity.getCategory(), entity.getSubcategory(), entity.getConfidenceScore()));
} | public void recognizePiiEntitiesWithRecognizePiiEntityOptions() {
PiiEntityCollection piiEntityCollection = textAnalyticsClient.recognizePiiEntities(
"My SSN is 859-98-0987", "en",
new RecognizePiiEntityOptions().setDomainFilter(PiiEntityDomainType.PROTECTED_HEALTH_INFORMATION));
System.out.printf("Redacted Text: %s%n", piiEntityCollection.getRedactedText());
piiEntityCollection.forEach(entity -> System.out.printf(
"Recognized Personally Identifiable Information entity: %s, entity category: %s,"
+ " entity subcategory: %s, confidence score: %f.%n",
entity.getText(), entity.getCategory(), entity.getSubcategory(), entity.getConfidenceScore()));
} | class TextAnalyticsClientJavaDocCodeSnippets {
private TextAnalyticsClient textAnalyticsClient = new TextAnalyticsClientBuilder().buildClient();
/**
* Code snippet for creating a {@link TextAnalyticsClient} with pipeline
*/
public void createTextAnalyticsClientWithPipeline() {
HttpPipeline pipeline = new HttpPipelineBuilder()
.policies(/* add policies */)
.build();
TextAnalyticsClient textAnalyticsClient = new TextAnalyticsClientBuilder()
.credential(new AzureKeyCredential("{key}"))
.endpoint("{endpoint}")
.pipeline(pipeline)
.buildClient();
}
/**
* Code snippet for creating a {@link TextAnalyticsClient}
*/
public void createTextAnalyticsClient() {
TextAnalyticsClient textAnalyticsClient = new TextAnalyticsClientBuilder()
.credential(new AzureKeyCredential("{key}"))
.endpoint("{endpoint}")
.buildClient();
}
/**
* Code snippet for {@link TextAnalyticsClient
*/
public void detectLanguage() {
DetectedLanguage detectedLanguage = textAnalyticsClient.detectLanguage("Bonjour tout le monde");
System.out.printf("Detected language name: %s, ISO 6391 name: %s, confidence score: %f.%n",
detectedLanguage.getName(), detectedLanguage.getIso6391Name(), detectedLanguage.getConfidenceScore());
}
/**
* Code snippet for {@link TextAnalyticsClient
*/
public void detectLanguageWithCountryHint() {
DetectedLanguage detectedLanguage = textAnalyticsClient.detectLanguage(
"This text is in English", "US");
System.out.printf("Detected language name: %s, ISO 6391 name: %s, confidence score: %f.%n",
detectedLanguage.getName(), detectedLanguage.getIso6391Name(), detectedLanguage.getConfidenceScore());
}
/**
* Code snippet for {@link TextAnalyticsClient
*/
public void detectLanguageStringListWithOptions() {
List<String> documents = Arrays.asList(
"This is written in English",
"Este es un documento escrito en Español."
);
DetectLanguageResultCollection resultCollection =
textAnalyticsClient.detectLanguageBatch(documents, "US", null);
TextDocumentBatchStatistics batchStatistics = resultCollection.getStatistics();
System.out.printf("A batch of documents statistics, transaction count: %s, valid document count: %s.%n",
batchStatistics.getTransactionCount(), batchStatistics.getValidDocumentCount());
resultCollection.forEach(detectLanguageResult -> {
System.out.printf("Document ID: %s%n", detectLanguageResult.getId());
DetectedLanguage detectedLanguage = detectLanguageResult.getPrimaryLanguage();
System.out.printf("Primary language name: %s, ISO 6391 name: %s, confidence score: %f.%n",
detectedLanguage.getName(), detectedLanguage.getIso6391Name(),
detectedLanguage.getConfidenceScore());
});
}
/**
* Code snippet for {@link TextAnalyticsClient
*/
public void detectBatchLanguagesMaxOverload() {
List<DetectLanguageInput> detectLanguageInputs = Arrays.asList(
new DetectLanguageInput("1", "This is written in English.", "US"),
new DetectLanguageInput("2", "Este es un documento escrito en Español.", "es")
);
Response<DetectLanguageResultCollection> response =
textAnalyticsClient.detectLanguageBatchWithResponse(detectLanguageInputs,
new TextAnalyticsRequestOptions().setIncludeStatistics(true), Context.NONE);
System.out.printf("Status code of request response: %d%n", response.getStatusCode());
DetectLanguageResultCollection detectedLanguageResultCollection = response.getValue();
TextDocumentBatchStatistics batchStatistics = detectedLanguageResultCollection.getStatistics();
System.out.printf(
"Documents statistics: document count = %s, erroneous document count = %s, transaction count = %s,"
+ " valid document count = %s.%n",
batchStatistics.getDocumentCount(), batchStatistics.getInvalidDocumentCount(),
batchStatistics.getTransactionCount(), batchStatistics.getValidDocumentCount());
detectedLanguageResultCollection.forEach(detectLanguageResult -> {
System.out.printf("Document ID: %s%n", detectLanguageResult.getId());
DetectedLanguage detectedLanguage = detectLanguageResult.getPrimaryLanguage();
System.out.printf("Primary language name: %s, ISO 6391 name: %s, confidence score: %f.%n",
detectedLanguage.getName(), detectedLanguage.getIso6391Name(),
detectedLanguage.getConfidenceScore());
});
}
/**
* Code snippet for {@link TextAnalyticsClient
*/
public void recognizeEntities() {
final CategorizedEntityCollection recognizeEntitiesResult =
textAnalyticsClient.recognizeEntities("Satya Nadella is the CEO of Microsoft");
for (CategorizedEntity entity : recognizeEntitiesResult) {
System.out.printf("Recognized entity: %s, entity category: %s, confidence score: %f.%n",
entity.getText(), entity.getCategory(), entity.getConfidenceScore());
}
}
/**
* Code snippet for {@link TextAnalyticsClient
*/
public void recognizeEntitiesWithLanguage() {
final CategorizedEntityCollection recognizeEntitiesResult =
textAnalyticsClient.recognizeEntities("Satya Nadella is the CEO of Microsoft", "en");
for (CategorizedEntity entity : recognizeEntitiesResult) {
System.out.printf("Recognized entity: %s, entity category: %s, confidence score: %f.%n",
entity.getText(), entity.getCategory(), entity.getConfidenceScore());
}
}
/**
* Code snippet for {@link TextAnalyticsClient
*/
public void recognizeEntitiesStringListWithOptions() {
List<String> documents = Arrays.asList(
"I had a wonderful trip to Seattle last week.",
"I work at Microsoft.");
RecognizeEntitiesResultCollection resultCollection =
textAnalyticsClient.recognizeEntitiesBatch(documents, "en", null);
TextDocumentBatchStatistics batchStatistics = resultCollection.getStatistics();
System.out.printf(
"A batch of documents statistics, transaction count: %s, valid document count: %s.%n",
batchStatistics.getTransactionCount(), batchStatistics.getValidDocumentCount());
resultCollection.forEach(recognizeEntitiesResult ->
recognizeEntitiesResult.getEntities().forEach(entity ->
System.out.printf("Recognized entity: %s, entity category: %s, confidence score: %f.%n",
entity.getText(), entity.getCategory(), entity.getConfidenceScore())));
}
/**
* Code snippet for {@link TextAnalyticsClient
*/
public void recognizeBatchEntitiesMaxOverload() {
List<TextDocumentInput> textDocumentInputs = Arrays.asList(
new TextDocumentInput("0", "I had a wonderful trip to Seattle last week.").setLanguage("en"),
new TextDocumentInput("1", "I work at Microsoft.").setLanguage("en")
);
Response<RecognizeEntitiesResultCollection> response =
textAnalyticsClient.recognizeEntitiesBatchWithResponse(textDocumentInputs,
new TextAnalyticsRequestOptions().setIncludeStatistics(true), Context.NONE);
System.out.printf("Status code of request response: %d%n", response.getStatusCode());
RecognizeEntitiesResultCollection recognizeEntitiesResultCollection = response.getValue();
TextDocumentBatchStatistics batchStatistics = recognizeEntitiesResultCollection.getStatistics();
System.out.printf(
"A batch of documents statistics, transaction count: %s, valid document count: %s.%n",
batchStatistics.getTransactionCount(), batchStatistics.getValidDocumentCount());
recognizeEntitiesResultCollection.forEach(recognizeEntitiesResult ->
recognizeEntitiesResult.getEntities().forEach(entity ->
System.out.printf("Recognized entity: %s, entity category: %s, confidence score: %f.%n",
entity.getText(), entity.getCategory(), entity.getConfidenceScore())));
}
/**
* Code snippet for {@link TextAnalyticsClient
*/
public void recognizePiiEntities() {
for (PiiEntity entity : textAnalyticsClient.recognizePiiEntities("My SSN is 859-98-0987")) {
System.out.printf(
"Recognized Personally Identifiable Information entity: %s, entity category: %s,"
+ " entity subcategory: %s, confidence score: %f.%n",
entity.getText(), entity.getCategory(), entity.getSubcategory(), entity.getConfidenceScore());
}
}
/**
* Code snippet for {@link TextAnalyticsClient
*/
public void recognizePiiEntitiesWithLanguage() {
textAnalyticsClient.recognizePiiEntities("My SSN is 859-98-0987", "en")
.forEach(entity -> System.out.printf(
"Recognized Personally Identifiable Information entity: %s, entity category: %s,"
+ " entity subcategory: %s, confidence score: %f.%n",
entity.getText(), entity.getCategory(), entity.getSubcategory(), entity.getConfidenceScore()));
}
/**
* Code snippet for {@link TextAnalyticsClient
*/
/**
* Code snippet for {@link TextAnalyticsClient
*/
public void recognizePiiEntitiesStringListWithOptions() {
List<String> documents = Arrays.asList(
"My SSN is 859-98-0987",
"Visa card 4111 1111 1111 1111"
);
RecognizePiiEntitiesResultCollection resultCollection = textAnalyticsClient.recognizePiiEntitiesBatch(
documents, "en", new RecognizePiiEntityOptions().setIncludeStatistics(true));
TextDocumentBatchStatistics batchStatistics = resultCollection.getStatistics();
System.out.printf("A batch of documents statistics, transaction count: %s, valid document count: %s.%n",
batchStatistics.getTransactionCount(), batchStatistics.getValidDocumentCount());
resultCollection.forEach(recognizePiiEntitiesResult ->
recognizePiiEntitiesResult.getEntities().forEach(entity -> System.out.printf(
"Recognized Personally Identifiable Information entity: %s, entity category: %s,"
+ " entity subcategory: %s, confidence score: %f.%n",
entity.getText(), entity.getCategory(), entity.getSubcategory(), entity.getConfidenceScore())));
}
/**
* Code snippet for {@link TextAnalyticsClient
*/
public void recognizeBatchPiiEntitiesMaxOverload() {
List<TextDocumentInput> textDocumentInputs = Arrays.asList(
new TextDocumentInput("0", "My SSN is 859-98-0987"),
new TextDocumentInput("1", "Visa card 4111 1111 1111 1111")
);
Response<RecognizePiiEntitiesResultCollection> response =
textAnalyticsClient.recognizePiiEntitiesBatchWithResponse(textDocumentInputs,
new RecognizePiiEntityOptions().setIncludeStatistics(true), Context.NONE);
RecognizePiiEntitiesResultCollection resultCollection = response.getValue();
TextDocumentBatchStatistics batchStatistics = resultCollection.getStatistics();
System.out.printf("A batch of documents statistics, transaction count: %s, valid document count: %s.%n",
batchStatistics.getTransactionCount(), batchStatistics.getValidDocumentCount());
resultCollection.forEach(recognizePiiEntitiesResult ->
recognizePiiEntitiesResult.getEntities().forEach(entity -> System.out.printf(
"Recognized Personally Identifiable Information entity: %s, entity category: %s,"
+ " entity subcategory: %s, confidence score: %f.%n",
entity.getText(), entity.getCategory(), entity.getSubcategory(), entity.getConfidenceScore())));
}
/**
* Code snippet for {@link TextAnalyticsClient
*/
public void recognizeLinkedEntities() {
final String document = "Old Faithful is a geyser at Yellowstone Park.";
System.out.println("Linked Entities:");
textAnalyticsClient.recognizeLinkedEntities(document).forEach(linkedEntity -> {
System.out.printf("Name: %s, entity ID in data source: %s, URL: %s, data source: %s.%n",
linkedEntity.getName(), linkedEntity.getDataSourceEntityId(), linkedEntity.getUrl(),
linkedEntity.getDataSource());
linkedEntity.getMatches().forEach(entityMatch -> System.out.printf(
"Matched entity: %s, confidence score: %f.%n",
entityMatch.getText(), entityMatch.getConfidenceScore()));
});
}
/**
* Code snippet for {@link TextAnalyticsClient
*/
public void recognizeLinkedEntitiesWithLanguage() {
String document = "Old Faithful is a geyser at Yellowstone Park.";
textAnalyticsClient.recognizeLinkedEntities(document, "en").forEach(linkedEntity -> {
System.out.printf("Name: %s, entity ID in data source: %s, URL: %s, data source: %s.%n",
linkedEntity.getName(), linkedEntity.getDataSourceEntityId(), linkedEntity.getUrl(),
linkedEntity.getDataSource());
linkedEntity.getMatches().forEach(entityMatch -> System.out.printf(
"Matched entity: %s, confidence score: %f.%n",
entityMatch.getText(), entityMatch.getConfidenceScore()));
});
}
/**
* Code snippet for {@link TextAnalyticsClient
*/
public void recognizeLinkedEntitiesStringListWithOptions() {
List<String> documents = Arrays.asList(
"Old Faithful is a geyser at Yellowstone Park.",
"Mount Shasta has lenticular clouds."
);
RecognizeLinkedEntitiesResultCollection resultCollection =
textAnalyticsClient.recognizeLinkedEntitiesBatch(documents, "en", null);
TextDocumentBatchStatistics batchStatistics = resultCollection.getStatistics();
System.out.printf("A batch of documents statistics, transaction count: %s, valid document count: %s.%n",
batchStatistics.getTransactionCount(), batchStatistics.getValidDocumentCount());
resultCollection.forEach(recognizeLinkedEntitiesResult ->
recognizeLinkedEntitiesResult.getEntities().forEach(linkedEntity -> {
System.out.println("Linked Entities:");
System.out.printf("Name: %s, entity ID in data source: %s, URL: %s, data source: %s.%n",
linkedEntity.getName(), linkedEntity.getDataSourceEntityId(), linkedEntity.getUrl(),
linkedEntity.getDataSource());
linkedEntity.getMatches().forEach(entityMatch -> System.out.printf(
"Matched entity: %s, confidence score: %f.%n",
entityMatch.getText(), entityMatch.getConfidenceScore()));
}));
}
/**
* Code snippet for {@link TextAnalyticsClient
*/
public void recognizeLinkedEntitiesBatchMaxOverload() {
List<TextDocumentInput> textDocumentInputs = Arrays.asList(
new TextDocumentInput("1", "Old Faithful is a geyser at Yellowstone Park.").setLanguage("en"),
new TextDocumentInput("2", "Mount Shasta has lenticular clouds.").setLanguage("en")
);
Response<RecognizeLinkedEntitiesResultCollection> response =
textAnalyticsClient.recognizeLinkedEntitiesBatchWithResponse(textDocumentInputs,
new TextAnalyticsRequestOptions().setIncludeStatistics(true), Context.NONE);
System.out.printf("Status code of request response: %d%n", response.getStatusCode());
RecognizeLinkedEntitiesResultCollection resultCollection = response.getValue();
TextDocumentBatchStatistics batchStatistics = resultCollection.getStatistics();
System.out.printf(
"A batch of documents statistics, transaction count: %s, valid document count: %s.%n",
batchStatistics.getTransactionCount(), batchStatistics.getValidDocumentCount());
resultCollection.forEach(recognizeLinkedEntitiesResult ->
recognizeLinkedEntitiesResult.getEntities().forEach(linkedEntity -> {
System.out.println("Linked Entities:");
System.out.printf("Name: %s, entity ID in data source: %s, URL: %s, data source: %s.%n",
linkedEntity.getName(), linkedEntity.getDataSourceEntityId(), linkedEntity.getUrl(),
linkedEntity.getDataSource());
linkedEntity.getMatches().forEach(entityMatch -> System.out.printf(
"Matched entity: %s, confidence score: %.2f.%n",
entityMatch.getText(), entityMatch.getConfidenceScore()));
}));
}
/**
* Code snippet for {@link TextAnalyticsClient
*/
public void extractKeyPhrases() {
System.out.println("Extracted phrases:");
for (String keyPhrase : textAnalyticsClient.extractKeyPhrases("My cat might need to see a veterinarian.")) {
System.out.printf("%s.%n", keyPhrase);
}
}
/**
* Code snippet for {@link TextAnalyticsClient
*/
public void extractKeyPhrasesWithLanguage() {
System.out.println("Extracted phrases:");
textAnalyticsClient.extractKeyPhrases("My cat might need to see a veterinarian.", "en")
.forEach(kegPhrase -> System.out.printf("%s.%n", kegPhrase));
}
/**
* Code snippet for {@link TextAnalyticsClient
*/
public void extractKeyPhrasesStringListWithOptions() {
List<String> documents = Arrays.asList(
"My cat might need to see a veterinarian.",
"The pitot tube is used to measure airspeed."
);
ExtractKeyPhrasesResultCollection resultCollection =
textAnalyticsClient.extractKeyPhrasesBatch(documents, "en", null);
TextDocumentBatchStatistics batchStatistics = resultCollection.getStatistics();
System.out.printf(
"A batch of documents statistics, transaction count: %s, valid document count: %s.%n",
batchStatistics.getTransactionCount(), batchStatistics.getValidDocumentCount());
resultCollection.forEach(extractKeyPhraseResult -> {
System.out.printf("Document ID: %s%n", extractKeyPhraseResult.getId());
System.out.println("Extracted phrases:");
extractKeyPhraseResult.getKeyPhrases().forEach(keyPhrase -> System.out.printf("%s.%n", keyPhrase));
});
}
/**
* Code snippet for {@link TextAnalyticsClient
*/
public void extractBatchKeyPhrasesMaxOverload() {
List<TextDocumentInput> textDocumentInputs = Arrays.asList(
new TextDocumentInput("1", "My cat might need to see a veterinarian.").setLanguage("en"),
new TextDocumentInput("2", "The pitot tube is used to measure airspeed.").setLanguage("en")
);
Response<ExtractKeyPhrasesResultCollection> response =
textAnalyticsClient.extractKeyPhrasesBatchWithResponse(textDocumentInputs,
new TextAnalyticsRequestOptions().setIncludeStatistics(true), Context.NONE);
System.out.printf("Status code of request response: %d%n", response.getStatusCode());
ExtractKeyPhrasesResultCollection resultCollection = response.getValue();
TextDocumentBatchStatistics batchStatistics = resultCollection.getStatistics();
System.out.printf(
"A batch of documents statistics, transaction count: %s, valid document count: %s.%n",
batchStatistics.getTransactionCount(), batchStatistics.getValidDocumentCount());
resultCollection.forEach(extractKeyPhraseResult -> {
System.out.printf("Document ID: %s%n", extractKeyPhraseResult.getId());
System.out.println("Extracted phrases:");
extractKeyPhraseResult.getKeyPhrases().forEach(keyPhrase ->
System.out.printf("%s.%n", keyPhrase));
});
}
/**
* Code snippet for {@link TextAnalyticsClient
*/
public void analyzeSentiment() {
final DocumentSentiment documentSentiment =
textAnalyticsClient.analyzeSentiment("The hotel was dark and unclean.");
System.out.printf(
"Recognized sentiment: %s, positive score: %.2f, neutral score: %.2f, negative score: %.2f.%n",
documentSentiment.getSentiment(),
documentSentiment.getConfidenceScores().getPositive(),
documentSentiment.getConfidenceScores().getNeutral(),
documentSentiment.getConfidenceScores().getNegative());
for (SentenceSentiment sentenceSentiment : documentSentiment.getSentences()) {
System.out.printf(
"Recognized sentence sentiment: %s, positive score: %.2f, neutral score: %.2f, negative score: %.2f.%n",
sentenceSentiment.getSentiment(),
sentenceSentiment.getConfidenceScores().getPositive(),
sentenceSentiment.getConfidenceScores().getNeutral(),
sentenceSentiment.getConfidenceScores().getNegative());
}
}
/**
* Code snippet for {@link TextAnalyticsClient
*/
public void analyzeSentimentWithLanguage() {
final DocumentSentiment documentSentiment = textAnalyticsClient.analyzeSentiment(
"The hotel was dark and unclean.", "en");
System.out.printf(
"Recognized sentiment: %s, positive score: %.2f, neutral score: %.2f, negative score: %.2f.%n",
documentSentiment.getSentiment(),
documentSentiment.getConfidenceScores().getPositive(),
documentSentiment.getConfidenceScores().getNeutral(),
documentSentiment.getConfidenceScores().getNegative());
for (SentenceSentiment sentenceSentiment : documentSentiment.getSentences()) {
System.out.printf(
"Recognized sentence sentiment: %s, positive score: %.2f, neutral score: %.2f, negative score: %.2f.%n",
sentenceSentiment.getSentiment(),
sentenceSentiment.getConfidenceScores().getPositive(),
sentenceSentiment.getConfidenceScores().getNeutral(),
sentenceSentiment.getConfidenceScores().getNegative());
}
}
/**
* Code snippet for {@link TextAnalyticsClient
*/
public void analyzeSentimentWithLanguageWithOpinionMining() {
final DocumentSentiment documentSentiment = textAnalyticsClient.analyzeSentiment(
"The hotel was dark and unclean.", "en",
new AnalyzeSentimentOptions().setIncludeOpinionMining(true));
for (SentenceSentiment sentenceSentiment : documentSentiment.getSentences()) {
System.out.printf("\tSentence sentiment: %s%n", sentenceSentiment.getSentiment());
sentenceSentiment.getMinedOpinions().forEach(minedOpinions -> {
AspectSentiment aspectSentiment = minedOpinions.getAspect();
System.out.printf("\tAspect sentiment: %s, aspect text: %s%n", aspectSentiment.getSentiment(),
aspectSentiment.getText());
for (OpinionSentiment opinionSentiment : minedOpinions.getOpinions()) {
System.out.printf("\t\t'%s' sentiment because of \"%s\". Is the opinion negated: %s.%n",
opinionSentiment.getSentiment(), opinionSentiment.getText(), opinionSentiment.isNegated());
}
});
}
}
/**
* Code snippet for {@link TextAnalyticsClient
*/
public void analyzeSentimentStringListWithOptions() {
List<String> documents = Arrays.asList(
"The hotel was dark and unclean. The restaurant had amazing gnocchi.",
"The restaurant had amazing gnocchi. The hotel was dark and unclean."
);
AnalyzeSentimentResultCollection resultCollection = textAnalyticsClient.analyzeSentimentBatch(
documents, "en", new TextAnalyticsRequestOptions().setIncludeStatistics(true));
TextDocumentBatchStatistics batchStatistics = resultCollection.getStatistics();
System.out.printf("A batch of documents statistics, transaction count: %s, valid document count: %s.%n",
batchStatistics.getTransactionCount(), batchStatistics.getValidDocumentCount());
resultCollection.forEach(analyzeSentimentResult -> {
System.out.printf("Document ID: %s%n", analyzeSentimentResult.getId());
DocumentSentiment documentSentiment = analyzeSentimentResult.getDocumentSentiment();
System.out.printf(
"Recognized document sentiment: %s, positive score: %.2f, neutral score: %.2f,"
+ " negative score: %.2f.%n",
documentSentiment.getSentiment(),
documentSentiment.getConfidenceScores().getPositive(),
documentSentiment.getConfidenceScores().getNeutral(),
documentSentiment.getConfidenceScores().getNegative());
documentSentiment.getSentences().forEach(sentenceSentiment -> System.out.printf(
"Recognized sentence sentiment: %s, positive score: %.2f, neutral score: %.2f,"
+ " negative score: %.2f.%n",
sentenceSentiment.getSentiment(),
sentenceSentiment.getConfidenceScores().getPositive(),
sentenceSentiment.getConfidenceScores().getNeutral(),
sentenceSentiment.getConfidenceScores().getNegative()));
});
}
/**
* Code snippet for {@link TextAnalyticsClient
*/
public void analyzeSentimentStringListWithOptionsAndOpinionMining() {
List<String> documents = Arrays.asList(
"The hotel was dark and unclean. The restaurant had amazing gnocchi.",
"The restaurant had amazing gnocchi. The hotel was dark and unclean."
);
AnalyzeSentimentResultCollection resultCollection = textAnalyticsClient.analyzeSentimentBatch(
documents, "en", new AnalyzeSentimentOptions().setIncludeOpinionMining(true));
resultCollection.forEach(analyzeSentimentResult -> {
System.out.printf("Document ID: %s%n", analyzeSentimentResult.getId());
DocumentSentiment documentSentiment = analyzeSentimentResult.getDocumentSentiment();
documentSentiment.getSentences().forEach(sentenceSentiment -> {
System.out.printf("\tSentence sentiment: %s%n", sentenceSentiment.getSentiment());
sentenceSentiment.getMinedOpinions().forEach(minedOpinions -> {
AspectSentiment aspectSentiment = minedOpinions.getAspect();
System.out.printf("\tAspect sentiment: %s, aspect text: %s%n", aspectSentiment.getSentiment(),
aspectSentiment.getText());
for (OpinionSentiment opinionSentiment : minedOpinions.getOpinions()) {
System.out.printf("\t\t'%s' sentiment because of \"%s\". Is the opinion negated: %s.%n",
opinionSentiment.getSentiment(), opinionSentiment.getText(), opinionSentiment.isNegated());
}
});
});
});
}
/**
* Code snippet for {@link TextAnalyticsClient
*/
public void analyzeBatchSentimentMaxOverload() {
List<TextDocumentInput> textDocumentInputs = Arrays.asList(
new TextDocumentInput("1", "The hotel was dark and unclean. The restaurant had amazing gnocchi.")
.setLanguage("en"),
new TextDocumentInput("2", "The restaurant had amazing gnocchi. The hotel was dark and unclean.")
.setLanguage("en")
);
Response<AnalyzeSentimentResultCollection> response =
textAnalyticsClient.analyzeSentimentBatchWithResponse(textDocumentInputs,
new TextAnalyticsRequestOptions().setIncludeStatistics(true), Context.NONE);
System.out.printf("Status code of request response: %d%n", response.getStatusCode());
AnalyzeSentimentResultCollection resultCollection = response.getValue();
TextDocumentBatchStatistics batchStatistics = resultCollection.getStatistics();
System.out.printf("A batch of documents statistics, transaction count: %s, valid document count: %s.%n",
batchStatistics.getTransactionCount(), batchStatistics.getValidDocumentCount());
resultCollection.forEach(analyzeSentimentResult -> {
System.out.printf("Document ID: %s%n", analyzeSentimentResult.getId());
DocumentSentiment documentSentiment = analyzeSentimentResult.getDocumentSentiment();
System.out.printf(
"Recognized document sentiment: %s, positive score: %.2f, neutral score: %.2f, "
+ "negative score: %.2f.%n",
documentSentiment.getSentiment(),
documentSentiment.getConfidenceScores().getPositive(),
documentSentiment.getConfidenceScores().getNeutral(),
documentSentiment.getConfidenceScores().getNegative());
documentSentiment.getSentences().forEach(sentenceSentiment -> {
System.out.printf(
"Recognized sentence sentiment: %s, positive score: %.2f, neutral score: %.2f,"
+ " negative score: %.2f.%n",
sentenceSentiment.getSentiment(),
sentenceSentiment.getConfidenceScores().getPositive(),
sentenceSentiment.getConfidenceScores().getNeutral(),
sentenceSentiment.getConfidenceScores().getNegative());
});
});
}
/**
* Code snippet for {@link TextAnalyticsClient
*/
public void analyzeBatchSentimentMaxOverloadWithOpinionMining() {
List<TextDocumentInput> textDocumentInputs = Arrays.asList(
new TextDocumentInput("1", "The hotel was dark and unclean. The restaurant had amazing gnocchi.")
.setLanguage("en"),
new TextDocumentInput("2", "The restaurant had amazing gnocchi. The hotel was dark and unclean.")
.setLanguage("en")
);
AnalyzeSentimentOptions options = new AnalyzeSentimentOptions().setIncludeOpinionMining(true)
.setIncludeStatistics(true);
Response<AnalyzeSentimentResultCollection> response =
textAnalyticsClient.analyzeSentimentBatchWithResponse(textDocumentInputs, options, Context.NONE);
System.out.printf("Status code of request response: %d%n", response.getStatusCode());
AnalyzeSentimentResultCollection resultCollection = response.getValue();
TextDocumentBatchStatistics batchStatistics = resultCollection.getStatistics();
System.out.printf("A batch of documents statistics, transaction count: %s, valid document count: %s.%n",
batchStatistics.getTransactionCount(), batchStatistics.getValidDocumentCount());
resultCollection.forEach(analyzeSentimentResult -> {
System.out.printf("Document ID: %s%n", analyzeSentimentResult.getId());
DocumentSentiment documentSentiment = analyzeSentimentResult.getDocumentSentiment();
documentSentiment.getSentences().forEach(sentenceSentiment -> {
System.out.printf("\tSentence sentiment: %s%n", sentenceSentiment.getSentiment());
sentenceSentiment.getMinedOpinions().forEach(minedOpinions -> {
AspectSentiment aspectSentiment = minedOpinions.getAspect();
System.out.printf("\tAspect sentiment: %s, aspect text: %s%n", aspectSentiment.getSentiment(),
aspectSentiment.getText());
for (OpinionSentiment opinionSentiment : minedOpinions.getOpinions()) {
System.out.printf("\t\t'%s' sentiment because of \"%s\". Is the opinion negated: %s.%n",
opinionSentiment.getSentiment(), opinionSentiment.getText(), opinionSentiment.isNegated());
}
});
});
});
}
} | class TextAnalyticsClientJavaDocCodeSnippets {
private TextAnalyticsClient textAnalyticsClient = new TextAnalyticsClientBuilder().buildClient();
/**
* Code snippet for creating a {@link TextAnalyticsClient} with pipeline
*/
public void createTextAnalyticsClientWithPipeline() {
HttpPipeline pipeline = new HttpPipelineBuilder()
.policies(/* add policies */)
.build();
TextAnalyticsClient textAnalyticsClient = new TextAnalyticsClientBuilder()
.credential(new AzureKeyCredential("{key}"))
.endpoint("{endpoint}")
.pipeline(pipeline)
.buildClient();
}
/**
* Code snippet for creating a {@link TextAnalyticsClient}
*/
public void createTextAnalyticsClient() {
TextAnalyticsClient textAnalyticsClient = new TextAnalyticsClientBuilder()
.credential(new AzureKeyCredential("{key}"))
.endpoint("{endpoint}")
.buildClient();
}
/**
* Code snippet for {@link TextAnalyticsClient
*/
public void detectLanguage() {
DetectedLanguage detectedLanguage = textAnalyticsClient.detectLanguage("Bonjour tout le monde");
System.out.printf("Detected language name: %s, ISO 6391 name: %s, confidence score: %f.%n",
detectedLanguage.getName(), detectedLanguage.getIso6391Name(), detectedLanguage.getConfidenceScore());
}
/**
* Code snippet for {@link TextAnalyticsClient
*/
public void detectLanguageWithCountryHint() {
DetectedLanguage detectedLanguage = textAnalyticsClient.detectLanguage(
"This text is in English", "US");
System.out.printf("Detected language name: %s, ISO 6391 name: %s, confidence score: %f.%n",
detectedLanguage.getName(), detectedLanguage.getIso6391Name(), detectedLanguage.getConfidenceScore());
}
/**
* Code snippet for {@link TextAnalyticsClient
*/
public void detectLanguageStringListWithOptions() {
List<String> documents = Arrays.asList(
"This is written in English",
"Este es un documento escrito en Español."
);
DetectLanguageResultCollection resultCollection =
textAnalyticsClient.detectLanguageBatch(documents, "US", null);
TextDocumentBatchStatistics batchStatistics = resultCollection.getStatistics();
System.out.printf("A batch of documents statistics, transaction count: %s, valid document count: %s.%n",
batchStatistics.getTransactionCount(), batchStatistics.getValidDocumentCount());
resultCollection.forEach(detectLanguageResult -> {
System.out.printf("Document ID: %s%n", detectLanguageResult.getId());
DetectedLanguage detectedLanguage = detectLanguageResult.getPrimaryLanguage();
System.out.printf("Primary language name: %s, ISO 6391 name: %s, confidence score: %f.%n",
detectedLanguage.getName(), detectedLanguage.getIso6391Name(),
detectedLanguage.getConfidenceScore());
});
}
/**
* Code snippet for {@link TextAnalyticsClient
*/
public void detectBatchLanguagesMaxOverload() {
List<DetectLanguageInput> detectLanguageInputs = Arrays.asList(
new DetectLanguageInput("1", "This is written in English.", "US"),
new DetectLanguageInput("2", "Este es un documento escrito en Español.", "es")
);
Response<DetectLanguageResultCollection> response =
textAnalyticsClient.detectLanguageBatchWithResponse(detectLanguageInputs,
new TextAnalyticsRequestOptions().setIncludeStatistics(true), Context.NONE);
System.out.printf("Status code of request response: %d%n", response.getStatusCode());
DetectLanguageResultCollection detectedLanguageResultCollection = response.getValue();
TextDocumentBatchStatistics batchStatistics = detectedLanguageResultCollection.getStatistics();
System.out.printf(
"Documents statistics: document count = %s, erroneous document count = %s, transaction count = %s,"
+ " valid document count = %s.%n",
batchStatistics.getDocumentCount(), batchStatistics.getInvalidDocumentCount(),
batchStatistics.getTransactionCount(), batchStatistics.getValidDocumentCount());
detectedLanguageResultCollection.forEach(detectLanguageResult -> {
System.out.printf("Document ID: %s%n", detectLanguageResult.getId());
DetectedLanguage detectedLanguage = detectLanguageResult.getPrimaryLanguage();
System.out.printf("Primary language name: %s, ISO 6391 name: %s, confidence score: %f.%n",
detectedLanguage.getName(), detectedLanguage.getIso6391Name(),
detectedLanguage.getConfidenceScore());
});
}
/**
* Code snippet for {@link TextAnalyticsClient
*/
public void recognizeEntities() {
final CategorizedEntityCollection recognizeEntitiesResult =
textAnalyticsClient.recognizeEntities("Satya Nadella is the CEO of Microsoft");
for (CategorizedEntity entity : recognizeEntitiesResult) {
System.out.printf("Recognized entity: %s, entity category: %s, confidence score: %f.%n",
entity.getText(), entity.getCategory(), entity.getConfidenceScore());
}
}
/**
* Code snippet for {@link TextAnalyticsClient
*/
public void recognizeEntitiesWithLanguage() {
final CategorizedEntityCollection recognizeEntitiesResult =
textAnalyticsClient.recognizeEntities("Satya Nadella is the CEO of Microsoft", "en");
for (CategorizedEntity entity : recognizeEntitiesResult) {
System.out.printf("Recognized entity: %s, entity category: %s, confidence score: %f.%n",
entity.getText(), entity.getCategory(), entity.getConfidenceScore());
}
}
/**
* Code snippet for {@link TextAnalyticsClient
*/
public void recognizeEntitiesStringListWithOptions() {
List<String> documents = Arrays.asList(
"I had a wonderful trip to Seattle last week.",
"I work at Microsoft.");
RecognizeEntitiesResultCollection resultCollection =
textAnalyticsClient.recognizeEntitiesBatch(documents, "en", null);
TextDocumentBatchStatistics batchStatistics = resultCollection.getStatistics();
System.out.printf(
"A batch of documents statistics, transaction count: %s, valid document count: %s.%n",
batchStatistics.getTransactionCount(), batchStatistics.getValidDocumentCount());
resultCollection.forEach(recognizeEntitiesResult ->
recognizeEntitiesResult.getEntities().forEach(entity ->
System.out.printf("Recognized entity: %s, entity category: %s, confidence score: %f.%n",
entity.getText(), entity.getCategory(), entity.getConfidenceScore())));
}
/**
* Code snippet for {@link TextAnalyticsClient
*/
public void recognizeBatchEntitiesMaxOverload() {
List<TextDocumentInput> textDocumentInputs = Arrays.asList(
new TextDocumentInput("0", "I had a wonderful trip to Seattle last week.").setLanguage("en"),
new TextDocumentInput("1", "I work at Microsoft.").setLanguage("en")
);
Response<RecognizeEntitiesResultCollection> response =
textAnalyticsClient.recognizeEntitiesBatchWithResponse(textDocumentInputs,
new TextAnalyticsRequestOptions().setIncludeStatistics(true), Context.NONE);
System.out.printf("Status code of request response: %d%n", response.getStatusCode());
RecognizeEntitiesResultCollection recognizeEntitiesResultCollection = response.getValue();
TextDocumentBatchStatistics batchStatistics = recognizeEntitiesResultCollection.getStatistics();
System.out.printf(
"A batch of documents statistics, transaction count: %s, valid document count: %s.%n",
batchStatistics.getTransactionCount(), batchStatistics.getValidDocumentCount());
recognizeEntitiesResultCollection.forEach(recognizeEntitiesResult ->
recognizeEntitiesResult.getEntities().forEach(entity ->
System.out.printf("Recognized entity: %s, entity category: %s, confidence score: %f.%n",
entity.getText(), entity.getCategory(), entity.getConfidenceScore())));
}
/**
* Code snippet for {@link TextAnalyticsClient
*/
public void recognizePiiEntities() {
PiiEntityCollection piiEntityCollection = textAnalyticsClient.recognizePiiEntities("My SSN is 859-98-0987");
System.out.printf("Redacted Text: %s%n", piiEntityCollection.getRedactedText());
for (PiiEntity entity : piiEntityCollection) {
System.out.printf(
"Recognized Personally Identifiable Information entity: %s, entity category: %s,"
+ " entity subcategory: %s, confidence score: %f.%n",
entity.getText(), entity.getCategory(), entity.getSubcategory(), entity.getConfidenceScore());
}
}
/**
* Code snippet for {@link TextAnalyticsClient
*/
public void recognizePiiEntitiesWithLanguage() {
PiiEntityCollection piiEntityCollection = textAnalyticsClient.recognizePiiEntities(
"My SSN is 859-98-0987", "en");
System.out.printf("Redacted Text: %s%n", piiEntityCollection.getRedactedText());
piiEntityCollection.forEach(entity -> System.out.printf(
"Recognized Personally Identifiable Information entity: %s, entity category: %s,"
+ " entity subcategory: %s, confidence score: %f.%n",
entity.getText(), entity.getCategory(), entity.getSubcategory(), entity.getConfidenceScore()));
}
/**
* Code snippet for {@link TextAnalyticsClient
*/
/**
* Code snippet for {@link TextAnalyticsClient
*/
public void recognizePiiEntitiesStringListWithOptions() {
List<String> documents = Arrays.asList(
"My SSN is 859-98-0987",
"Visa card 4111 1111 1111 1111"
);
RecognizePiiEntitiesResultCollection resultCollection = textAnalyticsClient.recognizePiiEntitiesBatch(
documents, "en", new RecognizePiiEntityOptions().setIncludeStatistics(true));
TextDocumentBatchStatistics batchStatistics = resultCollection.getStatistics();
System.out.printf("A batch of documents statistics, transaction count: %s, valid document count: %s.%n",
batchStatistics.getTransactionCount(), batchStatistics.getValidDocumentCount());
resultCollection.forEach(recognizePiiEntitiesResult -> {
PiiEntityCollection piiEntityCollection = recognizePiiEntitiesResult.getEntities();
System.out.printf("Redacted Text: %s%n", piiEntityCollection.getRedactedText());
piiEntityCollection.forEach(entity -> System.out.printf(
"Recognized Personally Identifiable Information entity: %s, entity category: %s,"
+ " entity subcategory: %s, confidence score: %f.%n",
entity.getText(), entity.getCategory(), entity.getSubcategory(), entity.getConfidenceScore()));
});
}
/**
* Code snippet for {@link TextAnalyticsClient
*/
public void recognizeBatchPiiEntitiesMaxOverload() {
List<TextDocumentInput> textDocumentInputs = Arrays.asList(
new TextDocumentInput("0", "My SSN is 859-98-0987"),
new TextDocumentInput("1", "Visa card 4111 1111 1111 1111")
);
Response<RecognizePiiEntitiesResultCollection> response =
textAnalyticsClient.recognizePiiEntitiesBatchWithResponse(textDocumentInputs,
new RecognizePiiEntityOptions().setIncludeStatistics(true), Context.NONE);
RecognizePiiEntitiesResultCollection resultCollection = response.getValue();
TextDocumentBatchStatistics batchStatistics = resultCollection.getStatistics();
System.out.printf("A batch of documents statistics, transaction count: %s, valid document count: %s.%n",
batchStatistics.getTransactionCount(), batchStatistics.getValidDocumentCount());
resultCollection.forEach(recognizePiiEntitiesResult -> {
PiiEntityCollection piiEntityCollection = recognizePiiEntitiesResult.getEntities();
System.out.printf("Redacted Text: %s%n", piiEntityCollection.getRedactedText());
piiEntityCollection.forEach(entity -> System.out.printf(
"Recognized Personally Identifiable Information entity: %s, entity category: %s,"
+ " entity subcategory: %s, confidence score: %f.%n",
entity.getText(), entity.getCategory(), entity.getSubcategory(), entity.getConfidenceScore()));
});
}
/**
* Code snippet for {@link TextAnalyticsClient
*/
public void recognizeLinkedEntities() {
final String document = "Old Faithful is a geyser at Yellowstone Park.";
System.out.println("Linked Entities:");
textAnalyticsClient.recognizeLinkedEntities(document).forEach(linkedEntity -> {
System.out.printf("Name: %s, entity ID in data source: %s, URL: %s, data source: %s.%n",
linkedEntity.getName(), linkedEntity.getDataSourceEntityId(), linkedEntity.getUrl(),
linkedEntity.getDataSource());
linkedEntity.getMatches().forEach(entityMatch -> System.out.printf(
"Matched entity: %s, confidence score: %f.%n",
entityMatch.getText(), entityMatch.getConfidenceScore()));
});
}
/**
* Code snippet for {@link TextAnalyticsClient
*/
public void recognizeLinkedEntitiesWithLanguage() {
String document = "Old Faithful is a geyser at Yellowstone Park.";
textAnalyticsClient.recognizeLinkedEntities(document, "en").forEach(linkedEntity -> {
System.out.printf("Name: %s, entity ID in data source: %s, URL: %s, data source: %s.%n",
linkedEntity.getName(), linkedEntity.getDataSourceEntityId(), linkedEntity.getUrl(),
linkedEntity.getDataSource());
linkedEntity.getMatches().forEach(entityMatch -> System.out.printf(
"Matched entity: %s, confidence score: %f.%n",
entityMatch.getText(), entityMatch.getConfidenceScore()));
});
}
/**
* Code snippet for {@link TextAnalyticsClient
*/
public void recognizeLinkedEntitiesStringListWithOptions() {
List<String> documents = Arrays.asList(
"Old Faithful is a geyser at Yellowstone Park.",
"Mount Shasta has lenticular clouds."
);
RecognizeLinkedEntitiesResultCollection resultCollection =
textAnalyticsClient.recognizeLinkedEntitiesBatch(documents, "en", null);
TextDocumentBatchStatistics batchStatistics = resultCollection.getStatistics();
System.out.printf("A batch of documents statistics, transaction count: %s, valid document count: %s.%n",
batchStatistics.getTransactionCount(), batchStatistics.getValidDocumentCount());
resultCollection.forEach(recognizeLinkedEntitiesResult ->
recognizeLinkedEntitiesResult.getEntities().forEach(linkedEntity -> {
System.out.println("Linked Entities:");
System.out.printf("Name: %s, entity ID in data source: %s, URL: %s, data source: %s.%n",
linkedEntity.getName(), linkedEntity.getDataSourceEntityId(), linkedEntity.getUrl(),
linkedEntity.getDataSource());
linkedEntity.getMatches().forEach(entityMatch -> System.out.printf(
"Matched entity: %s, confidence score: %f.%n",
entityMatch.getText(), entityMatch.getConfidenceScore()));
}));
}
/**
* Code snippet for {@link TextAnalyticsClient
*/
public void recognizeLinkedEntitiesBatchMaxOverload() {
List<TextDocumentInput> textDocumentInputs = Arrays.asList(
new TextDocumentInput("1", "Old Faithful is a geyser at Yellowstone Park.").setLanguage("en"),
new TextDocumentInput("2", "Mount Shasta has lenticular clouds.").setLanguage("en")
);
Response<RecognizeLinkedEntitiesResultCollection> response =
textAnalyticsClient.recognizeLinkedEntitiesBatchWithResponse(textDocumentInputs,
new TextAnalyticsRequestOptions().setIncludeStatistics(true), Context.NONE);
System.out.printf("Status code of request response: %d%n", response.getStatusCode());
RecognizeLinkedEntitiesResultCollection resultCollection = response.getValue();
TextDocumentBatchStatistics batchStatistics = resultCollection.getStatistics();
System.out.printf(
"A batch of documents statistics, transaction count: %s, valid document count: %s.%n",
batchStatistics.getTransactionCount(), batchStatistics.getValidDocumentCount());
resultCollection.forEach(recognizeLinkedEntitiesResult ->
recognizeLinkedEntitiesResult.getEntities().forEach(linkedEntity -> {
System.out.println("Linked Entities:");
System.out.printf("Name: %s, entity ID in data source: %s, URL: %s, data source: %s.%n",
linkedEntity.getName(), linkedEntity.getDataSourceEntityId(), linkedEntity.getUrl(),
linkedEntity.getDataSource());
linkedEntity.getMatches().forEach(entityMatch -> System.out.printf(
"Matched entity: %s, confidence score: %.2f.%n",
entityMatch.getText(), entityMatch.getConfidenceScore()));
}));
}
/**
* Code snippet for {@link TextAnalyticsClient
*/
public void extractKeyPhrases() {
System.out.println("Extracted phrases:");
for (String keyPhrase : textAnalyticsClient.extractKeyPhrases("My cat might need to see a veterinarian.")) {
System.out.printf("%s.%n", keyPhrase);
}
}
/**
* Code snippet for {@link TextAnalyticsClient
*/
public void extractKeyPhrasesWithLanguage() {
System.out.println("Extracted phrases:");
textAnalyticsClient.extractKeyPhrases("My cat might need to see a veterinarian.", "en")
.forEach(kegPhrase -> System.out.printf("%s.%n", kegPhrase));
}
/**
* Code snippet for {@link TextAnalyticsClient
*/
public void extractKeyPhrasesStringListWithOptions() {
List<String> documents = Arrays.asList(
"My cat might need to see a veterinarian.",
"The pitot tube is used to measure airspeed."
);
ExtractKeyPhrasesResultCollection resultCollection =
textAnalyticsClient.extractKeyPhrasesBatch(documents, "en", null);
TextDocumentBatchStatistics batchStatistics = resultCollection.getStatistics();
System.out.printf(
"A batch of documents statistics, transaction count: %s, valid document count: %s.%n",
batchStatistics.getTransactionCount(), batchStatistics.getValidDocumentCount());
resultCollection.forEach(extractKeyPhraseResult -> {
System.out.printf("Document ID: %s%n", extractKeyPhraseResult.getId());
System.out.println("Extracted phrases:");
extractKeyPhraseResult.getKeyPhrases().forEach(keyPhrase -> System.out.printf("%s.%n", keyPhrase));
});
}
/**
* Code snippet for {@link TextAnalyticsClient
*/
public void extractBatchKeyPhrasesMaxOverload() {
List<TextDocumentInput> textDocumentInputs = Arrays.asList(
new TextDocumentInput("1", "My cat might need to see a veterinarian.").setLanguage("en"),
new TextDocumentInput("2", "The pitot tube is used to measure airspeed.").setLanguage("en")
);
Response<ExtractKeyPhrasesResultCollection> response =
textAnalyticsClient.extractKeyPhrasesBatchWithResponse(textDocumentInputs,
new TextAnalyticsRequestOptions().setIncludeStatistics(true), Context.NONE);
System.out.printf("Status code of request response: %d%n", response.getStatusCode());
ExtractKeyPhrasesResultCollection resultCollection = response.getValue();
TextDocumentBatchStatistics batchStatistics = resultCollection.getStatistics();
System.out.printf(
"A batch of documents statistics, transaction count: %s, valid document count: %s.%n",
batchStatistics.getTransactionCount(), batchStatistics.getValidDocumentCount());
resultCollection.forEach(extractKeyPhraseResult -> {
System.out.printf("Document ID: %s%n", extractKeyPhraseResult.getId());
System.out.println("Extracted phrases:");
extractKeyPhraseResult.getKeyPhrases().forEach(keyPhrase ->
System.out.printf("%s.%n", keyPhrase));
});
}
/**
* Code snippet for {@link TextAnalyticsClient
*/
public void analyzeSentiment() {
final DocumentSentiment documentSentiment =
textAnalyticsClient.analyzeSentiment("The hotel was dark and unclean.");
System.out.printf(
"Recognized sentiment: %s, positive score: %.2f, neutral score: %.2f, negative score: %.2f.%n",
documentSentiment.getSentiment(),
documentSentiment.getConfidenceScores().getPositive(),
documentSentiment.getConfidenceScores().getNeutral(),
documentSentiment.getConfidenceScores().getNegative());
for (SentenceSentiment sentenceSentiment : documentSentiment.getSentences()) {
System.out.printf(
"Recognized sentence sentiment: %s, positive score: %.2f, neutral score: %.2f, negative score: %.2f.%n",
sentenceSentiment.getSentiment(),
sentenceSentiment.getConfidenceScores().getPositive(),
sentenceSentiment.getConfidenceScores().getNeutral(),
sentenceSentiment.getConfidenceScores().getNegative());
}
}
/**
* Code snippet for {@link TextAnalyticsClient
*/
public void analyzeSentimentWithLanguage() {
final DocumentSentiment documentSentiment = textAnalyticsClient.analyzeSentiment(
"The hotel was dark and unclean.", "en");
System.out.printf(
"Recognized sentiment: %s, positive score: %.2f, neutral score: %.2f, negative score: %.2f.%n",
documentSentiment.getSentiment(),
documentSentiment.getConfidenceScores().getPositive(),
documentSentiment.getConfidenceScores().getNeutral(),
documentSentiment.getConfidenceScores().getNegative());
for (SentenceSentiment sentenceSentiment : documentSentiment.getSentences()) {
System.out.printf(
"Recognized sentence sentiment: %s, positive score: %.2f, neutral score: %.2f, negative score: %.2f.%n",
sentenceSentiment.getSentiment(),
sentenceSentiment.getConfidenceScores().getPositive(),
sentenceSentiment.getConfidenceScores().getNeutral(),
sentenceSentiment.getConfidenceScores().getNegative());
}
}
/**
* Code snippet for {@link TextAnalyticsClient
*/
public void analyzeSentimentWithLanguageWithOpinionMining() {
final DocumentSentiment documentSentiment = textAnalyticsClient.analyzeSentiment(
"The hotel was dark and unclean.", "en",
new AnalyzeSentimentOptions().setIncludeOpinionMining(true));
for (SentenceSentiment sentenceSentiment : documentSentiment.getSentences()) {
System.out.printf("\tSentence sentiment: %s%n", sentenceSentiment.getSentiment());
sentenceSentiment.getMinedOpinions().forEach(minedOpinions -> {
AspectSentiment aspectSentiment = minedOpinions.getAspect();
System.out.printf("\tAspect sentiment: %s, aspect text: %s%n", aspectSentiment.getSentiment(),
aspectSentiment.getText());
for (OpinionSentiment opinionSentiment : minedOpinions.getOpinions()) {
System.out.printf("\t\t'%s' sentiment because of \"%s\". Is the opinion negated: %s.%n",
opinionSentiment.getSentiment(), opinionSentiment.getText(), opinionSentiment.isNegated());
}
});
}
}
/**
* Code snippet for {@link TextAnalyticsClient
*/
public void analyzeSentimentStringListWithOptions() {
List<String> documents = Arrays.asList(
"The hotel was dark and unclean. The restaurant had amazing gnocchi.",
"The restaurant had amazing gnocchi. The hotel was dark and unclean."
);
AnalyzeSentimentResultCollection resultCollection = textAnalyticsClient.analyzeSentimentBatch(
documents, "en", new TextAnalyticsRequestOptions().setIncludeStatistics(true));
TextDocumentBatchStatistics batchStatistics = resultCollection.getStatistics();
System.out.printf("A batch of documents statistics, transaction count: %s, valid document count: %s.%n",
batchStatistics.getTransactionCount(), batchStatistics.getValidDocumentCount());
resultCollection.forEach(analyzeSentimentResult -> {
System.out.printf("Document ID: %s%n", analyzeSentimentResult.getId());
DocumentSentiment documentSentiment = analyzeSentimentResult.getDocumentSentiment();
System.out.printf(
"Recognized document sentiment: %s, positive score: %.2f, neutral score: %.2f,"
+ " negative score: %.2f.%n",
documentSentiment.getSentiment(),
documentSentiment.getConfidenceScores().getPositive(),
documentSentiment.getConfidenceScores().getNeutral(),
documentSentiment.getConfidenceScores().getNegative());
documentSentiment.getSentences().forEach(sentenceSentiment -> System.out.printf(
"Recognized sentence sentiment: %s, positive score: %.2f, neutral score: %.2f,"
+ " negative score: %.2f.%n",
sentenceSentiment.getSentiment(),
sentenceSentiment.getConfidenceScores().getPositive(),
sentenceSentiment.getConfidenceScores().getNeutral(),
sentenceSentiment.getConfidenceScores().getNegative()));
});
}
/**
* Code snippet for {@link TextAnalyticsClient
*/
public void analyzeSentimentStringListWithOptionsAndOpinionMining() {
List<String> documents = Arrays.asList(
"The hotel was dark and unclean. The restaurant had amazing gnocchi.",
"The restaurant had amazing gnocchi. The hotel was dark and unclean."
);
AnalyzeSentimentResultCollection resultCollection = textAnalyticsClient.analyzeSentimentBatch(
documents, "en", new AnalyzeSentimentOptions().setIncludeOpinionMining(true));
resultCollection.forEach(analyzeSentimentResult -> {
System.out.printf("Document ID: %s%n", analyzeSentimentResult.getId());
DocumentSentiment documentSentiment = analyzeSentimentResult.getDocumentSentiment();
documentSentiment.getSentences().forEach(sentenceSentiment -> {
System.out.printf("\tSentence sentiment: %s%n", sentenceSentiment.getSentiment());
sentenceSentiment.getMinedOpinions().forEach(minedOpinions -> {
AspectSentiment aspectSentiment = minedOpinions.getAspect();
System.out.printf("\tAspect sentiment: %s, aspect text: %s%n", aspectSentiment.getSentiment(),
aspectSentiment.getText());
for (OpinionSentiment opinionSentiment : minedOpinions.getOpinions()) {
System.out.printf("\t\t'%s' sentiment because of \"%s\". Is the opinion negated: %s.%n",
opinionSentiment.getSentiment(), opinionSentiment.getText(), opinionSentiment.isNegated());
}
});
});
});
}
/**
* Code snippet for {@link TextAnalyticsClient
*/
public void analyzeBatchSentimentMaxOverload() {
List<TextDocumentInput> textDocumentInputs = Arrays.asList(
new TextDocumentInput("1", "The hotel was dark and unclean. The restaurant had amazing gnocchi.")
.setLanguage("en"),
new TextDocumentInput("2", "The restaurant had amazing gnocchi. The hotel was dark and unclean.")
.setLanguage("en")
);
Response<AnalyzeSentimentResultCollection> response =
textAnalyticsClient.analyzeSentimentBatchWithResponse(textDocumentInputs,
new TextAnalyticsRequestOptions().setIncludeStatistics(true), Context.NONE);
System.out.printf("Status code of request response: %d%n", response.getStatusCode());
AnalyzeSentimentResultCollection resultCollection = response.getValue();
TextDocumentBatchStatistics batchStatistics = resultCollection.getStatistics();
System.out.printf("A batch of documents statistics, transaction count: %s, valid document count: %s.%n",
batchStatistics.getTransactionCount(), batchStatistics.getValidDocumentCount());
resultCollection.forEach(analyzeSentimentResult -> {
System.out.printf("Document ID: %s%n", analyzeSentimentResult.getId());
DocumentSentiment documentSentiment = analyzeSentimentResult.getDocumentSentiment();
System.out.printf(
"Recognized document sentiment: %s, positive score: %.2f, neutral score: %.2f, "
+ "negative score: %.2f.%n",
documentSentiment.getSentiment(),
documentSentiment.getConfidenceScores().getPositive(),
documentSentiment.getConfidenceScores().getNeutral(),
documentSentiment.getConfidenceScores().getNegative());
documentSentiment.getSentences().forEach(sentenceSentiment -> {
System.out.printf(
"Recognized sentence sentiment: %s, positive score: %.2f, neutral score: %.2f,"
+ " negative score: %.2f.%n",
sentenceSentiment.getSentiment(),
sentenceSentiment.getConfidenceScores().getPositive(),
sentenceSentiment.getConfidenceScores().getNeutral(),
sentenceSentiment.getConfidenceScores().getNegative());
});
});
}
/**
* Code snippet for {@link TextAnalyticsClient
*/
public void analyzeBatchSentimentMaxOverloadWithOpinionMining() {
List<TextDocumentInput> textDocumentInputs = Arrays.asList(
new TextDocumentInput("1", "The hotel was dark and unclean. The restaurant had amazing gnocchi.")
.setLanguage("en"),
new TextDocumentInput("2", "The restaurant had amazing gnocchi. The hotel was dark and unclean.")
.setLanguage("en")
);
AnalyzeSentimentOptions options = new AnalyzeSentimentOptions().setIncludeOpinionMining(true)
.setIncludeStatistics(true);
Response<AnalyzeSentimentResultCollection> response =
textAnalyticsClient.analyzeSentimentBatchWithResponse(textDocumentInputs, options, Context.NONE);
System.out.printf("Status code of request response: %d%n", response.getStatusCode());
AnalyzeSentimentResultCollection resultCollection = response.getValue();
TextDocumentBatchStatistics batchStatistics = resultCollection.getStatistics();
System.out.printf("A batch of documents statistics, transaction count: %s, valid document count: %s.%n",
batchStatistics.getTransactionCount(), batchStatistics.getValidDocumentCount());
resultCollection.forEach(analyzeSentimentResult -> {
System.out.printf("Document ID: %s%n", analyzeSentimentResult.getId());
DocumentSentiment documentSentiment = analyzeSentimentResult.getDocumentSentiment();
documentSentiment.getSentences().forEach(sentenceSentiment -> {
System.out.printf("\tSentence sentiment: %s%n", sentenceSentiment.getSentiment());
sentenceSentiment.getMinedOpinions().forEach(minedOpinions -> {
AspectSentiment aspectSentiment = minedOpinions.getAspect();
System.out.printf("\tAspect sentiment: %s, aspect text: %s%n", aspectSentiment.getSentiment(),
aspectSentiment.getText());
for (OpinionSentiment opinionSentiment : minedOpinions.getOpinions()) {
System.out.printf("\t\t'%s' sentiment because of \"%s\". Is the opinion negated: %s.%n",
opinionSentiment.getSentiment(), opinionSentiment.getText(), opinionSentiment.isNegated());
}
});
});
});
}
} | |
This runnable is executed when the flux completes successfully. | public static void deleteTwins() throws IOException, InterruptedException {
System.out.println("DELETE DIGITAL TWINS");
Map<String, String> twins = FileHelper.loadAllFilesInPath(TwinsPath);
final Semaphore deleteTwinsSemaphore = new Semaphore(0);
final Semaphore deleteRelationshipsSemaphore = new Semaphore(0);
twins
.forEach((twinId, twinContent) -> {
client.listRelationships(twinId, BasicRelationship.class)
.doOnComplete(deleteRelationshipsSemaphore::release)
.doOnError(throwable -> {
if (throwable instanceof ErrorResponseException && ((ErrorResponseException) throwable).getResponse().getStatusCode() == HttpStatus.SC_NOT_FOUND) {
deleteRelationshipsSemaphore.release();
} else {
System.err.println("List relationships error: " + throwable);
}
})
.subscribe(
relationship -> client.deleteRelationship(twinId, relationship.getId())
.subscribe(
aVoid -> System.out.println("Found and deleted relationship: " + relationship.getId()),
throwable -> System.err.println("Delete relationship error: " + throwable)
));
client.listIncomingRelationships(twinId)
.doOnComplete(deleteRelationshipsSemaphore::release)
.doOnError(throwable -> {
if (throwable instanceof ErrorResponseException && ((ErrorResponseException) throwable).getResponse().getStatusCode() == HttpStatus.SC_NOT_FOUND) {
deleteRelationshipsSemaphore.release();
} else {
System.err.println("List relationships error: " + throwable);
}
})
.subscribe(
incomingRelationship -> client.deleteRelationship(incomingRelationship.getSourceId(), incomingRelationship.getRelationshipId())
.subscribe(
aVoid -> System.out.println("Found and deleted incoming relationship: " + incomingRelationship.getRelationshipId()),
throwable -> System.err.println("Delete relationship error: " + throwable)
));
try {
if (deleteRelationshipsSemaphore.tryAcquire(2, MaxWaitTimeAsyncOperationsInSeconds, TimeUnit.SECONDS)) {
client.deleteDigitalTwin(twinId)
.doOnSuccess(aVoid -> {
System.out.println("Deleted digital twin: " + twinId);
deleteTwinsSemaphore.release();
})
.doOnError(throwable -> {
if (throwable instanceof ErrorResponseException && ((ErrorResponseException) throwable).getResponse().getStatusCode() == HttpStatus.SC_NOT_FOUND) {
deleteTwinsSemaphore.release();
} else {
System.err.println("Could not delete digital twin " + twinId + " due to " + throwable);
}
})
.subscribe();
}
} catch (InterruptedException e) {
throw new RuntimeException("Could not cleanup the pre-existing resources: ", e);
}
});
boolean created = deleteTwinsSemaphore.tryAcquire(twins.size(), MaxWaitTimeAsyncOperationsInSeconds, TimeUnit.SECONDS);
System.out.println("Twins deleted: " + created);
} | .doOnComplete(deleteRelationshipsSemaphore::release) | public static void deleteTwins() throws IOException, InterruptedException {
System.out.println("DELETE DIGITAL TWINS");
Map<String, String> twins = FileHelper.loadAllFilesInPath(TwinsPath);
final Semaphore deleteTwinsSemaphore = new Semaphore(0);
twins
.forEach((twinId, twinContent) -> client.deleteDigitalTwin(twinId)
.doOnSuccess(aVoid -> System.out.println("Deleted digital twin: " + twinId))
.doOnError(throwable -> {
if (!(throwable instanceof ErrorResponseException) || !((ErrorResponseException) throwable).getValue().getError().getCode().equals("DigitalTwinNotFound")) {
System.err.println("Could not delete digital twin " + twinId + " due to " + throwable);
}
})
.doOnTerminate(deleteTwinsSemaphore::release)
.subscribe());
boolean created = deleteTwinsSemaphore.tryAcquire(twins.size(), MaxWaitTimeAsyncOperationsInSeconds, TimeUnit.SECONDS);
System.out.println("Twins deleted: " + created);
} | class DigitalTwinsLifecycleSample {
private static final String tenantId = System.getenv("TENANT_ID");
private static final String clientId = System.getenv("CLIENT_ID");
private static final String clientSecret = System.getenv("CLIENT_SECRET");
private static final String endpoint = System.getenv("DIGITAL_TWINS_ENDPOINT");
private static final int MaxWaitTimeAsyncOperationsInSeconds = 10;
private static final URL DtdlDirectoryUrl = DigitalTwinsLifecycleSample.class.getClassLoader().getResource("DTDL");
private static final Path DtDlDirectoryPath;
private static final Path TwinsPath;
private static final Path ModelsPath;
private static final Path RelationshipsPath;
private static final DigitalTwinsAsyncClient client;
static {
try {
assert DtdlDirectoryUrl != null;
DtDlDirectoryPath = Paths.get(DtdlDirectoryUrl.toURI());
} catch (URISyntaxException e) {
throw new RuntimeException("Unable to convert the DTDL directory URL to URI", e);
}
TwinsPath = Paths.get(DtDlDirectoryPath.toString(), "DigitalTwins");
ModelsPath = Paths.get(DtDlDirectoryPath.toString(), "Models");
RelationshipsPath = Paths.get(DtDlDirectoryPath.toString(), "Relationships");
client = new DigitalTwinsClientBuilder()
.tokenCredential(
new ClientSecretCredentialBuilder()
.tenantId(tenantId)
.clientId(clientId)
.clientSecret(clientSecret)
.build()
)
.endpoint(endpoint)
.httpLogOptions(
new HttpLogOptions()
.setLogLevel(HttpLogDetailLevel.NONE))
.buildAsyncClient();
}
public static void main(String[] args) throws IOException, InterruptedException {
deleteTwins();
createTwins();
}
public static void createTwins() throws IOException, InterruptedException {
System.out.println("CREATE DIGITAL TWINS");
Map<String, String> twins = FileHelper.loadAllFilesInPath(TwinsPath);
final Semaphore createTwinsSemaphore = new Semaphore(0);
twins
.forEach((twinId, twinContent) -> client.createDigitalTwinWithResponse(twinId, twinContent)
.subscribe(
response -> System.out.println("Created digital twin: " + twinId + "\n\t Body: " + response.getValue()),
throwable -> System.err.println("Could not create digital twin " + twinId + " due to " + throwable),
createTwinsSemaphore::release));
boolean created = createTwinsSemaphore.tryAcquire(twins.size(), MaxWaitTimeAsyncOperationsInSeconds, TimeUnit.SECONDS);
System.out.println("Twins created: " + created);
}
} | class DigitalTwinsLifecycleSample {
private static final String tenantId = System.getenv("TENANT_ID");
private static final String clientId = System.getenv("CLIENT_ID");
private static final String clientSecret = System.getenv("CLIENT_SECRET");
private static final String endpoint = System.getenv("DIGITAL_TWINS_ENDPOINT");
private static final int MaxWaitTimeAsyncOperationsInSeconds = 10;
private static final URL DtdlDirectoryUrl = DigitalTwinsLifecycleSample.class.getClassLoader().getResource("DTDL");
private static final Path DtDlDirectoryPath;
private static final Path TwinsPath;
private static final Path ModelsPath;
private static final Path RelationshipsPath;
private static final DigitalTwinsAsyncClient client;
static {
try {
assert DtdlDirectoryUrl != null;
DtDlDirectoryPath = Paths.get(DtdlDirectoryUrl.toURI());
} catch (URISyntaxException e) {
System.err.println("Unable to convert the DTDL directory URL to URI: " + e);
throw new RuntimeException(e);
}
TwinsPath = Paths.get(DtDlDirectoryPath.toString(), "DigitalTwins");
ModelsPath = Paths.get(DtDlDirectoryPath.toString(), "Models");
RelationshipsPath = Paths.get(DtDlDirectoryPath.toString(), "Relationships");
client = new DigitalTwinsClientBuilder()
.tokenCredential(
new ClientSecretCredentialBuilder()
.tenantId(tenantId)
.clientId(clientId)
.clientSecret(clientSecret)
.build()
)
.endpoint(endpoint)
.httpLogOptions(
new HttpLogOptions()
.setLogLevel(HttpLogDetailLevel.NONE))
.buildAsyncClient();
}
public static void main(String[] args) throws IOException, InterruptedException {
deleteTwins();
createTwins();
}
public static void createTwins() throws IOException, InterruptedException {
System.out.println("CREATE DIGITAL TWINS");
Map<String, String> twins = FileHelper.loadAllFilesInPath(TwinsPath);
final Semaphore createTwinsSemaphore = new Semaphore(0);
twins
.forEach((twinId, twinContent) -> client.createDigitalTwinWithResponse(twinId, twinContent)
.doOnSuccess(response -> System.out.println("Created digital twin: " + twinId + "\n\t Body: " + response.getValue()))
.doOnError(throwable -> System.err.println("Could not create digital twin " + twinId + " due to " + throwable))
.doOnTerminate(createTwinsSemaphore::release)
.subscribe());
boolean created = createTwinsSemaphore.tryAcquire(twins.size(), MaxWaitTimeAsyncOperationsInSeconds, TimeUnit.SECONDS);
System.out.println("Twins created: " + created);
}
} |
I was having intermittent 429 issues with failures when using `Mono.when` with multiple streams against the CosmosDB API. | void serviceListTablesWithTopAsync() {
final String tableName = testResourceNamer.randomName("test", 20);
final String tableName2 = testResourceNamer.randomName("test", 20);
final String tableName3 = testResourceNamer.randomName("test", 20);
ListTablesOptions options = new ListTablesOptions().setTop(2);
serviceClient.createTable(tableName).block(TIMEOUT);
serviceClient.createTable(tableName2).block(TIMEOUT);
serviceClient.createTable(tableName3).block(TIMEOUT);
StepVerifier.create(serviceClient.listTables(options))
.expectNextCount(2)
.thenConsumeWhile(x -> true)
.expectComplete()
.verify();
} | serviceClient.createTable(tableName).block(TIMEOUT); | void serviceListTablesWithTopAsync() {
final String tableName = testResourceNamer.randomName("test", 20);
final String tableName2 = testResourceNamer.randomName("test", 20);
final String tableName3 = testResourceNamer.randomName("test", 20);
ListTablesOptions options = new ListTablesOptions().setTop(2);
serviceClient.createTable(tableName).block(TIMEOUT);
serviceClient.createTable(tableName2).block(TIMEOUT);
serviceClient.createTable(tableName3).block(TIMEOUT);
StepVerifier.create(serviceClient.listTables(options))
.expectNextCount(2)
.thenConsumeWhile(x -> true)
.expectComplete()
.verify();
} | class TableServiceAsyncClientTest extends TestBase {
private static final Duration TIMEOUT = Duration.ofSeconds(100);
private TableServiceAsyncClient serviceClient;
@BeforeAll
static void beforeAll() {
StepVerifier.setDefaultTimeout(TIMEOUT);
}
@AfterAll
static void afterAll() {
StepVerifier.resetDefaultTimeout();
}
@Override
protected void beforeTest() {
final String connectionString = TestUtils.getConnectionString(interceptorManager.isPlaybackMode());
final TableServiceClientBuilder builder = new TableServiceClientBuilder()
.connectionString(connectionString)
.httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS));
if (interceptorManager.isPlaybackMode()) {
builder.httpClient(interceptorManager.getPlaybackClient());
} else {
builder.httpClient(HttpClient.createDefault());
if (!interceptorManager.isLiveMode()) {
builder.addPolicy(interceptorManager.getRecordPolicy());
}
builder.addPolicy(new RetryPolicy(new ExponentialBackoff(6, Duration.ofMillis(1500),
Duration.ofSeconds(100))));
}
serviceClient = builder.buildAsyncClient();
}
@Test
void serviceCreateTableAsync() {
String tableName = testResourceNamer.randomName("test", 20);
StepVerifier.create(serviceClient.createTable(tableName))
.expectComplete()
.verify();
}
@Test
void serviceCreateTableFailsIfExistsAsync() {
String tableName = testResourceNamer.randomName("test", 20);
serviceClient.createTable(tableName).block(TIMEOUT);
StepVerifier.create(serviceClient.createTable(tableName))
.expectErrorMatches(e -> e instanceof TableServiceErrorException
&& ((TableServiceErrorException) e).getResponse().getStatusCode() == 409)
.verify();
}
@Test
void serviceCreateTableWithResponseAsync() {
String tableName = testResourceNamer.randomName("test", 20);
int expectedStatusCode = 204;
StepVerifier.create(serviceClient.createTableWithResponse(tableName))
.assertNext(response -> {
Assertions.assertEquals(expectedStatusCode, response.getStatusCode());
})
.expectComplete()
.verify();
}
@Test
void serviceCreateTableIfNotExistsAsync() {
String tableName = testResourceNamer.randomName("test", 20);
StepVerifier.create(serviceClient.createTableIfNotExists(tableName))
.expectComplete()
.verify();
}
@Test
void serviceCreateTableIfNotExistsSucceedsIfExistsAsync() {
String tableName = testResourceNamer.randomName("test", 20);
serviceClient.createTable(tableName).block(TIMEOUT);
StepVerifier.create(serviceClient.createTableIfNotExists(tableName))
.expectComplete()
.verify();
}
@Test
void serviceCreateTableIfNotExistsWithResponseAsync() {
String tableName = testResourceNamer.randomName("test", 20);
int expectedStatusCode = 204;
StepVerifier.create(serviceClient.createTableIfNotExistsWithResponse(tableName))
.assertNext(response -> {
Assertions.assertEquals(expectedStatusCode, response.getStatusCode());
})
.expectComplete()
.verify();
}
@Test
void serviceCreateTableIfNotExistsWithResponseSucceedsIfExistsAsync() {
String tableName = testResourceNamer.randomName("test", 20);
int expectedStatusCode = 409;
serviceClient.createTable(tableName).block(TIMEOUT);
StepVerifier.create(serviceClient.createTableIfNotExistsWithResponse(tableName))
.assertNext(response -> {
Assertions.assertEquals(expectedStatusCode, response.getStatusCode());
})
.expectComplete()
.verify();
}
@Test
void serviceDeleteTableAsync() {
final String tableName = testResourceNamer.randomName("test", 20);
serviceClient.createTable(tableName).block(TIMEOUT);
StepVerifier.create(serviceClient.deleteTable(tableName))
.expectComplete()
.verify();
}
@Test
void serviceDeleteTableWithResponseAsync() {
String tableName = testResourceNamer.randomName("test", 20);
int expectedStatusCode = 204;
serviceClient.createTable(tableName).block();
StepVerifier.create(serviceClient.deleteTableWithResponse(tableName))
.assertNext(response -> {
Assertions.assertEquals(expectedStatusCode, response.getStatusCode());
})
.expectComplete()
.verify();
}
@Test
@Tag("ListTables")
void serviceListTablesAsync() {
final String tableName = testResourceNamer.randomName("test", 20);
final String tableName2 = testResourceNamer.randomName("test", 20);
serviceClient.createTable(tableName).block(TIMEOUT);
serviceClient.createTable(tableName2).block(TIMEOUT);
StepVerifier.create(serviceClient.listTables())
.expectNextCount(2)
.thenConsumeWhile(x -> true)
.expectComplete()
.verify();
}
@Test
@Tag("ListTables")
void serviceListTablesWithFilterAsync() {
final String tableName = testResourceNamer.randomName("test", 20);
final String tableName2 = testResourceNamer.randomName("test", 20);
ListTablesOptions options = new ListTablesOptions().setFilter("TableName eq '" + tableName + "'");
serviceClient.createTable(tableName).block(TIMEOUT);
serviceClient.createTable(tableName2).block(TIMEOUT);
StepVerifier.create(serviceClient.listTables(options))
.assertNext(table -> {
assertEquals(tableName, table.getName());
})
.expectNextCount(0)
.thenConsumeWhile(x -> true)
.expectComplete()
.verify();
}
@Test
@Tag("ListTables")
} | class TableServiceAsyncClientTest extends TestBase {
private static final Duration TIMEOUT = Duration.ofSeconds(100);
private TableServiceAsyncClient serviceClient;
@BeforeAll
static void beforeAll() {
StepVerifier.setDefaultTimeout(TIMEOUT);
}
@AfterAll
static void afterAll() {
StepVerifier.resetDefaultTimeout();
}
@Override
protected void beforeTest() {
final String connectionString = TestUtils.getConnectionString(interceptorManager.isPlaybackMode());
final TableServiceClientBuilder builder = new TableServiceClientBuilder()
.connectionString(connectionString)
.httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS));
if (interceptorManager.isPlaybackMode()) {
builder.httpClient(interceptorManager.getPlaybackClient());
} else {
builder.httpClient(HttpClient.createDefault());
if (!interceptorManager.isLiveMode()) {
builder.addPolicy(interceptorManager.getRecordPolicy());
}
builder.addPolicy(new RetryPolicy(new ExponentialBackoff(6, Duration.ofMillis(1500),
Duration.ofSeconds(100))));
}
serviceClient = builder.buildAsyncClient();
}
@Test
void serviceCreateTableAsync() {
String tableName = testResourceNamer.randomName("test", 20);
StepVerifier.create(serviceClient.createTable(tableName))
.expectComplete()
.verify();
}
@Test
void serviceCreateTableFailsIfExistsAsync() {
String tableName = testResourceNamer.randomName("test", 20);
serviceClient.createTable(tableName).block(TIMEOUT);
StepVerifier.create(serviceClient.createTable(tableName))
.expectErrorMatches(e -> e instanceof TableServiceErrorException
&& ((TableServiceErrorException) e).getResponse().getStatusCode() == 409)
.verify();
}
@Test
void serviceCreateTableWithResponseAsync() {
String tableName = testResourceNamer.randomName("test", 20);
int expectedStatusCode = 204;
StepVerifier.create(serviceClient.createTableWithResponse(tableName))
.assertNext(response -> {
Assertions.assertEquals(expectedStatusCode, response.getStatusCode());
})
.expectComplete()
.verify();
}
@Test
void serviceCreateTableIfNotExistsAsync() {
String tableName = testResourceNamer.randomName("test", 20);
StepVerifier.create(serviceClient.createTableIfNotExists(tableName))
.expectComplete()
.verify();
}
@Test
void serviceCreateTableIfNotExistsSucceedsIfExistsAsync() {
String tableName = testResourceNamer.randomName("test", 20);
serviceClient.createTable(tableName).block(TIMEOUT);
StepVerifier.create(serviceClient.createTableIfNotExists(tableName))
.expectComplete()
.verify();
}
@Test
void serviceCreateTableIfNotExistsWithResponseAsync() {
String tableName = testResourceNamer.randomName("test", 20);
int expectedStatusCode = 204;
StepVerifier.create(serviceClient.createTableIfNotExistsWithResponse(tableName))
.assertNext(response -> {
Assertions.assertEquals(expectedStatusCode, response.getStatusCode());
})
.expectComplete()
.verify();
}
@Test
void serviceCreateTableIfNotExistsWithResponseSucceedsIfExistsAsync() {
String tableName = testResourceNamer.randomName("test", 20);
int expectedStatusCode = 409;
serviceClient.createTable(tableName).block(TIMEOUT);
StepVerifier.create(serviceClient.createTableIfNotExistsWithResponse(tableName))
.assertNext(response -> {
Assertions.assertEquals(expectedStatusCode, response.getStatusCode());
})
.expectComplete()
.verify();
}
@Test
void serviceDeleteTableAsync() {
final String tableName = testResourceNamer.randomName("test", 20);
serviceClient.createTable(tableName).block(TIMEOUT);
StepVerifier.create(serviceClient.deleteTable(tableName))
.expectComplete()
.verify();
}
@Test
void serviceDeleteTableWithResponseAsync() {
String tableName = testResourceNamer.randomName("test", 20);
int expectedStatusCode = 204;
serviceClient.createTable(tableName).block();
StepVerifier.create(serviceClient.deleteTableWithResponse(tableName))
.assertNext(response -> {
Assertions.assertEquals(expectedStatusCode, response.getStatusCode());
})
.expectComplete()
.verify();
}
@Test
@Tag("ListTables")
void serviceListTablesAsync() {
final String tableName = testResourceNamer.randomName("test", 20);
final String tableName2 = testResourceNamer.randomName("test", 20);
serviceClient.createTable(tableName).block(TIMEOUT);
serviceClient.createTable(tableName2).block(TIMEOUT);
StepVerifier.create(serviceClient.listTables())
.expectNextCount(2)
.thenConsumeWhile(x -> true)
.expectComplete()
.verify();
}
@Test
@Tag("ListTables")
void serviceListTablesWithFilterAsync() {
final String tableName = testResourceNamer.randomName("test", 20);
final String tableName2 = testResourceNamer.randomName("test", 20);
ListTablesOptions options = new ListTablesOptions().setFilter("TableName eq '" + tableName + "'");
serviceClient.createTable(tableName).block(TIMEOUT);
serviceClient.createTable(tableName2).block(TIMEOUT);
StepVerifier.create(serviceClient.listTables(options))
.assertNext(table -> {
assertEquals(tableName, table.getName());
})
.expectNextCount(0)
.thenConsumeWhile(x -> true)
.expectComplete()
.verify();
}
@Test
@Tag("ListTables")
} |
Should we also add this change to the changelog? | Mono<PiiEntityCollection> recognizePiiEntities(String document, String language) {
try {
Objects.requireNonNull(document, "'document' cannot be null.");
return recognizePiiEntitiesBatch(
Collections.singletonList(new TextDocumentInput("0", document).setLanguage(language)), null)
.map(resultCollectionResponse -> {
PiiEntityCollection entityCollection = null;
for (RecognizePiiEntitiesResult entitiesResult : resultCollectionResponse.getValue()) {
if (entitiesResult.isError()) {
throw logger.logExceptionAsError(toTextAnalyticsException(entitiesResult.getError()));
}
entityCollection = new PiiEntityCollection(entitiesResult.getEntities(),
entitiesResult.getEntities().getRedactedText(),
entitiesResult.getEntities().getWarnings());
}
return entityCollection;
});
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
} | throw logger.logExceptionAsError(toTextAnalyticsException(entitiesResult.getError())); | Mono<PiiEntityCollection> recognizePiiEntities(String document, String language) {
try {
Objects.requireNonNull(document, "'document' cannot be null.");
return recognizePiiEntitiesBatch(
Collections.singletonList(new TextDocumentInput("0", document).setLanguage(language)), null)
.map(resultCollectionResponse -> {
PiiEntityCollection entityCollection = null;
for (RecognizePiiEntitiesResult entitiesResult : resultCollectionResponse.getValue()) {
if (entitiesResult.isError()) {
throw logger.logExceptionAsError(toTextAnalyticsException(entitiesResult.getError()));
}
entityCollection = new PiiEntityCollection(entitiesResult.getEntities(),
entitiesResult.getEntities().getRedactedText(),
entitiesResult.getEntities().getWarnings());
}
return entityCollection;
});
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
} | class RecognizePiiEntityAsyncClient {
private final ClientLogger logger = new ClientLogger(RecognizePiiEntityAsyncClient.class);
private final TextAnalyticsClientImpl service;
/**
* Create a {@link RecognizePiiEntityAsyncClient} that sends requests to the Text Analytics services's
* recognize Personally Identifiable Information entity endpoint.
*
* @param service The proxy service used to perform REST calls.
*/
RecognizePiiEntityAsyncClient(TextAnalyticsClientImpl service) {
this.service = service;
}
/**
* Helper function for calling service with max overloaded parameters that returns a {@link Mono}
* which contains {@link PiiEntityCollection}.
*
* @param document A single document.
* @param language The language code.
*
* @return The {@link Mono} of {@link PiiEntityCollection}.
*/
/**
* Helper function for calling service with max overloaded parameters.
*
* @param documents The list of documents to recognize Personally Identifiable Information entities for.
* @param options The {@link TextAnalyticsRequestOptions} request options.
*
* @return A mono {@link Response} that contains {@link RecognizePiiEntitiesResultCollection}.
*/
Mono<Response<RecognizePiiEntitiesResultCollection>> recognizePiiEntitiesBatch(
Iterable<TextDocumentInput> documents, TextAnalyticsRequestOptions options) {
try {
inputDocumentsValidation(documents);
return withContext(context -> getRecognizePiiEntitiesResponse(documents, options, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Helper function for calling service with max overloaded parameters with {@link Context} is given.
*
* @param documents The list of documents to recognize Personally Identifiable Information entities for.
* @param options The {@link TextAnalyticsRequestOptions} request options.
* @param context Additional context that is passed through the Http pipeline during the service call.
*
* @return A mono {@link Response} that contains {@link RecognizePiiEntitiesResultCollection}.
*/
Mono<Response<RecognizePiiEntitiesResultCollection>> recognizePiiEntitiesBatchWithContext(
Iterable<TextDocumentInput> documents, TextAnalyticsRequestOptions options, Context context) {
try {
inputDocumentsValidation(documents);
return getRecognizePiiEntitiesResponse(documents, options, context);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Helper method to convert the service response of {@link EntitiesResult} to {@link Response} which contains
* {@link RecognizePiiEntitiesResultCollection}.
*
* @param response the {@link Response} of {@link EntitiesResult} returned by the service.
*
* @return A {@link Response} that contains {@link RecognizePiiEntitiesResultCollection}.
*/
private Response<RecognizePiiEntitiesResultCollection> toRecognizePiiEntitiesResultCollectionResponse(
final Response<PiiEntitiesResult> response) {
final PiiEntitiesResult piiEntitiesResult = response.getValue();
final List<RecognizePiiEntitiesResult> recognizeEntitiesResults = new ArrayList<>();
piiEntitiesResult.getDocuments().forEach(documentEntities -> {
final List<PiiEntity> piiEntities = documentEntities.getEntities().stream().map(entity ->
new PiiEntity(entity.getText(), EntityCategory.fromString(entity.getCategory()),
entity.getSubcategory(), entity.getConfidenceScore(), entity.getOffset(), entity.getLength()))
.collect(Collectors.toList());
final List<TextAnalyticsWarning> warnings = documentEntities.getWarnings().stream()
.map(warning -> {
final WarningCodeValue warningCodeValue = warning.getCode();
return new TextAnalyticsWarning(
WarningCode.fromString(warningCodeValue == null ? null : warningCodeValue.toString()),
warning.getMessage());
}).collect(Collectors.toList());
recognizeEntitiesResults.add(new RecognizePiiEntitiesResult(
documentEntities.getId(),
documentEntities.getStatistics() == null ? null
: toTextDocumentStatistics(documentEntities.getStatistics()),
null,
new PiiEntityCollection(new IterableStream<>(piiEntities), documentEntities.getRedactedText(),
new IterableStream<>(warnings))
));
});
for (DocumentError documentError : piiEntitiesResult.getErrors()) {
recognizeEntitiesResults.add(new RecognizePiiEntitiesResult(documentError.getId(), null,
toTextAnalyticsError(documentError.getError()), null));
}
return new SimpleResponse<>(response,
new RecognizePiiEntitiesResultCollection(recognizeEntitiesResults, piiEntitiesResult.getModelVersion(),
piiEntitiesResult.getStatistics() == null ? null : toBatchStatistics(piiEntitiesResult.getStatistics())
));
}
/**
* Call the service with REST response, convert to a {@link Mono} of {@link Response} that contains
* {@link RecognizePiiEntitiesResultCollection} from a {@link SimpleResponse} of {@link EntitiesResult}.
*
* @param documents The list of documents to recognize Personally Identifiable Information entities for.
* @param options The {@link TextAnalyticsRequestOptions} request options.
* @param context Additional context that is passed through the Http pipeline during the service call.
*
* @return A mono {@link Response} that contains {@link RecognizePiiEntitiesResultCollection}.
*/
private Mono<Response<RecognizePiiEntitiesResultCollection>> getRecognizePiiEntitiesResponse(
Iterable<TextDocumentInput> documents, TextAnalyticsRequestOptions options, Context context) {
return service.entitiesRecognitionPiiWithResponseAsync(
new MultiLanguageBatchInput().setDocuments(toMultiLanguageInput(documents)),
options == null ? null : options.getModelVersion(),
options == null ? null : options.isIncludeStatistics(),
null,
null,
context.addData(AZ_TRACING_NAMESPACE_KEY, COGNITIVE_TRACING_NAMESPACE_VALUE))
.doOnSubscribe(ignoredValue -> logger.info(
"Start recognizing Personally Identifiable Information entities for a batch of documents."))
.doOnSuccess(response -> logger.info(
"Successfully recognized Personally Identifiable Information entities for a batch of documents."))
.doOnError(error ->
logger.warning("Failed to recognize Personally Identifiable Information entities - {}", error))
.map(this::toRecognizePiiEntitiesResultCollectionResponse)
.onErrorMap(throwable -> mapToHttpResponseExceptionIfExist(throwable));
}
} | class RecognizePiiEntityAsyncClient {
private final ClientLogger logger = new ClientLogger(RecognizePiiEntityAsyncClient.class);
private final TextAnalyticsClientImpl service;
/**
* Create a {@link RecognizePiiEntityAsyncClient} that sends requests to the Text Analytics services's
* recognize Personally Identifiable Information entity endpoint.
*
* @param service The proxy service used to perform REST calls.
*/
RecognizePiiEntityAsyncClient(TextAnalyticsClientImpl service) {
this.service = service;
}
/**
* Helper function for calling service with max overloaded parameters that returns a {@link Mono}
* which contains {@link PiiEntityCollection}.
*
* @param document A single document.
* @param language The language code.
*
* @return The {@link Mono} of {@link PiiEntityCollection}.
*/
/**
* Helper function for calling service with max overloaded parameters.
*
* @param documents The list of documents to recognize Personally Identifiable Information entities for.
* @param options The {@link TextAnalyticsRequestOptions} request options.
*
* @return A mono {@link Response} that contains {@link RecognizePiiEntitiesResultCollection}.
*/
Mono<Response<RecognizePiiEntitiesResultCollection>> recognizePiiEntitiesBatch(
Iterable<TextDocumentInput> documents, TextAnalyticsRequestOptions options) {
try {
inputDocumentsValidation(documents);
return withContext(context -> getRecognizePiiEntitiesResponse(documents, options, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Helper function for calling service with max overloaded parameters with {@link Context} is given.
*
* @param documents The list of documents to recognize Personally Identifiable Information entities for.
* @param options The {@link TextAnalyticsRequestOptions} request options.
* @param context Additional context that is passed through the Http pipeline during the service call.
*
* @return A mono {@link Response} that contains {@link RecognizePiiEntitiesResultCollection}.
*/
Mono<Response<RecognizePiiEntitiesResultCollection>> recognizePiiEntitiesBatchWithContext(
Iterable<TextDocumentInput> documents, TextAnalyticsRequestOptions options, Context context) {
try {
inputDocumentsValidation(documents);
return getRecognizePiiEntitiesResponse(documents, options, context);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Helper method to convert the service response of {@link EntitiesResult} to {@link Response} which contains
* {@link RecognizePiiEntitiesResultCollection}.
*
* @param response the {@link Response} of {@link EntitiesResult} returned by the service.
*
* @return A {@link Response} that contains {@link RecognizePiiEntitiesResultCollection}.
*/
private Response<RecognizePiiEntitiesResultCollection> toRecognizePiiEntitiesResultCollectionResponse(
final Response<PiiEntitiesResult> response) {
final PiiEntitiesResult piiEntitiesResult = response.getValue();
final List<RecognizePiiEntitiesResult> recognizeEntitiesResults = new ArrayList<>();
piiEntitiesResult.getDocuments().forEach(documentEntities -> {
final List<PiiEntity> piiEntities = documentEntities.getEntities().stream().map(entity ->
new PiiEntity(entity.getText(), EntityCategory.fromString(entity.getCategory()),
entity.getSubcategory(), entity.getConfidenceScore(), entity.getOffset(), entity.getLength()))
.collect(Collectors.toList());
final List<TextAnalyticsWarning> warnings = documentEntities.getWarnings().stream()
.map(warning -> {
final WarningCodeValue warningCodeValue = warning.getCode();
return new TextAnalyticsWarning(
WarningCode.fromString(warningCodeValue == null ? null : warningCodeValue.toString()),
warning.getMessage());
}).collect(Collectors.toList());
recognizeEntitiesResults.add(new RecognizePiiEntitiesResult(
documentEntities.getId(),
documentEntities.getStatistics() == null ? null
: toTextDocumentStatistics(documentEntities.getStatistics()),
null,
new PiiEntityCollection(new IterableStream<>(piiEntities), documentEntities.getRedactedText(),
new IterableStream<>(warnings))
));
});
for (DocumentError documentError : piiEntitiesResult.getErrors()) {
recognizeEntitiesResults.add(new RecognizePiiEntitiesResult(documentError.getId(), null,
toTextAnalyticsError(documentError.getError()), null));
}
return new SimpleResponse<>(response,
new RecognizePiiEntitiesResultCollection(recognizeEntitiesResults, piiEntitiesResult.getModelVersion(),
piiEntitiesResult.getStatistics() == null ? null : toBatchStatistics(piiEntitiesResult.getStatistics())
));
}
/**
* Call the service with REST response, convert to a {@link Mono} of {@link Response} that contains
* {@link RecognizePiiEntitiesResultCollection} from a {@link SimpleResponse} of {@link EntitiesResult}.
*
* @param documents The list of documents to recognize Personally Identifiable Information entities for.
* @param options The {@link TextAnalyticsRequestOptions} request options.
* @param context Additional context that is passed through the Http pipeline during the service call.
*
* @return A mono {@link Response} that contains {@link RecognizePiiEntitiesResultCollection}.
*/
private Mono<Response<RecognizePiiEntitiesResultCollection>> getRecognizePiiEntitiesResponse(
Iterable<TextDocumentInput> documents, TextAnalyticsRequestOptions options, Context context) {
return service.entitiesRecognitionPiiWithResponseAsync(
new MultiLanguageBatchInput().setDocuments(toMultiLanguageInput(documents)),
options == null ? null : options.getModelVersion(),
options == null ? null : options.isIncludeStatistics(),
null,
null,
context.addData(AZ_TRACING_NAMESPACE_KEY, COGNITIVE_TRACING_NAMESPACE_VALUE))
.doOnSubscribe(ignoredValue -> logger.info(
"Start recognizing Personally Identifiable Information entities for a batch of documents."))
.doOnSuccess(response -> logger.info(
"Successfully recognized Personally Identifiable Information entities for a batch of documents."))
.doOnError(error ->
logger.warning("Failed to recognize Personally Identifiable Information entities - {}", error))
.map(this::toRecognizePiiEntitiesResultCollectionResponse)
.onErrorMap(throwable -> mapToHttpResponseExceptionIfExist(throwable));
}
} |
? what changes? | Mono<PiiEntityCollection> recognizePiiEntities(String document, String language) {
try {
Objects.requireNonNull(document, "'document' cannot be null.");
return recognizePiiEntitiesBatch(
Collections.singletonList(new TextDocumentInput("0", document).setLanguage(language)), null)
.map(resultCollectionResponse -> {
PiiEntityCollection entityCollection = null;
for (RecognizePiiEntitiesResult entitiesResult : resultCollectionResponse.getValue()) {
if (entitiesResult.isError()) {
throw logger.logExceptionAsError(toTextAnalyticsException(entitiesResult.getError()));
}
entityCollection = new PiiEntityCollection(entitiesResult.getEntities(),
entitiesResult.getEntities().getRedactedText(),
entitiesResult.getEntities().getWarnings());
}
return entityCollection;
});
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
} | throw logger.logExceptionAsError(toTextAnalyticsException(entitiesResult.getError())); | Mono<PiiEntityCollection> recognizePiiEntities(String document, String language) {
try {
Objects.requireNonNull(document, "'document' cannot be null.");
return recognizePiiEntitiesBatch(
Collections.singletonList(new TextDocumentInput("0", document).setLanguage(language)), null)
.map(resultCollectionResponse -> {
PiiEntityCollection entityCollection = null;
for (RecognizePiiEntitiesResult entitiesResult : resultCollectionResponse.getValue()) {
if (entitiesResult.isError()) {
throw logger.logExceptionAsError(toTextAnalyticsException(entitiesResult.getError()));
}
entityCollection = new PiiEntityCollection(entitiesResult.getEntities(),
entitiesResult.getEntities().getRedactedText(),
entitiesResult.getEntities().getWarnings());
}
return entityCollection;
});
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
} | class RecognizePiiEntityAsyncClient {
private final ClientLogger logger = new ClientLogger(RecognizePiiEntityAsyncClient.class);
private final TextAnalyticsClientImpl service;
/**
* Create a {@link RecognizePiiEntityAsyncClient} that sends requests to the Text Analytics services's
* recognize Personally Identifiable Information entity endpoint.
*
* @param service The proxy service used to perform REST calls.
*/
RecognizePiiEntityAsyncClient(TextAnalyticsClientImpl service) {
this.service = service;
}
/**
* Helper function for calling service with max overloaded parameters that returns a {@link Mono}
* which contains {@link PiiEntityCollection}.
*
* @param document A single document.
* @param language The language code.
*
* @return The {@link Mono} of {@link PiiEntityCollection}.
*/
/**
* Helper function for calling service with max overloaded parameters.
*
* @param documents The list of documents to recognize Personally Identifiable Information entities for.
* @param options The {@link TextAnalyticsRequestOptions} request options.
*
* @return A mono {@link Response} that contains {@link RecognizePiiEntitiesResultCollection}.
*/
Mono<Response<RecognizePiiEntitiesResultCollection>> recognizePiiEntitiesBatch(
Iterable<TextDocumentInput> documents, TextAnalyticsRequestOptions options) {
try {
inputDocumentsValidation(documents);
return withContext(context -> getRecognizePiiEntitiesResponse(documents, options, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Helper function for calling service with max overloaded parameters with {@link Context} is given.
*
* @param documents The list of documents to recognize Personally Identifiable Information entities for.
* @param options The {@link TextAnalyticsRequestOptions} request options.
* @param context Additional context that is passed through the Http pipeline during the service call.
*
* @return A mono {@link Response} that contains {@link RecognizePiiEntitiesResultCollection}.
*/
Mono<Response<RecognizePiiEntitiesResultCollection>> recognizePiiEntitiesBatchWithContext(
Iterable<TextDocumentInput> documents, TextAnalyticsRequestOptions options, Context context) {
try {
inputDocumentsValidation(documents);
return getRecognizePiiEntitiesResponse(documents, options, context);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Helper method to convert the service response of {@link EntitiesResult} to {@link Response} which contains
* {@link RecognizePiiEntitiesResultCollection}.
*
* @param response the {@link Response} of {@link EntitiesResult} returned by the service.
*
* @return A {@link Response} that contains {@link RecognizePiiEntitiesResultCollection}.
*/
private Response<RecognizePiiEntitiesResultCollection> toRecognizePiiEntitiesResultCollectionResponse(
final Response<PiiEntitiesResult> response) {
final PiiEntitiesResult piiEntitiesResult = response.getValue();
final List<RecognizePiiEntitiesResult> recognizeEntitiesResults = new ArrayList<>();
piiEntitiesResult.getDocuments().forEach(documentEntities -> {
final List<PiiEntity> piiEntities = documentEntities.getEntities().stream().map(entity ->
new PiiEntity(entity.getText(), EntityCategory.fromString(entity.getCategory()),
entity.getSubcategory(), entity.getConfidenceScore(), entity.getOffset(), entity.getLength()))
.collect(Collectors.toList());
final List<TextAnalyticsWarning> warnings = documentEntities.getWarnings().stream()
.map(warning -> {
final WarningCodeValue warningCodeValue = warning.getCode();
return new TextAnalyticsWarning(
WarningCode.fromString(warningCodeValue == null ? null : warningCodeValue.toString()),
warning.getMessage());
}).collect(Collectors.toList());
recognizeEntitiesResults.add(new RecognizePiiEntitiesResult(
documentEntities.getId(),
documentEntities.getStatistics() == null ? null
: toTextDocumentStatistics(documentEntities.getStatistics()),
null,
new PiiEntityCollection(new IterableStream<>(piiEntities), documentEntities.getRedactedText(),
new IterableStream<>(warnings))
));
});
for (DocumentError documentError : piiEntitiesResult.getErrors()) {
recognizeEntitiesResults.add(new RecognizePiiEntitiesResult(documentError.getId(), null,
toTextAnalyticsError(documentError.getError()), null));
}
return new SimpleResponse<>(response,
new RecognizePiiEntitiesResultCollection(recognizeEntitiesResults, piiEntitiesResult.getModelVersion(),
piiEntitiesResult.getStatistics() == null ? null : toBatchStatistics(piiEntitiesResult.getStatistics())
));
}
/**
* Call the service with REST response, convert to a {@link Mono} of {@link Response} that contains
* {@link RecognizePiiEntitiesResultCollection} from a {@link SimpleResponse} of {@link EntitiesResult}.
*
* @param documents The list of documents to recognize Personally Identifiable Information entities for.
* @param options The {@link TextAnalyticsRequestOptions} request options.
* @param context Additional context that is passed through the Http pipeline during the service call.
*
* @return A mono {@link Response} that contains {@link RecognizePiiEntitiesResultCollection}.
*/
private Mono<Response<RecognizePiiEntitiesResultCollection>> getRecognizePiiEntitiesResponse(
Iterable<TextDocumentInput> documents, TextAnalyticsRequestOptions options, Context context) {
return service.entitiesRecognitionPiiWithResponseAsync(
new MultiLanguageBatchInput().setDocuments(toMultiLanguageInput(documents)),
options == null ? null : options.getModelVersion(),
options == null ? null : options.isIncludeStatistics(),
null,
null,
context.addData(AZ_TRACING_NAMESPACE_KEY, COGNITIVE_TRACING_NAMESPACE_VALUE))
.doOnSubscribe(ignoredValue -> logger.info(
"Start recognizing Personally Identifiable Information entities for a batch of documents."))
.doOnSuccess(response -> logger.info(
"Successfully recognized Personally Identifiable Information entities for a batch of documents."))
.doOnError(error ->
logger.warning("Failed to recognize Personally Identifiable Information entities - {}", error))
.map(this::toRecognizePiiEntitiesResultCollectionResponse)
.onErrorMap(throwable -> mapToHttpResponseExceptionIfExist(throwable));
}
} | class RecognizePiiEntityAsyncClient {
private final ClientLogger logger = new ClientLogger(RecognizePiiEntityAsyncClient.class);
private final TextAnalyticsClientImpl service;
/**
* Create a {@link RecognizePiiEntityAsyncClient} that sends requests to the Text Analytics services's
* recognize Personally Identifiable Information entity endpoint.
*
* @param service The proxy service used to perform REST calls.
*/
RecognizePiiEntityAsyncClient(TextAnalyticsClientImpl service) {
this.service = service;
}
/**
* Helper function for calling service with max overloaded parameters that returns a {@link Mono}
* which contains {@link PiiEntityCollection}.
*
* @param document A single document.
* @param language The language code.
*
* @return The {@link Mono} of {@link PiiEntityCollection}.
*/
/**
* Helper function for calling service with max overloaded parameters.
*
* @param documents The list of documents to recognize Personally Identifiable Information entities for.
* @param options The {@link TextAnalyticsRequestOptions} request options.
*
* @return A mono {@link Response} that contains {@link RecognizePiiEntitiesResultCollection}.
*/
Mono<Response<RecognizePiiEntitiesResultCollection>> recognizePiiEntitiesBatch(
Iterable<TextDocumentInput> documents, TextAnalyticsRequestOptions options) {
try {
inputDocumentsValidation(documents);
return withContext(context -> getRecognizePiiEntitiesResponse(documents, options, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Helper function for calling service with max overloaded parameters with {@link Context} is given.
*
* @param documents The list of documents to recognize Personally Identifiable Information entities for.
* @param options The {@link TextAnalyticsRequestOptions} request options.
* @param context Additional context that is passed through the Http pipeline during the service call.
*
* @return A mono {@link Response} that contains {@link RecognizePiiEntitiesResultCollection}.
*/
Mono<Response<RecognizePiiEntitiesResultCollection>> recognizePiiEntitiesBatchWithContext(
Iterable<TextDocumentInput> documents, TextAnalyticsRequestOptions options, Context context) {
try {
inputDocumentsValidation(documents);
return getRecognizePiiEntitiesResponse(documents, options, context);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Helper method to convert the service response of {@link EntitiesResult} to {@link Response} which contains
* {@link RecognizePiiEntitiesResultCollection}.
*
* @param response the {@link Response} of {@link EntitiesResult} returned by the service.
*
* @return A {@link Response} that contains {@link RecognizePiiEntitiesResultCollection}.
*/
private Response<RecognizePiiEntitiesResultCollection> toRecognizePiiEntitiesResultCollectionResponse(
final Response<PiiEntitiesResult> response) {
final PiiEntitiesResult piiEntitiesResult = response.getValue();
final List<RecognizePiiEntitiesResult> recognizeEntitiesResults = new ArrayList<>();
piiEntitiesResult.getDocuments().forEach(documentEntities -> {
final List<PiiEntity> piiEntities = documentEntities.getEntities().stream().map(entity ->
new PiiEntity(entity.getText(), EntityCategory.fromString(entity.getCategory()),
entity.getSubcategory(), entity.getConfidenceScore(), entity.getOffset(), entity.getLength()))
.collect(Collectors.toList());
final List<TextAnalyticsWarning> warnings = documentEntities.getWarnings().stream()
.map(warning -> {
final WarningCodeValue warningCodeValue = warning.getCode();
return new TextAnalyticsWarning(
WarningCode.fromString(warningCodeValue == null ? null : warningCodeValue.toString()),
warning.getMessage());
}).collect(Collectors.toList());
recognizeEntitiesResults.add(new RecognizePiiEntitiesResult(
documentEntities.getId(),
documentEntities.getStatistics() == null ? null
: toTextDocumentStatistics(documentEntities.getStatistics()),
null,
new PiiEntityCollection(new IterableStream<>(piiEntities), documentEntities.getRedactedText(),
new IterableStream<>(warnings))
));
});
for (DocumentError documentError : piiEntitiesResult.getErrors()) {
recognizeEntitiesResults.add(new RecognizePiiEntitiesResult(documentError.getId(), null,
toTextAnalyticsError(documentError.getError()), null));
}
return new SimpleResponse<>(response,
new RecognizePiiEntitiesResultCollection(recognizeEntitiesResults, piiEntitiesResult.getModelVersion(),
piiEntitiesResult.getStatistics() == null ? null : toBatchStatistics(piiEntitiesResult.getStatistics())
));
}
/**
* Call the service with REST response, convert to a {@link Mono} of {@link Response} that contains
* {@link RecognizePiiEntitiesResultCollection} from a {@link SimpleResponse} of {@link EntitiesResult}.
*
* @param documents The list of documents to recognize Personally Identifiable Information entities for.
* @param options The {@link TextAnalyticsRequestOptions} request options.
* @param context Additional context that is passed through the Http pipeline during the service call.
*
* @return A mono {@link Response} that contains {@link RecognizePiiEntitiesResultCollection}.
*/
private Mono<Response<RecognizePiiEntitiesResultCollection>> getRecognizePiiEntitiesResponse(
Iterable<TextDocumentInput> documents, TextAnalyticsRequestOptions options, Context context) {
return service.entitiesRecognitionPiiWithResponseAsync(
new MultiLanguageBatchInput().setDocuments(toMultiLanguageInput(documents)),
options == null ? null : options.getModelVersion(),
options == null ? null : options.isIncludeStatistics(),
null,
null,
context.addData(AZ_TRACING_NAMESPACE_KEY, COGNITIVE_TRACING_NAMESPACE_VALUE))
.doOnSubscribe(ignoredValue -> logger.info(
"Start recognizing Personally Identifiable Information entities for a batch of documents."))
.doOnSuccess(response -> logger.info(
"Successfully recognized Personally Identifiable Information entities for a batch of documents."))
.doOnError(error ->
logger.warning("Failed to recognize Personally Identifiable Information entities - {}", error))
.map(this::toRecognizePiiEntitiesResultCollectionResponse)
.onErrorMap(throwable -> mapToHttpResponseExceptionIfExist(throwable));
}
} |
Is this the bingEntitySearchApiId ? If yes, then why is the one on L302 different, or just test data? | static List<LinkedEntity> getLinkedEntitiesList1() {
final LinkedEntityMatch linkedEntityMatch = new LinkedEntityMatch("Seattle", 0.0, 26, 7);
LinkedEntity linkedEntity = new LinkedEntity(
"Seattle", new IterableStream<>(Collections.singletonList(linkedEntityMatch)),
"en", "Seattle", "https:
"Wikipedia", "5fbba6b8-85e1-4d41-9444-d9055436e473");
return asList(linkedEntity);
} | "Wikipedia", "5fbba6b8-85e1-4d41-9444-d9055436e473"); | static List<LinkedEntity> getLinkedEntitiesList1() {
final LinkedEntityMatch linkedEntityMatch = new LinkedEntityMatch("Seattle", 0.0, 26, 7);
LinkedEntity linkedEntity = new LinkedEntity(
"Seattle", new IterableStream<>(Collections.singletonList(linkedEntityMatch)),
"en", "Seattle", "https:
"Wikipedia", "5fbba6b8-85e1-4d41-9444-d9055436e473");
return asList(linkedEntity);
} | class TestUtils {
private static final String DEFAULT_MODEL_VERSION = "2019-10-01";
static final String INVALID_URL = "htttttttps:
static final String VALID_HTTPS_LOCALHOST = "https:
static final String FAKE_API_KEY = "1234567890";
static final String AZURE_TEXT_ANALYTICS_API_KEY = "AZURE_TEXT_ANALYTICS_API_KEY";
static final List<String> SENTIMENT_INPUTS = asList("The hotel was dark and unclean. The restaurant had amazing gnocchi.",
"The restaurant had amazing gnocchi. The hotel was dark and unclean.");
static final List<String> CATEGORIZED_ENTITY_INPUTS = asList(
"I had a wonderful trip to Seattle last week.", "I work at Microsoft.");
static final List<String> PII_ENTITY_INPUTS = asList(
"Microsoft employee with ssn 859-98-0987 is using our awesome API's.",
"Your ABA number - 111000025 - is the first 9 digits in the lower left hand corner of your personal check.");
static final List<String> LINKED_ENTITY_INPUTS = asList(
"I had a wonderful trip to Seattle last week.",
"I work at Microsoft.");
static final List<String> KEY_PHRASE_INPUTS = asList(
"Hello world. This is some input text that I love.",
"Bonjour tout le monde");
static final String TOO_LONG_INPUT = "Thisisaveryveryverylongtextwhichgoesonforalongtimeandwhichalmostdoesn'tseemtostopatanygivenpointintime.ThereasonforthistestistotryandseewhathappenswhenwesubmitaveryveryverylongtexttoLanguage.Thisshouldworkjustfinebutjustincaseitisalwaysgoodtohaveatestcase.ThisallowsustotestwhathappensifitisnotOK.Ofcourseitisgoingtobeokbutthenagainitisalsobettertobesure!";
static final List<String> KEY_PHRASE_FRENCH_INPUTS = asList(
"Bonjour tout le monde.",
"Je m'appelle Mondly.");
static final List<String> DETECT_LANGUAGE_INPUTS = asList(
"This is written in English", "Este es un documento escrito en Español.", "~@!~:)");
static final List<String> SPANISH_SAME_AS_ENGLISH_INPUTS = asList("personal", "social");
static final DetectedLanguage DETECTED_LANGUAGE_SPANISH = new DetectedLanguage("Spanish", "es", 1.0, null);
static final DetectedLanguage DETECTED_LANGUAGE_ENGLISH = new DetectedLanguage("English", "en", 1.0, null);
static final List<DetectedLanguage> DETECT_SPANISH_LANGUAGE_RESULTS = asList(
DETECTED_LANGUAGE_SPANISH, DETECTED_LANGUAGE_SPANISH);
static final List<DetectedLanguage> DETECT_ENGLISH_LANGUAGE_RESULTS = asList(
DETECTED_LANGUAGE_ENGLISH, DETECTED_LANGUAGE_ENGLISH);
static final HttpResponseException HTTP_RESPONSE_EXCEPTION_CLASS = new HttpResponseException("", null);
static final String DISPLAY_NAME_WITH_ARGUMENTS = "{displayName} with [{arguments}]";
private static final String AZURE_TEXT_ANALYTICS_TEST_SERVICE_VERSIONS =
"AZURE_TEXT_ANALYTICS_TEST_SERVICE_VERSIONS";
static List<DetectLanguageInput> getDetectLanguageInputs() {
return asList(
new DetectLanguageInput("0", DETECT_LANGUAGE_INPUTS.get(0), "US"),
new DetectLanguageInput("1", DETECT_LANGUAGE_INPUTS.get(1), "US"),
new DetectLanguageInput("2", DETECT_LANGUAGE_INPUTS.get(2), "US")
);
}
static List<DetectLanguageInput> getDuplicateIdDetectLanguageInputs() {
return asList(
new DetectLanguageInput("0", DETECT_LANGUAGE_INPUTS.get(0), "US"),
new DetectLanguageInput("0", DETECT_LANGUAGE_INPUTS.get(0), "US")
);
}
static List<TextDocumentInput> getDuplicateTextDocumentInputs() {
return asList(
new TextDocumentInput("0", CATEGORIZED_ENTITY_INPUTS.get(0)),
new TextDocumentInput("0", CATEGORIZED_ENTITY_INPUTS.get(0)),
new TextDocumentInput("0", CATEGORIZED_ENTITY_INPUTS.get(0))
);
}
static List<TextDocumentInput> getWarningsTextDocumentInputs() {
return asList(
new TextDocumentInput("0", TOO_LONG_INPUT),
new TextDocumentInput("1", CATEGORIZED_ENTITY_INPUTS.get(1))
);
}
static List<TextDocumentInput> getTextDocumentInputs(List<String> inputs) {
return IntStream.range(0, inputs.size())
.mapToObj(index ->
new TextDocumentInput(String.valueOf(index), inputs.get(index)))
.collect(Collectors.toList());
}
/**
* Helper method to get the expected Batch Detected Languages
*
* @return A {@link DetectLanguageResultCollection}.
*/
static DetectLanguageResultCollection getExpectedBatchDetectedLanguages() {
final TextDocumentBatchStatistics textDocumentBatchStatistics = new TextDocumentBatchStatistics(3, 3, 0, 3);
final List<DetectLanguageResult> detectLanguageResultList = asList(
new DetectLanguageResult("0", new TextDocumentStatistics(26, 1), null, getDetectedLanguageEnglish()),
new DetectLanguageResult("1", new TextDocumentStatistics(40, 1), null, getDetectedLanguageSpanish()),
new DetectLanguageResult("2", new TextDocumentStatistics(6, 1), null, getUnknownDetectedLanguage()));
return new DetectLanguageResultCollection(detectLanguageResultList, DEFAULT_MODEL_VERSION, textDocumentBatchStatistics);
}
static DetectedLanguage getDetectedLanguageEnglish() {
return new DetectedLanguage("English", "en", 0.0, null);
}
static DetectedLanguage getDetectedLanguageSpanish() {
return new DetectedLanguage("Spanish", "es", 0.0, null);
}
static DetectedLanguage getUnknownDetectedLanguage() {
return new DetectedLanguage("(Unknown)", "(Unknown)", 0.0, null);
}
/**
* Helper method to get the expected Batch Categorized Entities
*
* @return A {@link RecognizeEntitiesResultCollection}.
*/
static RecognizeEntitiesResultCollection getExpectedBatchCategorizedEntities() {
return new RecognizeEntitiesResultCollection(
asList(getExpectedBatchCategorizedEntities1(), getExpectedBatchCategorizedEntities2()),
DEFAULT_MODEL_VERSION,
new TextDocumentBatchStatistics(2, 2, 0, 2));
}
/**
* Helper method to get the expected Categorized Entities List 1
*/
static List<CategorizedEntity> getCategorizedEntitiesList1() {
CategorizedEntity categorizedEntity1 = new CategorizedEntity("trip", EntityCategory.EVENT, null, 0.0, 18, 4);
CategorizedEntity categorizedEntity2 = new CategorizedEntity("Seattle", EntityCategory.LOCATION, "GPE", 0.0, 26, 7);
CategorizedEntity categorizedEntity3 = new CategorizedEntity("last week", EntityCategory.DATE_TIME, "DateRange", 0.0, 34, 9);
return asList(categorizedEntity1, categorizedEntity2, categorizedEntity3);
}
/**
* Helper method to get the expected Categorized Entities List 2
*/
static List<CategorizedEntity> getCategorizedEntitiesList2() {
return asList(new CategorizedEntity("Microsoft", EntityCategory.ORGANIZATION, null, 0.0, 10, 9));
}
/**
* Helper method to get the expected Batch Categorized Entities
*/
static RecognizeEntitiesResult getExpectedBatchCategorizedEntities1() {
IterableStream<CategorizedEntity> categorizedEntityList1 = new IterableStream<>(getCategorizedEntitiesList1());
TextDocumentStatistics textDocumentStatistics1 = new TextDocumentStatistics(44, 1);
RecognizeEntitiesResult recognizeEntitiesResult1 = new RecognizeEntitiesResult("0", textDocumentStatistics1, null, new CategorizedEntityCollection(categorizedEntityList1, null));
return recognizeEntitiesResult1;
}
/**
* Helper method to get the expected Batch Categorized Entities
*/
static RecognizeEntitiesResult getExpectedBatchCategorizedEntities2() {
IterableStream<CategorizedEntity> categorizedEntityList2 = new IterableStream<>(getCategorizedEntitiesList2());
TextDocumentStatistics textDocumentStatistics2 = new TextDocumentStatistics(20, 1);
RecognizeEntitiesResult recognizeEntitiesResult2 = new RecognizeEntitiesResult("1", textDocumentStatistics2, null, new CategorizedEntityCollection(categorizedEntityList2, null));
return recognizeEntitiesResult2;
}
/**
* Helper method to get the expected batch of Personally Identifiable Information entities
*/
static RecognizePiiEntitiesResultCollection getExpectedBatchPiiEntities() {
PiiEntityCollection piiEntityCollection = new PiiEntityCollection(new IterableStream<>(getPiiEntitiesList1()), null);
PiiEntityCollection piiEntityCollection2 = new PiiEntityCollection(new IterableStream<>(getPiiEntitiesList2()), null);
TextDocumentStatistics textDocumentStatistics1 = new TextDocumentStatistics(67, 1);
TextDocumentStatistics textDocumentStatistics2 = new TextDocumentStatistics(105, 1);
RecognizePiiEntitiesResult recognizeEntitiesResult1 = new RecognizePiiEntitiesResult("0", textDocumentStatistics1, null, piiEntityCollection);
RecognizePiiEntitiesResult recognizeEntitiesResult2 = new RecognizePiiEntitiesResult("1", textDocumentStatistics2, null, piiEntityCollection2);
return new RecognizePiiEntitiesResultCollection(
asList(recognizeEntitiesResult1, recognizeEntitiesResult2),
DEFAULT_MODEL_VERSION,
new TextDocumentBatchStatistics(2, 2, 0, 2));
}
/**
* Helper method to get the expected Categorized Entities List 1
*/
static List<PiiEntity> getPiiEntitiesList1() {
PiiEntity piiEntity0 = new PiiEntity("Microsoft", EntityCategory.ORGANIZATION, null, 1.0, 0, 9);
PiiEntity piiEntity1 = new PiiEntity("859-98-0987", EntityCategory.fromString("U.S. Social Security Number (SSN)"), null, 0.65, 28, 11);
return asList(piiEntity0, piiEntity1);
}
/**
* Helper method to get the expected Categorized Entities List 2
*/
static List<PiiEntity> getPiiEntitiesList2() {
PiiEntity piiEntity2 = new PiiEntity("111000025", EntityCategory.fromString("Phone Number"), null, 0.8, 18, 9);
PiiEntity piiEntity3 = new PiiEntity("111000025", EntityCategory.fromString("ABA Routing Number"), null, 0.75, 18, 9);
PiiEntity piiEntity4 = new PiiEntity("111000025", EntityCategory.fromString("New Zealand Social Welfare Number"), null, 0.65, 18, 9);
PiiEntity piiEntity5 = new PiiEntity("111000025", EntityCategory.fromString("Portugal Tax Identification Number"), null, 0.65, 18, 9);
return asList(piiEntity2, piiEntity3, piiEntity4, piiEntity5);
}
/**
* Helper method to get the expected Batch Linked Entities
* @return A {@link RecognizeLinkedEntitiesResultCollection}.
*/
static RecognizeLinkedEntitiesResultCollection getExpectedBatchLinkedEntities() {
final TextDocumentBatchStatistics textDocumentBatchStatistics = new TextDocumentBatchStatistics(2, 2, 0, 2);
final List<RecognizeLinkedEntitiesResult> recognizeLinkedEntitiesResultList =
asList(
new RecognizeLinkedEntitiesResult(
"0", new TextDocumentStatistics(44, 1), null,
new LinkedEntityCollection(new IterableStream<>(getLinkedEntitiesList1()), null)),
new RecognizeLinkedEntitiesResult(
"1", new TextDocumentStatistics(20, 1), null,
new LinkedEntityCollection(new IterableStream<>(getLinkedEntitiesList2()), null)));
return new RecognizeLinkedEntitiesResultCollection(recognizeLinkedEntitiesResultList, DEFAULT_MODEL_VERSION, textDocumentBatchStatistics);
}
/**
* Helper method to get the expected linked Entities List 1
*/
/**
* Helper method to get the expected linked Entities List 2
*/
static List<LinkedEntity> getLinkedEntitiesList2() {
LinkedEntityMatch linkedEntityMatch = new LinkedEntityMatch("Microsoft", 0.0, 10, 9);
LinkedEntity linkedEntity = new LinkedEntity(
"Microsoft", new IterableStream<>(Collections.singletonList(linkedEntityMatch)),
"en", "Microsoft", "https:
"Wikipedia", "a093e9b9-90f5-a3d5-c4b8-5855e1b01f85");
return asList(linkedEntity);
}
/**
* Helper method to get the expected Batch Key Phrases.
*/
static ExtractKeyPhrasesResultCollection getExpectedBatchKeyPhrases() {
TextDocumentStatistics textDocumentStatistics1 = new TextDocumentStatistics(49, 1);
TextDocumentStatistics textDocumentStatistics2 = new TextDocumentStatistics(21, 1);
ExtractKeyPhraseResult extractKeyPhraseResult1 = new ExtractKeyPhraseResult("0", textDocumentStatistics1, null, new KeyPhrasesCollection(new IterableStream<>(asList("input text", "world")), null));
ExtractKeyPhraseResult extractKeyPhraseResult2 = new ExtractKeyPhraseResult("1", textDocumentStatistics2, null, new KeyPhrasesCollection(new IterableStream<>(Collections.singletonList("monde")), null));
TextDocumentBatchStatistics textDocumentBatchStatistics = new TextDocumentBatchStatistics(2, 2, 0, 2);
List<ExtractKeyPhraseResult> extractKeyPhraseResultList = asList(extractKeyPhraseResult1, extractKeyPhraseResult2);
return new ExtractKeyPhrasesResultCollection(extractKeyPhraseResultList, DEFAULT_MODEL_VERSION, textDocumentBatchStatistics);
}
/**
* Helper method to get the expected Batch Text Sentiments
*/
static AnalyzeSentimentResultCollection getExpectedBatchTextSentiment() {
final TextDocumentStatistics textDocumentStatistics = new TextDocumentStatistics(67, 1);
final AnalyzeSentimentResult analyzeSentimentResult1 = new AnalyzeSentimentResult("0",
textDocumentStatistics, null, getExpectedDocumentSentiment());
final AnalyzeSentimentResult analyzeSentimentResult2 = new AnalyzeSentimentResult("1",
textDocumentStatistics, null, getExpectedDocumentSentiment2());
return new AnalyzeSentimentResultCollection(
asList(analyzeSentimentResult1, analyzeSentimentResult2),
DEFAULT_MODEL_VERSION, new TextDocumentBatchStatistics(2, 2, 0, 2));
}
/**
* Helper method that get the first expected DocumentSentiment result.
*/
static DocumentSentiment getExpectedDocumentSentiment() {
return new DocumentSentiment(TextSentiment.MIXED,
new SentimentConfidenceScores(0.0, 0.0, 0.0),
new IterableStream<>(asList(
new SentenceSentiment("The hotel was dark and unclean.", TextSentiment.NEGATIVE,
new SentimentConfidenceScores(0.0, 0.0, 0.0),
new IterableStream<>(asList(new MinedOpinion(
new AspectSentiment("hotel", TextSentiment.NEGATIVE, 4, 5, new SentimentConfidenceScores(0.0, 0.0, 0.0)),
new IterableStream<>(asList(
new OpinionSentiment("dark", TextSentiment.NEGATIVE, 14, 4, false, new SentimentConfidenceScores(0.0, 0.0, 0.0)),
new OpinionSentiment("unclean", TextSentiment.NEGATIVE, 23, 7, false, new SentimentConfidenceScores(0.0, 0.0, 0.0))
))))),
0, 31
),
new SentenceSentiment("The restaurant had amazing gnocchi.", TextSentiment.POSITIVE,
new SentimentConfidenceScores(0.0, 0.0, 0.0),
new IterableStream<>(asList(new MinedOpinion(
new AspectSentiment("gnocchi", TextSentiment.POSITIVE, 59, 7, new SentimentConfidenceScores(0.0, 0.0, 0.0)),
new IterableStream<>(asList(
new OpinionSentiment("amazing", TextSentiment.POSITIVE, 51, 7, false, new SentimentConfidenceScores(0.0, 0.0, 0.0))
))))),
32, 35
)
)), null);
}
/**
* Helper method that get the second expected DocumentSentiment result.
*/
static DocumentSentiment getExpectedDocumentSentiment2() {
return new DocumentSentiment(TextSentiment.MIXED,
new SentimentConfidenceScores(0.0, 0.0, 0.0),
new IterableStream<>(asList(
new SentenceSentiment("The restaurant had amazing gnocchi.", TextSentiment.POSITIVE,
new SentimentConfidenceScores(0.0, 0.0, 0.0),
new IterableStream<>(asList(new MinedOpinion(
new AspectSentiment("gnocchi", TextSentiment.POSITIVE, 27, 7, new SentimentConfidenceScores(0.0, 0.0, 0.0)),
new IterableStream<>(asList(
new OpinionSentiment("amazing", TextSentiment.POSITIVE, 19, 7, false, new SentimentConfidenceScores(0.0, 0.0, 0.0))
))))),
0, 35
),
new SentenceSentiment("The hotel was dark and unclean.", TextSentiment.NEGATIVE,
new SentimentConfidenceScores(0.0, 0.0, 0.0), new IterableStream<>(asList(new MinedOpinion(
new AspectSentiment("hotel", TextSentiment.NEGATIVE, 40, 5, new SentimentConfidenceScores(0.0, 0.0, 0.0)),
new IterableStream<>(asList(
new OpinionSentiment("dark", TextSentiment.NEGATIVE, 50, 4, false, new SentimentConfidenceScores(0.0, 0.0, 0.0)),
new OpinionSentiment("unclean", TextSentiment.NEGATIVE, 59, 7, false, new SentimentConfidenceScores(0.0, 0.0, 0.0))
))))),
36, 31
)
)), null);
}
/**
* Returns a stream of arguments that includes all combinations of eligible {@link HttpClient HttpClients} and
* service versions that should be tested.
*
* @return A stream of HttpClient and service version combinations to test.
*/
static Stream<Arguments> getTestParameters() {
List<Arguments> argumentsList = new ArrayList<>();
getHttpClients()
.forEach(httpClient -> {
Arrays.stream(TextAnalyticsServiceVersion.values()).filter(
TestUtils::shouldServiceVersionBeTested)
.forEach(serviceVersion -> argumentsList.add(Arguments.of(httpClient, serviceVersion)));
});
return argumentsList.stream();
}
/**
* Returns whether the given service version match the rules of test framework.
*
* <ul>
* <li>Using latest service version as default if no environment variable is set.</li>
* <li>If it's set to ALL, all Service versions in {@link TextAnalyticsServiceVersion} will be tested.</li>
* <li>Otherwise, Service version string should match env variable.</li>
* </ul>
*
* Environment values currently supported are: "ALL", "${version}".
* Use comma to separate http clients want to test.
* e.g. {@code set AZURE_TEST_SERVICE_VERSIONS = V1_0, V2_0}
*
* @param serviceVersion ServiceVersion needs to check
* @return Boolean indicates whether filters out the service version or not.
*/
private static boolean shouldServiceVersionBeTested(TextAnalyticsServiceVersion serviceVersion) {
String serviceVersionFromEnv =
Configuration.getGlobalConfiguration().get(AZURE_TEXT_ANALYTICS_TEST_SERVICE_VERSIONS);
if (CoreUtils.isNullOrEmpty(serviceVersionFromEnv)) {
return TextAnalyticsServiceVersion.getLatest().equals(serviceVersion);
}
if (AZURE_TEST_SERVICE_VERSIONS_VALUE_ALL.equalsIgnoreCase(serviceVersionFromEnv)) {
return true;
}
String[] configuredServiceVersionList = serviceVersionFromEnv.split(",");
return Arrays.stream(configuredServiceVersionList).anyMatch(configuredServiceVersion ->
serviceVersion.getVersion().equals(configuredServiceVersion.trim()));
}
private TestUtils() {
}
} | class TestUtils {
private static final String DEFAULT_MODEL_VERSION = "2019-10-01";
static final String INVALID_URL = "htttttttps:
static final String VALID_HTTPS_LOCALHOST = "https:
static final String FAKE_API_KEY = "1234567890";
static final String AZURE_TEXT_ANALYTICS_API_KEY = "AZURE_TEXT_ANALYTICS_API_KEY";
static final List<String> SENTIMENT_INPUTS = asList("The hotel was dark and unclean. The restaurant had amazing gnocchi.",
"The restaurant had amazing gnocchi. The hotel was dark and unclean.");
static final List<String> CATEGORIZED_ENTITY_INPUTS = asList(
"I had a wonderful trip to Seattle last week.", "I work at Microsoft.");
static final List<String> PII_ENTITY_INPUTS = asList(
"Microsoft employee with ssn 859-98-0987 is using our awesome API's.",
"Your ABA number - 111000025 - is the first 9 digits in the lower left hand corner of your personal check.");
static final List<String> LINKED_ENTITY_INPUTS = asList(
"I had a wonderful trip to Seattle last week.",
"I work at Microsoft.");
static final List<String> KEY_PHRASE_INPUTS = asList(
"Hello world. This is some input text that I love.",
"Bonjour tout le monde");
static final String TOO_LONG_INPUT = "Thisisaveryveryverylongtextwhichgoesonforalongtimeandwhichalmostdoesn'tseemtostopatanygivenpointintime.ThereasonforthistestistotryandseewhathappenswhenwesubmitaveryveryverylongtexttoLanguage.Thisshouldworkjustfinebutjustincaseitisalwaysgoodtohaveatestcase.ThisallowsustotestwhathappensifitisnotOK.Ofcourseitisgoingtobeokbutthenagainitisalsobettertobesure!";
static final List<String> KEY_PHRASE_FRENCH_INPUTS = asList(
"Bonjour tout le monde.",
"Je m'appelle Mondly.");
static final List<String> DETECT_LANGUAGE_INPUTS = asList(
"This is written in English", "Este es un documento escrito en Español.", "~@!~:)");
static final List<String> SPANISH_SAME_AS_ENGLISH_INPUTS = asList("personal", "social");
static final DetectedLanguage DETECTED_LANGUAGE_SPANISH = new DetectedLanguage("Spanish", "es", 1.0, null);
static final DetectedLanguage DETECTED_LANGUAGE_ENGLISH = new DetectedLanguage("English", "en", 1.0, null);
static final List<DetectedLanguage> DETECT_SPANISH_LANGUAGE_RESULTS = asList(
DETECTED_LANGUAGE_SPANISH, DETECTED_LANGUAGE_SPANISH);
static final List<DetectedLanguage> DETECT_ENGLISH_LANGUAGE_RESULTS = asList(
DETECTED_LANGUAGE_ENGLISH, DETECTED_LANGUAGE_ENGLISH);
static final HttpResponseException HTTP_RESPONSE_EXCEPTION_CLASS = new HttpResponseException("", null);
static final String DISPLAY_NAME_WITH_ARGUMENTS = "{displayName} with [{arguments}]";
private static final String AZURE_TEXT_ANALYTICS_TEST_SERVICE_VERSIONS =
"AZURE_TEXT_ANALYTICS_TEST_SERVICE_VERSIONS";
static List<DetectLanguageInput> getDetectLanguageInputs() {
return asList(
new DetectLanguageInput("0", DETECT_LANGUAGE_INPUTS.get(0), "US"),
new DetectLanguageInput("1", DETECT_LANGUAGE_INPUTS.get(1), "US"),
new DetectLanguageInput("2", DETECT_LANGUAGE_INPUTS.get(2), "US")
);
}
static List<DetectLanguageInput> getDuplicateIdDetectLanguageInputs() {
return asList(
new DetectLanguageInput("0", DETECT_LANGUAGE_INPUTS.get(0), "US"),
new DetectLanguageInput("0", DETECT_LANGUAGE_INPUTS.get(0), "US")
);
}
static List<TextDocumentInput> getDuplicateTextDocumentInputs() {
return asList(
new TextDocumentInput("0", CATEGORIZED_ENTITY_INPUTS.get(0)),
new TextDocumentInput("0", CATEGORIZED_ENTITY_INPUTS.get(0)),
new TextDocumentInput("0", CATEGORIZED_ENTITY_INPUTS.get(0))
);
}
static List<TextDocumentInput> getWarningsTextDocumentInputs() {
return asList(
new TextDocumentInput("0", TOO_LONG_INPUT),
new TextDocumentInput("1", CATEGORIZED_ENTITY_INPUTS.get(1))
);
}
static List<TextDocumentInput> getTextDocumentInputs(List<String> inputs) {
return IntStream.range(0, inputs.size())
.mapToObj(index ->
new TextDocumentInput(String.valueOf(index), inputs.get(index)))
.collect(Collectors.toList());
}
/**
* Helper method to get the expected Batch Detected Languages
*
* @return A {@link DetectLanguageResultCollection}.
*/
static DetectLanguageResultCollection getExpectedBatchDetectedLanguages() {
final TextDocumentBatchStatistics textDocumentBatchStatistics = new TextDocumentBatchStatistics(3, 3, 0, 3);
final List<DetectLanguageResult> detectLanguageResultList = asList(
new DetectLanguageResult("0", new TextDocumentStatistics(26, 1), null, getDetectedLanguageEnglish()),
new DetectLanguageResult("1", new TextDocumentStatistics(40, 1), null, getDetectedLanguageSpanish()),
new DetectLanguageResult("2", new TextDocumentStatistics(6, 1), null, getUnknownDetectedLanguage()));
return new DetectLanguageResultCollection(detectLanguageResultList, DEFAULT_MODEL_VERSION, textDocumentBatchStatistics);
}
static DetectedLanguage getDetectedLanguageEnglish() {
return new DetectedLanguage("English", "en", 0.0, null);
}
static DetectedLanguage getDetectedLanguageSpanish() {
return new DetectedLanguage("Spanish", "es", 0.0, null);
}
static DetectedLanguage getUnknownDetectedLanguage() {
return new DetectedLanguage("(Unknown)", "(Unknown)", 0.0, null);
}
/**
* Helper method to get the expected Batch Categorized Entities
*
* @return A {@link RecognizeEntitiesResultCollection}.
*/
static RecognizeEntitiesResultCollection getExpectedBatchCategorizedEntities() {
return new RecognizeEntitiesResultCollection(
asList(getExpectedBatchCategorizedEntities1(), getExpectedBatchCategorizedEntities2()),
DEFAULT_MODEL_VERSION,
new TextDocumentBatchStatistics(2, 2, 0, 2));
}
/**
* Helper method to get the expected Categorized Entities List 1
*/
static List<CategorizedEntity> getCategorizedEntitiesList1() {
CategorizedEntity categorizedEntity1 = new CategorizedEntity("trip", EntityCategory.EVENT, null, 0.0, 18, 4);
CategorizedEntity categorizedEntity2 = new CategorizedEntity("Seattle", EntityCategory.LOCATION, "GPE", 0.0, 26, 7);
CategorizedEntity categorizedEntity3 = new CategorizedEntity("last week", EntityCategory.DATE_TIME, "DateRange", 0.0, 34, 9);
return asList(categorizedEntity1, categorizedEntity2, categorizedEntity3);
}
/**
* Helper method to get the expected Categorized Entities List 2
*/
static List<CategorizedEntity> getCategorizedEntitiesList2() {
return asList(new CategorizedEntity("Microsoft", EntityCategory.ORGANIZATION, null, 0.0, 10, 9));
}
/**
* Helper method to get the expected Batch Categorized Entities
*/
static RecognizeEntitiesResult getExpectedBatchCategorizedEntities1() {
IterableStream<CategorizedEntity> categorizedEntityList1 = new IterableStream<>(getCategorizedEntitiesList1());
TextDocumentStatistics textDocumentStatistics1 = new TextDocumentStatistics(44, 1);
RecognizeEntitiesResult recognizeEntitiesResult1 = new RecognizeEntitiesResult("0", textDocumentStatistics1, null, new CategorizedEntityCollection(categorizedEntityList1, null));
return recognizeEntitiesResult1;
}
/**
* Helper method to get the expected Batch Categorized Entities
*/
static RecognizeEntitiesResult getExpectedBatchCategorizedEntities2() {
IterableStream<CategorizedEntity> categorizedEntityList2 = new IterableStream<>(getCategorizedEntitiesList2());
TextDocumentStatistics textDocumentStatistics2 = new TextDocumentStatistics(20, 1);
RecognizeEntitiesResult recognizeEntitiesResult2 = new RecognizeEntitiesResult("1", textDocumentStatistics2, null, new CategorizedEntityCollection(categorizedEntityList2, null));
return recognizeEntitiesResult2;
}
/**
* Helper method to get the expected batch of Personally Identifiable Information entities
*/
static RecognizePiiEntitiesResultCollection getExpectedBatchPiiEntities() {
PiiEntityCollection piiEntityCollection = new PiiEntityCollection(new IterableStream<>(getPiiEntitiesList1()), null);
PiiEntityCollection piiEntityCollection2 = new PiiEntityCollection(new IterableStream<>(getPiiEntitiesList2()), null);
TextDocumentStatistics textDocumentStatistics1 = new TextDocumentStatistics(67, 1);
TextDocumentStatistics textDocumentStatistics2 = new TextDocumentStatistics(105, 1);
RecognizePiiEntitiesResult recognizeEntitiesResult1 = new RecognizePiiEntitiesResult("0", textDocumentStatistics1, null, piiEntityCollection);
RecognizePiiEntitiesResult recognizeEntitiesResult2 = new RecognizePiiEntitiesResult("1", textDocumentStatistics2, null, piiEntityCollection2);
return new RecognizePiiEntitiesResultCollection(
asList(recognizeEntitiesResult1, recognizeEntitiesResult2),
DEFAULT_MODEL_VERSION,
new TextDocumentBatchStatistics(2, 2, 0, 2));
}
/**
* Helper method to get the expected Categorized Entities List 1
*/
static List<PiiEntity> getPiiEntitiesList1() {
PiiEntity piiEntity0 = new PiiEntity("Microsoft", EntityCategory.ORGANIZATION, null, 1.0, 0, 9);
PiiEntity piiEntity1 = new PiiEntity("859-98-0987", EntityCategory.fromString("U.S. Social Security Number (SSN)"), null, 0.65, 28, 11);
return asList(piiEntity0, piiEntity1);
}
/**
* Helper method to get the expected Categorized Entities List 2
*/
static List<PiiEntity> getPiiEntitiesList2() {
PiiEntity piiEntity2 = new PiiEntity("111000025", EntityCategory.fromString("Phone Number"), null, 0.8, 18, 9);
PiiEntity piiEntity3 = new PiiEntity("111000025", EntityCategory.fromString("ABA Routing Number"), null, 0.75, 18, 9);
PiiEntity piiEntity4 = new PiiEntity("111000025", EntityCategory.fromString("New Zealand Social Welfare Number"), null, 0.65, 18, 9);
PiiEntity piiEntity5 = new PiiEntity("111000025", EntityCategory.fromString("Portugal Tax Identification Number"), null, 0.65, 18, 9);
return asList(piiEntity2, piiEntity3, piiEntity4, piiEntity5);
}
/**
* Helper method to get the expected Batch Linked Entities
* @return A {@link RecognizeLinkedEntitiesResultCollection}.
*/
static RecognizeLinkedEntitiesResultCollection getExpectedBatchLinkedEntities() {
final TextDocumentBatchStatistics textDocumentBatchStatistics = new TextDocumentBatchStatistics(2, 2, 0, 2);
final List<RecognizeLinkedEntitiesResult> recognizeLinkedEntitiesResultList =
asList(
new RecognizeLinkedEntitiesResult(
"0", new TextDocumentStatistics(44, 1), null,
new LinkedEntityCollection(new IterableStream<>(getLinkedEntitiesList1()), null)),
new RecognizeLinkedEntitiesResult(
"1", new TextDocumentStatistics(20, 1), null,
new LinkedEntityCollection(new IterableStream<>(getLinkedEntitiesList2()), null)));
return new RecognizeLinkedEntitiesResultCollection(recognizeLinkedEntitiesResultList, DEFAULT_MODEL_VERSION, textDocumentBatchStatistics);
}
/**
* Helper method to get the expected linked Entities List 1
*/
/**
* Helper method to get the expected linked Entities List 2
*/
static List<LinkedEntity> getLinkedEntitiesList2() {
LinkedEntityMatch linkedEntityMatch = new LinkedEntityMatch("Microsoft", 0.0, 10, 9);
LinkedEntity linkedEntity = new LinkedEntity(
"Microsoft", new IterableStream<>(Collections.singletonList(linkedEntityMatch)),
"en", "Microsoft", "https:
"Wikipedia", "a093e9b9-90f5-a3d5-c4b8-5855e1b01f85");
return asList(linkedEntity);
}
/**
* Helper method to get the expected Batch Key Phrases.
*/
static ExtractKeyPhrasesResultCollection getExpectedBatchKeyPhrases() {
TextDocumentStatistics textDocumentStatistics1 = new TextDocumentStatistics(49, 1);
TextDocumentStatistics textDocumentStatistics2 = new TextDocumentStatistics(21, 1);
ExtractKeyPhraseResult extractKeyPhraseResult1 = new ExtractKeyPhraseResult("0", textDocumentStatistics1, null, new KeyPhrasesCollection(new IterableStream<>(asList("input text", "world")), null));
ExtractKeyPhraseResult extractKeyPhraseResult2 = new ExtractKeyPhraseResult("1", textDocumentStatistics2, null, new KeyPhrasesCollection(new IterableStream<>(Collections.singletonList("monde")), null));
TextDocumentBatchStatistics textDocumentBatchStatistics = new TextDocumentBatchStatistics(2, 2, 0, 2);
List<ExtractKeyPhraseResult> extractKeyPhraseResultList = asList(extractKeyPhraseResult1, extractKeyPhraseResult2);
return new ExtractKeyPhrasesResultCollection(extractKeyPhraseResultList, DEFAULT_MODEL_VERSION, textDocumentBatchStatistics);
}
/**
* Helper method to get the expected Batch Text Sentiments
*/
static AnalyzeSentimentResultCollection getExpectedBatchTextSentiment() {
final TextDocumentStatistics textDocumentStatistics = new TextDocumentStatistics(67, 1);
final AnalyzeSentimentResult analyzeSentimentResult1 = new AnalyzeSentimentResult("0",
textDocumentStatistics, null, getExpectedDocumentSentiment());
final AnalyzeSentimentResult analyzeSentimentResult2 = new AnalyzeSentimentResult("1",
textDocumentStatistics, null, getExpectedDocumentSentiment2());
return new AnalyzeSentimentResultCollection(
asList(analyzeSentimentResult1, analyzeSentimentResult2),
DEFAULT_MODEL_VERSION, new TextDocumentBatchStatistics(2, 2, 0, 2));
}
/**
* Helper method that get the first expected DocumentSentiment result.
*/
static DocumentSentiment getExpectedDocumentSentiment() {
return new DocumentSentiment(TextSentiment.MIXED,
new SentimentConfidenceScores(0.0, 0.0, 0.0),
new IterableStream<>(asList(
new SentenceSentiment("The hotel was dark and unclean.", TextSentiment.NEGATIVE,
new SentimentConfidenceScores(0.0, 0.0, 0.0),
new IterableStream<>(asList(new MinedOpinion(
new AspectSentiment("hotel", TextSentiment.NEGATIVE, 4, 5, new SentimentConfidenceScores(0.0, 0.0, 0.0)),
new IterableStream<>(asList(
new OpinionSentiment("dark", TextSentiment.NEGATIVE, 14, 4, false, new SentimentConfidenceScores(0.0, 0.0, 0.0)),
new OpinionSentiment("unclean", TextSentiment.NEGATIVE, 23, 7, false, new SentimentConfidenceScores(0.0, 0.0, 0.0))
))))),
0, 31
),
new SentenceSentiment("The restaurant had amazing gnocchi.", TextSentiment.POSITIVE,
new SentimentConfidenceScores(0.0, 0.0, 0.0),
new IterableStream<>(asList(new MinedOpinion(
new AspectSentiment("gnocchi", TextSentiment.POSITIVE, 59, 7, new SentimentConfidenceScores(0.0, 0.0, 0.0)),
new IterableStream<>(asList(
new OpinionSentiment("amazing", TextSentiment.POSITIVE, 51, 7, false, new SentimentConfidenceScores(0.0, 0.0, 0.0))
))))),
32, 35
)
)), null);
}
/**
* Helper method that get the second expected DocumentSentiment result.
*/
static DocumentSentiment getExpectedDocumentSentiment2() {
return new DocumentSentiment(TextSentiment.MIXED,
new SentimentConfidenceScores(0.0, 0.0, 0.0),
new IterableStream<>(asList(
new SentenceSentiment("The restaurant had amazing gnocchi.", TextSentiment.POSITIVE,
new SentimentConfidenceScores(0.0, 0.0, 0.0),
new IterableStream<>(asList(new MinedOpinion(
new AspectSentiment("gnocchi", TextSentiment.POSITIVE, 27, 7, new SentimentConfidenceScores(0.0, 0.0, 0.0)),
new IterableStream<>(asList(
new OpinionSentiment("amazing", TextSentiment.POSITIVE, 19, 7, false, new SentimentConfidenceScores(0.0, 0.0, 0.0))
))))),
0, 35
),
new SentenceSentiment("The hotel was dark and unclean.", TextSentiment.NEGATIVE,
new SentimentConfidenceScores(0.0, 0.0, 0.0), new IterableStream<>(asList(new MinedOpinion(
new AspectSentiment("hotel", TextSentiment.NEGATIVE, 40, 5, new SentimentConfidenceScores(0.0, 0.0, 0.0)),
new IterableStream<>(asList(
new OpinionSentiment("dark", TextSentiment.NEGATIVE, 50, 4, false, new SentimentConfidenceScores(0.0, 0.0, 0.0)),
new OpinionSentiment("unclean", TextSentiment.NEGATIVE, 59, 7, false, new SentimentConfidenceScores(0.0, 0.0, 0.0))
))))),
36, 31
)
)), null);
}
/**
* Returns a stream of arguments that includes all combinations of eligible {@link HttpClient HttpClients} and
* service versions that should be tested.
*
* @return A stream of HttpClient and service version combinations to test.
*/
static Stream<Arguments> getTestParameters() {
List<Arguments> argumentsList = new ArrayList<>();
getHttpClients()
.forEach(httpClient -> {
Arrays.stream(TextAnalyticsServiceVersion.values()).filter(
TestUtils::shouldServiceVersionBeTested)
.forEach(serviceVersion -> argumentsList.add(Arguments.of(httpClient, serviceVersion)));
});
return argumentsList.stream();
}
/**
* Returns whether the given service version match the rules of test framework.
*
* <ul>
* <li>Using latest service version as default if no environment variable is set.</li>
* <li>If it's set to ALL, all Service versions in {@link TextAnalyticsServiceVersion} will be tested.</li>
* <li>Otherwise, Service version string should match env variable.</li>
* </ul>
*
* Environment values currently supported are: "ALL", "${version}".
* Use comma to separate http clients want to test.
* e.g. {@code set AZURE_TEST_SERVICE_VERSIONS = V1_0, V2_0}
*
* @param serviceVersion ServiceVersion needs to check
* @return Boolean indicates whether filters out the service version or not.
*/
private static boolean shouldServiceVersionBeTested(TextAnalyticsServiceVersion serviceVersion) {
String serviceVersionFromEnv =
Configuration.getGlobalConfiguration().get(AZURE_TEXT_ANALYTICS_TEST_SERVICE_VERSIONS);
if (CoreUtils.isNullOrEmpty(serviceVersionFromEnv)) {
return TextAnalyticsServiceVersion.getLatest().equals(serviceVersion);
}
if (AZURE_TEST_SERVICE_VERSIONS_VALUE_ALL.equalsIgnoreCase(serviceVersionFromEnv)) {
return true;
}
String[] configuredServiceVersionList = serviceVersionFromEnv.split(",");
return Arrays.stream(configuredServiceVersionList).anyMatch(configuredServiceVersion ->
serviceVersion.getVersion().equals(configuredServiceVersion.trim()));
}
private TestUtils() {
}
} |
they are two difference bingId. | static List<LinkedEntity> getLinkedEntitiesList1() {
final LinkedEntityMatch linkedEntityMatch = new LinkedEntityMatch("Seattle", 0.0, 26, 7);
LinkedEntity linkedEntity = new LinkedEntity(
"Seattle", new IterableStream<>(Collections.singletonList(linkedEntityMatch)),
"en", "Seattle", "https:
"Wikipedia", "5fbba6b8-85e1-4d41-9444-d9055436e473");
return asList(linkedEntity);
} | "Wikipedia", "5fbba6b8-85e1-4d41-9444-d9055436e473"); | static List<LinkedEntity> getLinkedEntitiesList1() {
final LinkedEntityMatch linkedEntityMatch = new LinkedEntityMatch("Seattle", 0.0, 26, 7);
LinkedEntity linkedEntity = new LinkedEntity(
"Seattle", new IterableStream<>(Collections.singletonList(linkedEntityMatch)),
"en", "Seattle", "https:
"Wikipedia", "5fbba6b8-85e1-4d41-9444-d9055436e473");
return asList(linkedEntity);
} | class TestUtils {
private static final String DEFAULT_MODEL_VERSION = "2019-10-01";
static final String INVALID_URL = "htttttttps:
static final String VALID_HTTPS_LOCALHOST = "https:
static final String FAKE_API_KEY = "1234567890";
static final String AZURE_TEXT_ANALYTICS_API_KEY = "AZURE_TEXT_ANALYTICS_API_KEY";
static final List<String> SENTIMENT_INPUTS = asList("The hotel was dark and unclean. The restaurant had amazing gnocchi.",
"The restaurant had amazing gnocchi. The hotel was dark and unclean.");
static final List<String> CATEGORIZED_ENTITY_INPUTS = asList(
"I had a wonderful trip to Seattle last week.", "I work at Microsoft.");
static final List<String> PII_ENTITY_INPUTS = asList(
"Microsoft employee with ssn 859-98-0987 is using our awesome API's.",
"Your ABA number - 111000025 - is the first 9 digits in the lower left hand corner of your personal check.");
static final List<String> LINKED_ENTITY_INPUTS = asList(
"I had a wonderful trip to Seattle last week.",
"I work at Microsoft.");
static final List<String> KEY_PHRASE_INPUTS = asList(
"Hello world. This is some input text that I love.",
"Bonjour tout le monde");
static final String TOO_LONG_INPUT = "Thisisaveryveryverylongtextwhichgoesonforalongtimeandwhichalmostdoesn'tseemtostopatanygivenpointintime.ThereasonforthistestistotryandseewhathappenswhenwesubmitaveryveryverylongtexttoLanguage.Thisshouldworkjustfinebutjustincaseitisalwaysgoodtohaveatestcase.ThisallowsustotestwhathappensifitisnotOK.Ofcourseitisgoingtobeokbutthenagainitisalsobettertobesure!";
static final List<String> KEY_PHRASE_FRENCH_INPUTS = asList(
"Bonjour tout le monde.",
"Je m'appelle Mondly.");
static final List<String> DETECT_LANGUAGE_INPUTS = asList(
"This is written in English", "Este es un documento escrito en Español.", "~@!~:)");
static final List<String> SPANISH_SAME_AS_ENGLISH_INPUTS = asList("personal", "social");
static final DetectedLanguage DETECTED_LANGUAGE_SPANISH = new DetectedLanguage("Spanish", "es", 1.0, null);
static final DetectedLanguage DETECTED_LANGUAGE_ENGLISH = new DetectedLanguage("English", "en", 1.0, null);
static final List<DetectedLanguage> DETECT_SPANISH_LANGUAGE_RESULTS = asList(
DETECTED_LANGUAGE_SPANISH, DETECTED_LANGUAGE_SPANISH);
static final List<DetectedLanguage> DETECT_ENGLISH_LANGUAGE_RESULTS = asList(
DETECTED_LANGUAGE_ENGLISH, DETECTED_LANGUAGE_ENGLISH);
static final HttpResponseException HTTP_RESPONSE_EXCEPTION_CLASS = new HttpResponseException("", null);
static final String DISPLAY_NAME_WITH_ARGUMENTS = "{displayName} with [{arguments}]";
private static final String AZURE_TEXT_ANALYTICS_TEST_SERVICE_VERSIONS =
"AZURE_TEXT_ANALYTICS_TEST_SERVICE_VERSIONS";
static List<DetectLanguageInput> getDetectLanguageInputs() {
return asList(
new DetectLanguageInput("0", DETECT_LANGUAGE_INPUTS.get(0), "US"),
new DetectLanguageInput("1", DETECT_LANGUAGE_INPUTS.get(1), "US"),
new DetectLanguageInput("2", DETECT_LANGUAGE_INPUTS.get(2), "US")
);
}
static List<DetectLanguageInput> getDuplicateIdDetectLanguageInputs() {
return asList(
new DetectLanguageInput("0", DETECT_LANGUAGE_INPUTS.get(0), "US"),
new DetectLanguageInput("0", DETECT_LANGUAGE_INPUTS.get(0), "US")
);
}
static List<TextDocumentInput> getDuplicateTextDocumentInputs() {
return asList(
new TextDocumentInput("0", CATEGORIZED_ENTITY_INPUTS.get(0)),
new TextDocumentInput("0", CATEGORIZED_ENTITY_INPUTS.get(0)),
new TextDocumentInput("0", CATEGORIZED_ENTITY_INPUTS.get(0))
);
}
static List<TextDocumentInput> getWarningsTextDocumentInputs() {
return asList(
new TextDocumentInput("0", TOO_LONG_INPUT),
new TextDocumentInput("1", CATEGORIZED_ENTITY_INPUTS.get(1))
);
}
static List<TextDocumentInput> getTextDocumentInputs(List<String> inputs) {
return IntStream.range(0, inputs.size())
.mapToObj(index ->
new TextDocumentInput(String.valueOf(index), inputs.get(index)))
.collect(Collectors.toList());
}
/**
* Helper method to get the expected Batch Detected Languages
*
* @return A {@link DetectLanguageResultCollection}.
*/
static DetectLanguageResultCollection getExpectedBatchDetectedLanguages() {
final TextDocumentBatchStatistics textDocumentBatchStatistics = new TextDocumentBatchStatistics(3, 3, 0, 3);
final List<DetectLanguageResult> detectLanguageResultList = asList(
new DetectLanguageResult("0", new TextDocumentStatistics(26, 1), null, getDetectedLanguageEnglish()),
new DetectLanguageResult("1", new TextDocumentStatistics(40, 1), null, getDetectedLanguageSpanish()),
new DetectLanguageResult("2", new TextDocumentStatistics(6, 1), null, getUnknownDetectedLanguage()));
return new DetectLanguageResultCollection(detectLanguageResultList, DEFAULT_MODEL_VERSION, textDocumentBatchStatistics);
}
static DetectedLanguage getDetectedLanguageEnglish() {
return new DetectedLanguage("English", "en", 0.0, null);
}
static DetectedLanguage getDetectedLanguageSpanish() {
return new DetectedLanguage("Spanish", "es", 0.0, null);
}
static DetectedLanguage getUnknownDetectedLanguage() {
return new DetectedLanguage("(Unknown)", "(Unknown)", 0.0, null);
}
/**
* Helper method to get the expected Batch Categorized Entities
*
* @return A {@link RecognizeEntitiesResultCollection}.
*/
static RecognizeEntitiesResultCollection getExpectedBatchCategorizedEntities() {
return new RecognizeEntitiesResultCollection(
asList(getExpectedBatchCategorizedEntities1(), getExpectedBatchCategorizedEntities2()),
DEFAULT_MODEL_VERSION,
new TextDocumentBatchStatistics(2, 2, 0, 2));
}
/**
* Helper method to get the expected Categorized Entities List 1
*/
static List<CategorizedEntity> getCategorizedEntitiesList1() {
CategorizedEntity categorizedEntity1 = new CategorizedEntity("trip", EntityCategory.EVENT, null, 0.0, 18, 4);
CategorizedEntity categorizedEntity2 = new CategorizedEntity("Seattle", EntityCategory.LOCATION, "GPE", 0.0, 26, 7);
CategorizedEntity categorizedEntity3 = new CategorizedEntity("last week", EntityCategory.DATE_TIME, "DateRange", 0.0, 34, 9);
return asList(categorizedEntity1, categorizedEntity2, categorizedEntity3);
}
/**
* Helper method to get the expected Categorized Entities List 2
*/
static List<CategorizedEntity> getCategorizedEntitiesList2() {
return asList(new CategorizedEntity("Microsoft", EntityCategory.ORGANIZATION, null, 0.0, 10, 9));
}
/**
* Helper method to get the expected Batch Categorized Entities
*/
static RecognizeEntitiesResult getExpectedBatchCategorizedEntities1() {
IterableStream<CategorizedEntity> categorizedEntityList1 = new IterableStream<>(getCategorizedEntitiesList1());
TextDocumentStatistics textDocumentStatistics1 = new TextDocumentStatistics(44, 1);
RecognizeEntitiesResult recognizeEntitiesResult1 = new RecognizeEntitiesResult("0", textDocumentStatistics1, null, new CategorizedEntityCollection(categorizedEntityList1, null));
return recognizeEntitiesResult1;
}
/**
* Helper method to get the expected Batch Categorized Entities
*/
static RecognizeEntitiesResult getExpectedBatchCategorizedEntities2() {
IterableStream<CategorizedEntity> categorizedEntityList2 = new IterableStream<>(getCategorizedEntitiesList2());
TextDocumentStatistics textDocumentStatistics2 = new TextDocumentStatistics(20, 1);
RecognizeEntitiesResult recognizeEntitiesResult2 = new RecognizeEntitiesResult("1", textDocumentStatistics2, null, new CategorizedEntityCollection(categorizedEntityList2, null));
return recognizeEntitiesResult2;
}
/**
* Helper method to get the expected batch of Personally Identifiable Information entities
*/
static RecognizePiiEntitiesResultCollection getExpectedBatchPiiEntities() {
PiiEntityCollection piiEntityCollection = new PiiEntityCollection(new IterableStream<>(getPiiEntitiesList1()), null);
PiiEntityCollection piiEntityCollection2 = new PiiEntityCollection(new IterableStream<>(getPiiEntitiesList2()), null);
TextDocumentStatistics textDocumentStatistics1 = new TextDocumentStatistics(67, 1);
TextDocumentStatistics textDocumentStatistics2 = new TextDocumentStatistics(105, 1);
RecognizePiiEntitiesResult recognizeEntitiesResult1 = new RecognizePiiEntitiesResult("0", textDocumentStatistics1, null, piiEntityCollection);
RecognizePiiEntitiesResult recognizeEntitiesResult2 = new RecognizePiiEntitiesResult("1", textDocumentStatistics2, null, piiEntityCollection2);
return new RecognizePiiEntitiesResultCollection(
asList(recognizeEntitiesResult1, recognizeEntitiesResult2),
DEFAULT_MODEL_VERSION,
new TextDocumentBatchStatistics(2, 2, 0, 2));
}
/**
* Helper method to get the expected Categorized Entities List 1
*/
static List<PiiEntity> getPiiEntitiesList1() {
PiiEntity piiEntity0 = new PiiEntity("Microsoft", EntityCategory.ORGANIZATION, null, 1.0, 0, 9);
PiiEntity piiEntity1 = new PiiEntity("859-98-0987", EntityCategory.fromString("U.S. Social Security Number (SSN)"), null, 0.65, 28, 11);
return asList(piiEntity0, piiEntity1);
}
/**
* Helper method to get the expected Categorized Entities List 2
*/
static List<PiiEntity> getPiiEntitiesList2() {
PiiEntity piiEntity2 = new PiiEntity("111000025", EntityCategory.fromString("Phone Number"), null, 0.8, 18, 9);
PiiEntity piiEntity3 = new PiiEntity("111000025", EntityCategory.fromString("ABA Routing Number"), null, 0.75, 18, 9);
PiiEntity piiEntity4 = new PiiEntity("111000025", EntityCategory.fromString("New Zealand Social Welfare Number"), null, 0.65, 18, 9);
PiiEntity piiEntity5 = new PiiEntity("111000025", EntityCategory.fromString("Portugal Tax Identification Number"), null, 0.65, 18, 9);
return asList(piiEntity2, piiEntity3, piiEntity4, piiEntity5);
}
/**
* Helper method to get the expected Batch Linked Entities
* @return A {@link RecognizeLinkedEntitiesResultCollection}.
*/
static RecognizeLinkedEntitiesResultCollection getExpectedBatchLinkedEntities() {
final TextDocumentBatchStatistics textDocumentBatchStatistics = new TextDocumentBatchStatistics(2, 2, 0, 2);
final List<RecognizeLinkedEntitiesResult> recognizeLinkedEntitiesResultList =
asList(
new RecognizeLinkedEntitiesResult(
"0", new TextDocumentStatistics(44, 1), null,
new LinkedEntityCollection(new IterableStream<>(getLinkedEntitiesList1()), null)),
new RecognizeLinkedEntitiesResult(
"1", new TextDocumentStatistics(20, 1), null,
new LinkedEntityCollection(new IterableStream<>(getLinkedEntitiesList2()), null)));
return new RecognizeLinkedEntitiesResultCollection(recognizeLinkedEntitiesResultList, DEFAULT_MODEL_VERSION, textDocumentBatchStatistics);
}
/**
* Helper method to get the expected linked Entities List 1
*/
/**
* Helper method to get the expected linked Entities List 2
*/
static List<LinkedEntity> getLinkedEntitiesList2() {
LinkedEntityMatch linkedEntityMatch = new LinkedEntityMatch("Microsoft", 0.0, 10, 9);
LinkedEntity linkedEntity = new LinkedEntity(
"Microsoft", new IterableStream<>(Collections.singletonList(linkedEntityMatch)),
"en", "Microsoft", "https:
"Wikipedia", "a093e9b9-90f5-a3d5-c4b8-5855e1b01f85");
return asList(linkedEntity);
}
/**
* Helper method to get the expected Batch Key Phrases.
*/
static ExtractKeyPhrasesResultCollection getExpectedBatchKeyPhrases() {
TextDocumentStatistics textDocumentStatistics1 = new TextDocumentStatistics(49, 1);
TextDocumentStatistics textDocumentStatistics2 = new TextDocumentStatistics(21, 1);
ExtractKeyPhraseResult extractKeyPhraseResult1 = new ExtractKeyPhraseResult("0", textDocumentStatistics1, null, new KeyPhrasesCollection(new IterableStream<>(asList("input text", "world")), null));
ExtractKeyPhraseResult extractKeyPhraseResult2 = new ExtractKeyPhraseResult("1", textDocumentStatistics2, null, new KeyPhrasesCollection(new IterableStream<>(Collections.singletonList("monde")), null));
TextDocumentBatchStatistics textDocumentBatchStatistics = new TextDocumentBatchStatistics(2, 2, 0, 2);
List<ExtractKeyPhraseResult> extractKeyPhraseResultList = asList(extractKeyPhraseResult1, extractKeyPhraseResult2);
return new ExtractKeyPhrasesResultCollection(extractKeyPhraseResultList, DEFAULT_MODEL_VERSION, textDocumentBatchStatistics);
}
/**
* Helper method to get the expected Batch Text Sentiments
*/
static AnalyzeSentimentResultCollection getExpectedBatchTextSentiment() {
final TextDocumentStatistics textDocumentStatistics = new TextDocumentStatistics(67, 1);
final AnalyzeSentimentResult analyzeSentimentResult1 = new AnalyzeSentimentResult("0",
textDocumentStatistics, null, getExpectedDocumentSentiment());
final AnalyzeSentimentResult analyzeSentimentResult2 = new AnalyzeSentimentResult("1",
textDocumentStatistics, null, getExpectedDocumentSentiment2());
return new AnalyzeSentimentResultCollection(
asList(analyzeSentimentResult1, analyzeSentimentResult2),
DEFAULT_MODEL_VERSION, new TextDocumentBatchStatistics(2, 2, 0, 2));
}
/**
* Helper method that get the first expected DocumentSentiment result.
*/
static DocumentSentiment getExpectedDocumentSentiment() {
return new DocumentSentiment(TextSentiment.MIXED,
new SentimentConfidenceScores(0.0, 0.0, 0.0),
new IterableStream<>(asList(
new SentenceSentiment("The hotel was dark and unclean.", TextSentiment.NEGATIVE,
new SentimentConfidenceScores(0.0, 0.0, 0.0),
new IterableStream<>(asList(new MinedOpinion(
new AspectSentiment("hotel", TextSentiment.NEGATIVE, 4, 5, new SentimentConfidenceScores(0.0, 0.0, 0.0)),
new IterableStream<>(asList(
new OpinionSentiment("dark", TextSentiment.NEGATIVE, 14, 4, false, new SentimentConfidenceScores(0.0, 0.0, 0.0)),
new OpinionSentiment("unclean", TextSentiment.NEGATIVE, 23, 7, false, new SentimentConfidenceScores(0.0, 0.0, 0.0))
))))),
0, 31
),
new SentenceSentiment("The restaurant had amazing gnocchi.", TextSentiment.POSITIVE,
new SentimentConfidenceScores(0.0, 0.0, 0.0),
new IterableStream<>(asList(new MinedOpinion(
new AspectSentiment("gnocchi", TextSentiment.POSITIVE, 59, 7, new SentimentConfidenceScores(0.0, 0.0, 0.0)),
new IterableStream<>(asList(
new OpinionSentiment("amazing", TextSentiment.POSITIVE, 51, 7, false, new SentimentConfidenceScores(0.0, 0.0, 0.0))
))))),
32, 35
)
)), null);
}
/**
* Helper method that get the second expected DocumentSentiment result.
*/
static DocumentSentiment getExpectedDocumentSentiment2() {
return new DocumentSentiment(TextSentiment.MIXED,
new SentimentConfidenceScores(0.0, 0.0, 0.0),
new IterableStream<>(asList(
new SentenceSentiment("The restaurant had amazing gnocchi.", TextSentiment.POSITIVE,
new SentimentConfidenceScores(0.0, 0.0, 0.0),
new IterableStream<>(asList(new MinedOpinion(
new AspectSentiment("gnocchi", TextSentiment.POSITIVE, 27, 7, new SentimentConfidenceScores(0.0, 0.0, 0.0)),
new IterableStream<>(asList(
new OpinionSentiment("amazing", TextSentiment.POSITIVE, 19, 7, false, new SentimentConfidenceScores(0.0, 0.0, 0.0))
))))),
0, 35
),
new SentenceSentiment("The hotel was dark and unclean.", TextSentiment.NEGATIVE,
new SentimentConfidenceScores(0.0, 0.0, 0.0), new IterableStream<>(asList(new MinedOpinion(
new AspectSentiment("hotel", TextSentiment.NEGATIVE, 40, 5, new SentimentConfidenceScores(0.0, 0.0, 0.0)),
new IterableStream<>(asList(
new OpinionSentiment("dark", TextSentiment.NEGATIVE, 50, 4, false, new SentimentConfidenceScores(0.0, 0.0, 0.0)),
new OpinionSentiment("unclean", TextSentiment.NEGATIVE, 59, 7, false, new SentimentConfidenceScores(0.0, 0.0, 0.0))
))))),
36, 31
)
)), null);
}
/**
* Returns a stream of arguments that includes all combinations of eligible {@link HttpClient HttpClients} and
* service versions that should be tested.
*
* @return A stream of HttpClient and service version combinations to test.
*/
static Stream<Arguments> getTestParameters() {
List<Arguments> argumentsList = new ArrayList<>();
getHttpClients()
.forEach(httpClient -> {
Arrays.stream(TextAnalyticsServiceVersion.values()).filter(
TestUtils::shouldServiceVersionBeTested)
.forEach(serviceVersion -> argumentsList.add(Arguments.of(httpClient, serviceVersion)));
});
return argumentsList.stream();
}
/**
* Returns whether the given service version match the rules of test framework.
*
* <ul>
* <li>Using latest service version as default if no environment variable is set.</li>
* <li>If it's set to ALL, all Service versions in {@link TextAnalyticsServiceVersion} will be tested.</li>
* <li>Otherwise, Service version string should match env variable.</li>
* </ul>
*
* Environment values currently supported are: "ALL", "${version}".
* Use comma to separate http clients want to test.
* e.g. {@code set AZURE_TEST_SERVICE_VERSIONS = V1_0, V2_0}
*
* @param serviceVersion ServiceVersion needs to check
* @return Boolean indicates whether filters out the service version or not.
*/
private static boolean shouldServiceVersionBeTested(TextAnalyticsServiceVersion serviceVersion) {
String serviceVersionFromEnv =
Configuration.getGlobalConfiguration().get(AZURE_TEXT_ANALYTICS_TEST_SERVICE_VERSIONS);
if (CoreUtils.isNullOrEmpty(serviceVersionFromEnv)) {
return TextAnalyticsServiceVersion.getLatest().equals(serviceVersion);
}
if (AZURE_TEST_SERVICE_VERSIONS_VALUE_ALL.equalsIgnoreCase(serviceVersionFromEnv)) {
return true;
}
String[] configuredServiceVersionList = serviceVersionFromEnv.split(",");
return Arrays.stream(configuredServiceVersionList).anyMatch(configuredServiceVersion ->
serviceVersion.getVersion().equals(configuredServiceVersion.trim()));
}
private TestUtils() {
}
} | class TestUtils {
private static final String DEFAULT_MODEL_VERSION = "2019-10-01";
static final String INVALID_URL = "htttttttps:
static final String VALID_HTTPS_LOCALHOST = "https:
static final String FAKE_API_KEY = "1234567890";
static final String AZURE_TEXT_ANALYTICS_API_KEY = "AZURE_TEXT_ANALYTICS_API_KEY";
static final List<String> SENTIMENT_INPUTS = asList("The hotel was dark and unclean. The restaurant had amazing gnocchi.",
"The restaurant had amazing gnocchi. The hotel was dark and unclean.");
static final List<String> CATEGORIZED_ENTITY_INPUTS = asList(
"I had a wonderful trip to Seattle last week.", "I work at Microsoft.");
static final List<String> PII_ENTITY_INPUTS = asList(
"Microsoft employee with ssn 859-98-0987 is using our awesome API's.",
"Your ABA number - 111000025 - is the first 9 digits in the lower left hand corner of your personal check.");
static final List<String> LINKED_ENTITY_INPUTS = asList(
"I had a wonderful trip to Seattle last week.",
"I work at Microsoft.");
static final List<String> KEY_PHRASE_INPUTS = asList(
"Hello world. This is some input text that I love.",
"Bonjour tout le monde");
static final String TOO_LONG_INPUT = "Thisisaveryveryverylongtextwhichgoesonforalongtimeandwhichalmostdoesn'tseemtostopatanygivenpointintime.ThereasonforthistestistotryandseewhathappenswhenwesubmitaveryveryverylongtexttoLanguage.Thisshouldworkjustfinebutjustincaseitisalwaysgoodtohaveatestcase.ThisallowsustotestwhathappensifitisnotOK.Ofcourseitisgoingtobeokbutthenagainitisalsobettertobesure!";
static final List<String> KEY_PHRASE_FRENCH_INPUTS = asList(
"Bonjour tout le monde.",
"Je m'appelle Mondly.");
static final List<String> DETECT_LANGUAGE_INPUTS = asList(
"This is written in English", "Este es un documento escrito en Español.", "~@!~:)");
static final List<String> SPANISH_SAME_AS_ENGLISH_INPUTS = asList("personal", "social");
static final DetectedLanguage DETECTED_LANGUAGE_SPANISH = new DetectedLanguage("Spanish", "es", 1.0, null);
static final DetectedLanguage DETECTED_LANGUAGE_ENGLISH = new DetectedLanguage("English", "en", 1.0, null);
static final List<DetectedLanguage> DETECT_SPANISH_LANGUAGE_RESULTS = asList(
DETECTED_LANGUAGE_SPANISH, DETECTED_LANGUAGE_SPANISH);
static final List<DetectedLanguage> DETECT_ENGLISH_LANGUAGE_RESULTS = asList(
DETECTED_LANGUAGE_ENGLISH, DETECTED_LANGUAGE_ENGLISH);
static final HttpResponseException HTTP_RESPONSE_EXCEPTION_CLASS = new HttpResponseException("", null);
static final String DISPLAY_NAME_WITH_ARGUMENTS = "{displayName} with [{arguments}]";
private static final String AZURE_TEXT_ANALYTICS_TEST_SERVICE_VERSIONS =
"AZURE_TEXT_ANALYTICS_TEST_SERVICE_VERSIONS";
static List<DetectLanguageInput> getDetectLanguageInputs() {
return asList(
new DetectLanguageInput("0", DETECT_LANGUAGE_INPUTS.get(0), "US"),
new DetectLanguageInput("1", DETECT_LANGUAGE_INPUTS.get(1), "US"),
new DetectLanguageInput("2", DETECT_LANGUAGE_INPUTS.get(2), "US")
);
}
static List<DetectLanguageInput> getDuplicateIdDetectLanguageInputs() {
return asList(
new DetectLanguageInput("0", DETECT_LANGUAGE_INPUTS.get(0), "US"),
new DetectLanguageInput("0", DETECT_LANGUAGE_INPUTS.get(0), "US")
);
}
static List<TextDocumentInput> getDuplicateTextDocumentInputs() {
return asList(
new TextDocumentInput("0", CATEGORIZED_ENTITY_INPUTS.get(0)),
new TextDocumentInput("0", CATEGORIZED_ENTITY_INPUTS.get(0)),
new TextDocumentInput("0", CATEGORIZED_ENTITY_INPUTS.get(0))
);
}
static List<TextDocumentInput> getWarningsTextDocumentInputs() {
return asList(
new TextDocumentInput("0", TOO_LONG_INPUT),
new TextDocumentInput("1", CATEGORIZED_ENTITY_INPUTS.get(1))
);
}
static List<TextDocumentInput> getTextDocumentInputs(List<String> inputs) {
return IntStream.range(0, inputs.size())
.mapToObj(index ->
new TextDocumentInput(String.valueOf(index), inputs.get(index)))
.collect(Collectors.toList());
}
/**
* Helper method to get the expected Batch Detected Languages
*
* @return A {@link DetectLanguageResultCollection}.
*/
static DetectLanguageResultCollection getExpectedBatchDetectedLanguages() {
final TextDocumentBatchStatistics textDocumentBatchStatistics = new TextDocumentBatchStatistics(3, 3, 0, 3);
final List<DetectLanguageResult> detectLanguageResultList = asList(
new DetectLanguageResult("0", new TextDocumentStatistics(26, 1), null, getDetectedLanguageEnglish()),
new DetectLanguageResult("1", new TextDocumentStatistics(40, 1), null, getDetectedLanguageSpanish()),
new DetectLanguageResult("2", new TextDocumentStatistics(6, 1), null, getUnknownDetectedLanguage()));
return new DetectLanguageResultCollection(detectLanguageResultList, DEFAULT_MODEL_VERSION, textDocumentBatchStatistics);
}
static DetectedLanguage getDetectedLanguageEnglish() {
return new DetectedLanguage("English", "en", 0.0, null);
}
static DetectedLanguage getDetectedLanguageSpanish() {
return new DetectedLanguage("Spanish", "es", 0.0, null);
}
static DetectedLanguage getUnknownDetectedLanguage() {
return new DetectedLanguage("(Unknown)", "(Unknown)", 0.0, null);
}
/**
* Helper method to get the expected Batch Categorized Entities
*
* @return A {@link RecognizeEntitiesResultCollection}.
*/
static RecognizeEntitiesResultCollection getExpectedBatchCategorizedEntities() {
return new RecognizeEntitiesResultCollection(
asList(getExpectedBatchCategorizedEntities1(), getExpectedBatchCategorizedEntities2()),
DEFAULT_MODEL_VERSION,
new TextDocumentBatchStatistics(2, 2, 0, 2));
}
/**
* Helper method to get the expected Categorized Entities List 1
*/
static List<CategorizedEntity> getCategorizedEntitiesList1() {
CategorizedEntity categorizedEntity1 = new CategorizedEntity("trip", EntityCategory.EVENT, null, 0.0, 18, 4);
CategorizedEntity categorizedEntity2 = new CategorizedEntity("Seattle", EntityCategory.LOCATION, "GPE", 0.0, 26, 7);
CategorizedEntity categorizedEntity3 = new CategorizedEntity("last week", EntityCategory.DATE_TIME, "DateRange", 0.0, 34, 9);
return asList(categorizedEntity1, categorizedEntity2, categorizedEntity3);
}
/**
* Helper method to get the expected Categorized Entities List 2
*/
static List<CategorizedEntity> getCategorizedEntitiesList2() {
return asList(new CategorizedEntity("Microsoft", EntityCategory.ORGANIZATION, null, 0.0, 10, 9));
}
/**
* Helper method to get the expected Batch Categorized Entities
*/
static RecognizeEntitiesResult getExpectedBatchCategorizedEntities1() {
IterableStream<CategorizedEntity> categorizedEntityList1 = new IterableStream<>(getCategorizedEntitiesList1());
TextDocumentStatistics textDocumentStatistics1 = new TextDocumentStatistics(44, 1);
RecognizeEntitiesResult recognizeEntitiesResult1 = new RecognizeEntitiesResult("0", textDocumentStatistics1, null, new CategorizedEntityCollection(categorizedEntityList1, null));
return recognizeEntitiesResult1;
}
/**
* Helper method to get the expected Batch Categorized Entities
*/
static RecognizeEntitiesResult getExpectedBatchCategorizedEntities2() {
IterableStream<CategorizedEntity> categorizedEntityList2 = new IterableStream<>(getCategorizedEntitiesList2());
TextDocumentStatistics textDocumentStatistics2 = new TextDocumentStatistics(20, 1);
RecognizeEntitiesResult recognizeEntitiesResult2 = new RecognizeEntitiesResult("1", textDocumentStatistics2, null, new CategorizedEntityCollection(categorizedEntityList2, null));
return recognizeEntitiesResult2;
}
/**
* Helper method to get the expected batch of Personally Identifiable Information entities
*/
static RecognizePiiEntitiesResultCollection getExpectedBatchPiiEntities() {
PiiEntityCollection piiEntityCollection = new PiiEntityCollection(new IterableStream<>(getPiiEntitiesList1()), null);
PiiEntityCollection piiEntityCollection2 = new PiiEntityCollection(new IterableStream<>(getPiiEntitiesList2()), null);
TextDocumentStatistics textDocumentStatistics1 = new TextDocumentStatistics(67, 1);
TextDocumentStatistics textDocumentStatistics2 = new TextDocumentStatistics(105, 1);
RecognizePiiEntitiesResult recognizeEntitiesResult1 = new RecognizePiiEntitiesResult("0", textDocumentStatistics1, null, piiEntityCollection);
RecognizePiiEntitiesResult recognizeEntitiesResult2 = new RecognizePiiEntitiesResult("1", textDocumentStatistics2, null, piiEntityCollection2);
return new RecognizePiiEntitiesResultCollection(
asList(recognizeEntitiesResult1, recognizeEntitiesResult2),
DEFAULT_MODEL_VERSION,
new TextDocumentBatchStatistics(2, 2, 0, 2));
}
/**
* Helper method to get the expected Categorized Entities List 1
*/
static List<PiiEntity> getPiiEntitiesList1() {
PiiEntity piiEntity0 = new PiiEntity("Microsoft", EntityCategory.ORGANIZATION, null, 1.0, 0, 9);
PiiEntity piiEntity1 = new PiiEntity("859-98-0987", EntityCategory.fromString("U.S. Social Security Number (SSN)"), null, 0.65, 28, 11);
return asList(piiEntity0, piiEntity1);
}
/**
* Helper method to get the expected Categorized Entities List 2
*/
static List<PiiEntity> getPiiEntitiesList2() {
PiiEntity piiEntity2 = new PiiEntity("111000025", EntityCategory.fromString("Phone Number"), null, 0.8, 18, 9);
PiiEntity piiEntity3 = new PiiEntity("111000025", EntityCategory.fromString("ABA Routing Number"), null, 0.75, 18, 9);
PiiEntity piiEntity4 = new PiiEntity("111000025", EntityCategory.fromString("New Zealand Social Welfare Number"), null, 0.65, 18, 9);
PiiEntity piiEntity5 = new PiiEntity("111000025", EntityCategory.fromString("Portugal Tax Identification Number"), null, 0.65, 18, 9);
return asList(piiEntity2, piiEntity3, piiEntity4, piiEntity5);
}
/**
* Helper method to get the expected Batch Linked Entities
* @return A {@link RecognizeLinkedEntitiesResultCollection}.
*/
static RecognizeLinkedEntitiesResultCollection getExpectedBatchLinkedEntities() {
final TextDocumentBatchStatistics textDocumentBatchStatistics = new TextDocumentBatchStatistics(2, 2, 0, 2);
final List<RecognizeLinkedEntitiesResult> recognizeLinkedEntitiesResultList =
asList(
new RecognizeLinkedEntitiesResult(
"0", new TextDocumentStatistics(44, 1), null,
new LinkedEntityCollection(new IterableStream<>(getLinkedEntitiesList1()), null)),
new RecognizeLinkedEntitiesResult(
"1", new TextDocumentStatistics(20, 1), null,
new LinkedEntityCollection(new IterableStream<>(getLinkedEntitiesList2()), null)));
return new RecognizeLinkedEntitiesResultCollection(recognizeLinkedEntitiesResultList, DEFAULT_MODEL_VERSION, textDocumentBatchStatistics);
}
/**
* Helper method to get the expected linked Entities List 1
*/
/**
* Helper method to get the expected linked Entities List 2
*/
static List<LinkedEntity> getLinkedEntitiesList2() {
LinkedEntityMatch linkedEntityMatch = new LinkedEntityMatch("Microsoft", 0.0, 10, 9);
LinkedEntity linkedEntity = new LinkedEntity(
"Microsoft", new IterableStream<>(Collections.singletonList(linkedEntityMatch)),
"en", "Microsoft", "https:
"Wikipedia", "a093e9b9-90f5-a3d5-c4b8-5855e1b01f85");
return asList(linkedEntity);
}
/**
* Helper method to get the expected Batch Key Phrases.
*/
static ExtractKeyPhrasesResultCollection getExpectedBatchKeyPhrases() {
TextDocumentStatistics textDocumentStatistics1 = new TextDocumentStatistics(49, 1);
TextDocumentStatistics textDocumentStatistics2 = new TextDocumentStatistics(21, 1);
ExtractKeyPhraseResult extractKeyPhraseResult1 = new ExtractKeyPhraseResult("0", textDocumentStatistics1, null, new KeyPhrasesCollection(new IterableStream<>(asList("input text", "world")), null));
ExtractKeyPhraseResult extractKeyPhraseResult2 = new ExtractKeyPhraseResult("1", textDocumentStatistics2, null, new KeyPhrasesCollection(new IterableStream<>(Collections.singletonList("monde")), null));
TextDocumentBatchStatistics textDocumentBatchStatistics = new TextDocumentBatchStatistics(2, 2, 0, 2);
List<ExtractKeyPhraseResult> extractKeyPhraseResultList = asList(extractKeyPhraseResult1, extractKeyPhraseResult2);
return new ExtractKeyPhrasesResultCollection(extractKeyPhraseResultList, DEFAULT_MODEL_VERSION, textDocumentBatchStatistics);
}
/**
* Helper method to get the expected Batch Text Sentiments
*/
static AnalyzeSentimentResultCollection getExpectedBatchTextSentiment() {
final TextDocumentStatistics textDocumentStatistics = new TextDocumentStatistics(67, 1);
final AnalyzeSentimentResult analyzeSentimentResult1 = new AnalyzeSentimentResult("0",
textDocumentStatistics, null, getExpectedDocumentSentiment());
final AnalyzeSentimentResult analyzeSentimentResult2 = new AnalyzeSentimentResult("1",
textDocumentStatistics, null, getExpectedDocumentSentiment2());
return new AnalyzeSentimentResultCollection(
asList(analyzeSentimentResult1, analyzeSentimentResult2),
DEFAULT_MODEL_VERSION, new TextDocumentBatchStatistics(2, 2, 0, 2));
}
/**
* Helper method that get the first expected DocumentSentiment result.
*/
static DocumentSentiment getExpectedDocumentSentiment() {
return new DocumentSentiment(TextSentiment.MIXED,
new SentimentConfidenceScores(0.0, 0.0, 0.0),
new IterableStream<>(asList(
new SentenceSentiment("The hotel was dark and unclean.", TextSentiment.NEGATIVE,
new SentimentConfidenceScores(0.0, 0.0, 0.0),
new IterableStream<>(asList(new MinedOpinion(
new AspectSentiment("hotel", TextSentiment.NEGATIVE, 4, 5, new SentimentConfidenceScores(0.0, 0.0, 0.0)),
new IterableStream<>(asList(
new OpinionSentiment("dark", TextSentiment.NEGATIVE, 14, 4, false, new SentimentConfidenceScores(0.0, 0.0, 0.0)),
new OpinionSentiment("unclean", TextSentiment.NEGATIVE, 23, 7, false, new SentimentConfidenceScores(0.0, 0.0, 0.0))
))))),
0, 31
),
new SentenceSentiment("The restaurant had amazing gnocchi.", TextSentiment.POSITIVE,
new SentimentConfidenceScores(0.0, 0.0, 0.0),
new IterableStream<>(asList(new MinedOpinion(
new AspectSentiment("gnocchi", TextSentiment.POSITIVE, 59, 7, new SentimentConfidenceScores(0.0, 0.0, 0.0)),
new IterableStream<>(asList(
new OpinionSentiment("amazing", TextSentiment.POSITIVE, 51, 7, false, new SentimentConfidenceScores(0.0, 0.0, 0.0))
))))),
32, 35
)
)), null);
}
/**
* Helper method that get the second expected DocumentSentiment result.
*/
static DocumentSentiment getExpectedDocumentSentiment2() {
return new DocumentSentiment(TextSentiment.MIXED,
new SentimentConfidenceScores(0.0, 0.0, 0.0),
new IterableStream<>(asList(
new SentenceSentiment("The restaurant had amazing gnocchi.", TextSentiment.POSITIVE,
new SentimentConfidenceScores(0.0, 0.0, 0.0),
new IterableStream<>(asList(new MinedOpinion(
new AspectSentiment("gnocchi", TextSentiment.POSITIVE, 27, 7, new SentimentConfidenceScores(0.0, 0.0, 0.0)),
new IterableStream<>(asList(
new OpinionSentiment("amazing", TextSentiment.POSITIVE, 19, 7, false, new SentimentConfidenceScores(0.0, 0.0, 0.0))
))))),
0, 35
),
new SentenceSentiment("The hotel was dark and unclean.", TextSentiment.NEGATIVE,
new SentimentConfidenceScores(0.0, 0.0, 0.0), new IterableStream<>(asList(new MinedOpinion(
new AspectSentiment("hotel", TextSentiment.NEGATIVE, 40, 5, new SentimentConfidenceScores(0.0, 0.0, 0.0)),
new IterableStream<>(asList(
new OpinionSentiment("dark", TextSentiment.NEGATIVE, 50, 4, false, new SentimentConfidenceScores(0.0, 0.0, 0.0)),
new OpinionSentiment("unclean", TextSentiment.NEGATIVE, 59, 7, false, new SentimentConfidenceScores(0.0, 0.0, 0.0))
))))),
36, 31
)
)), null);
}
/**
* Returns a stream of arguments that includes all combinations of eligible {@link HttpClient HttpClients} and
* service versions that should be tested.
*
* @return A stream of HttpClient and service version combinations to test.
*/
static Stream<Arguments> getTestParameters() {
List<Arguments> argumentsList = new ArrayList<>();
getHttpClients()
.forEach(httpClient -> {
Arrays.stream(TextAnalyticsServiceVersion.values()).filter(
TestUtils::shouldServiceVersionBeTested)
.forEach(serviceVersion -> argumentsList.add(Arguments.of(httpClient, serviceVersion)));
});
return argumentsList.stream();
}
/**
* Returns whether the given service version match the rules of test framework.
*
* <ul>
* <li>Using latest service version as default if no environment variable is set.</li>
* <li>If it's set to ALL, all Service versions in {@link TextAnalyticsServiceVersion} will be tested.</li>
* <li>Otherwise, Service version string should match env variable.</li>
* </ul>
*
* Environment values currently supported are: "ALL", "${version}".
* Use comma to separate http clients want to test.
* e.g. {@code set AZURE_TEST_SERVICE_VERSIONS = V1_0, V2_0}
*
* @param serviceVersion ServiceVersion needs to check
* @return Boolean indicates whether filters out the service version or not.
*/
private static boolean shouldServiceVersionBeTested(TextAnalyticsServiceVersion serviceVersion) {
String serviceVersionFromEnv =
Configuration.getGlobalConfiguration().get(AZURE_TEXT_ANALYTICS_TEST_SERVICE_VERSIONS);
if (CoreUtils.isNullOrEmpty(serviceVersionFromEnv)) {
return TextAnalyticsServiceVersion.getLatest().equals(serviceVersion);
}
if (AZURE_TEST_SERVICE_VERSIONS_VALUE_ALL.equalsIgnoreCase(serviceVersionFromEnv)) {
return true;
}
String[] configuredServiceVersionList = serviceVersionFromEnv.split(",");
return Arrays.stream(configuredServiceVersionList).anyMatch(configuredServiceVersion ->
serviceVersion.getVersion().equals(configuredServiceVersion.trim()));
}
private TestUtils() {
}
} |
what this change for ? | public Flux<ByteBuf> body() {
return bodyIntern()
.doOnSubscribe(this::updateSubscriptionState);
} | .doOnSubscribe(this::updateSubscriptionState); | public Flux<ByteBuf> body() {
return bodyIntern()
.doOnSubscribe(this::updateSubscriptionState);
} | class ReactorNettyHttpResponse extends HttpResponse {
private final AtomicReference<ReactorNettyResponseState> state = new AtomicReference<>(ReactorNettyResponseState.NOT_SUBSCRIBED);
private final HttpClientResponse reactorNettyResponse;
private final Connection reactorNettyConnection;
ReactorNettyHttpResponse(HttpClientResponse reactorNettyResponse, Connection reactorNettyConnection) {
this.reactorNettyResponse = reactorNettyResponse;
this.reactorNettyConnection = reactorNettyConnection;
}
@Override
public int statusCode() {
return reactorNettyResponse.status().code();
}
@Override
public String headerValue(String name) {
return reactorNettyResponse.responseHeaders().get(name);
}
@Override
public HttpHeaders headers() {
HttpHeaders headers = new HttpHeaders(reactorNettyResponse.responseHeaders().size());
reactorNettyResponse.responseHeaders().forEach(e -> headers.set(e.getKey(), e.getValue()));
return headers;
}
@Override
@Override
public Mono<byte[]> bodyAsByteArray() {
return bodyIntern().aggregate()
.asByteArray()
.doOnSubscribe(this::updateSubscriptionState);
}
@Override
public Mono<String> bodyAsString() {
return bodyIntern().aggregate()
.asString()
.doOnSubscribe(this::updateSubscriptionState);
}
@Override
public Mono<String> bodyAsString(Charset charset) {
return bodyIntern().aggregate()
.asString(charset)
.doOnSubscribe(this::updateSubscriptionState);
}
private ByteBufFlux bodyIntern() {
return reactorNettyConnection.inbound().receive();
}
@Override
Connection internConnection() {
return reactorNettyConnection;
}
private void updateSubscriptionState(Subscription subscription) {
if (this.state.compareAndSet(ReactorNettyResponseState.NOT_SUBSCRIBED, ReactorNettyResponseState.SUBSCRIBED)) {
return;
}
if (this.state.get() == ReactorNettyResponseState.CANCELLED) {
throw new IllegalStateException(
"The client response body has been released already due to cancellation.");
}
}
/**
* Called by {@link ReactorNettyClient} when a cancellation is detected
* but the content has not been subscribed to. If the subscription never
* materializes then the content will remain not drained. Or it could still
* materialize if the cancellation happened very early, or the response
* reading was delayed for some reason.
*/
private void releaseAfterCancel(HttpMethod method) {
if (this.state.compareAndSet(ReactorNettyResponseState.NOT_SUBSCRIBED, ReactorNettyResponseState.CANCELLED)) {
if (logger.isDebugEnabled()) {
logger.debug("Releasing body, not yet subscribed");
}
this.bodyIntern()
.doOnNext(byteBuf -> {})
.subscribe(byteBuf -> {}, ex -> {});
}
}
} | class ReactorNettyHttpResponse extends HttpResponse {
private final AtomicReference<ReactorNettyResponseState> state = new AtomicReference<>(ReactorNettyResponseState.NOT_SUBSCRIBED);
private final HttpClientResponse reactorNettyResponse;
private final Connection reactorNettyConnection;
ReactorNettyHttpResponse(HttpClientResponse reactorNettyResponse, Connection reactorNettyConnection) {
this.reactorNettyResponse = reactorNettyResponse;
this.reactorNettyConnection = reactorNettyConnection;
}
@Override
public int statusCode() {
return reactorNettyResponse.status().code();
}
@Override
public String headerValue(String name) {
return reactorNettyResponse.responseHeaders().get(name);
}
@Override
public HttpHeaders headers() {
HttpHeaders headers = new HttpHeaders(reactorNettyResponse.responseHeaders().size());
reactorNettyResponse.responseHeaders().forEach(e -> headers.set(e.getKey(), e.getValue()));
return headers;
}
@Override
@Override
public Mono<byte[]> bodyAsByteArray() {
return bodyIntern().aggregate()
.asByteArray()
.doOnSubscribe(this::updateSubscriptionState);
}
@Override
public Mono<String> bodyAsString() {
return bodyIntern().aggregate()
.asString()
.doOnSubscribe(this::updateSubscriptionState);
}
@Override
public Mono<String> bodyAsString(Charset charset) {
return bodyIntern().aggregate()
.asString(charset)
.doOnSubscribe(this::updateSubscriptionState);
}
private ByteBufFlux bodyIntern() {
return reactorNettyConnection.inbound().receive();
}
@Override
Connection internConnection() {
return reactorNettyConnection;
}
private void updateSubscriptionState(Subscription subscription) {
if (this.state.compareAndSet(ReactorNettyResponseState.NOT_SUBSCRIBED, ReactorNettyResponseState.SUBSCRIBED)) {
return;
}
if (this.state.get() == ReactorNettyResponseState.CANCELLED) {
throw new IllegalStateException(
"The client response body has been released already due to cancellation.");
}
}
/**
* Called by {@link ReactorNettyClient} when a cancellation is detected
* but the content has not been subscribed to. If the subscription never
* materializes then the content will remain not drained. Or it could still
* materialize if the cancellation happened very early, or the response
* reading was delayed for some reason.
*/
private void releaseAfterCancel(HttpMethod method) {
if (this.state.compareAndSet(ReactorNettyResponseState.NOT_SUBSCRIBED, ReactorNettyResponseState.CANCELLED)) {
if (logger.isDebugEnabled()) {
logger.debug("Releasing body, not yet subscribed");
}
this.bodyIntern()
.doOnNext(byteBuf -> {})
.subscribe(byteBuf -> {}, ex -> {});
}
}
} |
Just removed the unnecessary `map` operator. We don't need to retain the byteBuf here, as it is not released afterwards. This can potentially raise IllegalReferenceCount issue with netty. Although, we don't use this API, which is why no one has seen this issue. | public Flux<ByteBuf> body() {
return bodyIntern()
.doOnSubscribe(this::updateSubscriptionState);
} | .doOnSubscribe(this::updateSubscriptionState); | public Flux<ByteBuf> body() {
return bodyIntern()
.doOnSubscribe(this::updateSubscriptionState);
} | class ReactorNettyHttpResponse extends HttpResponse {
private final AtomicReference<ReactorNettyResponseState> state = new AtomicReference<>(ReactorNettyResponseState.NOT_SUBSCRIBED);
private final HttpClientResponse reactorNettyResponse;
private final Connection reactorNettyConnection;
ReactorNettyHttpResponse(HttpClientResponse reactorNettyResponse, Connection reactorNettyConnection) {
this.reactorNettyResponse = reactorNettyResponse;
this.reactorNettyConnection = reactorNettyConnection;
}
@Override
public int statusCode() {
return reactorNettyResponse.status().code();
}
@Override
public String headerValue(String name) {
return reactorNettyResponse.responseHeaders().get(name);
}
@Override
public HttpHeaders headers() {
HttpHeaders headers = new HttpHeaders(reactorNettyResponse.responseHeaders().size());
reactorNettyResponse.responseHeaders().forEach(e -> headers.set(e.getKey(), e.getValue()));
return headers;
}
@Override
@Override
public Mono<byte[]> bodyAsByteArray() {
return bodyIntern().aggregate()
.asByteArray()
.doOnSubscribe(this::updateSubscriptionState);
}
@Override
public Mono<String> bodyAsString() {
return bodyIntern().aggregate()
.asString()
.doOnSubscribe(this::updateSubscriptionState);
}
@Override
public Mono<String> bodyAsString(Charset charset) {
return bodyIntern().aggregate()
.asString(charset)
.doOnSubscribe(this::updateSubscriptionState);
}
private ByteBufFlux bodyIntern() {
return reactorNettyConnection.inbound().receive();
}
@Override
Connection internConnection() {
return reactorNettyConnection;
}
private void updateSubscriptionState(Subscription subscription) {
if (this.state.compareAndSet(ReactorNettyResponseState.NOT_SUBSCRIBED, ReactorNettyResponseState.SUBSCRIBED)) {
return;
}
if (this.state.get() == ReactorNettyResponseState.CANCELLED) {
throw new IllegalStateException(
"The client response body has been released already due to cancellation.");
}
}
/**
* Called by {@link ReactorNettyClient} when a cancellation is detected
* but the content has not been subscribed to. If the subscription never
* materializes then the content will remain not drained. Or it could still
* materialize if the cancellation happened very early, or the response
* reading was delayed for some reason.
*/
private void releaseAfterCancel(HttpMethod method) {
if (this.state.compareAndSet(ReactorNettyResponseState.NOT_SUBSCRIBED, ReactorNettyResponseState.CANCELLED)) {
if (logger.isDebugEnabled()) {
logger.debug("Releasing body, not yet subscribed");
}
this.bodyIntern()
.doOnNext(byteBuf -> {})
.subscribe(byteBuf -> {}, ex -> {});
}
}
} | class ReactorNettyHttpResponse extends HttpResponse {
private final AtomicReference<ReactorNettyResponseState> state = new AtomicReference<>(ReactorNettyResponseState.NOT_SUBSCRIBED);
private final HttpClientResponse reactorNettyResponse;
private final Connection reactorNettyConnection;
ReactorNettyHttpResponse(HttpClientResponse reactorNettyResponse, Connection reactorNettyConnection) {
this.reactorNettyResponse = reactorNettyResponse;
this.reactorNettyConnection = reactorNettyConnection;
}
@Override
public int statusCode() {
return reactorNettyResponse.status().code();
}
@Override
public String headerValue(String name) {
return reactorNettyResponse.responseHeaders().get(name);
}
@Override
public HttpHeaders headers() {
HttpHeaders headers = new HttpHeaders(reactorNettyResponse.responseHeaders().size());
reactorNettyResponse.responseHeaders().forEach(e -> headers.set(e.getKey(), e.getValue()));
return headers;
}
@Override
@Override
public Mono<byte[]> bodyAsByteArray() {
return bodyIntern().aggregate()
.asByteArray()
.doOnSubscribe(this::updateSubscriptionState);
}
@Override
public Mono<String> bodyAsString() {
return bodyIntern().aggregate()
.asString()
.doOnSubscribe(this::updateSubscriptionState);
}
@Override
public Mono<String> bodyAsString(Charset charset) {
return bodyIntern().aggregate()
.asString(charset)
.doOnSubscribe(this::updateSubscriptionState);
}
private ByteBufFlux bodyIntern() {
return reactorNettyConnection.inbound().receive();
}
@Override
Connection internConnection() {
return reactorNettyConnection;
}
private void updateSubscriptionState(Subscription subscription) {
if (this.state.compareAndSet(ReactorNettyResponseState.NOT_SUBSCRIBED, ReactorNettyResponseState.SUBSCRIBED)) {
return;
}
if (this.state.get() == ReactorNettyResponseState.CANCELLED) {
throw new IllegalStateException(
"The client response body has been released already due to cancellation.");
}
}
/**
* Called by {@link ReactorNettyClient} when a cancellation is detected
* but the content has not been subscribed to. If the subscription never
* materializes then the content will remain not drained. Or it could still
* materialize if the cancellation happened very early, or the response
* reading was delayed for some reason.
*/
private void releaseAfterCancel(HttpMethod method) {
if (this.state.compareAndSet(ReactorNettyResponseState.NOT_SUBSCRIBED, ReactorNettyResponseState.CANCELLED)) {
if (logger.isDebugEnabled()) {
logger.debug("Releasing body, not yet subscribed");
}
this.bodyIntern()
.doOnNext(byteBuf -> {})
.subscribe(byteBuf -> {}, ex -> {});
}
}
} |
This function is executed when the flux completes with an error | public static void deleteTwins() throws IOException, InterruptedException {
System.out.println("DELETE DIGITAL TWINS");
Map<String, String> twins = FileHelper.loadAllFilesInPath(TwinsPath);
final Semaphore deleteTwinsSemaphore = new Semaphore(0);
final Semaphore deleteRelationshipsSemaphore = new Semaphore(0);
twins
.forEach((twinId, twinContent) -> {
client.listRelationships(twinId, BasicRelationship.class)
.doOnComplete(deleteRelationshipsSemaphore::release)
.doOnError(throwable -> {
if (throwable instanceof ErrorResponseException && ((ErrorResponseException) throwable).getResponse().getStatusCode() == HttpStatus.SC_NOT_FOUND) {
deleteRelationshipsSemaphore.release();
} else {
System.err.println("List relationships error: " + throwable);
}
})
.subscribe(
relationship -> client.deleteRelationship(twinId, relationship.getId())
.subscribe(
aVoid -> System.out.println("Found and deleted relationship: " + relationship.getId()),
throwable -> System.err.println("Delete relationship error: " + throwable)
));
client.listIncomingRelationships(twinId)
.doOnComplete(deleteRelationshipsSemaphore::release)
.doOnError(throwable -> {
if (throwable instanceof ErrorResponseException && ((ErrorResponseException) throwable).getResponse().getStatusCode() == HttpStatus.SC_NOT_FOUND) {
deleteRelationshipsSemaphore.release();
} else {
System.err.println("List relationships error: " + throwable);
}
})
.subscribe(
incomingRelationship -> client.deleteRelationship(incomingRelationship.getSourceId(), incomingRelationship.getRelationshipId())
.subscribe(
aVoid -> System.out.println("Found and deleted incoming relationship: " + incomingRelationship.getRelationshipId()),
throwable -> System.err.println("Delete relationship error: " + throwable)
));
try {
if (deleteRelationshipsSemaphore.tryAcquire(2, MaxWaitTimeAsyncOperationsInSeconds, TimeUnit.SECONDS)) {
client.deleteDigitalTwin(twinId)
.doOnSuccess(aVoid -> {
System.out.println("Deleted digital twin: " + twinId);
deleteTwinsSemaphore.release();
})
.doOnError(throwable -> {
if (throwable instanceof ErrorResponseException && ((ErrorResponseException) throwable).getResponse().getStatusCode() == HttpStatus.SC_NOT_FOUND) {
deleteTwinsSemaphore.release();
} else {
System.err.println("Could not delete digital twin " + twinId + " due to " + throwable);
}
})
.subscribe();
}
} catch (InterruptedException e) {
throw new RuntimeException("Could not cleanup the pre-existing resources: ", e);
}
});
boolean created = deleteTwinsSemaphore.tryAcquire(twins.size(), MaxWaitTimeAsyncOperationsInSeconds, TimeUnit.SECONDS);
System.out.println("Twins deleted: " + created);
} | .doOnError(throwable -> { | public static void deleteTwins() throws IOException, InterruptedException {
System.out.println("DELETE DIGITAL TWINS");
Map<String, String> twins = FileHelper.loadAllFilesInPath(TwinsPath);
final Semaphore deleteTwinsSemaphore = new Semaphore(0);
twins
.forEach((twinId, twinContent) -> client.deleteDigitalTwin(twinId)
.doOnSuccess(aVoid -> System.out.println("Deleted digital twin: " + twinId))
.doOnError(throwable -> {
if (!(throwable instanceof ErrorResponseException) || !((ErrorResponseException) throwable).getValue().getError().getCode().equals("DigitalTwinNotFound")) {
System.err.println("Could not delete digital twin " + twinId + " due to " + throwable);
}
})
.doOnTerminate(deleteTwinsSemaphore::release)
.subscribe());
boolean created = deleteTwinsSemaphore.tryAcquire(twins.size(), MaxWaitTimeAsyncOperationsInSeconds, TimeUnit.SECONDS);
System.out.println("Twins deleted: " + created);
} | class DigitalTwinsLifecycleSample {
private static final String tenantId = System.getenv("TENANT_ID");
private static final String clientId = System.getenv("CLIENT_ID");
private static final String clientSecret = System.getenv("CLIENT_SECRET");
private static final String endpoint = System.getenv("DIGITAL_TWINS_ENDPOINT");
private static final int MaxWaitTimeAsyncOperationsInSeconds = 10;
private static final URL DtdlDirectoryUrl = DigitalTwinsLifecycleSample.class.getClassLoader().getResource("DTDL");
private static final Path DtDlDirectoryPath;
private static final Path TwinsPath;
private static final Path ModelsPath;
private static final Path RelationshipsPath;
private static final DigitalTwinsAsyncClient client;
static {
try {
assert DtdlDirectoryUrl != null;
DtDlDirectoryPath = Paths.get(DtdlDirectoryUrl.toURI());
} catch (URISyntaxException e) {
throw new RuntimeException("Unable to convert the DTDL directory URL to URI", e);
}
TwinsPath = Paths.get(DtDlDirectoryPath.toString(), "DigitalTwins");
ModelsPath = Paths.get(DtDlDirectoryPath.toString(), "Models");
RelationshipsPath = Paths.get(DtDlDirectoryPath.toString(), "Relationships");
client = new DigitalTwinsClientBuilder()
.tokenCredential(
new ClientSecretCredentialBuilder()
.tenantId(tenantId)
.clientId(clientId)
.clientSecret(clientSecret)
.build()
)
.endpoint(endpoint)
.httpLogOptions(
new HttpLogOptions()
.setLogLevel(HttpLogDetailLevel.NONE))
.buildAsyncClient();
}
public static void main(String[] args) throws IOException, InterruptedException {
deleteTwins();
createTwins();
}
public static void createTwins() throws IOException, InterruptedException {
System.out.println("CREATE DIGITAL TWINS");
Map<String, String> twins = FileHelper.loadAllFilesInPath(TwinsPath);
final Semaphore createTwinsSemaphore = new Semaphore(0);
twins
.forEach((twinId, twinContent) -> client.createDigitalTwinWithResponse(twinId, twinContent)
.subscribe(
response -> System.out.println("Created digital twin: " + twinId + "\n\t Body: " + response.getValue()),
throwable -> System.err.println("Could not create digital twin " + twinId + " due to " + throwable),
createTwinsSemaphore::release));
boolean created = createTwinsSemaphore.tryAcquire(twins.size(), MaxWaitTimeAsyncOperationsInSeconds, TimeUnit.SECONDS);
System.out.println("Twins created: " + created);
}
} | class DigitalTwinsLifecycleSample {
private static final String tenantId = System.getenv("TENANT_ID");
private static final String clientId = System.getenv("CLIENT_ID");
private static final String clientSecret = System.getenv("CLIENT_SECRET");
private static final String endpoint = System.getenv("DIGITAL_TWINS_ENDPOINT");
private static final int MaxWaitTimeAsyncOperationsInSeconds = 10;
private static final URL DtdlDirectoryUrl = DigitalTwinsLifecycleSample.class.getClassLoader().getResource("DTDL");
private static final Path DtDlDirectoryPath;
private static final Path TwinsPath;
private static final Path ModelsPath;
private static final Path RelationshipsPath;
private static final DigitalTwinsAsyncClient client;
static {
try {
assert DtdlDirectoryUrl != null;
DtDlDirectoryPath = Paths.get(DtdlDirectoryUrl.toURI());
} catch (URISyntaxException e) {
System.err.println("Unable to convert the DTDL directory URL to URI: " + e);
throw new RuntimeException(e);
}
TwinsPath = Paths.get(DtDlDirectoryPath.toString(), "DigitalTwins");
ModelsPath = Paths.get(DtDlDirectoryPath.toString(), "Models");
RelationshipsPath = Paths.get(DtDlDirectoryPath.toString(), "Relationships");
client = new DigitalTwinsClientBuilder()
.tokenCredential(
new ClientSecretCredentialBuilder()
.tenantId(tenantId)
.clientId(clientId)
.clientSecret(clientSecret)
.build()
)
.endpoint(endpoint)
.httpLogOptions(
new HttpLogOptions()
.setLogLevel(HttpLogDetailLevel.NONE))
.buildAsyncClient();
}
public static void main(String[] args) throws IOException, InterruptedException {
deleteTwins();
createTwins();
}
public static void createTwins() throws IOException, InterruptedException {
System.out.println("CREATE DIGITAL TWINS");
Map<String, String> twins = FileHelper.loadAllFilesInPath(TwinsPath);
final Semaphore createTwinsSemaphore = new Semaphore(0);
twins
.forEach((twinId, twinContent) -> client.createDigitalTwinWithResponse(twinId, twinContent)
.doOnSuccess(response -> System.out.println("Created digital twin: " + twinId + "\n\t Body: " + response.getValue()))
.doOnError(throwable -> System.err.println("Could not create digital twin " + twinId + " due to " + throwable))
.doOnTerminate(createTwinsSemaphore::release)
.subscribe());
boolean created = createTwinsSemaphore.tryAcquire(twins.size(), MaxWaitTimeAsyncOperationsInSeconds, TimeUnit.SECONDS);
System.out.println("Twins created: " + created);
}
} |
To understand why do we need semaphore here? Do we have some limitations for parallel operations? | public static void createTwins() throws IOException, InterruptedException {
System.out.println("CREATE DIGITAL TWINS");
Map<String, String> twins = FileHelper.loadAllFilesInPath(TwinsPath);
final Semaphore createTwinsSemaphore = new Semaphore(0);
twins
.forEach((twinId, twinContent) -> client.createDigitalTwinWithResponse(twinId, twinContent)
.subscribe(
response -> System.out.println("Created digital twin: " + twinId + "\n\t Body: " + response.getValue()),
throwable -> System.err.println("Could not create digital twin " + twinId + " due to " + throwable),
createTwinsSemaphore::release));
boolean created = createTwinsSemaphore.tryAcquire(twins.size(), MaxWaitTimeAsyncOperationsInSeconds, TimeUnit.SECONDS);
System.out.println("Twins created: " + created);
} | final Semaphore createTwinsSemaphore = new Semaphore(0); | public static void createTwins() throws IOException, InterruptedException {
System.out.println("CREATE DIGITAL TWINS");
Map<String, String> twins = FileHelper.loadAllFilesInPath(TwinsPath);
final Semaphore createTwinsSemaphore = new Semaphore(0);
twins
.forEach((twinId, twinContent) -> client.createDigitalTwinWithResponse(twinId, twinContent)
.subscribe(
response -> System.out.println("Created digital twin: " + twinId + "\n\t Body: " + response.getValue()),
throwable -> System.err.println("Could not create digital twin " + twinId + " due to " + throwable),
createTwinsSemaphore::release));
boolean created = createTwinsSemaphore.tryAcquire(twins.size(), MaxWaitTimeAsyncOperationsInSeconds, TimeUnit.SECONDS);
System.out.println("Twins created: " + created);
} | class DigitalTwinsLifecycleAsyncSample {
private static final String tenantId = System.getenv("TENANT_ID");
private static final String clientId = System.getenv("CLIENT_ID");
private static final String clientSecret = System.getenv("CLIENT_SECRET");
private static final String endpoint = System.getenv("DIGITAL_TWINS_ENDPOINT");
private static final int MaxWaitTimeAsyncOperationsInSeconds = 10;
private static final URL DtdlDirectoryUrl = DigitalTwinsLifecycleAsyncSample.class.getClassLoader().getResource("DTDL");
private static final Path DtDlDirectoryPath;
private static final Path TwinsPath;
private static final Path ModelsPath;
private static final Path RelationshipsPath;
private static final DigitalTwinsAsyncClient client;
static {
try {
assert DtdlDirectoryUrl != null;
DtDlDirectoryPath = Paths.get(DtdlDirectoryUrl.toURI());
} catch (URISyntaxException e) {
throw new RuntimeException("Unable to convert the DTDL directory URL to URI", e);
}
TwinsPath = Paths.get(DtDlDirectoryPath.toString(), "DigitalTwins");
ModelsPath = Paths.get(DtDlDirectoryPath.toString(), "Models");
RelationshipsPath = Paths.get(DtDlDirectoryPath.toString(), "Relationships");
client = new DigitalTwinsClientBuilder()
.tokenCredential(
new ClientSecretCredentialBuilder()
.tenantId(tenantId)
.clientId(clientId)
.clientSecret(clientSecret)
.build()
)
.endpoint(endpoint)
.httpLogOptions(
new HttpLogOptions()
.setLogLevel(HttpLogDetailLevel.NONE))
.buildAsyncClient();
}
public static void main(String[] args) throws IOException, InterruptedException {
deleteTwins();
createTwins();
}
/**
* Delete a twin, and any relationships it might have.
* @throws IOException If an I/O error is thrown when accessing the starting file.
* @throws InterruptedException If the current thread is interrupted while waiting to acquire permits on a semaphore.
*/
public static void deleteTwins() throws IOException, InterruptedException {
System.out.println("DELETE DIGITAL TWINS");
Map<String, String> twins = FileHelper.loadAllFilesInPath(TwinsPath);
final Semaphore deleteTwinsSemaphore = new Semaphore(0);
final Semaphore deleteRelationshipsSemaphore = new Semaphore(0);
twins
.forEach((twinId, twinContent) -> {
client.listRelationships(twinId, BasicRelationship.class)
.doOnComplete(deleteRelationshipsSemaphore::release)
.doOnError(throwable -> {
if (throwable instanceof ErrorResponseException && ((ErrorResponseException) throwable).getResponse().getStatusCode() == HttpStatus.SC_NOT_FOUND) {
deleteRelationshipsSemaphore.release();
} else {
System.err.println("List relationships error: " + throwable);
}
})
.subscribe(
relationship -> client.deleteRelationship(twinId, relationship.getId())
.subscribe(
aVoid -> System.out.println("Found and deleted relationship: " + relationship.getId()),
throwable -> System.err.println("Delete relationship error: " + throwable)
));
client.listIncomingRelationships(twinId)
.doOnComplete(deleteRelationshipsSemaphore::release)
.doOnError(throwable -> {
if (throwable instanceof ErrorResponseException && ((ErrorResponseException) throwable).getResponse().getStatusCode() == HttpStatus.SC_NOT_FOUND) {
deleteRelationshipsSemaphore.release();
} else {
System.err.println("List incoming relationships error: " + throwable);
}
})
.subscribe(
incomingRelationship -> client.deleteRelationship(incomingRelationship.getSourceId(), incomingRelationship.getRelationshipId())
.subscribe(
aVoid -> System.out.println("Found and deleted incoming relationship: " + incomingRelationship.getRelationshipId()),
throwable -> System.err.println("Delete incoming relationship error: " + throwable)
));
try {
if (deleteRelationshipsSemaphore.tryAcquire(2, MaxWaitTimeAsyncOperationsInSeconds, TimeUnit.SECONDS)) {
client.deleteDigitalTwin(twinId)
.doOnSuccess(aVoid -> {
System.out.println("Deleted digital twin: " + twinId);
deleteTwinsSemaphore.release();
})
.doOnError(throwable -> {
if (throwable instanceof ErrorResponseException && ((ErrorResponseException) throwable).getResponse().getStatusCode() == HttpStatus.SC_NOT_FOUND) {
deleteTwinsSemaphore.release();
} else {
System.err.println("Could not delete digital twin " + twinId + " due to " + throwable);
}
})
.subscribe();
}
} catch (InterruptedException e) {
throw new RuntimeException("Could not cleanup the pre-existing resources: ", e);
}
});
boolean created = deleteTwinsSemaphore.tryAcquire(twins.size(), MaxWaitTimeAsyncOperationsInSeconds, TimeUnit.SECONDS);
System.out.println("Twins deleted: " + created);
}
/**
* Creates all twins specified in the DTDL->DigitalTwins directory.
* @throws IOException If an I/O error is thrown when accessing the starting file.
* @throws InterruptedException If the current thread is interrupted while waiting to acquire permits on a semaphore.
*/
} | class DigitalTwinsLifecycleAsyncSample {
private static final String tenantId = System.getenv("TENANT_ID");
private static final String clientId = System.getenv("CLIENT_ID");
private static final String clientSecret = System.getenv("CLIENT_SECRET");
private static final String endpoint = System.getenv("DIGITAL_TWINS_ENDPOINT");
private static final int MaxWaitTimeAsyncOperationsInSeconds = 10;
private static final URL DtdlDirectoryUrl = DigitalTwinsLifecycleAsyncSample.class.getClassLoader().getResource("DTDL");
private static final Path DtDlDirectoryPath;
private static final Path TwinsPath;
private static final Path ModelsPath;
private static final Path RelationshipsPath;
private static final DigitalTwinsAsyncClient client;
static {
try {
assert DtdlDirectoryUrl != null;
DtDlDirectoryPath = Paths.get(DtdlDirectoryUrl.toURI());
} catch (URISyntaxException e) {
throw new RuntimeException("Unable to convert the DTDL directory URL to URI", e);
}
TwinsPath = Paths.get(DtDlDirectoryPath.toString(), "DigitalTwins");
ModelsPath = Paths.get(DtDlDirectoryPath.toString(), "Models");
RelationshipsPath = Paths.get(DtDlDirectoryPath.toString(), "Relationships");
client = new DigitalTwinsClientBuilder()
.tokenCredential(
new ClientSecretCredentialBuilder()
.tenantId(tenantId)
.clientId(clientId)
.clientSecret(clientSecret)
.build()
)
.endpoint(endpoint)
.httpLogOptions(
new HttpLogOptions()
.setLogLevel(HttpLogDetailLevel.NONE))
.buildAsyncClient();
}
public static void main(String[] args) throws IOException, InterruptedException {
deleteTwins();
createTwins();
}
/**
* Delete a twin, and any relationships it might have.
* @throws IOException If an I/O error is thrown when accessing the starting file.
* @throws InterruptedException If the current thread is interrupted while waiting to acquire permits on a semaphore.
*/
public static void deleteTwins() throws IOException, InterruptedException {
System.out.println("DELETE DIGITAL TWINS");
Map<String, String> twins = FileHelper.loadAllFilesInPath(TwinsPath);
final Semaphore deleteTwinsSemaphore = new Semaphore(0);
final Semaphore deleteRelationshipsSemaphore = new Semaphore(0);
twins
.forEach((twinId, twinContent) -> {
client.listRelationships(twinId, BasicRelationship.class)
.doOnComplete(deleteRelationshipsSemaphore::release)
.doOnError(throwable -> {
if (throwable instanceof ErrorResponseException && ((ErrorResponseException) throwable).getResponse().getStatusCode() == HttpStatus.SC_NOT_FOUND) {
deleteRelationshipsSemaphore.release();
} else {
System.err.println("List relationships error: " + throwable);
}
})
.subscribe(
relationship -> client.deleteRelationship(twinId, relationship.getId())
.subscribe(
aVoid -> System.out.println("Found and deleted relationship: " + relationship.getId()),
throwable -> System.err.println("Delete relationship error: " + throwable)
));
client.listIncomingRelationships(twinId)
.doOnComplete(deleteRelationshipsSemaphore::release)
.doOnError(throwable -> {
if (throwable instanceof ErrorResponseException && ((ErrorResponseException) throwable).getResponse().getStatusCode() == HttpStatus.SC_NOT_FOUND) {
deleteRelationshipsSemaphore.release();
} else {
System.err.println("List incoming relationships error: " + throwable);
}
})
.subscribe(
incomingRelationship -> client.deleteRelationship(incomingRelationship.getSourceId(), incomingRelationship.getRelationshipId())
.subscribe(
aVoid -> System.out.println("Found and deleted incoming relationship: " + incomingRelationship.getRelationshipId()),
throwable -> System.err.println("Delete incoming relationship error: " + throwable)
));
try {
if (deleteRelationshipsSemaphore.tryAcquire(2, MaxWaitTimeAsyncOperationsInSeconds, TimeUnit.SECONDS)) {
client.deleteDigitalTwin(twinId)
.doOnSuccess(aVoid -> {
System.out.println("Deleted digital twin: " + twinId);
deleteTwinsSemaphore.release();
})
.doOnError(throwable -> {
if (throwable instanceof ErrorResponseException && ((ErrorResponseException) throwable).getResponse().getStatusCode() == HttpStatus.SC_NOT_FOUND) {
deleteTwinsSemaphore.release();
} else {
System.err.println("Could not delete digital twin " + twinId + " due to " + throwable);
}
})
.subscribe();
}
} catch (InterruptedException e) {
throw new RuntimeException("Could not cleanup the pre-existing resources: ", e);
}
});
boolean created = deleteTwinsSemaphore.tryAcquire(twins.size(), MaxWaitTimeAsyncOperationsInSeconds, TimeUnit.SECONDS);
System.out.println("Twins deleted: " + created);
}
/**
* Creates all twins specified in the DTDL->DigitalTwins directory.
* @throws IOException If an I/O error is thrown when accessing the starting file.
* @throws InterruptedException If the current thread is interrupted while waiting to acquire permits on a semaphore.
*/
} |
No, not really. The semaphore is to ensure that we do not exit before the async operation has completed. We start all async operations and then release the semaphore only once the async call has completed. That way, the subsequent operations are executed after the previous call has completed -> similar to doing a await on a Task. | public static void createTwins() throws IOException, InterruptedException {
System.out.println("CREATE DIGITAL TWINS");
Map<String, String> twins = FileHelper.loadAllFilesInPath(TwinsPath);
final Semaphore createTwinsSemaphore = new Semaphore(0);
twins
.forEach((twinId, twinContent) -> client.createDigitalTwinWithResponse(twinId, twinContent)
.subscribe(
response -> System.out.println("Created digital twin: " + twinId + "\n\t Body: " + response.getValue()),
throwable -> System.err.println("Could not create digital twin " + twinId + " due to " + throwable),
createTwinsSemaphore::release));
boolean created = createTwinsSemaphore.tryAcquire(twins.size(), MaxWaitTimeAsyncOperationsInSeconds, TimeUnit.SECONDS);
System.out.println("Twins created: " + created);
} | final Semaphore createTwinsSemaphore = new Semaphore(0); | public static void createTwins() throws IOException, InterruptedException {
System.out.println("CREATE DIGITAL TWINS");
Map<String, String> twins = FileHelper.loadAllFilesInPath(TwinsPath);
final Semaphore createTwinsSemaphore = new Semaphore(0);
twins
.forEach((twinId, twinContent) -> client.createDigitalTwinWithResponse(twinId, twinContent)
.subscribe(
response -> System.out.println("Created digital twin: " + twinId + "\n\t Body: " + response.getValue()),
throwable -> System.err.println("Could not create digital twin " + twinId + " due to " + throwable),
createTwinsSemaphore::release));
boolean created = createTwinsSemaphore.tryAcquire(twins.size(), MaxWaitTimeAsyncOperationsInSeconds, TimeUnit.SECONDS);
System.out.println("Twins created: " + created);
} | class DigitalTwinsLifecycleAsyncSample {
private static final String tenantId = System.getenv("TENANT_ID");
private static final String clientId = System.getenv("CLIENT_ID");
private static final String clientSecret = System.getenv("CLIENT_SECRET");
private static final String endpoint = System.getenv("DIGITAL_TWINS_ENDPOINT");
private static final int MaxWaitTimeAsyncOperationsInSeconds = 10;
private static final URL DtdlDirectoryUrl = DigitalTwinsLifecycleAsyncSample.class.getClassLoader().getResource("DTDL");
private static final Path DtDlDirectoryPath;
private static final Path TwinsPath;
private static final Path ModelsPath;
private static final Path RelationshipsPath;
private static final DigitalTwinsAsyncClient client;
static {
try {
assert DtdlDirectoryUrl != null;
DtDlDirectoryPath = Paths.get(DtdlDirectoryUrl.toURI());
} catch (URISyntaxException e) {
throw new RuntimeException("Unable to convert the DTDL directory URL to URI", e);
}
TwinsPath = Paths.get(DtDlDirectoryPath.toString(), "DigitalTwins");
ModelsPath = Paths.get(DtDlDirectoryPath.toString(), "Models");
RelationshipsPath = Paths.get(DtDlDirectoryPath.toString(), "Relationships");
client = new DigitalTwinsClientBuilder()
.tokenCredential(
new ClientSecretCredentialBuilder()
.tenantId(tenantId)
.clientId(clientId)
.clientSecret(clientSecret)
.build()
)
.endpoint(endpoint)
.httpLogOptions(
new HttpLogOptions()
.setLogLevel(HttpLogDetailLevel.NONE))
.buildAsyncClient();
}
public static void main(String[] args) throws IOException, InterruptedException {
deleteTwins();
createTwins();
}
/**
* Delete a twin, and any relationships it might have.
* @throws IOException If an I/O error is thrown when accessing the starting file.
* @throws InterruptedException If the current thread is interrupted while waiting to acquire permits on a semaphore.
*/
public static void deleteTwins() throws IOException, InterruptedException {
System.out.println("DELETE DIGITAL TWINS");
Map<String, String> twins = FileHelper.loadAllFilesInPath(TwinsPath);
final Semaphore deleteTwinsSemaphore = new Semaphore(0);
final Semaphore deleteRelationshipsSemaphore = new Semaphore(0);
twins
.forEach((twinId, twinContent) -> {
client.listRelationships(twinId, BasicRelationship.class)
.doOnComplete(deleteRelationshipsSemaphore::release)
.doOnError(throwable -> {
if (throwable instanceof ErrorResponseException && ((ErrorResponseException) throwable).getResponse().getStatusCode() == HttpStatus.SC_NOT_FOUND) {
deleteRelationshipsSemaphore.release();
} else {
System.err.println("List relationships error: " + throwable);
}
})
.subscribe(
relationship -> client.deleteRelationship(twinId, relationship.getId())
.subscribe(
aVoid -> System.out.println("Found and deleted relationship: " + relationship.getId()),
throwable -> System.err.println("Delete relationship error: " + throwable)
));
client.listIncomingRelationships(twinId)
.doOnComplete(deleteRelationshipsSemaphore::release)
.doOnError(throwable -> {
if (throwable instanceof ErrorResponseException && ((ErrorResponseException) throwable).getResponse().getStatusCode() == HttpStatus.SC_NOT_FOUND) {
deleteRelationshipsSemaphore.release();
} else {
System.err.println("List incoming relationships error: " + throwable);
}
})
.subscribe(
incomingRelationship -> client.deleteRelationship(incomingRelationship.getSourceId(), incomingRelationship.getRelationshipId())
.subscribe(
aVoid -> System.out.println("Found and deleted incoming relationship: " + incomingRelationship.getRelationshipId()),
throwable -> System.err.println("Delete incoming relationship error: " + throwable)
));
try {
if (deleteRelationshipsSemaphore.tryAcquire(2, MaxWaitTimeAsyncOperationsInSeconds, TimeUnit.SECONDS)) {
client.deleteDigitalTwin(twinId)
.doOnSuccess(aVoid -> {
System.out.println("Deleted digital twin: " + twinId);
deleteTwinsSemaphore.release();
})
.doOnError(throwable -> {
if (throwable instanceof ErrorResponseException && ((ErrorResponseException) throwable).getResponse().getStatusCode() == HttpStatus.SC_NOT_FOUND) {
deleteTwinsSemaphore.release();
} else {
System.err.println("Could not delete digital twin " + twinId + " due to " + throwable);
}
})
.subscribe();
}
} catch (InterruptedException e) {
throw new RuntimeException("Could not cleanup the pre-existing resources: ", e);
}
});
boolean created = deleteTwinsSemaphore.tryAcquire(twins.size(), MaxWaitTimeAsyncOperationsInSeconds, TimeUnit.SECONDS);
System.out.println("Twins deleted: " + created);
}
/**
* Creates all twins specified in the DTDL->DigitalTwins directory.
* @throws IOException If an I/O error is thrown when accessing the starting file.
* @throws InterruptedException If the current thread is interrupted while waiting to acquire permits on a semaphore.
*/
} | class DigitalTwinsLifecycleAsyncSample {
private static final String tenantId = System.getenv("TENANT_ID");
private static final String clientId = System.getenv("CLIENT_ID");
private static final String clientSecret = System.getenv("CLIENT_SECRET");
private static final String endpoint = System.getenv("DIGITAL_TWINS_ENDPOINT");
private static final int MaxWaitTimeAsyncOperationsInSeconds = 10;
private static final URL DtdlDirectoryUrl = DigitalTwinsLifecycleAsyncSample.class.getClassLoader().getResource("DTDL");
private static final Path DtDlDirectoryPath;
private static final Path TwinsPath;
private static final Path ModelsPath;
private static final Path RelationshipsPath;
private static final DigitalTwinsAsyncClient client;
static {
try {
assert DtdlDirectoryUrl != null;
DtDlDirectoryPath = Paths.get(DtdlDirectoryUrl.toURI());
} catch (URISyntaxException e) {
throw new RuntimeException("Unable to convert the DTDL directory URL to URI", e);
}
TwinsPath = Paths.get(DtDlDirectoryPath.toString(), "DigitalTwins");
ModelsPath = Paths.get(DtDlDirectoryPath.toString(), "Models");
RelationshipsPath = Paths.get(DtDlDirectoryPath.toString(), "Relationships");
client = new DigitalTwinsClientBuilder()
.tokenCredential(
new ClientSecretCredentialBuilder()
.tenantId(tenantId)
.clientId(clientId)
.clientSecret(clientSecret)
.build()
)
.endpoint(endpoint)
.httpLogOptions(
new HttpLogOptions()
.setLogLevel(HttpLogDetailLevel.NONE))
.buildAsyncClient();
}
public static void main(String[] args) throws IOException, InterruptedException {
deleteTwins();
createTwins();
}
/**
* Delete a twin, and any relationships it might have.
* @throws IOException If an I/O error is thrown when accessing the starting file.
* @throws InterruptedException If the current thread is interrupted while waiting to acquire permits on a semaphore.
*/
public static void deleteTwins() throws IOException, InterruptedException {
System.out.println("DELETE DIGITAL TWINS");
Map<String, String> twins = FileHelper.loadAllFilesInPath(TwinsPath);
final Semaphore deleteTwinsSemaphore = new Semaphore(0);
final Semaphore deleteRelationshipsSemaphore = new Semaphore(0);
twins
.forEach((twinId, twinContent) -> {
client.listRelationships(twinId, BasicRelationship.class)
.doOnComplete(deleteRelationshipsSemaphore::release)
.doOnError(throwable -> {
if (throwable instanceof ErrorResponseException && ((ErrorResponseException) throwable).getResponse().getStatusCode() == HttpStatus.SC_NOT_FOUND) {
deleteRelationshipsSemaphore.release();
} else {
System.err.println("List relationships error: " + throwable);
}
})
.subscribe(
relationship -> client.deleteRelationship(twinId, relationship.getId())
.subscribe(
aVoid -> System.out.println("Found and deleted relationship: " + relationship.getId()),
throwable -> System.err.println("Delete relationship error: " + throwable)
));
client.listIncomingRelationships(twinId)
.doOnComplete(deleteRelationshipsSemaphore::release)
.doOnError(throwable -> {
if (throwable instanceof ErrorResponseException && ((ErrorResponseException) throwable).getResponse().getStatusCode() == HttpStatus.SC_NOT_FOUND) {
deleteRelationshipsSemaphore.release();
} else {
System.err.println("List incoming relationships error: " + throwable);
}
})
.subscribe(
incomingRelationship -> client.deleteRelationship(incomingRelationship.getSourceId(), incomingRelationship.getRelationshipId())
.subscribe(
aVoid -> System.out.println("Found and deleted incoming relationship: " + incomingRelationship.getRelationshipId()),
throwable -> System.err.println("Delete incoming relationship error: " + throwable)
));
try {
if (deleteRelationshipsSemaphore.tryAcquire(2, MaxWaitTimeAsyncOperationsInSeconds, TimeUnit.SECONDS)) {
client.deleteDigitalTwin(twinId)
.doOnSuccess(aVoid -> {
System.out.println("Deleted digital twin: " + twinId);
deleteTwinsSemaphore.release();
})
.doOnError(throwable -> {
if (throwable instanceof ErrorResponseException && ((ErrorResponseException) throwable).getResponse().getStatusCode() == HttpStatus.SC_NOT_FOUND) {
deleteTwinsSemaphore.release();
} else {
System.err.println("Could not delete digital twin " + twinId + " due to " + throwable);
}
})
.subscribe();
}
} catch (InterruptedException e) {
throw new RuntimeException("Could not cleanup the pre-existing resources: ", e);
}
});
boolean created = deleteTwinsSemaphore.tryAcquire(twins.size(), MaxWaitTimeAsyncOperationsInSeconds, TimeUnit.SECONDS);
System.out.println("Twins deleted: " + created);
}
/**
* Creates all twins specified in the DTDL->DigitalTwins directory.
* @throws IOException If an I/O error is thrown when accessing the starting file.
* @throws InterruptedException If the current thread is interrupted while waiting to acquire permits on a semaphore.
*/
} |
`.map(Response::getValue)` returns null, which is not a valid return item from a Mono. So we need to map it to `Mono.empty()` instead. | public Mono<Void> deleteModel(String modelId) {
return deleteModelWithResponse(modelId)
.flatMap(voidResponse -> Mono.empty());
} | .flatMap(voidResponse -> Mono.empty()); | public Mono<Void> deleteModel(String modelId) {
return deleteModelWithResponse(modelId)
.flatMap(voidResponse -> Mono.empty());
} | class to convert the relationship to.
* @param <T> The generic type to convert the relationship to.
* @return A {@link PagedFlux} | class to convert the relationship to.
* @param <T> The generic type to convert the relationship to.
* @return A {@link PagedFlux} |
This implementation is very long and verbose. I am trying to see how I could chain the list and delete operations together, I'll put up an update in the next PR. | public static void deleteTwins() throws IOException, InterruptedException {
System.out.println("DELETE DIGITAL TWINS");
Map<String, String> twins = FileHelper.loadAllFilesInPath(TwinsPath);
for (Map.Entry<String, String> twin : twins.entrySet()) {
String twinId = twin.getKey();
List<BasicRelationship> relationshipList = new ArrayList<>();
Semaphore listRelationshipSemaphore = new Semaphore(0);
Semaphore deleteRelationshipsSemaphore = new Semaphore(0);
CountDownLatch deleteTwinsLatch = new CountDownLatch(1);
client.listRelationships(twinId, BasicRelationship.class)
.doOnNext(relationshipList::add)
.doOnError(throwable -> {
if (!(throwable instanceof ErrorResponseException) || ((ErrorResponseException) throwable).getResponse().getStatusCode() != HttpStatus.SC_NOT_FOUND) {
System.err.println("List relationships error: " + throwable);
}
})
.doOnTerminate(listRelationshipSemaphore::release)
.subscribe();
client.listIncomingRelationships(twinId)
.doOnNext(e -> relationshipList.add(mapper.convertValue(e, BasicRelationship.class)))
.doOnError(throwable -> {
if (!(throwable instanceof ErrorResponseException) || ((ErrorResponseException) throwable).getResponse().getStatusCode() != HttpStatus.SC_NOT_FOUND) {
System.err.println("List incoming relationships error: " + throwable);
}
})
.doOnTerminate(listRelationshipSemaphore::release)
.subscribe();
if (listRelationshipSemaphore.tryAcquire(2, MaxWaitTimeAsyncOperationsInSeconds, TimeUnit.SECONDS)) {
relationshipList
.forEach(relationship -> client.deleteRelationship(relationship.getSourceId(), relationship.getId())
.doOnSuccess(aVoid -> {
if (twinId.equals(relationship.getSourceId())) {
System.out.println("Found and deleted relationship: " + relationship.getId());
} else {
System.out.println("Found and deleted incoming relationship: " + relationship.getId());
}
})
.doOnError(throwable -> {
if (!(throwable instanceof ErrorResponseException) || ((ErrorResponseException) throwable).getResponse().getStatusCode() != HttpStatus.SC_NOT_FOUND) {
System.err.println("List relationships error: " + throwable);
}
})
.doOnTerminate(deleteRelationshipsSemaphore::release)
.subscribe());
}
if (deleteRelationshipsSemaphore.tryAcquire(relationshipList.size(), MaxWaitTimeAsyncOperationsInSeconds, TimeUnit.SECONDS)) {
client.deleteDigitalTwin(twinId)
.doOnSuccess(aVoid -> System.out.println("Deleted digital twin: " + twinId))
.doOnError(throwable -> {
if (!(throwable instanceof ErrorResponseException) || ((ErrorResponseException) throwable).getResponse().getStatusCode() != HttpStatus.SC_NOT_FOUND) {
System.err.println("Delete twin error: " + throwable);
}
})
.doOnTerminate(deleteTwinsLatch::countDown)
.subscribe();
deleteTwinsLatch.await(MaxWaitTimeAsyncOperationsInSeconds, TimeUnit.SECONDS);
}
}
} | public static void deleteTwins() throws IOException, InterruptedException {
System.out.println("DELETE DIGITAL TWINS");
Map<String, String> twins = FileHelper.loadAllFilesInPath(TwinsPath);
for (Map.Entry<String, String> twin : twins.entrySet()) {
String twinId = twin.getKey();
List<BasicRelationship> relationshipList = Collections.synchronizedList(new ArrayList<>());
Semaphore listRelationshipSemaphore = new Semaphore(0);
Semaphore deleteRelationshipsSemaphore = new Semaphore(0);
CountDownLatch deleteTwinsLatch = new CountDownLatch(1);
client.listRelationships(twinId, BasicRelationship.class)
.doOnNext(relationshipList::add)
.doOnError(IgnoreNotFoundError)
.doOnTerminate(listRelationshipSemaphore::release)
.subscribe();
client.listIncomingRelationships(twinId)
.doOnNext(e -> relationshipList.add(mapper.convertValue(e, BasicRelationship.class)))
.doOnError(IgnoreNotFoundError)
.doOnTerminate(listRelationshipSemaphore::release)
.subscribe();
if (listRelationshipSemaphore.tryAcquire(2, MaxWaitTimeAsyncOperationsInSeconds, TimeUnit.SECONDS)) {
relationshipList
.forEach(relationship -> client.deleteRelationship(relationship.getSourceId(), relationship.getId())
.doOnSuccess(aVoid -> {
if (twinId.equals(relationship.getSourceId())) {
System.out.println("Found and deleted relationship: " + relationship.getId());
} else {
System.out.println("Found and deleted incoming relationship: " + relationship.getId());
}
})
.doOnError(IgnoreNotFoundError)
.doOnTerminate(deleteRelationshipsSemaphore::release)
.subscribe());
}
if (deleteRelationshipsSemaphore.tryAcquire(relationshipList.size(), MaxWaitTimeAsyncOperationsInSeconds, TimeUnit.SECONDS)) {
client.deleteDigitalTwin(twinId)
.doOnSuccess(aVoid -> System.out.println("Deleted digital twin: " + twinId))
.doOnError(IgnoreNotFoundError)
.doOnTerminate(deleteTwinsLatch::countDown)
.subscribe();
deleteTwinsLatch.await(MaxWaitTimeAsyncOperationsInSeconds, TimeUnit.SECONDS);
}
}
} | class DigitalTwinsLifecycleAsyncSample {
private static final String tenantId = System.getenv("TENANT_ID");
private static final String clientId = System.getenv("CLIENT_ID");
private static final String clientSecret = System.getenv("CLIENT_SECRET");
private static final String endpoint = System.getenv("DIGITAL_TWINS_ENDPOINT");
private static final int MaxWaitTimeAsyncOperationsInSeconds = 10;
private static final ObjectMapper mapper = new ObjectMapper();
private static final URL DtdlDirectoryUrl = DigitalTwinsLifecycleAsyncSample.class.getClassLoader().getResource("DTDL");
private static final Path DtDlDirectoryPath;
private static final Path TwinsPath;
private static final Path ModelsPath;
private static final Path RelationshipsPath;
private static final DigitalTwinsAsyncClient client;
static {
try {
assert DtdlDirectoryUrl != null;
DtDlDirectoryPath = Paths.get(DtdlDirectoryUrl.toURI());
} catch (URISyntaxException e) {
throw new RuntimeException("Unable to convert the DTDL directory URL to URI", e);
}
TwinsPath = Paths.get(DtDlDirectoryPath.toString(), "DigitalTwins");
ModelsPath = Paths.get(DtDlDirectoryPath.toString(), "Models");
RelationshipsPath = Paths.get(DtDlDirectoryPath.toString(), "Relationships");
client = new DigitalTwinsClientBuilder()
.tokenCredential(
new ClientSecretCredentialBuilder()
.tenantId(tenantId)
.clientId(clientId)
.clientSecret(clientSecret)
.build()
)
.endpoint(endpoint)
.httpLogOptions(
new HttpLogOptions()
.setLogLevel(HttpLogDetailLevel.NONE))
.buildAsyncClient();
}
public static void main(String[] args) throws IOException, InterruptedException {
deleteTwins();
deleteAllModels();
createAllModels();
listAllModels();
createAllTwins();
connectTwinsTogether();
}
/**
* Delete a twin, and any relationships it might have.
* @throws IOException If an I/O error is thrown when accessing the starting file.
* @throws InterruptedException If the current thread is interrupted while waiting to acquire latch.
*/
/**
* Delete models created by FullLifecycleSample for the ADT service instance.
* @throws InterruptedException If the current thread is interrupted while waiting to acquire latch.
*/
public static void deleteAllModels() throws InterruptedException {
System.out.println("DELETING MODELS");
List<String> models = asList(RoomModelId, WifiModelId, BuildingModelId, FloorModelId, HvacModelId);
models
.forEach(modelId -> {
try {
client.deleteModel(modelId).block();
System.out.println("Deleted model: " + modelId);
} catch (ErrorResponseException ex) {
if (ex.getResponse().getStatusCode() != HttpStatus.SC_NOT_FOUND) {
System.err.println("Could not delete model " + modelId + " due to " + ex);
}
}
});
}
/**
* Loads all the models found in the Models directory into memory and uses CreateModelsAsync API to create all the models in the ADT service instance.
* @throws IOException If an I/O error is thrown when accessing the starting file.
* @throws InterruptedException If the current thread is interrupted while waiting to acquire latch.
*/
public static void createAllModels() throws IOException, InterruptedException {
System.out.println("CREATING MODELS");
List<String> modelsToCreate = new ArrayList<>(FileHelper.loadAllFilesInPath(ModelsPath).values());
final CountDownLatch createModelsLatch = new CountDownLatch(1);
client.createModels(modelsToCreate)
.doOnNext(modelData -> System.out.println("Created model: " + modelData.getId()))
.doOnError(throwable -> {
if (!(throwable instanceof ErrorResponseException) || ((ErrorResponseException) throwable).getResponse().getStatusCode() != HttpStatus.SC_CONFLICT) {
System.err.println("Create models error: " + throwable);
}
})
.doOnTerminate(createModelsLatch::countDown)
.subscribe();
boolean created = createModelsLatch.await(MaxWaitTimeAsyncOperationsInSeconds, TimeUnit.SECONDS);
System.out.println("Models created: " + created);
}
/**
* Gets all the models within the ADT service instance.
* @throws InterruptedException If the current thread is interrupted while waiting to acquire latch.
*/
public static void listAllModels() throws InterruptedException {
System.out.println("LISTING MODELS");
final CountDownLatch listModelsLatch = new CountDownLatch(1);
client.listModels()
.doOnNext(modelData -> System.out.println(String.format("Retrieved model: %s, display name '%s', upload time '%s' and decommissioned '%s'",
modelData.getId(), modelData.getDisplayName().get("en"), modelData.getUploadTime(), modelData.isDecommissioned())))
.doOnError(throwable -> System.err.println("List models error: " + throwable))
.doOnTerminate(listModelsLatch::countDown)
.subscribe();
boolean created = listModelsLatch.await(MaxWaitTimeAsyncOperationsInSeconds, TimeUnit.SECONDS);
System.out.println("Models retrieved: " + created);
}
/**
* Creates all twins specified in the DTDL->DigitalTwins directory.
* @throws IOException If an I/O error is thrown when accessing the starting file.
* @throws InterruptedException If the current thread is interrupted while waiting to acquire latch.
*/
public static void createAllTwins() throws IOException, InterruptedException {
System.out.println("CREATE DIGITAL TWINS");
Map<String, String> twins = FileHelper.loadAllFilesInPath(TwinsPath);
final CountDownLatch createTwinsLatch = new CountDownLatch(twins.size());
twins
.forEach((twinId, twinContent) -> client.createDigitalTwin(twinId, twinContent)
.subscribe(
twin -> System.out.println("Created digital twin: " + twinId + "\n\t Body: " + twin),
throwable -> System.err.println("Could not create digital twin " + twinId + " due to " + throwable),
createTwinsLatch::countDown));
boolean created = createTwinsLatch.await(MaxWaitTimeAsyncOperationsInSeconds, TimeUnit.SECONDS);
System.out.println("Twins created: " + created);
}
public static void connectTwinsTogether() throws IOException, InterruptedException {
System.out.println("CONNECT DIGITAL TWINS");
Map<String, String> allRelationships = FileHelper.loadAllFilesInPath(RelationshipsPath);
final CountDownLatch connectTwinsLatch = new CountDownLatch(4);
allRelationships.values().forEach(
relationshipContent -> {
try {
List<BasicRelationship> relationships = mapper.readValue(relationshipContent, new TypeReference<>() { });
relationships
.forEach(relationship -> {
try {
client.createRelationship(relationship.getSourceId(), relationship.getId(), mapper.writeValueAsString(relationship))
.doOnSuccess(s -> System.out.println("Linked twin " + relationship.getSourceId() + " to twin " + relationship.getTargetId() + " as " + relationship.getName()))
.doOnError(throwable -> {
if (!(throwable instanceof ErrorResponseException) || ((ErrorResponseException) throwable).getResponse().getStatusCode() != HttpStatus.SC_CONFLICT) {
System.err.println("Could not linked twin " + relationship.getSourceId() + " to twin " + relationship.getTargetId() + " as " + relationship.getName() +
" due to " + throwable);
}
})
.doOnTerminate(connectTwinsLatch::countDown)
.subscribe();
} catch (JsonProcessingException e) {
throw new RuntimeException("JsonProcessingException while serializing relationship string from BasicRelationship: ", e);
}
});
} catch (JsonProcessingException e) {
throw new RuntimeException("JsonProcessingException while deserializing relationship string to BasicRelationship: ", e);
}
}
);
boolean created = connectTwinsLatch.await(MaxWaitTimeAsyncOperationsInSeconds, TimeUnit.SECONDS);
System.out.println("Twins connected: " + created);
}
} | class DigitalTwinsLifecycleAsyncSample {
private static final String tenantId = System.getenv("TENANT_ID");
private static final String clientId = System.getenv("CLIENT_ID");
private static final String clientSecret = System.getenv("CLIENT_SECRET");
private static final String endpoint = System.getenv("DIGITAL_TWINS_ENDPOINT");
private static final int MaxWaitTimeAsyncOperationsInSeconds = 10;
private static final ObjectMapper mapper = new ObjectMapper();
private static final URL DtdlDirectoryUrl = DigitalTwinsLifecycleAsyncSample.class.getClassLoader().getResource("DTDL");
private static final Path DtDlDirectoryPath;
private static final Path TwinsPath;
private static final Path ModelsPath;
private static final Path RelationshipsPath;
private static final DigitalTwinsAsyncClient client;
static {
try {
assert DtdlDirectoryUrl != null;
DtDlDirectoryPath = Paths.get(DtdlDirectoryUrl.toURI());
} catch (URISyntaxException e) {
throw new RuntimeException("Unable to convert the DTDL directory URL to URI", e);
}
TwinsPath = Paths.get(DtDlDirectoryPath.toString(), "DigitalTwins");
ModelsPath = Paths.get(DtDlDirectoryPath.toString(), "Models");
RelationshipsPath = Paths.get(DtDlDirectoryPath.toString(), "Relationships");
client = new DigitalTwinsClientBuilder()
.tokenCredential(
new ClientSecretCredentialBuilder()
.tenantId(tenantId)
.clientId(clientId)
.clientSecret(clientSecret)
.build()
)
.endpoint(endpoint)
.httpLogOptions(
new HttpLogOptions()
.setLogLevel(HttpLogDetailLevel.NONE))
.buildAsyncClient();
}
public static void main(String[] args) throws IOException, InterruptedException {
deleteTwins();
deleteAllModels();
createAllModels();
listAllModels();
createAllTwins();
connectTwinsTogether();
}
/**
* Delete a twin, and any relationships it might have.
* @throws IOException If an I/O error is thrown when accessing the starting file.
* @throws InterruptedException If the current thread is interrupted while waiting to acquire latch.
*/
/**
* Delete models created by FullLifecycleSample for the ADT service instance.
* @throws InterruptedException If the current thread is interrupted while waiting to acquire latch.
*/
public static void deleteAllModels() throws InterruptedException {
System.out.println("DELETING MODELS");
List<String> models = asList(RoomModelId, WifiModelId, BuildingModelId, FloorModelId, HvacModelId);
models
.forEach(modelId -> {
try {
client.deleteModel(modelId).block();
System.out.println("Deleted model: " + modelId);
} catch (ErrorResponseException ex) {
if (ex.getResponse().getStatusCode() != HttpStatus.SC_NOT_FOUND) {
System.err.println("Could not delete model " + modelId + " due to " + ex);
}
}
});
}
/**
* Loads all the models found in the Models directory into memory and uses CreateModelsAsync API to create all the models in the ADT service instance.
* @throws IOException If an I/O error is thrown when accessing the starting file.
* @throws InterruptedException If the current thread is interrupted while waiting to acquire latch.
*/
public static void createAllModels() throws IOException, InterruptedException {
System.out.println("CREATING MODELS");
List<String> modelsToCreate = new ArrayList<>(FileHelper.loadAllFilesInPath(ModelsPath).values());
final CountDownLatch createModelsLatch = new CountDownLatch(1);
client.createModels(modelsToCreate)
.doOnNext(modelData -> System.out.println("Created model: " + modelData.getId()))
.doOnError(IgnoreConflictError)
.doOnTerminate(createModelsLatch::countDown)
.subscribe();
createModelsLatch.await(MaxWaitTimeAsyncOperationsInSeconds, TimeUnit.SECONDS);
}
/**
* Gets all the models within the ADT service instance.
* @throws InterruptedException If the current thread is interrupted while waiting to acquire latch.
*/
public static void listAllModels() throws InterruptedException {
System.out.println("LISTING MODELS");
final CountDownLatch listModelsLatch = new CountDownLatch(1);
client.listModels()
.doOnNext(modelData -> System.out.println("Retrieved model: " + modelData.getId() + ", display name '" + modelData.getDisplayName().get("en") + "'," +
" upload time '" + modelData.getUploadTime() + "' and decommissioned '" + modelData.isDecommissioned() + "'"))
.doOnError(throwable -> System.err.println("List models error: " + throwable))
.doOnTerminate(listModelsLatch::countDown)
.subscribe();
listModelsLatch.await(MaxWaitTimeAsyncOperationsInSeconds, TimeUnit.SECONDS);
}
/**
* Creates all twins specified in the DTDL->DigitalTwins directory.
* @throws IOException If an I/O error is thrown when accessing the starting file.
* @throws InterruptedException If the current thread is interrupted while waiting to acquire latch.
*/
public static void createAllTwins() throws IOException, InterruptedException {
System.out.println("CREATE DIGITAL TWINS");
Map<String, String> twins = FileHelper.loadAllFilesInPath(TwinsPath);
final CountDownLatch createTwinsLatch = new CountDownLatch(twins.size());
twins
.forEach((twinId, twinContent) -> client.createDigitalTwin(twinId, twinContent)
.subscribe(
twin -> System.out.println("Created digital twin: " + twinId + "\n\t Body: " + twin),
throwable -> System.err.println("Could not create digital twin " + twinId + " due to " + throwable),
createTwinsLatch::countDown));
createTwinsLatch.await(MaxWaitTimeAsyncOperationsInSeconds, TimeUnit.SECONDS);
}
/**
* Creates all the relationships defined in the DTDL->Relationships directory
* @throws IOException If an I/O error is thrown when accessing the starting file.
* @throws InterruptedException If the current thread is interrupted while waiting to acquire latch.
*/
public static void connectTwinsTogether() throws IOException, InterruptedException {
System.out.println("CONNECT DIGITAL TWINS");
Map<String, String> allRelationships = FileHelper.loadAllFilesInPath(RelationshipsPath);
final CountDownLatch connectTwinsLatch = new CountDownLatch(4);
allRelationships.values().forEach(
relationshipContent -> {
try {
List<BasicRelationship> relationships = mapper.readValue(relationshipContent, new TypeReference<List<BasicRelationship>>() { });
relationships
.forEach(relationship -> {
try {
client.createRelationship(relationship.getSourceId(), relationship.getId(), mapper.writeValueAsString(relationship))
.doOnSuccess(s -> System.out.println("Linked twin " + relationship.getSourceId() + " to twin " + relationship.getTargetId() + " as " + relationship.getName()))
.doOnError(IgnoreConflictError)
.doOnTerminate(connectTwinsLatch::countDown)
.subscribe();
} catch (JsonProcessingException e) {
throw new RuntimeException("JsonProcessingException while serializing relationship string from BasicRelationship: ", e);
}
});
} catch (JsonProcessingException e) {
throw new RuntimeException("JsonProcessingException while deserializing relationship string to BasicRelationship: ", e);
}
}
);
connectTwinsLatch.await(MaxWaitTimeAsyncOperationsInSeconds, TimeUnit.SECONDS);
}
} | |
We should have been able to schedule the async API on a single thread, and forced them to run sequentially; however, I didn't have success with that. I am blocking the async API call for now, until I figure that out. | public static void deleteAllModels() throws InterruptedException {
System.out.println("DELETING MODELS");
List<String> models = asList(RoomModelId, WifiModelId, BuildingModelId, FloorModelId, HvacModelId);
models
.forEach(modelId -> {
try {
client.deleteModel(modelId).block();
System.out.println("Deleted model: " + modelId);
} catch (ErrorResponseException ex) {
if (ex.getResponse().getStatusCode() != HttpStatus.SC_NOT_FOUND) {
System.err.println("Could not delete model " + modelId + " due to " + ex);
}
}
});
} | public static void deleteAllModels() throws InterruptedException {
System.out.println("DELETING MODELS");
List<String> models = asList(RoomModelId, WifiModelId, BuildingModelId, FloorModelId, HvacModelId);
models
.forEach(modelId -> {
try {
client.deleteModel(modelId).block();
System.out.println("Deleted model: " + modelId);
} catch (ErrorResponseException ex) {
if (ex.getResponse().getStatusCode() != HttpStatus.SC_NOT_FOUND) {
System.err.println("Could not delete model " + modelId + " due to " + ex);
}
}
});
} | class DigitalTwinsLifecycleAsyncSample {
private static final String tenantId = System.getenv("TENANT_ID");
private static final String clientId = System.getenv("CLIENT_ID");
private static final String clientSecret = System.getenv("CLIENT_SECRET");
private static final String endpoint = System.getenv("DIGITAL_TWINS_ENDPOINT");
private static final int MaxWaitTimeAsyncOperationsInSeconds = 10;
private static final ObjectMapper mapper = new ObjectMapper();
private static final URL DtdlDirectoryUrl = DigitalTwinsLifecycleAsyncSample.class.getClassLoader().getResource("DTDL");
private static final Path DtDlDirectoryPath;
private static final Path TwinsPath;
private static final Path ModelsPath;
private static final Path RelationshipsPath;
private static final DigitalTwinsAsyncClient client;
static {
try {
assert DtdlDirectoryUrl != null;
DtDlDirectoryPath = Paths.get(DtdlDirectoryUrl.toURI());
} catch (URISyntaxException e) {
throw new RuntimeException("Unable to convert the DTDL directory URL to URI", e);
}
TwinsPath = Paths.get(DtDlDirectoryPath.toString(), "DigitalTwins");
ModelsPath = Paths.get(DtDlDirectoryPath.toString(), "Models");
RelationshipsPath = Paths.get(DtDlDirectoryPath.toString(), "Relationships");
client = new DigitalTwinsClientBuilder()
.tokenCredential(
new ClientSecretCredentialBuilder()
.tenantId(tenantId)
.clientId(clientId)
.clientSecret(clientSecret)
.build()
)
.endpoint(endpoint)
.httpLogOptions(
new HttpLogOptions()
.setLogLevel(HttpLogDetailLevel.NONE))
.buildAsyncClient();
}
public static void main(String[] args) throws IOException, InterruptedException {
deleteTwins();
deleteAllModels();
createAllModels();
listAllModels();
createAllTwins();
connectTwinsTogether();
}
/**
* Delete a twin, and any relationships it might have.
* @throws IOException If an I/O error is thrown when accessing the starting file.
* @throws InterruptedException If the current thread is interrupted while waiting to acquire latch.
*/
public static void deleteTwins() throws IOException, InterruptedException {
System.out.println("DELETE DIGITAL TWINS");
Map<String, String> twins = FileHelper.loadAllFilesInPath(TwinsPath);
for (Map.Entry<String, String> twin : twins.entrySet()) {
String twinId = twin.getKey();
List<BasicRelationship> relationshipList = new ArrayList<>();
Semaphore listRelationshipSemaphore = new Semaphore(0);
Semaphore deleteRelationshipsSemaphore = new Semaphore(0);
CountDownLatch deleteTwinsLatch = new CountDownLatch(1);
client.listRelationships(twinId, BasicRelationship.class)
.doOnNext(relationshipList::add)
.doOnError(throwable -> {
if (!(throwable instanceof ErrorResponseException) || ((ErrorResponseException) throwable).getResponse().getStatusCode() != HttpStatus.SC_NOT_FOUND) {
System.err.println("List relationships error: " + throwable);
}
})
.doOnTerminate(listRelationshipSemaphore::release)
.subscribe();
client.listIncomingRelationships(twinId)
.doOnNext(e -> relationshipList.add(mapper.convertValue(e, BasicRelationship.class)))
.doOnError(throwable -> {
if (!(throwable instanceof ErrorResponseException) || ((ErrorResponseException) throwable).getResponse().getStatusCode() != HttpStatus.SC_NOT_FOUND) {
System.err.println("List incoming relationships error: " + throwable);
}
})
.doOnTerminate(listRelationshipSemaphore::release)
.subscribe();
if (listRelationshipSemaphore.tryAcquire(2, MaxWaitTimeAsyncOperationsInSeconds, TimeUnit.SECONDS)) {
relationshipList
.forEach(relationship -> client.deleteRelationship(relationship.getSourceId(), relationship.getId())
.doOnSuccess(aVoid -> {
if (twinId.equals(relationship.getSourceId())) {
System.out.println("Found and deleted relationship: " + relationship.getId());
} else {
System.out.println("Found and deleted incoming relationship: " + relationship.getId());
}
})
.doOnError(throwable -> {
if (!(throwable instanceof ErrorResponseException) || ((ErrorResponseException) throwable).getResponse().getStatusCode() != HttpStatus.SC_NOT_FOUND) {
System.err.println("List relationships error: " + throwable);
}
})
.doOnTerminate(deleteRelationshipsSemaphore::release)
.subscribe());
}
if (deleteRelationshipsSemaphore.tryAcquire(relationshipList.size(), MaxWaitTimeAsyncOperationsInSeconds, TimeUnit.SECONDS)) {
client.deleteDigitalTwin(twinId)
.doOnSuccess(aVoid -> System.out.println("Deleted digital twin: " + twinId))
.doOnError(throwable -> {
if (!(throwable instanceof ErrorResponseException) || ((ErrorResponseException) throwable).getResponse().getStatusCode() != HttpStatus.SC_NOT_FOUND) {
System.err.println("Delete twin error: " + throwable);
}
})
.doOnTerminate(deleteTwinsLatch::countDown)
.subscribe();
deleteTwinsLatch.await(MaxWaitTimeAsyncOperationsInSeconds, TimeUnit.SECONDS);
}
}
}
/**
* Delete models created by FullLifecycleSample for the ADT service instance.
* @throws InterruptedException If the current thread is interrupted while waiting to acquire latch.
*/
/**
* Loads all the models found in the Models directory into memory and uses CreateModelsAsync API to create all the models in the ADT service instance.
* @throws IOException If an I/O error is thrown when accessing the starting file.
* @throws InterruptedException If the current thread is interrupted while waiting to acquire latch.
*/
public static void createAllModels() throws IOException, InterruptedException {
System.out.println("CREATING MODELS");
List<String> modelsToCreate = new ArrayList<>(FileHelper.loadAllFilesInPath(ModelsPath).values());
final CountDownLatch createModelsLatch = new CountDownLatch(1);
client.createModels(modelsToCreate)
.doOnNext(modelData -> System.out.println("Created model: " + modelData.getId()))
.doOnError(throwable -> {
if (!(throwable instanceof ErrorResponseException) || ((ErrorResponseException) throwable).getResponse().getStatusCode() != HttpStatus.SC_CONFLICT) {
System.err.println("Create models error: " + throwable);
}
})
.doOnTerminate(createModelsLatch::countDown)
.subscribe();
boolean created = createModelsLatch.await(MaxWaitTimeAsyncOperationsInSeconds, TimeUnit.SECONDS);
System.out.println("Models created: " + created);
}
/**
* Gets all the models within the ADT service instance.
* @throws InterruptedException If the current thread is interrupted while waiting to acquire latch.
*/
public static void listAllModels() throws InterruptedException {
System.out.println("LISTING MODELS");
final CountDownLatch listModelsLatch = new CountDownLatch(1);
client.listModels()
.doOnNext(modelData -> System.out.println(String.format("Retrieved model: %s, display name '%s', upload time '%s' and decommissioned '%s'",
modelData.getId(), modelData.getDisplayName().get("en"), modelData.getUploadTime(), modelData.isDecommissioned())))
.doOnError(throwable -> System.err.println("List models error: " + throwable))
.doOnTerminate(listModelsLatch::countDown)
.subscribe();
boolean created = listModelsLatch.await(MaxWaitTimeAsyncOperationsInSeconds, TimeUnit.SECONDS);
System.out.println("Models retrieved: " + created);
}
/**
* Creates all twins specified in the DTDL->DigitalTwins directory.
* @throws IOException If an I/O error is thrown when accessing the starting file.
* @throws InterruptedException If the current thread is interrupted while waiting to acquire latch.
*/
public static void createAllTwins() throws IOException, InterruptedException {
System.out.println("CREATE DIGITAL TWINS");
Map<String, String> twins = FileHelper.loadAllFilesInPath(TwinsPath);
final CountDownLatch createTwinsLatch = new CountDownLatch(twins.size());
twins
.forEach((twinId, twinContent) -> client.createDigitalTwin(twinId, twinContent)
.subscribe(
twin -> System.out.println("Created digital twin: " + twinId + "\n\t Body: " + twin),
throwable -> System.err.println("Could not create digital twin " + twinId + " due to " + throwable),
createTwinsLatch::countDown));
boolean created = createTwinsLatch.await(MaxWaitTimeAsyncOperationsInSeconds, TimeUnit.SECONDS);
System.out.println("Twins created: " + created);
}
public static void connectTwinsTogether() throws IOException, InterruptedException {
System.out.println("CONNECT DIGITAL TWINS");
Map<String, String> allRelationships = FileHelper.loadAllFilesInPath(RelationshipsPath);
final CountDownLatch connectTwinsLatch = new CountDownLatch(4);
allRelationships.values().forEach(
relationshipContent -> {
try {
List<BasicRelationship> relationships = mapper.readValue(relationshipContent, new TypeReference<>() { });
relationships
.forEach(relationship -> {
try {
client.createRelationship(relationship.getSourceId(), relationship.getId(), mapper.writeValueAsString(relationship))
.doOnSuccess(s -> System.out.println("Linked twin " + relationship.getSourceId() + " to twin " + relationship.getTargetId() + " as " + relationship.getName()))
.doOnError(throwable -> {
if (!(throwable instanceof ErrorResponseException) || ((ErrorResponseException) throwable).getResponse().getStatusCode() != HttpStatus.SC_CONFLICT) {
System.err.println("Could not linked twin " + relationship.getSourceId() + " to twin " + relationship.getTargetId() + " as " + relationship.getName() +
" due to " + throwable);
}
})
.doOnTerminate(connectTwinsLatch::countDown)
.subscribe();
} catch (JsonProcessingException e) {
throw new RuntimeException("JsonProcessingException while serializing relationship string from BasicRelationship: ", e);
}
});
} catch (JsonProcessingException e) {
throw new RuntimeException("JsonProcessingException while deserializing relationship string to BasicRelationship: ", e);
}
}
);
boolean created = connectTwinsLatch.await(MaxWaitTimeAsyncOperationsInSeconds, TimeUnit.SECONDS);
System.out.println("Twins connected: " + created);
}
} | class DigitalTwinsLifecycleAsyncSample {
private static final String tenantId = System.getenv("TENANT_ID");
private static final String clientId = System.getenv("CLIENT_ID");
private static final String clientSecret = System.getenv("CLIENT_SECRET");
private static final String endpoint = System.getenv("DIGITAL_TWINS_ENDPOINT");
private static final int MaxWaitTimeAsyncOperationsInSeconds = 10;
private static final ObjectMapper mapper = new ObjectMapper();
private static final URL DtdlDirectoryUrl = DigitalTwinsLifecycleAsyncSample.class.getClassLoader().getResource("DTDL");
private static final Path DtDlDirectoryPath;
private static final Path TwinsPath;
private static final Path ModelsPath;
private static final Path RelationshipsPath;
private static final DigitalTwinsAsyncClient client;
static {
try {
assert DtdlDirectoryUrl != null;
DtDlDirectoryPath = Paths.get(DtdlDirectoryUrl.toURI());
} catch (URISyntaxException e) {
throw new RuntimeException("Unable to convert the DTDL directory URL to URI", e);
}
TwinsPath = Paths.get(DtDlDirectoryPath.toString(), "DigitalTwins");
ModelsPath = Paths.get(DtDlDirectoryPath.toString(), "Models");
RelationshipsPath = Paths.get(DtDlDirectoryPath.toString(), "Relationships");
client = new DigitalTwinsClientBuilder()
.tokenCredential(
new ClientSecretCredentialBuilder()
.tenantId(tenantId)
.clientId(clientId)
.clientSecret(clientSecret)
.build()
)
.endpoint(endpoint)
.httpLogOptions(
new HttpLogOptions()
.setLogLevel(HttpLogDetailLevel.NONE))
.buildAsyncClient();
}
public static void main(String[] args) throws IOException, InterruptedException {
deleteTwins();
deleteAllModels();
createAllModels();
listAllModels();
createAllTwins();
connectTwinsTogether();
}
/**
* Delete a twin, and any relationships it might have.
* @throws IOException If an I/O error is thrown when accessing the starting file.
* @throws InterruptedException If the current thread is interrupted while waiting to acquire latch.
*/
public static void deleteTwins() throws IOException, InterruptedException {
System.out.println("DELETE DIGITAL TWINS");
Map<String, String> twins = FileHelper.loadAllFilesInPath(TwinsPath);
for (Map.Entry<String, String> twin : twins.entrySet()) {
String twinId = twin.getKey();
List<BasicRelationship> relationshipList = Collections.synchronizedList(new ArrayList<>());
Semaphore listRelationshipSemaphore = new Semaphore(0);
Semaphore deleteRelationshipsSemaphore = new Semaphore(0);
CountDownLatch deleteTwinsLatch = new CountDownLatch(1);
client.listRelationships(twinId, BasicRelationship.class)
.doOnNext(relationshipList::add)
.doOnError(IgnoreNotFoundError)
.doOnTerminate(listRelationshipSemaphore::release)
.subscribe();
client.listIncomingRelationships(twinId)
.doOnNext(e -> relationshipList.add(mapper.convertValue(e, BasicRelationship.class)))
.doOnError(IgnoreNotFoundError)
.doOnTerminate(listRelationshipSemaphore::release)
.subscribe();
if (listRelationshipSemaphore.tryAcquire(2, MaxWaitTimeAsyncOperationsInSeconds, TimeUnit.SECONDS)) {
relationshipList
.forEach(relationship -> client.deleteRelationship(relationship.getSourceId(), relationship.getId())
.doOnSuccess(aVoid -> {
if (twinId.equals(relationship.getSourceId())) {
System.out.println("Found and deleted relationship: " + relationship.getId());
} else {
System.out.println("Found and deleted incoming relationship: " + relationship.getId());
}
})
.doOnError(IgnoreNotFoundError)
.doOnTerminate(deleteRelationshipsSemaphore::release)
.subscribe());
}
if (deleteRelationshipsSemaphore.tryAcquire(relationshipList.size(), MaxWaitTimeAsyncOperationsInSeconds, TimeUnit.SECONDS)) {
client.deleteDigitalTwin(twinId)
.doOnSuccess(aVoid -> System.out.println("Deleted digital twin: " + twinId))
.doOnError(IgnoreNotFoundError)
.doOnTerminate(deleteTwinsLatch::countDown)
.subscribe();
deleteTwinsLatch.await(MaxWaitTimeAsyncOperationsInSeconds, TimeUnit.SECONDS);
}
}
}
/**
* Delete models created by FullLifecycleSample for the ADT service instance.
* @throws InterruptedException If the current thread is interrupted while waiting to acquire latch.
*/
/**
* Loads all the models found in the Models directory into memory and uses CreateModelsAsync API to create all the models in the ADT service instance.
* @throws IOException If an I/O error is thrown when accessing the starting file.
* @throws InterruptedException If the current thread is interrupted while waiting to acquire latch.
*/
public static void createAllModels() throws IOException, InterruptedException {
System.out.println("CREATING MODELS");
List<String> modelsToCreate = new ArrayList<>(FileHelper.loadAllFilesInPath(ModelsPath).values());
final CountDownLatch createModelsLatch = new CountDownLatch(1);
client.createModels(modelsToCreate)
.doOnNext(modelData -> System.out.println("Created model: " + modelData.getId()))
.doOnError(IgnoreConflictError)
.doOnTerminate(createModelsLatch::countDown)
.subscribe();
createModelsLatch.await(MaxWaitTimeAsyncOperationsInSeconds, TimeUnit.SECONDS);
}
/**
* Gets all the models within the ADT service instance.
* @throws InterruptedException If the current thread is interrupted while waiting to acquire latch.
*/
public static void listAllModels() throws InterruptedException {
System.out.println("LISTING MODELS");
final CountDownLatch listModelsLatch = new CountDownLatch(1);
client.listModels()
.doOnNext(modelData -> System.out.println("Retrieved model: " + modelData.getId() + ", display name '" + modelData.getDisplayName().get("en") + "'," +
" upload time '" + modelData.getUploadTime() + "' and decommissioned '" + modelData.isDecommissioned() + "'"))
.doOnError(throwable -> System.err.println("List models error: " + throwable))
.doOnTerminate(listModelsLatch::countDown)
.subscribe();
listModelsLatch.await(MaxWaitTimeAsyncOperationsInSeconds, TimeUnit.SECONDS);
}
/**
* Creates all twins specified in the DTDL->DigitalTwins directory.
* @throws IOException If an I/O error is thrown when accessing the starting file.
* @throws InterruptedException If the current thread is interrupted while waiting to acquire latch.
*/
public static void createAllTwins() throws IOException, InterruptedException {
System.out.println("CREATE DIGITAL TWINS");
Map<String, String> twins = FileHelper.loadAllFilesInPath(TwinsPath);
final CountDownLatch createTwinsLatch = new CountDownLatch(twins.size());
twins
.forEach((twinId, twinContent) -> client.createDigitalTwin(twinId, twinContent)
.subscribe(
twin -> System.out.println("Created digital twin: " + twinId + "\n\t Body: " + twin),
throwable -> System.err.println("Could not create digital twin " + twinId + " due to " + throwable),
createTwinsLatch::countDown));
createTwinsLatch.await(MaxWaitTimeAsyncOperationsInSeconds, TimeUnit.SECONDS);
}
/**
* Creates all the relationships defined in the DTDL->Relationships directory
* @throws IOException If an I/O error is thrown when accessing the starting file.
* @throws InterruptedException If the current thread is interrupted while waiting to acquire latch.
*/
public static void connectTwinsTogether() throws IOException, InterruptedException {
System.out.println("CONNECT DIGITAL TWINS");
Map<String, String> allRelationships = FileHelper.loadAllFilesInPath(RelationshipsPath);
final CountDownLatch connectTwinsLatch = new CountDownLatch(4);
allRelationships.values().forEach(
relationshipContent -> {
try {
List<BasicRelationship> relationships = mapper.readValue(relationshipContent, new TypeReference<List<BasicRelationship>>() { });
relationships
.forEach(relationship -> {
try {
client.createRelationship(relationship.getSourceId(), relationship.getId(), mapper.writeValueAsString(relationship))
.doOnSuccess(s -> System.out.println("Linked twin " + relationship.getSourceId() + " to twin " + relationship.getTargetId() + " as " + relationship.getName()))
.doOnError(IgnoreConflictError)
.doOnTerminate(connectTwinsLatch::countDown)
.subscribe();
} catch (JsonProcessingException e) {
throw new RuntimeException("JsonProcessingException while serializing relationship string from BasicRelationship: ", e);
}
});
} catch (JsonProcessingException e) {
throw new RuntimeException("JsonProcessingException while deserializing relationship string to BasicRelationship: ", e);
}
}
);
connectTwinsLatch.await(MaxWaitTimeAsyncOperationsInSeconds, TimeUnit.SECONDS);
}
} | |
For each async delete? Can you elaborate what you mean here? | public static void deleteTwins() throws IOException, InterruptedException {
System.out.println("DELETE DIGITAL TWINS");
Map<String, String> twins = FileHelper.loadAllFilesInPath(TwinsPath);
for (Map.Entry<String, String> twin : twins.entrySet()) {
String twinId = twin.getKey();
List<BasicRelationship> relationshipList = new ArrayList<>();
Semaphore listRelationshipSemaphore = new Semaphore(0);
Semaphore deleteRelationshipsSemaphore = new Semaphore(0);
CountDownLatch deleteTwinsLatch = new CountDownLatch(1);
client.listRelationships(twinId, BasicRelationship.class)
.doOnNext(relationshipList::add)
.doOnError(IgnoreNotFoundError)
.doOnTerminate(listRelationshipSemaphore::release)
.subscribe();
client.listIncomingRelationships(twinId)
.doOnNext(e -> relationshipList.add(mapper.convertValue(e, BasicRelationship.class)))
.doOnError(IgnoreNotFoundError)
.doOnTerminate(listRelationshipSemaphore::release)
.subscribe();
if (listRelationshipSemaphore.tryAcquire(2, MaxWaitTimeAsyncOperationsInSeconds, TimeUnit.SECONDS)) {
relationshipList
.forEach(relationship -> client.deleteRelationship(relationship.getSourceId(), relationship.getId())
.doOnSuccess(aVoid -> {
if (twinId.equals(relationship.getSourceId())) {
System.out.println("Found and deleted relationship: " + relationship.getId());
} else {
System.out.println("Found and deleted incoming relationship: " + relationship.getId());
}
})
.doOnError(IgnoreNotFoundError)
.doOnTerminate(deleteRelationshipsSemaphore::release)
.subscribe());
}
if (deleteRelationshipsSemaphore.tryAcquire(relationshipList.size(), MaxWaitTimeAsyncOperationsInSeconds, TimeUnit.SECONDS)) {
client.deleteDigitalTwin(twinId)
.doOnSuccess(aVoid -> System.out.println("Deleted digital twin: " + twinId))
.doOnError(IgnoreNotFoundError)
.doOnTerminate(deleteTwinsLatch::countDown)
.subscribe();
deleteTwinsLatch.await(MaxWaitTimeAsyncOperationsInSeconds, TimeUnit.SECONDS);
}
}
} | public static void deleteTwins() throws IOException, InterruptedException {
System.out.println("DELETE DIGITAL TWINS");
Map<String, String> twins = FileHelper.loadAllFilesInPath(TwinsPath);
for (Map.Entry<String, String> twin : twins.entrySet()) {
String twinId = twin.getKey();
List<BasicRelationship> relationshipList = Collections.synchronizedList(new ArrayList<>());
Semaphore listRelationshipSemaphore = new Semaphore(0);
Semaphore deleteRelationshipsSemaphore = new Semaphore(0);
CountDownLatch deleteTwinsLatch = new CountDownLatch(1);
client.listRelationships(twinId, BasicRelationship.class)
.doOnNext(relationshipList::add)
.doOnError(IgnoreNotFoundError)
.doOnTerminate(listRelationshipSemaphore::release)
.subscribe();
client.listIncomingRelationships(twinId)
.doOnNext(e -> relationshipList.add(mapper.convertValue(e, BasicRelationship.class)))
.doOnError(IgnoreNotFoundError)
.doOnTerminate(listRelationshipSemaphore::release)
.subscribe();
if (listRelationshipSemaphore.tryAcquire(2, MaxWaitTimeAsyncOperationsInSeconds, TimeUnit.SECONDS)) {
relationshipList
.forEach(relationship -> client.deleteRelationship(relationship.getSourceId(), relationship.getId())
.doOnSuccess(aVoid -> {
if (twinId.equals(relationship.getSourceId())) {
System.out.println("Found and deleted relationship: " + relationship.getId());
} else {
System.out.println("Found and deleted incoming relationship: " + relationship.getId());
}
})
.doOnError(IgnoreNotFoundError)
.doOnTerminate(deleteRelationshipsSemaphore::release)
.subscribe());
}
if (deleteRelationshipsSemaphore.tryAcquire(relationshipList.size(), MaxWaitTimeAsyncOperationsInSeconds, TimeUnit.SECONDS)) {
client.deleteDigitalTwin(twinId)
.doOnSuccess(aVoid -> System.out.println("Deleted digital twin: " + twinId))
.doOnError(IgnoreNotFoundError)
.doOnTerminate(deleteTwinsLatch::countDown)
.subscribe();
deleteTwinsLatch.await(MaxWaitTimeAsyncOperationsInSeconds, TimeUnit.SECONDS);
}
}
} | class DigitalTwinsLifecycleAsyncSample {
private static final String tenantId = System.getenv("TENANT_ID");
private static final String clientId = System.getenv("CLIENT_ID");
private static final String clientSecret = System.getenv("CLIENT_SECRET");
private static final String endpoint = System.getenv("DIGITAL_TWINS_ENDPOINT");
private static final int MaxWaitTimeAsyncOperationsInSeconds = 10;
private static final ObjectMapper mapper = new ObjectMapper();
private static final URL DtdlDirectoryUrl = DigitalTwinsLifecycleAsyncSample.class.getClassLoader().getResource("DTDL");
private static final Path DtDlDirectoryPath;
private static final Path TwinsPath;
private static final Path ModelsPath;
private static final Path RelationshipsPath;
private static final DigitalTwinsAsyncClient client;
static {
try {
assert DtdlDirectoryUrl != null;
DtDlDirectoryPath = Paths.get(DtdlDirectoryUrl.toURI());
} catch (URISyntaxException e) {
throw new RuntimeException("Unable to convert the DTDL directory URL to URI", e);
}
TwinsPath = Paths.get(DtDlDirectoryPath.toString(), "DigitalTwins");
ModelsPath = Paths.get(DtDlDirectoryPath.toString(), "Models");
RelationshipsPath = Paths.get(DtDlDirectoryPath.toString(), "Relationships");
client = new DigitalTwinsClientBuilder()
.tokenCredential(
new ClientSecretCredentialBuilder()
.tenantId(tenantId)
.clientId(clientId)
.clientSecret(clientSecret)
.build()
)
.endpoint(endpoint)
.httpLogOptions(
new HttpLogOptions()
.setLogLevel(HttpLogDetailLevel.NONE))
.buildAsyncClient();
}
public static void main(String[] args) throws IOException, InterruptedException {
deleteTwins();
deleteAllModels();
createAllModels();
listAllModels();
createAllTwins();
connectTwinsTogether();
}
/**
* Delete a twin, and any relationships it might have.
* @throws IOException If an I/O error is thrown when accessing the starting file.
* @throws InterruptedException If the current thread is interrupted while waiting to acquire latch.
*/
/**
* Delete models created by FullLifecycleSample for the ADT service instance.
* @throws InterruptedException If the current thread is interrupted while waiting to acquire latch.
*/
public static void deleteAllModels() throws InterruptedException {
System.out.println("DELETING MODELS");
List<String> models = asList(RoomModelId, WifiModelId, BuildingModelId, FloorModelId, HvacModelId);
models
.forEach(modelId -> {
try {
client.deleteModel(modelId).block();
System.out.println("Deleted model: " + modelId);
} catch (ErrorResponseException ex) {
if (ex.getResponse().getStatusCode() != HttpStatus.SC_NOT_FOUND) {
System.err.println("Could not delete model " + modelId + " due to " + ex);
}
}
});
}
/**
* Loads all the models found in the Models directory into memory and uses CreateModelsAsync API to create all the models in the ADT service instance.
* @throws IOException If an I/O error is thrown when accessing the starting file.
* @throws InterruptedException If the current thread is interrupted while waiting to acquire latch.
*/
public static void createAllModels() throws IOException, InterruptedException {
System.out.println("CREATING MODELS");
List<String> modelsToCreate = new ArrayList<>(FileHelper.loadAllFilesInPath(ModelsPath).values());
final CountDownLatch createModelsLatch = new CountDownLatch(1);
client.createModels(modelsToCreate)
.doOnNext(modelData -> System.out.println("Created model: " + modelData.getId()))
.doOnError(IgnoreConflictError)
.doOnTerminate(createModelsLatch::countDown)
.subscribe();
createModelsLatch.await(MaxWaitTimeAsyncOperationsInSeconds, TimeUnit.SECONDS);
}
/**
* Gets all the models within the ADT service instance.
* @throws InterruptedException If the current thread is interrupted while waiting to acquire latch.
*/
public static void listAllModels() throws InterruptedException {
System.out.println("LISTING MODELS");
final CountDownLatch listModelsLatch = new CountDownLatch(1);
client.listModels()
.doOnNext(modelData -> System.out.println(String.format("Retrieved model: %s, display name '%s', upload time '%s' and decommissioned '%s'",
modelData.getId(), modelData.getDisplayName().get("en"), modelData.getUploadTime(), modelData.isDecommissioned())))
.doOnError(throwable -> System.err.println("List models error: " + throwable))
.doOnTerminate(listModelsLatch::countDown)
.subscribe();
listModelsLatch.await(MaxWaitTimeAsyncOperationsInSeconds, TimeUnit.SECONDS);
}
/**
* Creates all twins specified in the DTDL->DigitalTwins directory.
* @throws IOException If an I/O error is thrown when accessing the starting file.
* @throws InterruptedException If the current thread is interrupted while waiting to acquire latch.
*/
public static void createAllTwins() throws IOException, InterruptedException {
System.out.println("CREATE DIGITAL TWINS");
Map<String, String> twins = FileHelper.loadAllFilesInPath(TwinsPath);
final CountDownLatch createTwinsLatch = new CountDownLatch(twins.size());
twins
.forEach((twinId, twinContent) -> client.createDigitalTwin(twinId, twinContent)
.subscribe(
twin -> System.out.println("Created digital twin: " + twinId + "\n\t Body: " + twin),
throwable -> System.err.println("Could not create digital twin " + twinId + " due to " + throwable),
createTwinsLatch::countDown));
createTwinsLatch.await(MaxWaitTimeAsyncOperationsInSeconds, TimeUnit.SECONDS);
}
public static void connectTwinsTogether() throws IOException, InterruptedException {
System.out.println("CONNECT DIGITAL TWINS");
Map<String, String> allRelationships = FileHelper.loadAllFilesInPath(RelationshipsPath);
final CountDownLatch connectTwinsLatch = new CountDownLatch(4);
allRelationships.values().forEach(
relationshipContent -> {
try {
List<BasicRelationship> relationships = mapper.readValue(relationshipContent, new TypeReference<List<BasicRelationship>>() { });
relationships
.forEach(relationship -> {
try {
client.createRelationship(relationship.getSourceId(), relationship.getId(), mapper.writeValueAsString(relationship))
.doOnSuccess(s -> System.out.println("Linked twin " + relationship.getSourceId() + " to twin " + relationship.getTargetId() + " as " + relationship.getName()))
.doOnError(IgnoreConflictError)
.doOnTerminate(connectTwinsLatch::countDown)
.subscribe();
} catch (JsonProcessingException e) {
throw new RuntimeException("JsonProcessingException while serializing relationship string from BasicRelationship: ", e);
}
});
} catch (JsonProcessingException e) {
throw new RuntimeException("JsonProcessingException while deserializing relationship string to BasicRelationship: ", e);
}
}
);
connectTwinsLatch.await(MaxWaitTimeAsyncOperationsInSeconds, TimeUnit.SECONDS);
}
} | class DigitalTwinsLifecycleAsyncSample {
private static final String tenantId = System.getenv("TENANT_ID");
private static final String clientId = System.getenv("CLIENT_ID");
private static final String clientSecret = System.getenv("CLIENT_SECRET");
private static final String endpoint = System.getenv("DIGITAL_TWINS_ENDPOINT");
private static final int MaxWaitTimeAsyncOperationsInSeconds = 10;
private static final ObjectMapper mapper = new ObjectMapper();
private static final URL DtdlDirectoryUrl = DigitalTwinsLifecycleAsyncSample.class.getClassLoader().getResource("DTDL");
private static final Path DtDlDirectoryPath;
private static final Path TwinsPath;
private static final Path ModelsPath;
private static final Path RelationshipsPath;
private static final DigitalTwinsAsyncClient client;
static {
try {
assert DtdlDirectoryUrl != null;
DtDlDirectoryPath = Paths.get(DtdlDirectoryUrl.toURI());
} catch (URISyntaxException e) {
throw new RuntimeException("Unable to convert the DTDL directory URL to URI", e);
}
TwinsPath = Paths.get(DtDlDirectoryPath.toString(), "DigitalTwins");
ModelsPath = Paths.get(DtDlDirectoryPath.toString(), "Models");
RelationshipsPath = Paths.get(DtDlDirectoryPath.toString(), "Relationships");
client = new DigitalTwinsClientBuilder()
.tokenCredential(
new ClientSecretCredentialBuilder()
.tenantId(tenantId)
.clientId(clientId)
.clientSecret(clientSecret)
.build()
)
.endpoint(endpoint)
.httpLogOptions(
new HttpLogOptions()
.setLogLevel(HttpLogDetailLevel.NONE))
.buildAsyncClient();
}
public static void main(String[] args) throws IOException, InterruptedException {
deleteTwins();
deleteAllModels();
createAllModels();
listAllModels();
createAllTwins();
connectTwinsTogether();
}
/**
* Delete a twin, and any relationships it might have.
* @throws IOException If an I/O error is thrown when accessing the starting file.
* @throws InterruptedException If the current thread is interrupted while waiting to acquire latch.
*/
/**
* Delete models created by FullLifecycleSample for the ADT service instance.
* @throws InterruptedException If the current thread is interrupted while waiting to acquire latch.
*/
public static void deleteAllModels() throws InterruptedException {
System.out.println("DELETING MODELS");
List<String> models = asList(RoomModelId, WifiModelId, BuildingModelId, FloorModelId, HvacModelId);
models
.forEach(modelId -> {
try {
client.deleteModel(modelId).block();
System.out.println("Deleted model: " + modelId);
} catch (ErrorResponseException ex) {
if (ex.getResponse().getStatusCode() != HttpStatus.SC_NOT_FOUND) {
System.err.println("Could not delete model " + modelId + " due to " + ex);
}
}
});
}
/**
* Loads all the models found in the Models directory into memory and uses CreateModelsAsync API to create all the models in the ADT service instance.
* @throws IOException If an I/O error is thrown when accessing the starting file.
* @throws InterruptedException If the current thread is interrupted while waiting to acquire latch.
*/
public static void createAllModels() throws IOException, InterruptedException {
System.out.println("CREATING MODELS");
List<String> modelsToCreate = new ArrayList<>(FileHelper.loadAllFilesInPath(ModelsPath).values());
final CountDownLatch createModelsLatch = new CountDownLatch(1);
client.createModels(modelsToCreate)
.doOnNext(modelData -> System.out.println("Created model: " + modelData.getId()))
.doOnError(IgnoreConflictError)
.doOnTerminate(createModelsLatch::countDown)
.subscribe();
createModelsLatch.await(MaxWaitTimeAsyncOperationsInSeconds, TimeUnit.SECONDS);
}
/**
* Gets all the models within the ADT service instance.
* @throws InterruptedException If the current thread is interrupted while waiting to acquire latch.
*/
public static void listAllModels() throws InterruptedException {
System.out.println("LISTING MODELS");
final CountDownLatch listModelsLatch = new CountDownLatch(1);
client.listModels()
.doOnNext(modelData -> System.out.println("Retrieved model: " + modelData.getId() + ", display name '" + modelData.getDisplayName().get("en") + "'," +
" upload time '" + modelData.getUploadTime() + "' and decommissioned '" + modelData.isDecommissioned() + "'"))
.doOnError(throwable -> System.err.println("List models error: " + throwable))
.doOnTerminate(listModelsLatch::countDown)
.subscribe();
listModelsLatch.await(MaxWaitTimeAsyncOperationsInSeconds, TimeUnit.SECONDS);
}
/**
* Creates all twins specified in the DTDL->DigitalTwins directory.
* @throws IOException If an I/O error is thrown when accessing the starting file.
* @throws InterruptedException If the current thread is interrupted while waiting to acquire latch.
*/
public static void createAllTwins() throws IOException, InterruptedException {
System.out.println("CREATE DIGITAL TWINS");
Map<String, String> twins = FileHelper.loadAllFilesInPath(TwinsPath);
final CountDownLatch createTwinsLatch = new CountDownLatch(twins.size());
twins
.forEach((twinId, twinContent) -> client.createDigitalTwin(twinId, twinContent)
.subscribe(
twin -> System.out.println("Created digital twin: " + twinId + "\n\t Body: " + twin),
throwable -> System.err.println("Could not create digital twin " + twinId + " due to " + throwable),
createTwinsLatch::countDown));
createTwinsLatch.await(MaxWaitTimeAsyncOperationsInSeconds, TimeUnit.SECONDS);
}
/**
* Creates all the relationships defined in the DTDL->Relationships directory
* @throws IOException If an I/O error is thrown when accessing the starting file.
* @throws InterruptedException If the current thread is interrupted while waiting to acquire latch.
*/
public static void connectTwinsTogether() throws IOException, InterruptedException {
System.out.println("CONNECT DIGITAL TWINS");
Map<String, String> allRelationships = FileHelper.loadAllFilesInPath(RelationshipsPath);
final CountDownLatch connectTwinsLatch = new CountDownLatch(4);
allRelationships.values().forEach(
relationshipContent -> {
try {
List<BasicRelationship> relationships = mapper.readValue(relationshipContent, new TypeReference<List<BasicRelationship>>() { });
relationships
.forEach(relationship -> {
try {
client.createRelationship(relationship.getSourceId(), relationship.getId(), mapper.writeValueAsString(relationship))
.doOnSuccess(s -> System.out.println("Linked twin " + relationship.getSourceId() + " to twin " + relationship.getTargetId() + " as " + relationship.getName()))
.doOnError(IgnoreConflictError)
.doOnTerminate(connectTwinsLatch::countDown)
.subscribe();
} catch (JsonProcessingException e) {
throw new RuntimeException("JsonProcessingException while serializing relationship string from BasicRelationship: ", e);
}
});
} catch (JsonProcessingException e) {
throw new RuntimeException("JsonProcessingException while deserializing relationship string to BasicRelationship: ", e);
}
}
);
connectTwinsLatch.await(MaxWaitTimeAsyncOperationsInSeconds, TimeUnit.SECONDS);
}
} | |
What is a latch? | public static void deleteTwins() throws IOException, InterruptedException {
System.out.println("DELETE DIGITAL TWINS");
Map<String, String> twins = FileHelper.loadAllFilesInPath(TwinsPath);
for (Map.Entry<String, String> twin : twins.entrySet()) {
String twinId = twin.getKey();
List<BasicRelationship> relationshipList = new ArrayList<>();
Semaphore listRelationshipSemaphore = new Semaphore(0);
Semaphore deleteRelationshipsSemaphore = new Semaphore(0);
CountDownLatch deleteTwinsLatch = new CountDownLatch(1);
client.listRelationships(twinId, BasicRelationship.class)
.doOnNext(relationshipList::add)
.doOnError(IgnoreNotFoundError)
.doOnTerminate(listRelationshipSemaphore::release)
.subscribe();
client.listIncomingRelationships(twinId)
.doOnNext(e -> relationshipList.add(mapper.convertValue(e, BasicRelationship.class)))
.doOnError(IgnoreNotFoundError)
.doOnTerminate(listRelationshipSemaphore::release)
.subscribe();
if (listRelationshipSemaphore.tryAcquire(2, MaxWaitTimeAsyncOperationsInSeconds, TimeUnit.SECONDS)) {
relationshipList
.forEach(relationship -> client.deleteRelationship(relationship.getSourceId(), relationship.getId())
.doOnSuccess(aVoid -> {
if (twinId.equals(relationship.getSourceId())) {
System.out.println("Found and deleted relationship: " + relationship.getId());
} else {
System.out.println("Found and deleted incoming relationship: " + relationship.getId());
}
})
.doOnError(IgnoreNotFoundError)
.doOnTerminate(deleteRelationshipsSemaphore::release)
.subscribe());
}
if (deleteRelationshipsSemaphore.tryAcquire(relationshipList.size(), MaxWaitTimeAsyncOperationsInSeconds, TimeUnit.SECONDS)) {
client.deleteDigitalTwin(twinId)
.doOnSuccess(aVoid -> System.out.println("Deleted digital twin: " + twinId))
.doOnError(IgnoreNotFoundError)
.doOnTerminate(deleteTwinsLatch::countDown)
.subscribe();
deleteTwinsLatch.await(MaxWaitTimeAsyncOperationsInSeconds, TimeUnit.SECONDS);
}
}
} | public static void deleteTwins() throws IOException, InterruptedException {
System.out.println("DELETE DIGITAL TWINS");
Map<String, String> twins = FileHelper.loadAllFilesInPath(TwinsPath);
for (Map.Entry<String, String> twin : twins.entrySet()) {
String twinId = twin.getKey();
List<BasicRelationship> relationshipList = Collections.synchronizedList(new ArrayList<>());
Semaphore listRelationshipSemaphore = new Semaphore(0);
Semaphore deleteRelationshipsSemaphore = new Semaphore(0);
CountDownLatch deleteTwinsLatch = new CountDownLatch(1);
client.listRelationships(twinId, BasicRelationship.class)
.doOnNext(relationshipList::add)
.doOnError(IgnoreNotFoundError)
.doOnTerminate(listRelationshipSemaphore::release)
.subscribe();
client.listIncomingRelationships(twinId)
.doOnNext(e -> relationshipList.add(mapper.convertValue(e, BasicRelationship.class)))
.doOnError(IgnoreNotFoundError)
.doOnTerminate(listRelationshipSemaphore::release)
.subscribe();
if (listRelationshipSemaphore.tryAcquire(2, MaxWaitTimeAsyncOperationsInSeconds, TimeUnit.SECONDS)) {
relationshipList
.forEach(relationship -> client.deleteRelationship(relationship.getSourceId(), relationship.getId())
.doOnSuccess(aVoid -> {
if (twinId.equals(relationship.getSourceId())) {
System.out.println("Found and deleted relationship: " + relationship.getId());
} else {
System.out.println("Found and deleted incoming relationship: " + relationship.getId());
}
})
.doOnError(IgnoreNotFoundError)
.doOnTerminate(deleteRelationshipsSemaphore::release)
.subscribe());
}
if (deleteRelationshipsSemaphore.tryAcquire(relationshipList.size(), MaxWaitTimeAsyncOperationsInSeconds, TimeUnit.SECONDS)) {
client.deleteDigitalTwin(twinId)
.doOnSuccess(aVoid -> System.out.println("Deleted digital twin: " + twinId))
.doOnError(IgnoreNotFoundError)
.doOnTerminate(deleteTwinsLatch::countDown)
.subscribe();
deleteTwinsLatch.await(MaxWaitTimeAsyncOperationsInSeconds, TimeUnit.SECONDS);
}
}
} | class DigitalTwinsLifecycleAsyncSample {
private static final String tenantId = System.getenv("TENANT_ID");
private static final String clientId = System.getenv("CLIENT_ID");
private static final String clientSecret = System.getenv("CLIENT_SECRET");
private static final String endpoint = System.getenv("DIGITAL_TWINS_ENDPOINT");
private static final int MaxWaitTimeAsyncOperationsInSeconds = 10;
private static final ObjectMapper mapper = new ObjectMapper();
private static final URL DtdlDirectoryUrl = DigitalTwinsLifecycleAsyncSample.class.getClassLoader().getResource("DTDL");
private static final Path DtDlDirectoryPath;
private static final Path TwinsPath;
private static final Path ModelsPath;
private static final Path RelationshipsPath;
private static final DigitalTwinsAsyncClient client;
static {
try {
assert DtdlDirectoryUrl != null;
DtDlDirectoryPath = Paths.get(DtdlDirectoryUrl.toURI());
} catch (URISyntaxException e) {
throw new RuntimeException("Unable to convert the DTDL directory URL to URI", e);
}
TwinsPath = Paths.get(DtDlDirectoryPath.toString(), "DigitalTwins");
ModelsPath = Paths.get(DtDlDirectoryPath.toString(), "Models");
RelationshipsPath = Paths.get(DtDlDirectoryPath.toString(), "Relationships");
client = new DigitalTwinsClientBuilder()
.tokenCredential(
new ClientSecretCredentialBuilder()
.tenantId(tenantId)
.clientId(clientId)
.clientSecret(clientSecret)
.build()
)
.endpoint(endpoint)
.httpLogOptions(
new HttpLogOptions()
.setLogLevel(HttpLogDetailLevel.NONE))
.buildAsyncClient();
}
public static void main(String[] args) throws IOException, InterruptedException {
deleteTwins();
deleteAllModels();
createAllModels();
listAllModels();
createAllTwins();
connectTwinsTogether();
}
/**
* Delete a twin, and any relationships it might have.
* @throws IOException If an I/O error is thrown when accessing the starting file.
* @throws InterruptedException If the current thread is interrupted while waiting to acquire latch.
*/
/**
* Delete models created by FullLifecycleSample for the ADT service instance.
* @throws InterruptedException If the current thread is interrupted while waiting to acquire latch.
*/
public static void deleteAllModels() throws InterruptedException {
System.out.println("DELETING MODELS");
List<String> models = asList(RoomModelId, WifiModelId, BuildingModelId, FloorModelId, HvacModelId);
models
.forEach(modelId -> {
try {
client.deleteModel(modelId).block();
System.out.println("Deleted model: " + modelId);
} catch (ErrorResponseException ex) {
if (ex.getResponse().getStatusCode() != HttpStatus.SC_NOT_FOUND) {
System.err.println("Could not delete model " + modelId + " due to " + ex);
}
}
});
}
/**
* Loads all the models found in the Models directory into memory and uses CreateModelsAsync API to create all the models in the ADT service instance.
* @throws IOException If an I/O error is thrown when accessing the starting file.
* @throws InterruptedException If the current thread is interrupted while waiting to acquire latch.
*/
public static void createAllModels() throws IOException, InterruptedException {
System.out.println("CREATING MODELS");
List<String> modelsToCreate = new ArrayList<>(FileHelper.loadAllFilesInPath(ModelsPath).values());
final CountDownLatch createModelsLatch = new CountDownLatch(1);
client.createModels(modelsToCreate)
.doOnNext(modelData -> System.out.println("Created model: " + modelData.getId()))
.doOnError(IgnoreConflictError)
.doOnTerminate(createModelsLatch::countDown)
.subscribe();
createModelsLatch.await(MaxWaitTimeAsyncOperationsInSeconds, TimeUnit.SECONDS);
}
/**
* Gets all the models within the ADT service instance.
* @throws InterruptedException If the current thread is interrupted while waiting to acquire latch.
*/
public static void listAllModels() throws InterruptedException {
System.out.println("LISTING MODELS");
final CountDownLatch listModelsLatch = new CountDownLatch(1);
client.listModels()
.doOnNext(modelData -> System.out.println(String.format("Retrieved model: %s, display name '%s', upload time '%s' and decommissioned '%s'",
modelData.getId(), modelData.getDisplayName().get("en"), modelData.getUploadTime(), modelData.isDecommissioned())))
.doOnError(throwable -> System.err.println("List models error: " + throwable))
.doOnTerminate(listModelsLatch::countDown)
.subscribe();
listModelsLatch.await(MaxWaitTimeAsyncOperationsInSeconds, TimeUnit.SECONDS);
}
/**
* Creates all twins specified in the DTDL->DigitalTwins directory.
* @throws IOException If an I/O error is thrown when accessing the starting file.
* @throws InterruptedException If the current thread is interrupted while waiting to acquire latch.
*/
public static void createAllTwins() throws IOException, InterruptedException {
System.out.println("CREATE DIGITAL TWINS");
Map<String, String> twins = FileHelper.loadAllFilesInPath(TwinsPath);
final CountDownLatch createTwinsLatch = new CountDownLatch(twins.size());
twins
.forEach((twinId, twinContent) -> client.createDigitalTwin(twinId, twinContent)
.subscribe(
twin -> System.out.println("Created digital twin: " + twinId + "\n\t Body: " + twin),
throwable -> System.err.println("Could not create digital twin " + twinId + " due to " + throwable),
createTwinsLatch::countDown));
createTwinsLatch.await(MaxWaitTimeAsyncOperationsInSeconds, TimeUnit.SECONDS);
}
public static void connectTwinsTogether() throws IOException, InterruptedException {
System.out.println("CONNECT DIGITAL TWINS");
Map<String, String> allRelationships = FileHelper.loadAllFilesInPath(RelationshipsPath);
final CountDownLatch connectTwinsLatch = new CountDownLatch(4);
allRelationships.values().forEach(
relationshipContent -> {
try {
List<BasicRelationship> relationships = mapper.readValue(relationshipContent, new TypeReference<List<BasicRelationship>>() { });
relationships
.forEach(relationship -> {
try {
client.createRelationship(relationship.getSourceId(), relationship.getId(), mapper.writeValueAsString(relationship))
.doOnSuccess(s -> System.out.println("Linked twin " + relationship.getSourceId() + " to twin " + relationship.getTargetId() + " as " + relationship.getName()))
.doOnError(IgnoreConflictError)
.doOnTerminate(connectTwinsLatch::countDown)
.subscribe();
} catch (JsonProcessingException e) {
throw new RuntimeException("JsonProcessingException while serializing relationship string from BasicRelationship: ", e);
}
});
} catch (JsonProcessingException e) {
throw new RuntimeException("JsonProcessingException while deserializing relationship string to BasicRelationship: ", e);
}
}
);
connectTwinsLatch.await(MaxWaitTimeAsyncOperationsInSeconds, TimeUnit.SECONDS);
}
} | class DigitalTwinsLifecycleAsyncSample {
private static final String tenantId = System.getenv("TENANT_ID");
private static final String clientId = System.getenv("CLIENT_ID");
private static final String clientSecret = System.getenv("CLIENT_SECRET");
private static final String endpoint = System.getenv("DIGITAL_TWINS_ENDPOINT");
private static final int MaxWaitTimeAsyncOperationsInSeconds = 10;
private static final ObjectMapper mapper = new ObjectMapper();
private static final URL DtdlDirectoryUrl = DigitalTwinsLifecycleAsyncSample.class.getClassLoader().getResource("DTDL");
private static final Path DtDlDirectoryPath;
private static final Path TwinsPath;
private static final Path ModelsPath;
private static final Path RelationshipsPath;
private static final DigitalTwinsAsyncClient client;
static {
try {
assert DtdlDirectoryUrl != null;
DtDlDirectoryPath = Paths.get(DtdlDirectoryUrl.toURI());
} catch (URISyntaxException e) {
throw new RuntimeException("Unable to convert the DTDL directory URL to URI", e);
}
TwinsPath = Paths.get(DtDlDirectoryPath.toString(), "DigitalTwins");
ModelsPath = Paths.get(DtDlDirectoryPath.toString(), "Models");
RelationshipsPath = Paths.get(DtDlDirectoryPath.toString(), "Relationships");
client = new DigitalTwinsClientBuilder()
.tokenCredential(
new ClientSecretCredentialBuilder()
.tenantId(tenantId)
.clientId(clientId)
.clientSecret(clientSecret)
.build()
)
.endpoint(endpoint)
.httpLogOptions(
new HttpLogOptions()
.setLogLevel(HttpLogDetailLevel.NONE))
.buildAsyncClient();
}
public static void main(String[] args) throws IOException, InterruptedException {
deleteTwins();
deleteAllModels();
createAllModels();
listAllModels();
createAllTwins();
connectTwinsTogether();
}
/**
* Delete a twin, and any relationships it might have.
* @throws IOException If an I/O error is thrown when accessing the starting file.
* @throws InterruptedException If the current thread is interrupted while waiting to acquire latch.
*/
/**
* Delete models created by FullLifecycleSample for the ADT service instance.
* @throws InterruptedException If the current thread is interrupted while waiting to acquire latch.
*/
public static void deleteAllModels() throws InterruptedException {
System.out.println("DELETING MODELS");
List<String> models = asList(RoomModelId, WifiModelId, BuildingModelId, FloorModelId, HvacModelId);
models
.forEach(modelId -> {
try {
client.deleteModel(modelId).block();
System.out.println("Deleted model: " + modelId);
} catch (ErrorResponseException ex) {
if (ex.getResponse().getStatusCode() != HttpStatus.SC_NOT_FOUND) {
System.err.println("Could not delete model " + modelId + " due to " + ex);
}
}
});
}
/**
* Loads all the models found in the Models directory into memory and uses CreateModelsAsync API to create all the models in the ADT service instance.
* @throws IOException If an I/O error is thrown when accessing the starting file.
* @throws InterruptedException If the current thread is interrupted while waiting to acquire latch.
*/
public static void createAllModels() throws IOException, InterruptedException {
System.out.println("CREATING MODELS");
List<String> modelsToCreate = new ArrayList<>(FileHelper.loadAllFilesInPath(ModelsPath).values());
final CountDownLatch createModelsLatch = new CountDownLatch(1);
client.createModels(modelsToCreate)
.doOnNext(modelData -> System.out.println("Created model: " + modelData.getId()))
.doOnError(IgnoreConflictError)
.doOnTerminate(createModelsLatch::countDown)
.subscribe();
createModelsLatch.await(MaxWaitTimeAsyncOperationsInSeconds, TimeUnit.SECONDS);
}
/**
* Gets all the models within the ADT service instance.
* @throws InterruptedException If the current thread is interrupted while waiting to acquire latch.
*/
public static void listAllModels() throws InterruptedException {
System.out.println("LISTING MODELS");
final CountDownLatch listModelsLatch = new CountDownLatch(1);
client.listModels()
.doOnNext(modelData -> System.out.println("Retrieved model: " + modelData.getId() + ", display name '" + modelData.getDisplayName().get("en") + "'," +
" upload time '" + modelData.getUploadTime() + "' and decommissioned '" + modelData.isDecommissioned() + "'"))
.doOnError(throwable -> System.err.println("List models error: " + throwable))
.doOnTerminate(listModelsLatch::countDown)
.subscribe();
listModelsLatch.await(MaxWaitTimeAsyncOperationsInSeconds, TimeUnit.SECONDS);
}
/**
* Creates all twins specified in the DTDL->DigitalTwins directory.
* @throws IOException If an I/O error is thrown when accessing the starting file.
* @throws InterruptedException If the current thread is interrupted while waiting to acquire latch.
*/
public static void createAllTwins() throws IOException, InterruptedException {
System.out.println("CREATE DIGITAL TWINS");
Map<String, String> twins = FileHelper.loadAllFilesInPath(TwinsPath);
final CountDownLatch createTwinsLatch = new CountDownLatch(twins.size());
twins
.forEach((twinId, twinContent) -> client.createDigitalTwin(twinId, twinContent)
.subscribe(
twin -> System.out.println("Created digital twin: " + twinId + "\n\t Body: " + twin),
throwable -> System.err.println("Could not create digital twin " + twinId + " due to " + throwable),
createTwinsLatch::countDown));
createTwinsLatch.await(MaxWaitTimeAsyncOperationsInSeconds, TimeUnit.SECONDS);
}
/**
* Creates all the relationships defined in the DTDL->Relationships directory
* @throws IOException If an I/O error is thrown when accessing the starting file.
* @throws InterruptedException If the current thread is interrupted while waiting to acquire latch.
*/
public static void connectTwinsTogether() throws IOException, InterruptedException {
System.out.println("CONNECT DIGITAL TWINS");
Map<String, String> allRelationships = FileHelper.loadAllFilesInPath(RelationshipsPath);
final CountDownLatch connectTwinsLatch = new CountDownLatch(4);
allRelationships.values().forEach(
relationshipContent -> {
try {
List<BasicRelationship> relationships = mapper.readValue(relationshipContent, new TypeReference<List<BasicRelationship>>() { });
relationships
.forEach(relationship -> {
try {
client.createRelationship(relationship.getSourceId(), relationship.getId(), mapper.writeValueAsString(relationship))
.doOnSuccess(s -> System.out.println("Linked twin " + relationship.getSourceId() + " to twin " + relationship.getTargetId() + " as " + relationship.getName()))
.doOnError(IgnoreConflictError)
.doOnTerminate(connectTwinsLatch::countDown)
.subscribe();
} catch (JsonProcessingException e) {
throw new RuntimeException("JsonProcessingException while serializing relationship string from BasicRelationship: ", e);
}
});
} catch (JsonProcessingException e) {
throw new RuntimeException("JsonProcessingException while deserializing relationship string to BasicRelationship: ", e);
}
}
);
connectTwinsLatch.await(MaxWaitTimeAsyncOperationsInSeconds, TimeUnit.SECONDS);
}
} | |
Does Java support string interpolation? | public static void deleteTwins() throws IOException, InterruptedException {
System.out.println("DELETE DIGITAL TWINS");
Map<String, String> twins = FileHelper.loadAllFilesInPath(TwinsPath);
for (Map.Entry<String, String> twin : twins.entrySet()) {
String twinId = twin.getKey();
List<BasicRelationship> relationshipList = new ArrayList<>();
Semaphore listRelationshipSemaphore = new Semaphore(0);
Semaphore deleteRelationshipsSemaphore = new Semaphore(0);
CountDownLatch deleteTwinsLatch = new CountDownLatch(1);
client.listRelationships(twinId, BasicRelationship.class)
.doOnNext(relationshipList::add)
.doOnError(IgnoreNotFoundError)
.doOnTerminate(listRelationshipSemaphore::release)
.subscribe();
client.listIncomingRelationships(twinId)
.doOnNext(e -> relationshipList.add(mapper.convertValue(e, BasicRelationship.class)))
.doOnError(IgnoreNotFoundError)
.doOnTerminate(listRelationshipSemaphore::release)
.subscribe();
if (listRelationshipSemaphore.tryAcquire(2, MaxWaitTimeAsyncOperationsInSeconds, TimeUnit.SECONDS)) {
relationshipList
.forEach(relationship -> client.deleteRelationship(relationship.getSourceId(), relationship.getId())
.doOnSuccess(aVoid -> {
if (twinId.equals(relationship.getSourceId())) {
System.out.println("Found and deleted relationship: " + relationship.getId());
} else {
System.out.println("Found and deleted incoming relationship: " + relationship.getId());
}
})
.doOnError(IgnoreNotFoundError)
.doOnTerminate(deleteRelationshipsSemaphore::release)
.subscribe());
}
if (deleteRelationshipsSemaphore.tryAcquire(relationshipList.size(), MaxWaitTimeAsyncOperationsInSeconds, TimeUnit.SECONDS)) {
client.deleteDigitalTwin(twinId)
.doOnSuccess(aVoid -> System.out.println("Deleted digital twin: " + twinId))
.doOnError(IgnoreNotFoundError)
.doOnTerminate(deleteTwinsLatch::countDown)
.subscribe();
deleteTwinsLatch.await(MaxWaitTimeAsyncOperationsInSeconds, TimeUnit.SECONDS);
}
}
} | System.out.println("Found and deleted relationship: " + relationship.getId()); | public static void deleteTwins() throws IOException, InterruptedException {
System.out.println("DELETE DIGITAL TWINS");
Map<String, String> twins = FileHelper.loadAllFilesInPath(TwinsPath);
for (Map.Entry<String, String> twin : twins.entrySet()) {
String twinId = twin.getKey();
List<BasicRelationship> relationshipList = Collections.synchronizedList(new ArrayList<>());
Semaphore listRelationshipSemaphore = new Semaphore(0);
Semaphore deleteRelationshipsSemaphore = new Semaphore(0);
CountDownLatch deleteTwinsLatch = new CountDownLatch(1);
client.listRelationships(twinId, BasicRelationship.class)
.doOnNext(relationshipList::add)
.doOnError(IgnoreNotFoundError)
.doOnTerminate(listRelationshipSemaphore::release)
.subscribe();
client.listIncomingRelationships(twinId)
.doOnNext(e -> relationshipList.add(mapper.convertValue(e, BasicRelationship.class)))
.doOnError(IgnoreNotFoundError)
.doOnTerminate(listRelationshipSemaphore::release)
.subscribe();
if (listRelationshipSemaphore.tryAcquire(2, MaxWaitTimeAsyncOperationsInSeconds, TimeUnit.SECONDS)) {
relationshipList
.forEach(relationship -> client.deleteRelationship(relationship.getSourceId(), relationship.getId())
.doOnSuccess(aVoid -> {
if (twinId.equals(relationship.getSourceId())) {
System.out.println("Found and deleted relationship: " + relationship.getId());
} else {
System.out.println("Found and deleted incoming relationship: " + relationship.getId());
}
})
.doOnError(IgnoreNotFoundError)
.doOnTerminate(deleteRelationshipsSemaphore::release)
.subscribe());
}
if (deleteRelationshipsSemaphore.tryAcquire(relationshipList.size(), MaxWaitTimeAsyncOperationsInSeconds, TimeUnit.SECONDS)) {
client.deleteDigitalTwin(twinId)
.doOnSuccess(aVoid -> System.out.println("Deleted digital twin: " + twinId))
.doOnError(IgnoreNotFoundError)
.doOnTerminate(deleteTwinsLatch::countDown)
.subscribe();
deleteTwinsLatch.await(MaxWaitTimeAsyncOperationsInSeconds, TimeUnit.SECONDS);
}
}
} | class DigitalTwinsLifecycleAsyncSample {
private static final String tenantId = System.getenv("TENANT_ID");
private static final String clientId = System.getenv("CLIENT_ID");
private static final String clientSecret = System.getenv("CLIENT_SECRET");
private static final String endpoint = System.getenv("DIGITAL_TWINS_ENDPOINT");
private static final int MaxWaitTimeAsyncOperationsInSeconds = 10;
private static final ObjectMapper mapper = new ObjectMapper();
private static final URL DtdlDirectoryUrl = DigitalTwinsLifecycleAsyncSample.class.getClassLoader().getResource("DTDL");
private static final Path DtDlDirectoryPath;
private static final Path TwinsPath;
private static final Path ModelsPath;
private static final Path RelationshipsPath;
private static final DigitalTwinsAsyncClient client;
static {
try {
assert DtdlDirectoryUrl != null;
DtDlDirectoryPath = Paths.get(DtdlDirectoryUrl.toURI());
} catch (URISyntaxException e) {
throw new RuntimeException("Unable to convert the DTDL directory URL to URI", e);
}
TwinsPath = Paths.get(DtDlDirectoryPath.toString(), "DigitalTwins");
ModelsPath = Paths.get(DtDlDirectoryPath.toString(), "Models");
RelationshipsPath = Paths.get(DtDlDirectoryPath.toString(), "Relationships");
client = new DigitalTwinsClientBuilder()
.tokenCredential(
new ClientSecretCredentialBuilder()
.tenantId(tenantId)
.clientId(clientId)
.clientSecret(clientSecret)
.build()
)
.endpoint(endpoint)
.httpLogOptions(
new HttpLogOptions()
.setLogLevel(HttpLogDetailLevel.NONE))
.buildAsyncClient();
}
public static void main(String[] args) throws IOException, InterruptedException {
deleteTwins();
deleteAllModels();
createAllModels();
listAllModels();
createAllTwins();
connectTwinsTogether();
}
/**
* Delete a twin, and any relationships it might have.
* @throws IOException If an I/O error is thrown when accessing the starting file.
* @throws InterruptedException If the current thread is interrupted while waiting to acquire latch.
*/
/**
* Delete models created by FullLifecycleSample for the ADT service instance.
* @throws InterruptedException If the current thread is interrupted while waiting to acquire latch.
*/
public static void deleteAllModels() throws InterruptedException {
System.out.println("DELETING MODELS");
List<String> models = asList(RoomModelId, WifiModelId, BuildingModelId, FloorModelId, HvacModelId);
models
.forEach(modelId -> {
try {
client.deleteModel(modelId).block();
System.out.println("Deleted model: " + modelId);
} catch (ErrorResponseException ex) {
if (ex.getResponse().getStatusCode() != HttpStatus.SC_NOT_FOUND) {
System.err.println("Could not delete model " + modelId + " due to " + ex);
}
}
});
}
/**
* Loads all the models found in the Models directory into memory and uses CreateModelsAsync API to create all the models in the ADT service instance.
* @throws IOException If an I/O error is thrown when accessing the starting file.
* @throws InterruptedException If the current thread is interrupted while waiting to acquire latch.
*/
public static void createAllModels() throws IOException, InterruptedException {
System.out.println("CREATING MODELS");
List<String> modelsToCreate = new ArrayList<>(FileHelper.loadAllFilesInPath(ModelsPath).values());
final CountDownLatch createModelsLatch = new CountDownLatch(1);
client.createModels(modelsToCreate)
.doOnNext(modelData -> System.out.println("Created model: " + modelData.getId()))
.doOnError(IgnoreConflictError)
.doOnTerminate(createModelsLatch::countDown)
.subscribe();
createModelsLatch.await(MaxWaitTimeAsyncOperationsInSeconds, TimeUnit.SECONDS);
}
/**
* Gets all the models within the ADT service instance.
* @throws InterruptedException If the current thread is interrupted while waiting to acquire latch.
*/
public static void listAllModels() throws InterruptedException {
System.out.println("LISTING MODELS");
final CountDownLatch listModelsLatch = new CountDownLatch(1);
client.listModels()
.doOnNext(modelData -> System.out.println(String.format("Retrieved model: %s, display name '%s', upload time '%s' and decommissioned '%s'",
modelData.getId(), modelData.getDisplayName().get("en"), modelData.getUploadTime(), modelData.isDecommissioned())))
.doOnError(throwable -> System.err.println("List models error: " + throwable))
.doOnTerminate(listModelsLatch::countDown)
.subscribe();
listModelsLatch.await(MaxWaitTimeAsyncOperationsInSeconds, TimeUnit.SECONDS);
}
/**
* Creates all twins specified in the DTDL->DigitalTwins directory.
* @throws IOException If an I/O error is thrown when accessing the starting file.
* @throws InterruptedException If the current thread is interrupted while waiting to acquire latch.
*/
public static void createAllTwins() throws IOException, InterruptedException {
System.out.println("CREATE DIGITAL TWINS");
Map<String, String> twins = FileHelper.loadAllFilesInPath(TwinsPath);
final CountDownLatch createTwinsLatch = new CountDownLatch(twins.size());
twins
.forEach((twinId, twinContent) -> client.createDigitalTwin(twinId, twinContent)
.subscribe(
twin -> System.out.println("Created digital twin: " + twinId + "\n\t Body: " + twin),
throwable -> System.err.println("Could not create digital twin " + twinId + " due to " + throwable),
createTwinsLatch::countDown));
createTwinsLatch.await(MaxWaitTimeAsyncOperationsInSeconds, TimeUnit.SECONDS);
}
public static void connectTwinsTogether() throws IOException, InterruptedException {
System.out.println("CONNECT DIGITAL TWINS");
Map<String, String> allRelationships = FileHelper.loadAllFilesInPath(RelationshipsPath);
final CountDownLatch connectTwinsLatch = new CountDownLatch(4);
allRelationships.values().forEach(
relationshipContent -> {
try {
List<BasicRelationship> relationships = mapper.readValue(relationshipContent, new TypeReference<List<BasicRelationship>>() { });
relationships
.forEach(relationship -> {
try {
client.createRelationship(relationship.getSourceId(), relationship.getId(), mapper.writeValueAsString(relationship))
.doOnSuccess(s -> System.out.println("Linked twin " + relationship.getSourceId() + " to twin " + relationship.getTargetId() + " as " + relationship.getName()))
.doOnError(IgnoreConflictError)
.doOnTerminate(connectTwinsLatch::countDown)
.subscribe();
} catch (JsonProcessingException e) {
throw new RuntimeException("JsonProcessingException while serializing relationship string from BasicRelationship: ", e);
}
});
} catch (JsonProcessingException e) {
throw new RuntimeException("JsonProcessingException while deserializing relationship string to BasicRelationship: ", e);
}
}
);
connectTwinsLatch.await(MaxWaitTimeAsyncOperationsInSeconds, TimeUnit.SECONDS);
}
} | class DigitalTwinsLifecycleAsyncSample {
private static final String tenantId = System.getenv("TENANT_ID");
private static final String clientId = System.getenv("CLIENT_ID");
private static final String clientSecret = System.getenv("CLIENT_SECRET");
private static final String endpoint = System.getenv("DIGITAL_TWINS_ENDPOINT");
private static final int MaxWaitTimeAsyncOperationsInSeconds = 10;
private static final ObjectMapper mapper = new ObjectMapper();
private static final URL DtdlDirectoryUrl = DigitalTwinsLifecycleAsyncSample.class.getClassLoader().getResource("DTDL");
private static final Path DtDlDirectoryPath;
private static final Path TwinsPath;
private static final Path ModelsPath;
private static final Path RelationshipsPath;
private static final DigitalTwinsAsyncClient client;
static {
try {
assert DtdlDirectoryUrl != null;
DtDlDirectoryPath = Paths.get(DtdlDirectoryUrl.toURI());
} catch (URISyntaxException e) {
throw new RuntimeException("Unable to convert the DTDL directory URL to URI", e);
}
TwinsPath = Paths.get(DtDlDirectoryPath.toString(), "DigitalTwins");
ModelsPath = Paths.get(DtDlDirectoryPath.toString(), "Models");
RelationshipsPath = Paths.get(DtDlDirectoryPath.toString(), "Relationships");
client = new DigitalTwinsClientBuilder()
.tokenCredential(
new ClientSecretCredentialBuilder()
.tenantId(tenantId)
.clientId(clientId)
.clientSecret(clientSecret)
.build()
)
.endpoint(endpoint)
.httpLogOptions(
new HttpLogOptions()
.setLogLevel(HttpLogDetailLevel.NONE))
.buildAsyncClient();
}
public static void main(String[] args) throws IOException, InterruptedException {
deleteTwins();
deleteAllModels();
createAllModels();
listAllModels();
createAllTwins();
connectTwinsTogether();
}
/**
* Delete a twin, and any relationships it might have.
* @throws IOException If an I/O error is thrown when accessing the starting file.
* @throws InterruptedException If the current thread is interrupted while waiting to acquire latch.
*/
/**
* Delete models created by FullLifecycleSample for the ADT service instance.
* @throws InterruptedException If the current thread is interrupted while waiting to acquire latch.
*/
public static void deleteAllModels() throws InterruptedException {
System.out.println("DELETING MODELS");
List<String> models = asList(RoomModelId, WifiModelId, BuildingModelId, FloorModelId, HvacModelId);
models
.forEach(modelId -> {
try {
client.deleteModel(modelId).block();
System.out.println("Deleted model: " + modelId);
} catch (ErrorResponseException ex) {
if (ex.getResponse().getStatusCode() != HttpStatus.SC_NOT_FOUND) {
System.err.println("Could not delete model " + modelId + " due to " + ex);
}
}
});
}
/**
* Loads all the models found in the Models directory into memory and uses CreateModelsAsync API to create all the models in the ADT service instance.
* @throws IOException If an I/O error is thrown when accessing the starting file.
* @throws InterruptedException If the current thread is interrupted while waiting to acquire latch.
*/
public static void createAllModels() throws IOException, InterruptedException {
System.out.println("CREATING MODELS");
List<String> modelsToCreate = new ArrayList<>(FileHelper.loadAllFilesInPath(ModelsPath).values());
final CountDownLatch createModelsLatch = new CountDownLatch(1);
client.createModels(modelsToCreate)
.doOnNext(modelData -> System.out.println("Created model: " + modelData.getId()))
.doOnError(IgnoreConflictError)
.doOnTerminate(createModelsLatch::countDown)
.subscribe();
createModelsLatch.await(MaxWaitTimeAsyncOperationsInSeconds, TimeUnit.SECONDS);
}
/**
* Gets all the models within the ADT service instance.
* @throws InterruptedException If the current thread is interrupted while waiting to acquire latch.
*/
public static void listAllModels() throws InterruptedException {
System.out.println("LISTING MODELS");
final CountDownLatch listModelsLatch = new CountDownLatch(1);
client.listModels()
.doOnNext(modelData -> System.out.println("Retrieved model: " + modelData.getId() + ", display name '" + modelData.getDisplayName().get("en") + "'," +
" upload time '" + modelData.getUploadTime() + "' and decommissioned '" + modelData.isDecommissioned() + "'"))
.doOnError(throwable -> System.err.println("List models error: " + throwable))
.doOnTerminate(listModelsLatch::countDown)
.subscribe();
listModelsLatch.await(MaxWaitTimeAsyncOperationsInSeconds, TimeUnit.SECONDS);
}
/**
* Creates all twins specified in the DTDL->DigitalTwins directory.
* @throws IOException If an I/O error is thrown when accessing the starting file.
* @throws InterruptedException If the current thread is interrupted while waiting to acquire latch.
*/
public static void createAllTwins() throws IOException, InterruptedException {
System.out.println("CREATE DIGITAL TWINS");
Map<String, String> twins = FileHelper.loadAllFilesInPath(TwinsPath);
final CountDownLatch createTwinsLatch = new CountDownLatch(twins.size());
twins
.forEach((twinId, twinContent) -> client.createDigitalTwin(twinId, twinContent)
.subscribe(
twin -> System.out.println("Created digital twin: " + twinId + "\n\t Body: " + twin),
throwable -> System.err.println("Could not create digital twin " + twinId + " due to " + throwable),
createTwinsLatch::countDown));
createTwinsLatch.await(MaxWaitTimeAsyncOperationsInSeconds, TimeUnit.SECONDS);
}
/**
* Creates all the relationships defined in the DTDL->Relationships directory
* @throws IOException If an I/O error is thrown when accessing the starting file.
* @throws InterruptedException If the current thread is interrupted while waiting to acquire latch.
*/
public static void connectTwinsTogether() throws IOException, InterruptedException {
System.out.println("CONNECT DIGITAL TWINS");
Map<String, String> allRelationships = FileHelper.loadAllFilesInPath(RelationshipsPath);
final CountDownLatch connectTwinsLatch = new CountDownLatch(4);
allRelationships.values().forEach(
relationshipContent -> {
try {
List<BasicRelationship> relationships = mapper.readValue(relationshipContent, new TypeReference<List<BasicRelationship>>() { });
relationships
.forEach(relationship -> {
try {
client.createRelationship(relationship.getSourceId(), relationship.getId(), mapper.writeValueAsString(relationship))
.doOnSuccess(s -> System.out.println("Linked twin " + relationship.getSourceId() + " to twin " + relationship.getTargetId() + " as " + relationship.getName()))
.doOnError(IgnoreConflictError)
.doOnTerminate(connectTwinsLatch::countDown)
.subscribe();
} catch (JsonProcessingException e) {
throw new RuntimeException("JsonProcessingException while serializing relationship string from BasicRelationship: ", e);
}
});
} catch (JsonProcessingException e) {
throw new RuntimeException("JsonProcessingException while deserializing relationship string to BasicRelationship: ", e);
}
}
);
connectTwinsLatch.await(MaxWaitTimeAsyncOperationsInSeconds, TimeUnit.SECONDS);
}
} |
Appears to be some kind of threadsafe counter, eh? I'd reword this to be "Wait until the latch count reaches zero..." | public static void deleteTwins() throws IOException, InterruptedException {
System.out.println("DELETE DIGITAL TWINS");
Map<String, String> twins = FileHelper.loadAllFilesInPath(TwinsPath);
for (Map.Entry<String, String> twin : twins.entrySet()) {
String twinId = twin.getKey();
List<BasicRelationship> relationshipList = new ArrayList<>();
Semaphore listRelationshipSemaphore = new Semaphore(0);
Semaphore deleteRelationshipsSemaphore = new Semaphore(0);
CountDownLatch deleteTwinsLatch = new CountDownLatch(1);
client.listRelationships(twinId, BasicRelationship.class)
.doOnNext(relationshipList::add)
.doOnError(IgnoreNotFoundError)
.doOnTerminate(listRelationshipSemaphore::release)
.subscribe();
client.listIncomingRelationships(twinId)
.doOnNext(e -> relationshipList.add(mapper.convertValue(e, BasicRelationship.class)))
.doOnError(IgnoreNotFoundError)
.doOnTerminate(listRelationshipSemaphore::release)
.subscribe();
if (listRelationshipSemaphore.tryAcquire(2, MaxWaitTimeAsyncOperationsInSeconds, TimeUnit.SECONDS)) {
relationshipList
.forEach(relationship -> client.deleteRelationship(relationship.getSourceId(), relationship.getId())
.doOnSuccess(aVoid -> {
if (twinId.equals(relationship.getSourceId())) {
System.out.println("Found and deleted relationship: " + relationship.getId());
} else {
System.out.println("Found and deleted incoming relationship: " + relationship.getId());
}
})
.doOnError(IgnoreNotFoundError)
.doOnTerminate(deleteRelationshipsSemaphore::release)
.subscribe());
}
if (deleteRelationshipsSemaphore.tryAcquire(relationshipList.size(), MaxWaitTimeAsyncOperationsInSeconds, TimeUnit.SECONDS)) {
client.deleteDigitalTwin(twinId)
.doOnSuccess(aVoid -> System.out.println("Deleted digital twin: " + twinId))
.doOnError(IgnoreNotFoundError)
.doOnTerminate(deleteTwinsLatch::countDown)
.subscribe();
deleteTwinsLatch.await(MaxWaitTimeAsyncOperationsInSeconds, TimeUnit.SECONDS);
}
}
} | public static void deleteTwins() throws IOException, InterruptedException {
System.out.println("DELETE DIGITAL TWINS");
Map<String, String> twins = FileHelper.loadAllFilesInPath(TwinsPath);
for (Map.Entry<String, String> twin : twins.entrySet()) {
String twinId = twin.getKey();
List<BasicRelationship> relationshipList = Collections.synchronizedList(new ArrayList<>());
Semaphore listRelationshipSemaphore = new Semaphore(0);
Semaphore deleteRelationshipsSemaphore = new Semaphore(0);
CountDownLatch deleteTwinsLatch = new CountDownLatch(1);
client.listRelationships(twinId, BasicRelationship.class)
.doOnNext(relationshipList::add)
.doOnError(IgnoreNotFoundError)
.doOnTerminate(listRelationshipSemaphore::release)
.subscribe();
client.listIncomingRelationships(twinId)
.doOnNext(e -> relationshipList.add(mapper.convertValue(e, BasicRelationship.class)))
.doOnError(IgnoreNotFoundError)
.doOnTerminate(listRelationshipSemaphore::release)
.subscribe();
if (listRelationshipSemaphore.tryAcquire(2, MaxWaitTimeAsyncOperationsInSeconds, TimeUnit.SECONDS)) {
relationshipList
.forEach(relationship -> client.deleteRelationship(relationship.getSourceId(), relationship.getId())
.doOnSuccess(aVoid -> {
if (twinId.equals(relationship.getSourceId())) {
System.out.println("Found and deleted relationship: " + relationship.getId());
} else {
System.out.println("Found and deleted incoming relationship: " + relationship.getId());
}
})
.doOnError(IgnoreNotFoundError)
.doOnTerminate(deleteRelationshipsSemaphore::release)
.subscribe());
}
if (deleteRelationshipsSemaphore.tryAcquire(relationshipList.size(), MaxWaitTimeAsyncOperationsInSeconds, TimeUnit.SECONDS)) {
client.deleteDigitalTwin(twinId)
.doOnSuccess(aVoid -> System.out.println("Deleted digital twin: " + twinId))
.doOnError(IgnoreNotFoundError)
.doOnTerminate(deleteTwinsLatch::countDown)
.subscribe();
deleteTwinsLatch.await(MaxWaitTimeAsyncOperationsInSeconds, TimeUnit.SECONDS);
}
}
} | class DigitalTwinsLifecycleAsyncSample {
private static final String tenantId = System.getenv("TENANT_ID");
private static final String clientId = System.getenv("CLIENT_ID");
private static final String clientSecret = System.getenv("CLIENT_SECRET");
private static final String endpoint = System.getenv("DIGITAL_TWINS_ENDPOINT");
private static final int MaxWaitTimeAsyncOperationsInSeconds = 10;
private static final ObjectMapper mapper = new ObjectMapper();
private static final URL DtdlDirectoryUrl = DigitalTwinsLifecycleAsyncSample.class.getClassLoader().getResource("DTDL");
private static final Path DtDlDirectoryPath;
private static final Path TwinsPath;
private static final Path ModelsPath;
private static final Path RelationshipsPath;
private static final DigitalTwinsAsyncClient client;
static {
try {
assert DtdlDirectoryUrl != null;
DtDlDirectoryPath = Paths.get(DtdlDirectoryUrl.toURI());
} catch (URISyntaxException e) {
throw new RuntimeException("Unable to convert the DTDL directory URL to URI", e);
}
TwinsPath = Paths.get(DtDlDirectoryPath.toString(), "DigitalTwins");
ModelsPath = Paths.get(DtDlDirectoryPath.toString(), "Models");
RelationshipsPath = Paths.get(DtDlDirectoryPath.toString(), "Relationships");
client = new DigitalTwinsClientBuilder()
.tokenCredential(
new ClientSecretCredentialBuilder()
.tenantId(tenantId)
.clientId(clientId)
.clientSecret(clientSecret)
.build()
)
.endpoint(endpoint)
.httpLogOptions(
new HttpLogOptions()
.setLogLevel(HttpLogDetailLevel.NONE))
.buildAsyncClient();
}
public static void main(String[] args) throws IOException, InterruptedException {
deleteTwins();
deleteAllModels();
createAllModels();
listAllModels();
createAllTwins();
connectTwinsTogether();
}
/**
* Delete a twin, and any relationships it might have.
* @throws IOException If an I/O error is thrown when accessing the starting file.
* @throws InterruptedException If the current thread is interrupted while waiting to acquire latch.
*/
/**
* Delete models created by FullLifecycleSample for the ADT service instance.
* @throws InterruptedException If the current thread is interrupted while waiting to acquire latch.
*/
public static void deleteAllModels() throws InterruptedException {
System.out.println("DELETING MODELS");
List<String> models = asList(RoomModelId, WifiModelId, BuildingModelId, FloorModelId, HvacModelId);
models
.forEach(modelId -> {
try {
client.deleteModel(modelId).block();
System.out.println("Deleted model: " + modelId);
} catch (ErrorResponseException ex) {
if (ex.getResponse().getStatusCode() != HttpStatus.SC_NOT_FOUND) {
System.err.println("Could not delete model " + modelId + " due to " + ex);
}
}
});
}
/**
* Loads all the models found in the Models directory into memory and uses CreateModelsAsync API to create all the models in the ADT service instance.
* @throws IOException If an I/O error is thrown when accessing the starting file.
* @throws InterruptedException If the current thread is interrupted while waiting to acquire latch.
*/
public static void createAllModels() throws IOException, InterruptedException {
System.out.println("CREATING MODELS");
List<String> modelsToCreate = new ArrayList<>(FileHelper.loadAllFilesInPath(ModelsPath).values());
final CountDownLatch createModelsLatch = new CountDownLatch(1);
client.createModels(modelsToCreate)
.doOnNext(modelData -> System.out.println("Created model: " + modelData.getId()))
.doOnError(IgnoreConflictError)
.doOnTerminate(createModelsLatch::countDown)
.subscribe();
createModelsLatch.await(MaxWaitTimeAsyncOperationsInSeconds, TimeUnit.SECONDS);
}
/**
* Gets all the models within the ADT service instance.
* @throws InterruptedException If the current thread is interrupted while waiting to acquire latch.
*/
public static void listAllModels() throws InterruptedException {
System.out.println("LISTING MODELS");
final CountDownLatch listModelsLatch = new CountDownLatch(1);
client.listModels()
.doOnNext(modelData -> System.out.println(String.format("Retrieved model: %s, display name '%s', upload time '%s' and decommissioned '%s'",
modelData.getId(), modelData.getDisplayName().get("en"), modelData.getUploadTime(), modelData.isDecommissioned())))
.doOnError(throwable -> System.err.println("List models error: " + throwable))
.doOnTerminate(listModelsLatch::countDown)
.subscribe();
listModelsLatch.await(MaxWaitTimeAsyncOperationsInSeconds, TimeUnit.SECONDS);
}
/**
* Creates all twins specified in the DTDL->DigitalTwins directory.
* @throws IOException If an I/O error is thrown when accessing the starting file.
* @throws InterruptedException If the current thread is interrupted while waiting to acquire latch.
*/
public static void createAllTwins() throws IOException, InterruptedException {
System.out.println("CREATE DIGITAL TWINS");
Map<String, String> twins = FileHelper.loadAllFilesInPath(TwinsPath);
final CountDownLatch createTwinsLatch = new CountDownLatch(twins.size());
twins
.forEach((twinId, twinContent) -> client.createDigitalTwin(twinId, twinContent)
.subscribe(
twin -> System.out.println("Created digital twin: " + twinId + "\n\t Body: " + twin),
throwable -> System.err.println("Could not create digital twin " + twinId + " due to " + throwable),
createTwinsLatch::countDown));
createTwinsLatch.await(MaxWaitTimeAsyncOperationsInSeconds, TimeUnit.SECONDS);
}
public static void connectTwinsTogether() throws IOException, InterruptedException {
System.out.println("CONNECT DIGITAL TWINS");
Map<String, String> allRelationships = FileHelper.loadAllFilesInPath(RelationshipsPath);
final CountDownLatch connectTwinsLatch = new CountDownLatch(4);
allRelationships.values().forEach(
relationshipContent -> {
try {
List<BasicRelationship> relationships = mapper.readValue(relationshipContent, new TypeReference<List<BasicRelationship>>() { });
relationships
.forEach(relationship -> {
try {
client.createRelationship(relationship.getSourceId(), relationship.getId(), mapper.writeValueAsString(relationship))
.doOnSuccess(s -> System.out.println("Linked twin " + relationship.getSourceId() + " to twin " + relationship.getTargetId() + " as " + relationship.getName()))
.doOnError(IgnoreConflictError)
.doOnTerminate(connectTwinsLatch::countDown)
.subscribe();
} catch (JsonProcessingException e) {
throw new RuntimeException("JsonProcessingException while serializing relationship string from BasicRelationship: ", e);
}
});
} catch (JsonProcessingException e) {
throw new RuntimeException("JsonProcessingException while deserializing relationship string to BasicRelationship: ", e);
}
}
);
connectTwinsLatch.await(MaxWaitTimeAsyncOperationsInSeconds, TimeUnit.SECONDS);
}
} | class DigitalTwinsLifecycleAsyncSample {
private static final String tenantId = System.getenv("TENANT_ID");
private static final String clientId = System.getenv("CLIENT_ID");
private static final String clientSecret = System.getenv("CLIENT_SECRET");
private static final String endpoint = System.getenv("DIGITAL_TWINS_ENDPOINT");
private static final int MaxWaitTimeAsyncOperationsInSeconds = 10;
private static final ObjectMapper mapper = new ObjectMapper();
private static final URL DtdlDirectoryUrl = DigitalTwinsLifecycleAsyncSample.class.getClassLoader().getResource("DTDL");
private static final Path DtDlDirectoryPath;
private static final Path TwinsPath;
private static final Path ModelsPath;
private static final Path RelationshipsPath;
private static final DigitalTwinsAsyncClient client;
static {
try {
assert DtdlDirectoryUrl != null;
DtDlDirectoryPath = Paths.get(DtdlDirectoryUrl.toURI());
} catch (URISyntaxException e) {
throw new RuntimeException("Unable to convert the DTDL directory URL to URI", e);
}
TwinsPath = Paths.get(DtDlDirectoryPath.toString(), "DigitalTwins");
ModelsPath = Paths.get(DtDlDirectoryPath.toString(), "Models");
RelationshipsPath = Paths.get(DtDlDirectoryPath.toString(), "Relationships");
client = new DigitalTwinsClientBuilder()
.tokenCredential(
new ClientSecretCredentialBuilder()
.tenantId(tenantId)
.clientId(clientId)
.clientSecret(clientSecret)
.build()
)
.endpoint(endpoint)
.httpLogOptions(
new HttpLogOptions()
.setLogLevel(HttpLogDetailLevel.NONE))
.buildAsyncClient();
}
public static void main(String[] args) throws IOException, InterruptedException {
deleteTwins();
deleteAllModels();
createAllModels();
listAllModels();
createAllTwins();
connectTwinsTogether();
}
/**
* Delete a twin, and any relationships it might have.
* @throws IOException If an I/O error is thrown when accessing the starting file.
* @throws InterruptedException If the current thread is interrupted while waiting to acquire latch.
*/
/**
* Delete models created by FullLifecycleSample for the ADT service instance.
* @throws InterruptedException If the current thread is interrupted while waiting to acquire latch.
*/
public static void deleteAllModels() throws InterruptedException {
System.out.println("DELETING MODELS");
List<String> models = asList(RoomModelId, WifiModelId, BuildingModelId, FloorModelId, HvacModelId);
models
.forEach(modelId -> {
try {
client.deleteModel(modelId).block();
System.out.println("Deleted model: " + modelId);
} catch (ErrorResponseException ex) {
if (ex.getResponse().getStatusCode() != HttpStatus.SC_NOT_FOUND) {
System.err.println("Could not delete model " + modelId + " due to " + ex);
}
}
});
}
/**
* Loads all the models found in the Models directory into memory and uses CreateModelsAsync API to create all the models in the ADT service instance.
* @throws IOException If an I/O error is thrown when accessing the starting file.
* @throws InterruptedException If the current thread is interrupted while waiting to acquire latch.
*/
public static void createAllModels() throws IOException, InterruptedException {
System.out.println("CREATING MODELS");
List<String> modelsToCreate = new ArrayList<>(FileHelper.loadAllFilesInPath(ModelsPath).values());
final CountDownLatch createModelsLatch = new CountDownLatch(1);
client.createModels(modelsToCreate)
.doOnNext(modelData -> System.out.println("Created model: " + modelData.getId()))
.doOnError(IgnoreConflictError)
.doOnTerminate(createModelsLatch::countDown)
.subscribe();
createModelsLatch.await(MaxWaitTimeAsyncOperationsInSeconds, TimeUnit.SECONDS);
}
/**
* Gets all the models within the ADT service instance.
* @throws InterruptedException If the current thread is interrupted while waiting to acquire latch.
*/
public static void listAllModels() throws InterruptedException {
System.out.println("LISTING MODELS");
final CountDownLatch listModelsLatch = new CountDownLatch(1);
client.listModels()
.doOnNext(modelData -> System.out.println("Retrieved model: " + modelData.getId() + ", display name '" + modelData.getDisplayName().get("en") + "'," +
" upload time '" + modelData.getUploadTime() + "' and decommissioned '" + modelData.isDecommissioned() + "'"))
.doOnError(throwable -> System.err.println("List models error: " + throwable))
.doOnTerminate(listModelsLatch::countDown)
.subscribe();
listModelsLatch.await(MaxWaitTimeAsyncOperationsInSeconds, TimeUnit.SECONDS);
}
/**
* Creates all twins specified in the DTDL->DigitalTwins directory.
* @throws IOException If an I/O error is thrown when accessing the starting file.
* @throws InterruptedException If the current thread is interrupted while waiting to acquire latch.
*/
public static void createAllTwins() throws IOException, InterruptedException {
System.out.println("CREATE DIGITAL TWINS");
Map<String, String> twins = FileHelper.loadAllFilesInPath(TwinsPath);
final CountDownLatch createTwinsLatch = new CountDownLatch(twins.size());
twins
.forEach((twinId, twinContent) -> client.createDigitalTwin(twinId, twinContent)
.subscribe(
twin -> System.out.println("Created digital twin: " + twinId + "\n\t Body: " + twin),
throwable -> System.err.println("Could not create digital twin " + twinId + " due to " + throwable),
createTwinsLatch::countDown));
createTwinsLatch.await(MaxWaitTimeAsyncOperationsInSeconds, TimeUnit.SECONDS);
}
/**
* Creates all the relationships defined in the DTDL->Relationships directory
* @throws IOException If an I/O error is thrown when accessing the starting file.
* @throws InterruptedException If the current thread is interrupted while waiting to acquire latch.
*/
public static void connectTwinsTogether() throws IOException, InterruptedException {
System.out.println("CONNECT DIGITAL TWINS");
Map<String, String> allRelationships = FileHelper.loadAllFilesInPath(RelationshipsPath);
final CountDownLatch connectTwinsLatch = new CountDownLatch(4);
allRelationships.values().forEach(
relationshipContent -> {
try {
List<BasicRelationship> relationships = mapper.readValue(relationshipContent, new TypeReference<List<BasicRelationship>>() { });
relationships
.forEach(relationship -> {
try {
client.createRelationship(relationship.getSourceId(), relationship.getId(), mapper.writeValueAsString(relationship))
.doOnSuccess(s -> System.out.println("Linked twin " + relationship.getSourceId() + " to twin " + relationship.getTargetId() + " as " + relationship.getName()))
.doOnError(IgnoreConflictError)
.doOnTerminate(connectTwinsLatch::countDown)
.subscribe();
} catch (JsonProcessingException e) {
throw new RuntimeException("JsonProcessingException while serializing relationship string from BasicRelationship: ", e);
}
});
} catch (JsonProcessingException e) {
throw new RuntimeException("JsonProcessingException while deserializing relationship string to BasicRelationship: ", e);
}
}
);
connectTwinsLatch.await(MaxWaitTimeAsyncOperationsInSeconds, TimeUnit.SECONDS);
}
} | |
Unfortunate that you have to know ahead of time how many items you are counting down. This presents a "magic" number, which can be confusing to someone else reviewing the code who doesn't realize the significance (this will be used to asynchronously delete 1 dt). Also, in C# we have a general rule of not declaring a variable until it is needed (so it is more contextual). Does Java have a different standard of all variables at the top? FWIW, I think this could at least use a comment. | public static void deleteTwins() throws IOException, InterruptedException {
System.out.println("DELETE DIGITAL TWINS");
Map<String, String> twins = FileHelper.loadAllFilesInPath(TwinsPath);
for (Map.Entry<String, String> twin : twins.entrySet()) {
String twinId = twin.getKey();
List<BasicRelationship> relationshipList = new ArrayList<>();
Semaphore listRelationshipSemaphore = new Semaphore(0);
Semaphore deleteRelationshipsSemaphore = new Semaphore(0);
CountDownLatch deleteTwinsLatch = new CountDownLatch(1);
client.listRelationships(twinId, BasicRelationship.class)
.doOnNext(relationshipList::add)
.doOnError(IgnoreNotFoundError)
.doOnTerminate(listRelationshipSemaphore::release)
.subscribe();
client.listIncomingRelationships(twinId)
.doOnNext(e -> relationshipList.add(mapper.convertValue(e, BasicRelationship.class)))
.doOnError(IgnoreNotFoundError)
.doOnTerminate(listRelationshipSemaphore::release)
.subscribe();
if (listRelationshipSemaphore.tryAcquire(2, MaxWaitTimeAsyncOperationsInSeconds, TimeUnit.SECONDS)) {
relationshipList
.forEach(relationship -> client.deleteRelationship(relationship.getSourceId(), relationship.getId())
.doOnSuccess(aVoid -> {
if (twinId.equals(relationship.getSourceId())) {
System.out.println("Found and deleted relationship: " + relationship.getId());
} else {
System.out.println("Found and deleted incoming relationship: " + relationship.getId());
}
})
.doOnError(IgnoreNotFoundError)
.doOnTerminate(deleteRelationshipsSemaphore::release)
.subscribe());
}
if (deleteRelationshipsSemaphore.tryAcquire(relationshipList.size(), MaxWaitTimeAsyncOperationsInSeconds, TimeUnit.SECONDS)) {
client.deleteDigitalTwin(twinId)
.doOnSuccess(aVoid -> System.out.println("Deleted digital twin: " + twinId))
.doOnError(IgnoreNotFoundError)
.doOnTerminate(deleteTwinsLatch::countDown)
.subscribe();
deleteTwinsLatch.await(MaxWaitTimeAsyncOperationsInSeconds, TimeUnit.SECONDS);
}
}
} | CountDownLatch deleteTwinsLatch = new CountDownLatch(1); | public static void deleteTwins() throws IOException, InterruptedException {
System.out.println("DELETE DIGITAL TWINS");
Map<String, String> twins = FileHelper.loadAllFilesInPath(TwinsPath);
for (Map.Entry<String, String> twin : twins.entrySet()) {
String twinId = twin.getKey();
List<BasicRelationship> relationshipList = Collections.synchronizedList(new ArrayList<>());
Semaphore listRelationshipSemaphore = new Semaphore(0);
Semaphore deleteRelationshipsSemaphore = new Semaphore(0);
CountDownLatch deleteTwinsLatch = new CountDownLatch(1);
client.listRelationships(twinId, BasicRelationship.class)
.doOnNext(relationshipList::add)
.doOnError(IgnoreNotFoundError)
.doOnTerminate(listRelationshipSemaphore::release)
.subscribe();
client.listIncomingRelationships(twinId)
.doOnNext(e -> relationshipList.add(mapper.convertValue(e, BasicRelationship.class)))
.doOnError(IgnoreNotFoundError)
.doOnTerminate(listRelationshipSemaphore::release)
.subscribe();
if (listRelationshipSemaphore.tryAcquire(2, MaxWaitTimeAsyncOperationsInSeconds, TimeUnit.SECONDS)) {
relationshipList
.forEach(relationship -> client.deleteRelationship(relationship.getSourceId(), relationship.getId())
.doOnSuccess(aVoid -> {
if (twinId.equals(relationship.getSourceId())) {
System.out.println("Found and deleted relationship: " + relationship.getId());
} else {
System.out.println("Found and deleted incoming relationship: " + relationship.getId());
}
})
.doOnError(IgnoreNotFoundError)
.doOnTerminate(deleteRelationshipsSemaphore::release)
.subscribe());
}
if (deleteRelationshipsSemaphore.tryAcquire(relationshipList.size(), MaxWaitTimeAsyncOperationsInSeconds, TimeUnit.SECONDS)) {
client.deleteDigitalTwin(twinId)
.doOnSuccess(aVoid -> System.out.println("Deleted digital twin: " + twinId))
.doOnError(IgnoreNotFoundError)
.doOnTerminate(deleteTwinsLatch::countDown)
.subscribe();
deleteTwinsLatch.await(MaxWaitTimeAsyncOperationsInSeconds, TimeUnit.SECONDS);
}
}
} | class DigitalTwinsLifecycleAsyncSample {
private static final String tenantId = System.getenv("TENANT_ID");
private static final String clientId = System.getenv("CLIENT_ID");
private static final String clientSecret = System.getenv("CLIENT_SECRET");
private static final String endpoint = System.getenv("DIGITAL_TWINS_ENDPOINT");
private static final int MaxWaitTimeAsyncOperationsInSeconds = 10;
private static final ObjectMapper mapper = new ObjectMapper();
private static final URL DtdlDirectoryUrl = DigitalTwinsLifecycleAsyncSample.class.getClassLoader().getResource("DTDL");
private static final Path DtDlDirectoryPath;
private static final Path TwinsPath;
private static final Path ModelsPath;
private static final Path RelationshipsPath;
private static final DigitalTwinsAsyncClient client;
static {
try {
assert DtdlDirectoryUrl != null;
DtDlDirectoryPath = Paths.get(DtdlDirectoryUrl.toURI());
} catch (URISyntaxException e) {
throw new RuntimeException("Unable to convert the DTDL directory URL to URI", e);
}
TwinsPath = Paths.get(DtDlDirectoryPath.toString(), "DigitalTwins");
ModelsPath = Paths.get(DtDlDirectoryPath.toString(), "Models");
RelationshipsPath = Paths.get(DtDlDirectoryPath.toString(), "Relationships");
client = new DigitalTwinsClientBuilder()
.tokenCredential(
new ClientSecretCredentialBuilder()
.tenantId(tenantId)
.clientId(clientId)
.clientSecret(clientSecret)
.build()
)
.endpoint(endpoint)
.httpLogOptions(
new HttpLogOptions()
.setLogLevel(HttpLogDetailLevel.NONE))
.buildAsyncClient();
}
public static void main(String[] args) throws IOException, InterruptedException {
deleteTwins();
deleteAllModels();
createAllModels();
listAllModels();
createAllTwins();
connectTwinsTogether();
}
/**
* Delete a twin, and any relationships it might have.
* @throws IOException If an I/O error is thrown when accessing the starting file.
* @throws InterruptedException If the current thread is interrupted while waiting to acquire latch.
*/
/**
* Delete models created by FullLifecycleSample for the ADT service instance.
* @throws InterruptedException If the current thread is interrupted while waiting to acquire latch.
*/
public static void deleteAllModels() throws InterruptedException {
System.out.println("DELETING MODELS");
List<String> models = asList(RoomModelId, WifiModelId, BuildingModelId, FloorModelId, HvacModelId);
models
.forEach(modelId -> {
try {
client.deleteModel(modelId).block();
System.out.println("Deleted model: " + modelId);
} catch (ErrorResponseException ex) {
if (ex.getResponse().getStatusCode() != HttpStatus.SC_NOT_FOUND) {
System.err.println("Could not delete model " + modelId + " due to " + ex);
}
}
});
}
/**
* Loads all the models found in the Models directory into memory and uses CreateModelsAsync API to create all the models in the ADT service instance.
* @throws IOException If an I/O error is thrown when accessing the starting file.
* @throws InterruptedException If the current thread is interrupted while waiting to acquire latch.
*/
public static void createAllModels() throws IOException, InterruptedException {
System.out.println("CREATING MODELS");
List<String> modelsToCreate = new ArrayList<>(FileHelper.loadAllFilesInPath(ModelsPath).values());
final CountDownLatch createModelsLatch = new CountDownLatch(1);
client.createModels(modelsToCreate)
.doOnNext(modelData -> System.out.println("Created model: " + modelData.getId()))
.doOnError(IgnoreConflictError)
.doOnTerminate(createModelsLatch::countDown)
.subscribe();
createModelsLatch.await(MaxWaitTimeAsyncOperationsInSeconds, TimeUnit.SECONDS);
}
/**
* Gets all the models within the ADT service instance.
* @throws InterruptedException If the current thread is interrupted while waiting to acquire latch.
*/
public static void listAllModels() throws InterruptedException {
System.out.println("LISTING MODELS");
final CountDownLatch listModelsLatch = new CountDownLatch(1);
client.listModels()
.doOnNext(modelData -> System.out.println(String.format("Retrieved model: %s, display name '%s', upload time '%s' and decommissioned '%s'",
modelData.getId(), modelData.getDisplayName().get("en"), modelData.getUploadTime(), modelData.isDecommissioned())))
.doOnError(throwable -> System.err.println("List models error: " + throwable))
.doOnTerminate(listModelsLatch::countDown)
.subscribe();
listModelsLatch.await(MaxWaitTimeAsyncOperationsInSeconds, TimeUnit.SECONDS);
}
/**
* Creates all twins specified in the DTDL->DigitalTwins directory.
* @throws IOException If an I/O error is thrown when accessing the starting file.
* @throws InterruptedException If the current thread is interrupted while waiting to acquire latch.
*/
public static void createAllTwins() throws IOException, InterruptedException {
System.out.println("CREATE DIGITAL TWINS");
Map<String, String> twins = FileHelper.loadAllFilesInPath(TwinsPath);
final CountDownLatch createTwinsLatch = new CountDownLatch(twins.size());
twins
.forEach((twinId, twinContent) -> client.createDigitalTwin(twinId, twinContent)
.subscribe(
twin -> System.out.println("Created digital twin: " + twinId + "\n\t Body: " + twin),
throwable -> System.err.println("Could not create digital twin " + twinId + " due to " + throwable),
createTwinsLatch::countDown));
createTwinsLatch.await(MaxWaitTimeAsyncOperationsInSeconds, TimeUnit.SECONDS);
}
public static void connectTwinsTogether() throws IOException, InterruptedException {
System.out.println("CONNECT DIGITAL TWINS");
Map<String, String> allRelationships = FileHelper.loadAllFilesInPath(RelationshipsPath);
final CountDownLatch connectTwinsLatch = new CountDownLatch(4);
allRelationships.values().forEach(
relationshipContent -> {
try {
List<BasicRelationship> relationships = mapper.readValue(relationshipContent, new TypeReference<List<BasicRelationship>>() { });
relationships
.forEach(relationship -> {
try {
client.createRelationship(relationship.getSourceId(), relationship.getId(), mapper.writeValueAsString(relationship))
.doOnSuccess(s -> System.out.println("Linked twin " + relationship.getSourceId() + " to twin " + relationship.getTargetId() + " as " + relationship.getName()))
.doOnError(IgnoreConflictError)
.doOnTerminate(connectTwinsLatch::countDown)
.subscribe();
} catch (JsonProcessingException e) {
throw new RuntimeException("JsonProcessingException while serializing relationship string from BasicRelationship: ", e);
}
});
} catch (JsonProcessingException e) {
throw new RuntimeException("JsonProcessingException while deserializing relationship string to BasicRelationship: ", e);
}
}
);
connectTwinsLatch.await(MaxWaitTimeAsyncOperationsInSeconds, TimeUnit.SECONDS);
}
} | class DigitalTwinsLifecycleAsyncSample {
private static final String tenantId = System.getenv("TENANT_ID");
private static final String clientId = System.getenv("CLIENT_ID");
private static final String clientSecret = System.getenv("CLIENT_SECRET");
private static final String endpoint = System.getenv("DIGITAL_TWINS_ENDPOINT");
private static final int MaxWaitTimeAsyncOperationsInSeconds = 10;
private static final ObjectMapper mapper = new ObjectMapper();
private static final URL DtdlDirectoryUrl = DigitalTwinsLifecycleAsyncSample.class.getClassLoader().getResource("DTDL");
private static final Path DtDlDirectoryPath;
private static final Path TwinsPath;
private static final Path ModelsPath;
private static final Path RelationshipsPath;
private static final DigitalTwinsAsyncClient client;
static {
try {
assert DtdlDirectoryUrl != null;
DtDlDirectoryPath = Paths.get(DtdlDirectoryUrl.toURI());
} catch (URISyntaxException e) {
throw new RuntimeException("Unable to convert the DTDL directory URL to URI", e);
}
TwinsPath = Paths.get(DtDlDirectoryPath.toString(), "DigitalTwins");
ModelsPath = Paths.get(DtDlDirectoryPath.toString(), "Models");
RelationshipsPath = Paths.get(DtDlDirectoryPath.toString(), "Relationships");
client = new DigitalTwinsClientBuilder()
.tokenCredential(
new ClientSecretCredentialBuilder()
.tenantId(tenantId)
.clientId(clientId)
.clientSecret(clientSecret)
.build()
)
.endpoint(endpoint)
.httpLogOptions(
new HttpLogOptions()
.setLogLevel(HttpLogDetailLevel.NONE))
.buildAsyncClient();
}
public static void main(String[] args) throws IOException, InterruptedException {
deleteTwins();
deleteAllModels();
createAllModels();
listAllModels();
createAllTwins();
connectTwinsTogether();
}
/**
* Delete a twin, and any relationships it might have.
* @throws IOException If an I/O error is thrown when accessing the starting file.
* @throws InterruptedException If the current thread is interrupted while waiting to acquire latch.
*/
/**
* Delete models created by FullLifecycleSample for the ADT service instance.
* @throws InterruptedException If the current thread is interrupted while waiting to acquire latch.
*/
public static void deleteAllModels() throws InterruptedException {
System.out.println("DELETING MODELS");
List<String> models = asList(RoomModelId, WifiModelId, BuildingModelId, FloorModelId, HvacModelId);
models
.forEach(modelId -> {
try {
client.deleteModel(modelId).block();
System.out.println("Deleted model: " + modelId);
} catch (ErrorResponseException ex) {
if (ex.getResponse().getStatusCode() != HttpStatus.SC_NOT_FOUND) {
System.err.println("Could not delete model " + modelId + " due to " + ex);
}
}
});
}
/**
* Loads all the models found in the Models directory into memory and uses CreateModelsAsync API to create all the models in the ADT service instance.
* @throws IOException If an I/O error is thrown when accessing the starting file.
* @throws InterruptedException If the current thread is interrupted while waiting to acquire latch.
*/
public static void createAllModels() throws IOException, InterruptedException {
System.out.println("CREATING MODELS");
List<String> modelsToCreate = new ArrayList<>(FileHelper.loadAllFilesInPath(ModelsPath).values());
final CountDownLatch createModelsLatch = new CountDownLatch(1);
client.createModels(modelsToCreate)
.doOnNext(modelData -> System.out.println("Created model: " + modelData.getId()))
.doOnError(IgnoreConflictError)
.doOnTerminate(createModelsLatch::countDown)
.subscribe();
createModelsLatch.await(MaxWaitTimeAsyncOperationsInSeconds, TimeUnit.SECONDS);
}
/**
* Gets all the models within the ADT service instance.
* @throws InterruptedException If the current thread is interrupted while waiting to acquire latch.
*/
public static void listAllModels() throws InterruptedException {
System.out.println("LISTING MODELS");
final CountDownLatch listModelsLatch = new CountDownLatch(1);
client.listModels()
.doOnNext(modelData -> System.out.println("Retrieved model: " + modelData.getId() + ", display name '" + modelData.getDisplayName().get("en") + "'," +
" upload time '" + modelData.getUploadTime() + "' and decommissioned '" + modelData.isDecommissioned() + "'"))
.doOnError(throwable -> System.err.println("List models error: " + throwable))
.doOnTerminate(listModelsLatch::countDown)
.subscribe();
listModelsLatch.await(MaxWaitTimeAsyncOperationsInSeconds, TimeUnit.SECONDS);
}
/**
* Creates all twins specified in the DTDL->DigitalTwins directory.
* @throws IOException If an I/O error is thrown when accessing the starting file.
* @throws InterruptedException If the current thread is interrupted while waiting to acquire latch.
*/
public static void createAllTwins() throws IOException, InterruptedException {
System.out.println("CREATE DIGITAL TWINS");
Map<String, String> twins = FileHelper.loadAllFilesInPath(TwinsPath);
final CountDownLatch createTwinsLatch = new CountDownLatch(twins.size());
twins
.forEach((twinId, twinContent) -> client.createDigitalTwin(twinId, twinContent)
.subscribe(
twin -> System.out.println("Created digital twin: " + twinId + "\n\t Body: " + twin),
throwable -> System.err.println("Could not create digital twin " + twinId + " due to " + throwable),
createTwinsLatch::countDown));
createTwinsLatch.await(MaxWaitTimeAsyncOperationsInSeconds, TimeUnit.SECONDS);
}
/**
* Creates all the relationships defined in the DTDL->Relationships directory
* @throws IOException If an I/O error is thrown when accessing the starting file.
* @throws InterruptedException If the current thread is interrupted while waiting to acquire latch.
*/
public static void connectTwinsTogether() throws IOException, InterruptedException {
System.out.println("CONNECT DIGITAL TWINS");
Map<String, String> allRelationships = FileHelper.loadAllFilesInPath(RelationshipsPath);
final CountDownLatch connectTwinsLatch = new CountDownLatch(4);
allRelationships.values().forEach(
relationshipContent -> {
try {
List<BasicRelationship> relationships = mapper.readValue(relationshipContent, new TypeReference<List<BasicRelationship>>() { });
relationships
.forEach(relationship -> {
try {
client.createRelationship(relationship.getSourceId(), relationship.getId(), mapper.writeValueAsString(relationship))
.doOnSuccess(s -> System.out.println("Linked twin " + relationship.getSourceId() + " to twin " + relationship.getTargetId() + " as " + relationship.getName()))
.doOnError(IgnoreConflictError)
.doOnTerminate(connectTwinsLatch::countDown)
.subscribe();
} catch (JsonProcessingException e) {
throw new RuntimeException("JsonProcessingException while serializing relationship string from BasicRelationship: ", e);
}
});
} catch (JsonProcessingException e) {
throw new RuntimeException("JsonProcessingException while deserializing relationship string to BasicRelationship: ", e);
}
}
);
connectTwinsLatch.await(MaxWaitTimeAsyncOperationsInSeconds, TimeUnit.SECONDS);
}
} |
A countdown latch is a mechanism to block the calling thread until other threads that are running in parallel have completed (counted down). The `.countdown()` essentially decrements a thread-safe counter. From this article online: https://www.baeldung.com/java-countdown-latch Simply put, a CountDownLatch has a counter field, which you can decrement as we require. We can then use it to block a calling thread until it's been counted down to zero. If we were doing some parallel processing, we could instantiate the CountDownLatch with the same value for the counter as a number of threads we want to work across. Then, we could just call countdown() after each thread finishes, guaranteeing that a dependent thread calling await() will block until the worker threads are finished. | public static void deleteTwins() throws IOException, InterruptedException {
System.out.println("DELETE DIGITAL TWINS");
Map<String, String> twins = FileHelper.loadAllFilesInPath(TwinsPath);
for (Map.Entry<String, String> twin : twins.entrySet()) {
String twinId = twin.getKey();
List<BasicRelationship> relationshipList = new ArrayList<>();
Semaphore listRelationshipSemaphore = new Semaphore(0);
Semaphore deleteRelationshipsSemaphore = new Semaphore(0);
CountDownLatch deleteTwinsLatch = new CountDownLatch(1);
client.listRelationships(twinId, BasicRelationship.class)
.doOnNext(relationshipList::add)
.doOnError(IgnoreNotFoundError)
.doOnTerminate(listRelationshipSemaphore::release)
.subscribe();
client.listIncomingRelationships(twinId)
.doOnNext(e -> relationshipList.add(mapper.convertValue(e, BasicRelationship.class)))
.doOnError(IgnoreNotFoundError)
.doOnTerminate(listRelationshipSemaphore::release)
.subscribe();
if (listRelationshipSemaphore.tryAcquire(2, MaxWaitTimeAsyncOperationsInSeconds, TimeUnit.SECONDS)) {
relationshipList
.forEach(relationship -> client.deleteRelationship(relationship.getSourceId(), relationship.getId())
.doOnSuccess(aVoid -> {
if (twinId.equals(relationship.getSourceId())) {
System.out.println("Found and deleted relationship: " + relationship.getId());
} else {
System.out.println("Found and deleted incoming relationship: " + relationship.getId());
}
})
.doOnError(IgnoreNotFoundError)
.doOnTerminate(deleteRelationshipsSemaphore::release)
.subscribe());
}
if (deleteRelationshipsSemaphore.tryAcquire(relationshipList.size(), MaxWaitTimeAsyncOperationsInSeconds, TimeUnit.SECONDS)) {
client.deleteDigitalTwin(twinId)
.doOnSuccess(aVoid -> System.out.println("Deleted digital twin: " + twinId))
.doOnError(IgnoreNotFoundError)
.doOnTerminate(deleteTwinsLatch::countDown)
.subscribe();
deleteTwinsLatch.await(MaxWaitTimeAsyncOperationsInSeconds, TimeUnit.SECONDS);
}
}
} | public static void deleteTwins() throws IOException, InterruptedException {
System.out.println("DELETE DIGITAL TWINS");
Map<String, String> twins = FileHelper.loadAllFilesInPath(TwinsPath);
for (Map.Entry<String, String> twin : twins.entrySet()) {
String twinId = twin.getKey();
List<BasicRelationship> relationshipList = Collections.synchronizedList(new ArrayList<>());
Semaphore listRelationshipSemaphore = new Semaphore(0);
Semaphore deleteRelationshipsSemaphore = new Semaphore(0);
CountDownLatch deleteTwinsLatch = new CountDownLatch(1);
client.listRelationships(twinId, BasicRelationship.class)
.doOnNext(relationshipList::add)
.doOnError(IgnoreNotFoundError)
.doOnTerminate(listRelationshipSemaphore::release)
.subscribe();
client.listIncomingRelationships(twinId)
.doOnNext(e -> relationshipList.add(mapper.convertValue(e, BasicRelationship.class)))
.doOnError(IgnoreNotFoundError)
.doOnTerminate(listRelationshipSemaphore::release)
.subscribe();
if (listRelationshipSemaphore.tryAcquire(2, MaxWaitTimeAsyncOperationsInSeconds, TimeUnit.SECONDS)) {
relationshipList
.forEach(relationship -> client.deleteRelationship(relationship.getSourceId(), relationship.getId())
.doOnSuccess(aVoid -> {
if (twinId.equals(relationship.getSourceId())) {
System.out.println("Found and deleted relationship: " + relationship.getId());
} else {
System.out.println("Found and deleted incoming relationship: " + relationship.getId());
}
})
.doOnError(IgnoreNotFoundError)
.doOnTerminate(deleteRelationshipsSemaphore::release)
.subscribe());
}
if (deleteRelationshipsSemaphore.tryAcquire(relationshipList.size(), MaxWaitTimeAsyncOperationsInSeconds, TimeUnit.SECONDS)) {
client.deleteDigitalTwin(twinId)
.doOnSuccess(aVoid -> System.out.println("Deleted digital twin: " + twinId))
.doOnError(IgnoreNotFoundError)
.doOnTerminate(deleteTwinsLatch::countDown)
.subscribe();
deleteTwinsLatch.await(MaxWaitTimeAsyncOperationsInSeconds, TimeUnit.SECONDS);
}
}
} | class DigitalTwinsLifecycleAsyncSample {
private static final String tenantId = System.getenv("TENANT_ID");
private static final String clientId = System.getenv("CLIENT_ID");
private static final String clientSecret = System.getenv("CLIENT_SECRET");
private static final String endpoint = System.getenv("DIGITAL_TWINS_ENDPOINT");
private static final int MaxWaitTimeAsyncOperationsInSeconds = 10;
private static final ObjectMapper mapper = new ObjectMapper();
private static final URL DtdlDirectoryUrl = DigitalTwinsLifecycleAsyncSample.class.getClassLoader().getResource("DTDL");
private static final Path DtDlDirectoryPath;
private static final Path TwinsPath;
private static final Path ModelsPath;
private static final Path RelationshipsPath;
private static final DigitalTwinsAsyncClient client;
static {
try {
assert DtdlDirectoryUrl != null;
DtDlDirectoryPath = Paths.get(DtdlDirectoryUrl.toURI());
} catch (URISyntaxException e) {
throw new RuntimeException("Unable to convert the DTDL directory URL to URI", e);
}
TwinsPath = Paths.get(DtDlDirectoryPath.toString(), "DigitalTwins");
ModelsPath = Paths.get(DtDlDirectoryPath.toString(), "Models");
RelationshipsPath = Paths.get(DtDlDirectoryPath.toString(), "Relationships");
client = new DigitalTwinsClientBuilder()
.tokenCredential(
new ClientSecretCredentialBuilder()
.tenantId(tenantId)
.clientId(clientId)
.clientSecret(clientSecret)
.build()
)
.endpoint(endpoint)
.httpLogOptions(
new HttpLogOptions()
.setLogLevel(HttpLogDetailLevel.NONE))
.buildAsyncClient();
}
public static void main(String[] args) throws IOException, InterruptedException {
deleteTwins();
deleteAllModels();
createAllModels();
listAllModels();
createAllTwins();
connectTwinsTogether();
}
/**
* Delete a twin, and any relationships it might have.
* @throws IOException If an I/O error is thrown when accessing the starting file.
* @throws InterruptedException If the current thread is interrupted while waiting to acquire latch.
*/
/**
* Delete models created by FullLifecycleSample for the ADT service instance.
* @throws InterruptedException If the current thread is interrupted while waiting to acquire latch.
*/
public static void deleteAllModels() throws InterruptedException {
System.out.println("DELETING MODELS");
List<String> models = asList(RoomModelId, WifiModelId, BuildingModelId, FloorModelId, HvacModelId);
models
.forEach(modelId -> {
try {
client.deleteModel(modelId).block();
System.out.println("Deleted model: " + modelId);
} catch (ErrorResponseException ex) {
if (ex.getResponse().getStatusCode() != HttpStatus.SC_NOT_FOUND) {
System.err.println("Could not delete model " + modelId + " due to " + ex);
}
}
});
}
/**
* Loads all the models found in the Models directory into memory and uses CreateModelsAsync API to create all the models in the ADT service instance.
* @throws IOException If an I/O error is thrown when accessing the starting file.
* @throws InterruptedException If the current thread is interrupted while waiting to acquire latch.
*/
public static void createAllModels() throws IOException, InterruptedException {
System.out.println("CREATING MODELS");
List<String> modelsToCreate = new ArrayList<>(FileHelper.loadAllFilesInPath(ModelsPath).values());
final CountDownLatch createModelsLatch = new CountDownLatch(1);
client.createModels(modelsToCreate)
.doOnNext(modelData -> System.out.println("Created model: " + modelData.getId()))
.doOnError(IgnoreConflictError)
.doOnTerminate(createModelsLatch::countDown)
.subscribe();
createModelsLatch.await(MaxWaitTimeAsyncOperationsInSeconds, TimeUnit.SECONDS);
}
/**
* Gets all the models within the ADT service instance.
* @throws InterruptedException If the current thread is interrupted while waiting to acquire latch.
*/
public static void listAllModels() throws InterruptedException {
System.out.println("LISTING MODELS");
final CountDownLatch listModelsLatch = new CountDownLatch(1);
client.listModels()
.doOnNext(modelData -> System.out.println(String.format("Retrieved model: %s, display name '%s', upload time '%s' and decommissioned '%s'",
modelData.getId(), modelData.getDisplayName().get("en"), modelData.getUploadTime(), modelData.isDecommissioned())))
.doOnError(throwable -> System.err.println("List models error: " + throwable))
.doOnTerminate(listModelsLatch::countDown)
.subscribe();
listModelsLatch.await(MaxWaitTimeAsyncOperationsInSeconds, TimeUnit.SECONDS);
}
/**
* Creates all twins specified in the DTDL->DigitalTwins directory.
* @throws IOException If an I/O error is thrown when accessing the starting file.
* @throws InterruptedException If the current thread is interrupted while waiting to acquire latch.
*/
public static void createAllTwins() throws IOException, InterruptedException {
System.out.println("CREATE DIGITAL TWINS");
Map<String, String> twins = FileHelper.loadAllFilesInPath(TwinsPath);
final CountDownLatch createTwinsLatch = new CountDownLatch(twins.size());
twins
.forEach((twinId, twinContent) -> client.createDigitalTwin(twinId, twinContent)
.subscribe(
twin -> System.out.println("Created digital twin: " + twinId + "\n\t Body: " + twin),
throwable -> System.err.println("Could not create digital twin " + twinId + " due to " + throwable),
createTwinsLatch::countDown));
createTwinsLatch.await(MaxWaitTimeAsyncOperationsInSeconds, TimeUnit.SECONDS);
}
public static void connectTwinsTogether() throws IOException, InterruptedException {
System.out.println("CONNECT DIGITAL TWINS");
Map<String, String> allRelationships = FileHelper.loadAllFilesInPath(RelationshipsPath);
final CountDownLatch connectTwinsLatch = new CountDownLatch(4);
allRelationships.values().forEach(
relationshipContent -> {
try {
List<BasicRelationship> relationships = mapper.readValue(relationshipContent, new TypeReference<List<BasicRelationship>>() { });
relationships
.forEach(relationship -> {
try {
client.createRelationship(relationship.getSourceId(), relationship.getId(), mapper.writeValueAsString(relationship))
.doOnSuccess(s -> System.out.println("Linked twin " + relationship.getSourceId() + " to twin " + relationship.getTargetId() + " as " + relationship.getName()))
.doOnError(IgnoreConflictError)
.doOnTerminate(connectTwinsLatch::countDown)
.subscribe();
} catch (JsonProcessingException e) {
throw new RuntimeException("JsonProcessingException while serializing relationship string from BasicRelationship: ", e);
}
});
} catch (JsonProcessingException e) {
throw new RuntimeException("JsonProcessingException while deserializing relationship string to BasicRelationship: ", e);
}
}
);
connectTwinsLatch.await(MaxWaitTimeAsyncOperationsInSeconds, TimeUnit.SECONDS);
}
} | class DigitalTwinsLifecycleAsyncSample {
private static final String tenantId = System.getenv("TENANT_ID");
private static final String clientId = System.getenv("CLIENT_ID");
private static final String clientSecret = System.getenv("CLIENT_SECRET");
private static final String endpoint = System.getenv("DIGITAL_TWINS_ENDPOINT");
private static final int MaxWaitTimeAsyncOperationsInSeconds = 10;
private static final ObjectMapper mapper = new ObjectMapper();
private static final URL DtdlDirectoryUrl = DigitalTwinsLifecycleAsyncSample.class.getClassLoader().getResource("DTDL");
private static final Path DtDlDirectoryPath;
private static final Path TwinsPath;
private static final Path ModelsPath;
private static final Path RelationshipsPath;
private static final DigitalTwinsAsyncClient client;
static {
try {
assert DtdlDirectoryUrl != null;
DtDlDirectoryPath = Paths.get(DtdlDirectoryUrl.toURI());
} catch (URISyntaxException e) {
throw new RuntimeException("Unable to convert the DTDL directory URL to URI", e);
}
TwinsPath = Paths.get(DtDlDirectoryPath.toString(), "DigitalTwins");
ModelsPath = Paths.get(DtDlDirectoryPath.toString(), "Models");
RelationshipsPath = Paths.get(DtDlDirectoryPath.toString(), "Relationships");
client = new DigitalTwinsClientBuilder()
.tokenCredential(
new ClientSecretCredentialBuilder()
.tenantId(tenantId)
.clientId(clientId)
.clientSecret(clientSecret)
.build()
)
.endpoint(endpoint)
.httpLogOptions(
new HttpLogOptions()
.setLogLevel(HttpLogDetailLevel.NONE))
.buildAsyncClient();
}
public static void main(String[] args) throws IOException, InterruptedException {
deleteTwins();
deleteAllModels();
createAllModels();
listAllModels();
createAllTwins();
connectTwinsTogether();
}
/**
* Delete a twin, and any relationships it might have.
* @throws IOException If an I/O error is thrown when accessing the starting file.
* @throws InterruptedException If the current thread is interrupted while waiting to acquire latch.
*/
/**
* Delete models created by FullLifecycleSample for the ADT service instance.
* @throws InterruptedException If the current thread is interrupted while waiting to acquire latch.
*/
public static void deleteAllModels() throws InterruptedException {
System.out.println("DELETING MODELS");
List<String> models = asList(RoomModelId, WifiModelId, BuildingModelId, FloorModelId, HvacModelId);
models
.forEach(modelId -> {
try {
client.deleteModel(modelId).block();
System.out.println("Deleted model: " + modelId);
} catch (ErrorResponseException ex) {
if (ex.getResponse().getStatusCode() != HttpStatus.SC_NOT_FOUND) {
System.err.println("Could not delete model " + modelId + " due to " + ex);
}
}
});
}
/**
* Loads all the models found in the Models directory into memory and uses CreateModelsAsync API to create all the models in the ADT service instance.
* @throws IOException If an I/O error is thrown when accessing the starting file.
* @throws InterruptedException If the current thread is interrupted while waiting to acquire latch.
*/
public static void createAllModels() throws IOException, InterruptedException {
System.out.println("CREATING MODELS");
List<String> modelsToCreate = new ArrayList<>(FileHelper.loadAllFilesInPath(ModelsPath).values());
final CountDownLatch createModelsLatch = new CountDownLatch(1);
client.createModels(modelsToCreate)
.doOnNext(modelData -> System.out.println("Created model: " + modelData.getId()))
.doOnError(IgnoreConflictError)
.doOnTerminate(createModelsLatch::countDown)
.subscribe();
createModelsLatch.await(MaxWaitTimeAsyncOperationsInSeconds, TimeUnit.SECONDS);
}
/**
* Gets all the models within the ADT service instance.
* @throws InterruptedException If the current thread is interrupted while waiting to acquire latch.
*/
public static void listAllModels() throws InterruptedException {
System.out.println("LISTING MODELS");
final CountDownLatch listModelsLatch = new CountDownLatch(1);
client.listModels()
.doOnNext(modelData -> System.out.println("Retrieved model: " + modelData.getId() + ", display name '" + modelData.getDisplayName().get("en") + "'," +
" upload time '" + modelData.getUploadTime() + "' and decommissioned '" + modelData.isDecommissioned() + "'"))
.doOnError(throwable -> System.err.println("List models error: " + throwable))
.doOnTerminate(listModelsLatch::countDown)
.subscribe();
listModelsLatch.await(MaxWaitTimeAsyncOperationsInSeconds, TimeUnit.SECONDS);
}
/**
* Creates all twins specified in the DTDL->DigitalTwins directory.
* @throws IOException If an I/O error is thrown when accessing the starting file.
* @throws InterruptedException If the current thread is interrupted while waiting to acquire latch.
*/
public static void createAllTwins() throws IOException, InterruptedException {
System.out.println("CREATE DIGITAL TWINS");
Map<String, String> twins = FileHelper.loadAllFilesInPath(TwinsPath);
final CountDownLatch createTwinsLatch = new CountDownLatch(twins.size());
twins
.forEach((twinId, twinContent) -> client.createDigitalTwin(twinId, twinContent)
.subscribe(
twin -> System.out.println("Created digital twin: " + twinId + "\n\t Body: " + twin),
throwable -> System.err.println("Could not create digital twin " + twinId + " due to " + throwable),
createTwinsLatch::countDown));
createTwinsLatch.await(MaxWaitTimeAsyncOperationsInSeconds, TimeUnit.SECONDS);
}
/**
* Creates all the relationships defined in the DTDL->Relationships directory
* @throws IOException If an I/O error is thrown when accessing the starting file.
* @throws InterruptedException If the current thread is interrupted while waiting to acquire latch.
*/
public static void connectTwinsTogether() throws IOException, InterruptedException {
System.out.println("CONNECT DIGITAL TWINS");
Map<String, String> allRelationships = FileHelper.loadAllFilesInPath(RelationshipsPath);
final CountDownLatch connectTwinsLatch = new CountDownLatch(4);
allRelationships.values().forEach(
relationshipContent -> {
try {
List<BasicRelationship> relationships = mapper.readValue(relationshipContent, new TypeReference<List<BasicRelationship>>() { });
relationships
.forEach(relationship -> {
try {
client.createRelationship(relationship.getSourceId(), relationship.getId(), mapper.writeValueAsString(relationship))
.doOnSuccess(s -> System.out.println("Linked twin " + relationship.getSourceId() + " to twin " + relationship.getTargetId() + " as " + relationship.getName()))
.doOnError(IgnoreConflictError)
.doOnTerminate(connectTwinsLatch::countDown)
.subscribe();
} catch (JsonProcessingException e) {
throw new RuntimeException("JsonProcessingException while serializing relationship string from BasicRelationship: ", e);
}
});
} catch (JsonProcessingException e) {
throw new RuntimeException("JsonProcessingException while deserializing relationship string to BasicRelationship: ", e);
}
}
);
connectTwinsLatch.await(MaxWaitTimeAsyncOperationsInSeconds, TimeUnit.SECONDS);
}
} | |
If Java doesn't have string interpolation, I'd think this would be much more readable as a string format (like below). | public static void deleteAllModels() throws InterruptedException {
System.out.println("DELETING MODELS");
List<String> models = asList(RoomModelId, WifiModelId, BuildingModelId, FloorModelId, HvacModelId);
models
.forEach(modelId -> {
try {
client.deleteModel(modelId).block();
System.out.println("Deleted model: " + modelId);
} catch (ErrorResponseException ex) {
if (ex.getResponse().getStatusCode() != HttpStatus.SC_NOT_FOUND) {
System.err.println("Could not delete model " + modelId + " due to " + ex);
}
}
});
} | System.err.println("Could not delete model " + modelId + " due to " + ex); | public static void deleteAllModels() throws InterruptedException {
System.out.println("DELETING MODELS");
List<String> models = asList(RoomModelId, WifiModelId, BuildingModelId, FloorModelId, HvacModelId);
models
.forEach(modelId -> {
try {
client.deleteModel(modelId).block();
System.out.println("Deleted model: " + modelId);
} catch (ErrorResponseException ex) {
if (ex.getResponse().getStatusCode() != HttpStatus.SC_NOT_FOUND) {
System.err.println("Could not delete model " + modelId + " due to " + ex);
}
}
});
} | class DigitalTwinsLifecycleAsyncSample {
private static final String tenantId = System.getenv("TENANT_ID");
private static final String clientId = System.getenv("CLIENT_ID");
private static final String clientSecret = System.getenv("CLIENT_SECRET");
private static final String endpoint = System.getenv("DIGITAL_TWINS_ENDPOINT");
private static final int MaxWaitTimeAsyncOperationsInSeconds = 10;
private static final ObjectMapper mapper = new ObjectMapper();
private static final URL DtdlDirectoryUrl = DigitalTwinsLifecycleAsyncSample.class.getClassLoader().getResource("DTDL");
private static final Path DtDlDirectoryPath;
private static final Path TwinsPath;
private static final Path ModelsPath;
private static final Path RelationshipsPath;
private static final DigitalTwinsAsyncClient client;
static {
try {
assert DtdlDirectoryUrl != null;
DtDlDirectoryPath = Paths.get(DtdlDirectoryUrl.toURI());
} catch (URISyntaxException e) {
throw new RuntimeException("Unable to convert the DTDL directory URL to URI", e);
}
TwinsPath = Paths.get(DtDlDirectoryPath.toString(), "DigitalTwins");
ModelsPath = Paths.get(DtDlDirectoryPath.toString(), "Models");
RelationshipsPath = Paths.get(DtDlDirectoryPath.toString(), "Relationships");
client = new DigitalTwinsClientBuilder()
.tokenCredential(
new ClientSecretCredentialBuilder()
.tenantId(tenantId)
.clientId(clientId)
.clientSecret(clientSecret)
.build()
)
.endpoint(endpoint)
.httpLogOptions(
new HttpLogOptions()
.setLogLevel(HttpLogDetailLevel.NONE))
.buildAsyncClient();
}
public static void main(String[] args) throws IOException, InterruptedException {
deleteTwins();
deleteAllModels();
createAllModels();
listAllModels();
createAllTwins();
connectTwinsTogether();
}
/**
* Delete a twin, and any relationships it might have.
* @throws IOException If an I/O error is thrown when accessing the starting file.
* @throws InterruptedException If the current thread is interrupted while waiting to acquire latch.
*/
public static void deleteTwins() throws IOException, InterruptedException {
System.out.println("DELETE DIGITAL TWINS");
Map<String, String> twins = FileHelper.loadAllFilesInPath(TwinsPath);
for (Map.Entry<String, String> twin : twins.entrySet()) {
String twinId = twin.getKey();
List<BasicRelationship> relationshipList = new ArrayList<>();
Semaphore listRelationshipSemaphore = new Semaphore(0);
Semaphore deleteRelationshipsSemaphore = new Semaphore(0);
CountDownLatch deleteTwinsLatch = new CountDownLatch(1);
client.listRelationships(twinId, BasicRelationship.class)
.doOnNext(relationshipList::add)
.doOnError(IgnoreNotFoundError)
.doOnTerminate(listRelationshipSemaphore::release)
.subscribe();
client.listIncomingRelationships(twinId)
.doOnNext(e -> relationshipList.add(mapper.convertValue(e, BasicRelationship.class)))
.doOnError(IgnoreNotFoundError)
.doOnTerminate(listRelationshipSemaphore::release)
.subscribe();
if (listRelationshipSemaphore.tryAcquire(2, MaxWaitTimeAsyncOperationsInSeconds, TimeUnit.SECONDS)) {
relationshipList
.forEach(relationship -> client.deleteRelationship(relationship.getSourceId(), relationship.getId())
.doOnSuccess(aVoid -> {
if (twinId.equals(relationship.getSourceId())) {
System.out.println("Found and deleted relationship: " + relationship.getId());
} else {
System.out.println("Found and deleted incoming relationship: " + relationship.getId());
}
})
.doOnError(IgnoreNotFoundError)
.doOnTerminate(deleteRelationshipsSemaphore::release)
.subscribe());
}
if (deleteRelationshipsSemaphore.tryAcquire(relationshipList.size(), MaxWaitTimeAsyncOperationsInSeconds, TimeUnit.SECONDS)) {
client.deleteDigitalTwin(twinId)
.doOnSuccess(aVoid -> System.out.println("Deleted digital twin: " + twinId))
.doOnError(IgnoreNotFoundError)
.doOnTerminate(deleteTwinsLatch::countDown)
.subscribe();
deleteTwinsLatch.await(MaxWaitTimeAsyncOperationsInSeconds, TimeUnit.SECONDS);
}
}
}
/**
* Delete models created by FullLifecycleSample for the ADT service instance.
* @throws InterruptedException If the current thread is interrupted while waiting to acquire latch.
*/
/**
* Loads all the models found in the Models directory into memory and uses CreateModelsAsync API to create all the models in the ADT service instance.
* @throws IOException If an I/O error is thrown when accessing the starting file.
* @throws InterruptedException If the current thread is interrupted while waiting to acquire latch.
*/
public static void createAllModels() throws IOException, InterruptedException {
System.out.println("CREATING MODELS");
List<String> modelsToCreate = new ArrayList<>(FileHelper.loadAllFilesInPath(ModelsPath).values());
final CountDownLatch createModelsLatch = new CountDownLatch(1);
client.createModels(modelsToCreate)
.doOnNext(modelData -> System.out.println("Created model: " + modelData.getId()))
.doOnError(IgnoreConflictError)
.doOnTerminate(createModelsLatch::countDown)
.subscribe();
createModelsLatch.await(MaxWaitTimeAsyncOperationsInSeconds, TimeUnit.SECONDS);
}
/**
* Gets all the models within the ADT service instance.
* @throws InterruptedException If the current thread is interrupted while waiting to acquire latch.
*/
public static void listAllModels() throws InterruptedException {
System.out.println("LISTING MODELS");
final CountDownLatch listModelsLatch = new CountDownLatch(1);
client.listModels()
.doOnNext(modelData -> System.out.println(String.format("Retrieved model: %s, display name '%s', upload time '%s' and decommissioned '%s'",
modelData.getId(), modelData.getDisplayName().get("en"), modelData.getUploadTime(), modelData.isDecommissioned())))
.doOnError(throwable -> System.err.println("List models error: " + throwable))
.doOnTerminate(listModelsLatch::countDown)
.subscribe();
listModelsLatch.await(MaxWaitTimeAsyncOperationsInSeconds, TimeUnit.SECONDS);
}
/**
* Creates all twins specified in the DTDL->DigitalTwins directory.
* @throws IOException If an I/O error is thrown when accessing the starting file.
* @throws InterruptedException If the current thread is interrupted while waiting to acquire latch.
*/
public static void createAllTwins() throws IOException, InterruptedException {
System.out.println("CREATE DIGITAL TWINS");
Map<String, String> twins = FileHelper.loadAllFilesInPath(TwinsPath);
final CountDownLatch createTwinsLatch = new CountDownLatch(twins.size());
twins
.forEach((twinId, twinContent) -> client.createDigitalTwin(twinId, twinContent)
.subscribe(
twin -> System.out.println("Created digital twin: " + twinId + "\n\t Body: " + twin),
throwable -> System.err.println("Could not create digital twin " + twinId + " due to " + throwable),
createTwinsLatch::countDown));
createTwinsLatch.await(MaxWaitTimeAsyncOperationsInSeconds, TimeUnit.SECONDS);
}
public static void connectTwinsTogether() throws IOException, InterruptedException {
System.out.println("CONNECT DIGITAL TWINS");
Map<String, String> allRelationships = FileHelper.loadAllFilesInPath(RelationshipsPath);
final CountDownLatch connectTwinsLatch = new CountDownLatch(4);
allRelationships.values().forEach(
relationshipContent -> {
try {
List<BasicRelationship> relationships = mapper.readValue(relationshipContent, new TypeReference<List<BasicRelationship>>() { });
relationships
.forEach(relationship -> {
try {
client.createRelationship(relationship.getSourceId(), relationship.getId(), mapper.writeValueAsString(relationship))
.doOnSuccess(s -> System.out.println("Linked twin " + relationship.getSourceId() + " to twin " + relationship.getTargetId() + " as " + relationship.getName()))
.doOnError(IgnoreConflictError)
.doOnTerminate(connectTwinsLatch::countDown)
.subscribe();
} catch (JsonProcessingException e) {
throw new RuntimeException("JsonProcessingException while serializing relationship string from BasicRelationship: ", e);
}
});
} catch (JsonProcessingException e) {
throw new RuntimeException("JsonProcessingException while deserializing relationship string to BasicRelationship: ", e);
}
}
);
connectTwinsLatch.await(MaxWaitTimeAsyncOperationsInSeconds, TimeUnit.SECONDS);
}
} | class DigitalTwinsLifecycleAsyncSample {
private static final String tenantId = System.getenv("TENANT_ID");
private static final String clientId = System.getenv("CLIENT_ID");
private static final String clientSecret = System.getenv("CLIENT_SECRET");
private static final String endpoint = System.getenv("DIGITAL_TWINS_ENDPOINT");
private static final int MaxWaitTimeAsyncOperationsInSeconds = 10;
private static final ObjectMapper mapper = new ObjectMapper();
private static final URL DtdlDirectoryUrl = DigitalTwinsLifecycleAsyncSample.class.getClassLoader().getResource("DTDL");
private static final Path DtDlDirectoryPath;
private static final Path TwinsPath;
private static final Path ModelsPath;
private static final Path RelationshipsPath;
private static final DigitalTwinsAsyncClient client;
static {
try {
assert DtdlDirectoryUrl != null;
DtDlDirectoryPath = Paths.get(DtdlDirectoryUrl.toURI());
} catch (URISyntaxException e) {
throw new RuntimeException("Unable to convert the DTDL directory URL to URI", e);
}
TwinsPath = Paths.get(DtDlDirectoryPath.toString(), "DigitalTwins");
ModelsPath = Paths.get(DtDlDirectoryPath.toString(), "Models");
RelationshipsPath = Paths.get(DtDlDirectoryPath.toString(), "Relationships");
client = new DigitalTwinsClientBuilder()
.tokenCredential(
new ClientSecretCredentialBuilder()
.tenantId(tenantId)
.clientId(clientId)
.clientSecret(clientSecret)
.build()
)
.endpoint(endpoint)
.httpLogOptions(
new HttpLogOptions()
.setLogLevel(HttpLogDetailLevel.NONE))
.buildAsyncClient();
}
public static void main(String[] args) throws IOException, InterruptedException {
deleteTwins();
deleteAllModels();
createAllModels();
listAllModels();
createAllTwins();
connectTwinsTogether();
}
/**
* Delete a twin, and any relationships it might have.
* @throws IOException If an I/O error is thrown when accessing the starting file.
* @throws InterruptedException If the current thread is interrupted while waiting to acquire latch.
*/
public static void deleteTwins() throws IOException, InterruptedException {
System.out.println("DELETE DIGITAL TWINS");
Map<String, String> twins = FileHelper.loadAllFilesInPath(TwinsPath);
for (Map.Entry<String, String> twin : twins.entrySet()) {
String twinId = twin.getKey();
List<BasicRelationship> relationshipList = Collections.synchronizedList(new ArrayList<>());
Semaphore listRelationshipSemaphore = new Semaphore(0);
Semaphore deleteRelationshipsSemaphore = new Semaphore(0);
CountDownLatch deleteTwinsLatch = new CountDownLatch(1);
client.listRelationships(twinId, BasicRelationship.class)
.doOnNext(relationshipList::add)
.doOnError(IgnoreNotFoundError)
.doOnTerminate(listRelationshipSemaphore::release)
.subscribe();
client.listIncomingRelationships(twinId)
.doOnNext(e -> relationshipList.add(mapper.convertValue(e, BasicRelationship.class)))
.doOnError(IgnoreNotFoundError)
.doOnTerminate(listRelationshipSemaphore::release)
.subscribe();
if (listRelationshipSemaphore.tryAcquire(2, MaxWaitTimeAsyncOperationsInSeconds, TimeUnit.SECONDS)) {
relationshipList
.forEach(relationship -> client.deleteRelationship(relationship.getSourceId(), relationship.getId())
.doOnSuccess(aVoid -> {
if (twinId.equals(relationship.getSourceId())) {
System.out.println("Found and deleted relationship: " + relationship.getId());
} else {
System.out.println("Found and deleted incoming relationship: " + relationship.getId());
}
})
.doOnError(IgnoreNotFoundError)
.doOnTerminate(deleteRelationshipsSemaphore::release)
.subscribe());
}
if (deleteRelationshipsSemaphore.tryAcquire(relationshipList.size(), MaxWaitTimeAsyncOperationsInSeconds, TimeUnit.SECONDS)) {
client.deleteDigitalTwin(twinId)
.doOnSuccess(aVoid -> System.out.println("Deleted digital twin: " + twinId))
.doOnError(IgnoreNotFoundError)
.doOnTerminate(deleteTwinsLatch::countDown)
.subscribe();
deleteTwinsLatch.await(MaxWaitTimeAsyncOperationsInSeconds, TimeUnit.SECONDS);
}
}
}
/**
* Delete models created by FullLifecycleSample for the ADT service instance.
* @throws InterruptedException If the current thread is interrupted while waiting to acquire latch.
*/
/**
* Loads all the models found in the Models directory into memory and uses CreateModelsAsync API to create all the models in the ADT service instance.
* @throws IOException If an I/O error is thrown when accessing the starting file.
* @throws InterruptedException If the current thread is interrupted while waiting to acquire latch.
*/
public static void createAllModels() throws IOException, InterruptedException {
System.out.println("CREATING MODELS");
List<String> modelsToCreate = new ArrayList<>(FileHelper.loadAllFilesInPath(ModelsPath).values());
final CountDownLatch createModelsLatch = new CountDownLatch(1);
client.createModels(modelsToCreate)
.doOnNext(modelData -> System.out.println("Created model: " + modelData.getId()))
.doOnError(IgnoreConflictError)
.doOnTerminate(createModelsLatch::countDown)
.subscribe();
createModelsLatch.await(MaxWaitTimeAsyncOperationsInSeconds, TimeUnit.SECONDS);
}
/**
* Gets all the models within the ADT service instance.
* @throws InterruptedException If the current thread is interrupted while waiting to acquire latch.
*/
public static void listAllModels() throws InterruptedException {
System.out.println("LISTING MODELS");
final CountDownLatch listModelsLatch = new CountDownLatch(1);
client.listModels()
.doOnNext(modelData -> System.out.println("Retrieved model: " + modelData.getId() + ", display name '" + modelData.getDisplayName().get("en") + "'," +
" upload time '" + modelData.getUploadTime() + "' and decommissioned '" + modelData.isDecommissioned() + "'"))
.doOnError(throwable -> System.err.println("List models error: " + throwable))
.doOnTerminate(listModelsLatch::countDown)
.subscribe();
listModelsLatch.await(MaxWaitTimeAsyncOperationsInSeconds, TimeUnit.SECONDS);
}
/**
* Creates all twins specified in the DTDL->DigitalTwins directory.
* @throws IOException If an I/O error is thrown when accessing the starting file.
* @throws InterruptedException If the current thread is interrupted while waiting to acquire latch.
*/
public static void createAllTwins() throws IOException, InterruptedException {
System.out.println("CREATE DIGITAL TWINS");
Map<String, String> twins = FileHelper.loadAllFilesInPath(TwinsPath);
final CountDownLatch createTwinsLatch = new CountDownLatch(twins.size());
twins
.forEach((twinId, twinContent) -> client.createDigitalTwin(twinId, twinContent)
.subscribe(
twin -> System.out.println("Created digital twin: " + twinId + "\n\t Body: " + twin),
throwable -> System.err.println("Could not create digital twin " + twinId + " due to " + throwable),
createTwinsLatch::countDown));
createTwinsLatch.await(MaxWaitTimeAsyncOperationsInSeconds, TimeUnit.SECONDS);
}
/**
* Creates all the relationships defined in the DTDL->Relationships directory
* @throws IOException If an I/O error is thrown when accessing the starting file.
* @throws InterruptedException If the current thread is interrupted while waiting to acquire latch.
*/
public static void connectTwinsTogether() throws IOException, InterruptedException {
System.out.println("CONNECT DIGITAL TWINS");
Map<String, String> allRelationships = FileHelper.loadAllFilesInPath(RelationshipsPath);
final CountDownLatch connectTwinsLatch = new CountDownLatch(4);
allRelationships.values().forEach(
relationshipContent -> {
try {
List<BasicRelationship> relationships = mapper.readValue(relationshipContent, new TypeReference<List<BasicRelationship>>() { });
relationships
.forEach(relationship -> {
try {
client.createRelationship(relationship.getSourceId(), relationship.getId(), mapper.writeValueAsString(relationship))
.doOnSuccess(s -> System.out.println("Linked twin " + relationship.getSourceId() + " to twin " + relationship.getTargetId() + " as " + relationship.getName()))
.doOnError(IgnoreConflictError)
.doOnTerminate(connectTwinsLatch::countDown)
.subscribe();
} catch (JsonProcessingException e) {
throw new RuntimeException("JsonProcessingException while serializing relationship string from BasicRelationship: ", e);
}
});
} catch (JsonProcessingException e) {
throw new RuntimeException("JsonProcessingException while deserializing relationship string to BasicRelationship: ", e);
}
}
);
connectTwinsLatch.await(MaxWaitTimeAsyncOperationsInSeconds, TimeUnit.SECONDS);
}
} |
We can use `String.format()` to specify a template, but nothing as handy as `$` in C#. | public static void deleteTwins() throws IOException, InterruptedException {
System.out.println("DELETE DIGITAL TWINS");
Map<String, String> twins = FileHelper.loadAllFilesInPath(TwinsPath);
for (Map.Entry<String, String> twin : twins.entrySet()) {
String twinId = twin.getKey();
List<BasicRelationship> relationshipList = new ArrayList<>();
Semaphore listRelationshipSemaphore = new Semaphore(0);
Semaphore deleteRelationshipsSemaphore = new Semaphore(0);
CountDownLatch deleteTwinsLatch = new CountDownLatch(1);
client.listRelationships(twinId, BasicRelationship.class)
.doOnNext(relationshipList::add)
.doOnError(IgnoreNotFoundError)
.doOnTerminate(listRelationshipSemaphore::release)
.subscribe();
client.listIncomingRelationships(twinId)
.doOnNext(e -> relationshipList.add(mapper.convertValue(e, BasicRelationship.class)))
.doOnError(IgnoreNotFoundError)
.doOnTerminate(listRelationshipSemaphore::release)
.subscribe();
if (listRelationshipSemaphore.tryAcquire(2, MaxWaitTimeAsyncOperationsInSeconds, TimeUnit.SECONDS)) {
relationshipList
.forEach(relationship -> client.deleteRelationship(relationship.getSourceId(), relationship.getId())
.doOnSuccess(aVoid -> {
if (twinId.equals(relationship.getSourceId())) {
System.out.println("Found and deleted relationship: " + relationship.getId());
} else {
System.out.println("Found and deleted incoming relationship: " + relationship.getId());
}
})
.doOnError(IgnoreNotFoundError)
.doOnTerminate(deleteRelationshipsSemaphore::release)
.subscribe());
}
if (deleteRelationshipsSemaphore.tryAcquire(relationshipList.size(), MaxWaitTimeAsyncOperationsInSeconds, TimeUnit.SECONDS)) {
client.deleteDigitalTwin(twinId)
.doOnSuccess(aVoid -> System.out.println("Deleted digital twin: " + twinId))
.doOnError(IgnoreNotFoundError)
.doOnTerminate(deleteTwinsLatch::countDown)
.subscribe();
deleteTwinsLatch.await(MaxWaitTimeAsyncOperationsInSeconds, TimeUnit.SECONDS);
}
}
} | System.out.println("Found and deleted relationship: " + relationship.getId()); | public static void deleteTwins() throws IOException, InterruptedException {
System.out.println("DELETE DIGITAL TWINS");
Map<String, String> twins = FileHelper.loadAllFilesInPath(TwinsPath);
for (Map.Entry<String, String> twin : twins.entrySet()) {
String twinId = twin.getKey();
List<BasicRelationship> relationshipList = Collections.synchronizedList(new ArrayList<>());
Semaphore listRelationshipSemaphore = new Semaphore(0);
Semaphore deleteRelationshipsSemaphore = new Semaphore(0);
CountDownLatch deleteTwinsLatch = new CountDownLatch(1);
client.listRelationships(twinId, BasicRelationship.class)
.doOnNext(relationshipList::add)
.doOnError(IgnoreNotFoundError)
.doOnTerminate(listRelationshipSemaphore::release)
.subscribe();
client.listIncomingRelationships(twinId)
.doOnNext(e -> relationshipList.add(mapper.convertValue(e, BasicRelationship.class)))
.doOnError(IgnoreNotFoundError)
.doOnTerminate(listRelationshipSemaphore::release)
.subscribe();
if (listRelationshipSemaphore.tryAcquire(2, MaxWaitTimeAsyncOperationsInSeconds, TimeUnit.SECONDS)) {
relationshipList
.forEach(relationship -> client.deleteRelationship(relationship.getSourceId(), relationship.getId())
.doOnSuccess(aVoid -> {
if (twinId.equals(relationship.getSourceId())) {
System.out.println("Found and deleted relationship: " + relationship.getId());
} else {
System.out.println("Found and deleted incoming relationship: " + relationship.getId());
}
})
.doOnError(IgnoreNotFoundError)
.doOnTerminate(deleteRelationshipsSemaphore::release)
.subscribe());
}
if (deleteRelationshipsSemaphore.tryAcquire(relationshipList.size(), MaxWaitTimeAsyncOperationsInSeconds, TimeUnit.SECONDS)) {
client.deleteDigitalTwin(twinId)
.doOnSuccess(aVoid -> System.out.println("Deleted digital twin: " + twinId))
.doOnError(IgnoreNotFoundError)
.doOnTerminate(deleteTwinsLatch::countDown)
.subscribe();
deleteTwinsLatch.await(MaxWaitTimeAsyncOperationsInSeconds, TimeUnit.SECONDS);
}
}
} | class DigitalTwinsLifecycleAsyncSample {
private static final String tenantId = System.getenv("TENANT_ID");
private static final String clientId = System.getenv("CLIENT_ID");
private static final String clientSecret = System.getenv("CLIENT_SECRET");
private static final String endpoint = System.getenv("DIGITAL_TWINS_ENDPOINT");
private static final int MaxWaitTimeAsyncOperationsInSeconds = 10;
private static final ObjectMapper mapper = new ObjectMapper();
private static final URL DtdlDirectoryUrl = DigitalTwinsLifecycleAsyncSample.class.getClassLoader().getResource("DTDL");
private static final Path DtDlDirectoryPath;
private static final Path TwinsPath;
private static final Path ModelsPath;
private static final Path RelationshipsPath;
private static final DigitalTwinsAsyncClient client;
static {
try {
assert DtdlDirectoryUrl != null;
DtDlDirectoryPath = Paths.get(DtdlDirectoryUrl.toURI());
} catch (URISyntaxException e) {
throw new RuntimeException("Unable to convert the DTDL directory URL to URI", e);
}
TwinsPath = Paths.get(DtDlDirectoryPath.toString(), "DigitalTwins");
ModelsPath = Paths.get(DtDlDirectoryPath.toString(), "Models");
RelationshipsPath = Paths.get(DtDlDirectoryPath.toString(), "Relationships");
client = new DigitalTwinsClientBuilder()
.tokenCredential(
new ClientSecretCredentialBuilder()
.tenantId(tenantId)
.clientId(clientId)
.clientSecret(clientSecret)
.build()
)
.endpoint(endpoint)
.httpLogOptions(
new HttpLogOptions()
.setLogLevel(HttpLogDetailLevel.NONE))
.buildAsyncClient();
}
public static void main(String[] args) throws IOException, InterruptedException {
deleteTwins();
deleteAllModels();
createAllModels();
listAllModels();
createAllTwins();
connectTwinsTogether();
}
/**
* Delete a twin, and any relationships it might have.
* @throws IOException If an I/O error is thrown when accessing the starting file.
* @throws InterruptedException If the current thread is interrupted while waiting to acquire latch.
*/
/**
* Delete models created by FullLifecycleSample for the ADT service instance.
* @throws InterruptedException If the current thread is interrupted while waiting to acquire latch.
*/
public static void deleteAllModels() throws InterruptedException {
System.out.println("DELETING MODELS");
List<String> models = asList(RoomModelId, WifiModelId, BuildingModelId, FloorModelId, HvacModelId);
models
.forEach(modelId -> {
try {
client.deleteModel(modelId).block();
System.out.println("Deleted model: " + modelId);
} catch (ErrorResponseException ex) {
if (ex.getResponse().getStatusCode() != HttpStatus.SC_NOT_FOUND) {
System.err.println("Could not delete model " + modelId + " due to " + ex);
}
}
});
}
/**
* Loads all the models found in the Models directory into memory and uses CreateModelsAsync API to create all the models in the ADT service instance.
* @throws IOException If an I/O error is thrown when accessing the starting file.
* @throws InterruptedException If the current thread is interrupted while waiting to acquire latch.
*/
public static void createAllModels() throws IOException, InterruptedException {
System.out.println("CREATING MODELS");
List<String> modelsToCreate = new ArrayList<>(FileHelper.loadAllFilesInPath(ModelsPath).values());
final CountDownLatch createModelsLatch = new CountDownLatch(1);
client.createModels(modelsToCreate)
.doOnNext(modelData -> System.out.println("Created model: " + modelData.getId()))
.doOnError(IgnoreConflictError)
.doOnTerminate(createModelsLatch::countDown)
.subscribe();
createModelsLatch.await(MaxWaitTimeAsyncOperationsInSeconds, TimeUnit.SECONDS);
}
/**
* Gets all the models within the ADT service instance.
* @throws InterruptedException If the current thread is interrupted while waiting to acquire latch.
*/
public static void listAllModels() throws InterruptedException {
System.out.println("LISTING MODELS");
final CountDownLatch listModelsLatch = new CountDownLatch(1);
client.listModels()
.doOnNext(modelData -> System.out.println(String.format("Retrieved model: %s, display name '%s', upload time '%s' and decommissioned '%s'",
modelData.getId(), modelData.getDisplayName().get("en"), modelData.getUploadTime(), modelData.isDecommissioned())))
.doOnError(throwable -> System.err.println("List models error: " + throwable))
.doOnTerminate(listModelsLatch::countDown)
.subscribe();
listModelsLatch.await(MaxWaitTimeAsyncOperationsInSeconds, TimeUnit.SECONDS);
}
/**
* Creates all twins specified in the DTDL->DigitalTwins directory.
* @throws IOException If an I/O error is thrown when accessing the starting file.
* @throws InterruptedException If the current thread is interrupted while waiting to acquire latch.
*/
public static void createAllTwins() throws IOException, InterruptedException {
System.out.println("CREATE DIGITAL TWINS");
Map<String, String> twins = FileHelper.loadAllFilesInPath(TwinsPath);
final CountDownLatch createTwinsLatch = new CountDownLatch(twins.size());
twins
.forEach((twinId, twinContent) -> client.createDigitalTwin(twinId, twinContent)
.subscribe(
twin -> System.out.println("Created digital twin: " + twinId + "\n\t Body: " + twin),
throwable -> System.err.println("Could not create digital twin " + twinId + " due to " + throwable),
createTwinsLatch::countDown));
createTwinsLatch.await(MaxWaitTimeAsyncOperationsInSeconds, TimeUnit.SECONDS);
}
public static void connectTwinsTogether() throws IOException, InterruptedException {
System.out.println("CONNECT DIGITAL TWINS");
Map<String, String> allRelationships = FileHelper.loadAllFilesInPath(RelationshipsPath);
final CountDownLatch connectTwinsLatch = new CountDownLatch(4);
allRelationships.values().forEach(
relationshipContent -> {
try {
List<BasicRelationship> relationships = mapper.readValue(relationshipContent, new TypeReference<List<BasicRelationship>>() { });
relationships
.forEach(relationship -> {
try {
client.createRelationship(relationship.getSourceId(), relationship.getId(), mapper.writeValueAsString(relationship))
.doOnSuccess(s -> System.out.println("Linked twin " + relationship.getSourceId() + " to twin " + relationship.getTargetId() + " as " + relationship.getName()))
.doOnError(IgnoreConflictError)
.doOnTerminate(connectTwinsLatch::countDown)
.subscribe();
} catch (JsonProcessingException e) {
throw new RuntimeException("JsonProcessingException while serializing relationship string from BasicRelationship: ", e);
}
});
} catch (JsonProcessingException e) {
throw new RuntimeException("JsonProcessingException while deserializing relationship string to BasicRelationship: ", e);
}
}
);
connectTwinsLatch.await(MaxWaitTimeAsyncOperationsInSeconds, TimeUnit.SECONDS);
}
} | class DigitalTwinsLifecycleAsyncSample {
private static final String tenantId = System.getenv("TENANT_ID");
private static final String clientId = System.getenv("CLIENT_ID");
private static final String clientSecret = System.getenv("CLIENT_SECRET");
private static final String endpoint = System.getenv("DIGITAL_TWINS_ENDPOINT");
private static final int MaxWaitTimeAsyncOperationsInSeconds = 10;
private static final ObjectMapper mapper = new ObjectMapper();
private static final URL DtdlDirectoryUrl = DigitalTwinsLifecycleAsyncSample.class.getClassLoader().getResource("DTDL");
private static final Path DtDlDirectoryPath;
private static final Path TwinsPath;
private static final Path ModelsPath;
private static final Path RelationshipsPath;
private static final DigitalTwinsAsyncClient client;
static {
try {
assert DtdlDirectoryUrl != null;
DtDlDirectoryPath = Paths.get(DtdlDirectoryUrl.toURI());
} catch (URISyntaxException e) {
throw new RuntimeException("Unable to convert the DTDL directory URL to URI", e);
}
TwinsPath = Paths.get(DtDlDirectoryPath.toString(), "DigitalTwins");
ModelsPath = Paths.get(DtDlDirectoryPath.toString(), "Models");
RelationshipsPath = Paths.get(DtDlDirectoryPath.toString(), "Relationships");
client = new DigitalTwinsClientBuilder()
.tokenCredential(
new ClientSecretCredentialBuilder()
.tenantId(tenantId)
.clientId(clientId)
.clientSecret(clientSecret)
.build()
)
.endpoint(endpoint)
.httpLogOptions(
new HttpLogOptions()
.setLogLevel(HttpLogDetailLevel.NONE))
.buildAsyncClient();
}
public static void main(String[] args) throws IOException, InterruptedException {
deleteTwins();
deleteAllModels();
createAllModels();
listAllModels();
createAllTwins();
connectTwinsTogether();
}
/**
* Delete a twin, and any relationships it might have.
* @throws IOException If an I/O error is thrown when accessing the starting file.
* @throws InterruptedException If the current thread is interrupted while waiting to acquire latch.
*/
/**
* Delete models created by FullLifecycleSample for the ADT service instance.
* @throws InterruptedException If the current thread is interrupted while waiting to acquire latch.
*/
public static void deleteAllModels() throws InterruptedException {
System.out.println("DELETING MODELS");
List<String> models = asList(RoomModelId, WifiModelId, BuildingModelId, FloorModelId, HvacModelId);
models
.forEach(modelId -> {
try {
client.deleteModel(modelId).block();
System.out.println("Deleted model: " + modelId);
} catch (ErrorResponseException ex) {
if (ex.getResponse().getStatusCode() != HttpStatus.SC_NOT_FOUND) {
System.err.println("Could not delete model " + modelId + " due to " + ex);
}
}
});
}
/**
* Loads all the models found in the Models directory into memory and uses CreateModelsAsync API to create all the models in the ADT service instance.
* @throws IOException If an I/O error is thrown when accessing the starting file.
* @throws InterruptedException If the current thread is interrupted while waiting to acquire latch.
*/
public static void createAllModels() throws IOException, InterruptedException {
System.out.println("CREATING MODELS");
List<String> modelsToCreate = new ArrayList<>(FileHelper.loadAllFilesInPath(ModelsPath).values());
final CountDownLatch createModelsLatch = new CountDownLatch(1);
client.createModels(modelsToCreate)
.doOnNext(modelData -> System.out.println("Created model: " + modelData.getId()))
.doOnError(IgnoreConflictError)
.doOnTerminate(createModelsLatch::countDown)
.subscribe();
createModelsLatch.await(MaxWaitTimeAsyncOperationsInSeconds, TimeUnit.SECONDS);
}
/**
* Gets all the models within the ADT service instance.
* @throws InterruptedException If the current thread is interrupted while waiting to acquire latch.
*/
public static void listAllModels() throws InterruptedException {
System.out.println("LISTING MODELS");
final CountDownLatch listModelsLatch = new CountDownLatch(1);
client.listModels()
.doOnNext(modelData -> System.out.println("Retrieved model: " + modelData.getId() + ", display name '" + modelData.getDisplayName().get("en") + "'," +
" upload time '" + modelData.getUploadTime() + "' and decommissioned '" + modelData.isDecommissioned() + "'"))
.doOnError(throwable -> System.err.println("List models error: " + throwable))
.doOnTerminate(listModelsLatch::countDown)
.subscribe();
listModelsLatch.await(MaxWaitTimeAsyncOperationsInSeconds, TimeUnit.SECONDS);
}
/**
* Creates all twins specified in the DTDL->DigitalTwins directory.
* @throws IOException If an I/O error is thrown when accessing the starting file.
* @throws InterruptedException If the current thread is interrupted while waiting to acquire latch.
*/
public static void createAllTwins() throws IOException, InterruptedException {
System.out.println("CREATE DIGITAL TWINS");
Map<String, String> twins = FileHelper.loadAllFilesInPath(TwinsPath);
final CountDownLatch createTwinsLatch = new CountDownLatch(twins.size());
twins
.forEach((twinId, twinContent) -> client.createDigitalTwin(twinId, twinContent)
.subscribe(
twin -> System.out.println("Created digital twin: " + twinId + "\n\t Body: " + twin),
throwable -> System.err.println("Could not create digital twin " + twinId + " due to " + throwable),
createTwinsLatch::countDown));
createTwinsLatch.await(MaxWaitTimeAsyncOperationsInSeconds, TimeUnit.SECONDS);
}
/**
* Creates all the relationships defined in the DTDL->Relationships directory
* @throws IOException If an I/O error is thrown when accessing the starting file.
* @throws InterruptedException If the current thread is interrupted while waiting to acquire latch.
*/
public static void connectTwinsTogether() throws IOException, InterruptedException {
System.out.println("CONNECT DIGITAL TWINS");
Map<String, String> allRelationships = FileHelper.loadAllFilesInPath(RelationshipsPath);
final CountDownLatch connectTwinsLatch = new CountDownLatch(4);
allRelationships.values().forEach(
relationshipContent -> {
try {
List<BasicRelationship> relationships = mapper.readValue(relationshipContent, new TypeReference<List<BasicRelationship>>() { });
relationships
.forEach(relationship -> {
try {
client.createRelationship(relationship.getSourceId(), relationship.getId(), mapper.writeValueAsString(relationship))
.doOnSuccess(s -> System.out.println("Linked twin " + relationship.getSourceId() + " to twin " + relationship.getTargetId() + " as " + relationship.getName()))
.doOnError(IgnoreConflictError)
.doOnTerminate(connectTwinsLatch::countDown)
.subscribe();
} catch (JsonProcessingException e) {
throw new RuntimeException("JsonProcessingException while serializing relationship string from BasicRelationship: ", e);
}
});
} catch (JsonProcessingException e) {
throw new RuntimeException("JsonProcessingException while deserializing relationship string to BasicRelationship: ", e);
}
}
);
connectTwinsLatch.await(MaxWaitTimeAsyncOperationsInSeconds, TimeUnit.SECONDS);
}
} |
We need to initialize these latches and semaphore within the scope that they are referenced in; but yes, I agree, the count can be confusing to understand. I'll add some more comments around this. | public static void deleteTwins() throws IOException, InterruptedException {
System.out.println("DELETE DIGITAL TWINS");
Map<String, String> twins = FileHelper.loadAllFilesInPath(TwinsPath);
for (Map.Entry<String, String> twin : twins.entrySet()) {
String twinId = twin.getKey();
List<BasicRelationship> relationshipList = new ArrayList<>();
Semaphore listRelationshipSemaphore = new Semaphore(0);
Semaphore deleteRelationshipsSemaphore = new Semaphore(0);
CountDownLatch deleteTwinsLatch = new CountDownLatch(1);
client.listRelationships(twinId, BasicRelationship.class)
.doOnNext(relationshipList::add)
.doOnError(IgnoreNotFoundError)
.doOnTerminate(listRelationshipSemaphore::release)
.subscribe();
client.listIncomingRelationships(twinId)
.doOnNext(e -> relationshipList.add(mapper.convertValue(e, BasicRelationship.class)))
.doOnError(IgnoreNotFoundError)
.doOnTerminate(listRelationshipSemaphore::release)
.subscribe();
if (listRelationshipSemaphore.tryAcquire(2, MaxWaitTimeAsyncOperationsInSeconds, TimeUnit.SECONDS)) {
relationshipList
.forEach(relationship -> client.deleteRelationship(relationship.getSourceId(), relationship.getId())
.doOnSuccess(aVoid -> {
if (twinId.equals(relationship.getSourceId())) {
System.out.println("Found and deleted relationship: " + relationship.getId());
} else {
System.out.println("Found and deleted incoming relationship: " + relationship.getId());
}
})
.doOnError(IgnoreNotFoundError)
.doOnTerminate(deleteRelationshipsSemaphore::release)
.subscribe());
}
if (deleteRelationshipsSemaphore.tryAcquire(relationshipList.size(), MaxWaitTimeAsyncOperationsInSeconds, TimeUnit.SECONDS)) {
client.deleteDigitalTwin(twinId)
.doOnSuccess(aVoid -> System.out.println("Deleted digital twin: " + twinId))
.doOnError(IgnoreNotFoundError)
.doOnTerminate(deleteTwinsLatch::countDown)
.subscribe();
deleteTwinsLatch.await(MaxWaitTimeAsyncOperationsInSeconds, TimeUnit.SECONDS);
}
}
} | CountDownLatch deleteTwinsLatch = new CountDownLatch(1); | public static void deleteTwins() throws IOException, InterruptedException {
System.out.println("DELETE DIGITAL TWINS");
Map<String, String> twins = FileHelper.loadAllFilesInPath(TwinsPath);
for (Map.Entry<String, String> twin : twins.entrySet()) {
String twinId = twin.getKey();
List<BasicRelationship> relationshipList = Collections.synchronizedList(new ArrayList<>());
Semaphore listRelationshipSemaphore = new Semaphore(0);
Semaphore deleteRelationshipsSemaphore = new Semaphore(0);
CountDownLatch deleteTwinsLatch = new CountDownLatch(1);
client.listRelationships(twinId, BasicRelationship.class)
.doOnNext(relationshipList::add)
.doOnError(IgnoreNotFoundError)
.doOnTerminate(listRelationshipSemaphore::release)
.subscribe();
client.listIncomingRelationships(twinId)
.doOnNext(e -> relationshipList.add(mapper.convertValue(e, BasicRelationship.class)))
.doOnError(IgnoreNotFoundError)
.doOnTerminate(listRelationshipSemaphore::release)
.subscribe();
if (listRelationshipSemaphore.tryAcquire(2, MaxWaitTimeAsyncOperationsInSeconds, TimeUnit.SECONDS)) {
relationshipList
.forEach(relationship -> client.deleteRelationship(relationship.getSourceId(), relationship.getId())
.doOnSuccess(aVoid -> {
if (twinId.equals(relationship.getSourceId())) {
System.out.println("Found and deleted relationship: " + relationship.getId());
} else {
System.out.println("Found and deleted incoming relationship: " + relationship.getId());
}
})
.doOnError(IgnoreNotFoundError)
.doOnTerminate(deleteRelationshipsSemaphore::release)
.subscribe());
}
if (deleteRelationshipsSemaphore.tryAcquire(relationshipList.size(), MaxWaitTimeAsyncOperationsInSeconds, TimeUnit.SECONDS)) {
client.deleteDigitalTwin(twinId)
.doOnSuccess(aVoid -> System.out.println("Deleted digital twin: " + twinId))
.doOnError(IgnoreNotFoundError)
.doOnTerminate(deleteTwinsLatch::countDown)
.subscribe();
deleteTwinsLatch.await(MaxWaitTimeAsyncOperationsInSeconds, TimeUnit.SECONDS);
}
}
} | class DigitalTwinsLifecycleAsyncSample {
private static final String tenantId = System.getenv("TENANT_ID");
private static final String clientId = System.getenv("CLIENT_ID");
private static final String clientSecret = System.getenv("CLIENT_SECRET");
private static final String endpoint = System.getenv("DIGITAL_TWINS_ENDPOINT");
private static final int MaxWaitTimeAsyncOperationsInSeconds = 10;
private static final ObjectMapper mapper = new ObjectMapper();
private static final URL DtdlDirectoryUrl = DigitalTwinsLifecycleAsyncSample.class.getClassLoader().getResource("DTDL");
private static final Path DtDlDirectoryPath;
private static final Path TwinsPath;
private static final Path ModelsPath;
private static final Path RelationshipsPath;
private static final DigitalTwinsAsyncClient client;
static {
try {
assert DtdlDirectoryUrl != null;
DtDlDirectoryPath = Paths.get(DtdlDirectoryUrl.toURI());
} catch (URISyntaxException e) {
throw new RuntimeException("Unable to convert the DTDL directory URL to URI", e);
}
TwinsPath = Paths.get(DtDlDirectoryPath.toString(), "DigitalTwins");
ModelsPath = Paths.get(DtDlDirectoryPath.toString(), "Models");
RelationshipsPath = Paths.get(DtDlDirectoryPath.toString(), "Relationships");
client = new DigitalTwinsClientBuilder()
.tokenCredential(
new ClientSecretCredentialBuilder()
.tenantId(tenantId)
.clientId(clientId)
.clientSecret(clientSecret)
.build()
)
.endpoint(endpoint)
.httpLogOptions(
new HttpLogOptions()
.setLogLevel(HttpLogDetailLevel.NONE))
.buildAsyncClient();
}
public static void main(String[] args) throws IOException, InterruptedException {
deleteTwins();
deleteAllModels();
createAllModels();
listAllModels();
createAllTwins();
connectTwinsTogether();
}
/**
* Delete a twin, and any relationships it might have.
* @throws IOException If an I/O error is thrown when accessing the starting file.
* @throws InterruptedException If the current thread is interrupted while waiting to acquire latch.
*/
/**
* Delete models created by FullLifecycleSample for the ADT service instance.
* @throws InterruptedException If the current thread is interrupted while waiting to acquire latch.
*/
public static void deleteAllModels() throws InterruptedException {
System.out.println("DELETING MODELS");
List<String> models = asList(RoomModelId, WifiModelId, BuildingModelId, FloorModelId, HvacModelId);
models
.forEach(modelId -> {
try {
client.deleteModel(modelId).block();
System.out.println("Deleted model: " + modelId);
} catch (ErrorResponseException ex) {
if (ex.getResponse().getStatusCode() != HttpStatus.SC_NOT_FOUND) {
System.err.println("Could not delete model " + modelId + " due to " + ex);
}
}
});
}
/**
* Loads all the models found in the Models directory into memory and uses CreateModelsAsync API to create all the models in the ADT service instance.
* @throws IOException If an I/O error is thrown when accessing the starting file.
* @throws InterruptedException If the current thread is interrupted while waiting to acquire latch.
*/
public static void createAllModels() throws IOException, InterruptedException {
System.out.println("CREATING MODELS");
List<String> modelsToCreate = new ArrayList<>(FileHelper.loadAllFilesInPath(ModelsPath).values());
final CountDownLatch createModelsLatch = new CountDownLatch(1);
client.createModels(modelsToCreate)
.doOnNext(modelData -> System.out.println("Created model: " + modelData.getId()))
.doOnError(IgnoreConflictError)
.doOnTerminate(createModelsLatch::countDown)
.subscribe();
createModelsLatch.await(MaxWaitTimeAsyncOperationsInSeconds, TimeUnit.SECONDS);
}
/**
* Gets all the models within the ADT service instance.
* @throws InterruptedException If the current thread is interrupted while waiting to acquire latch.
*/
public static void listAllModels() throws InterruptedException {
System.out.println("LISTING MODELS");
final CountDownLatch listModelsLatch = new CountDownLatch(1);
client.listModels()
.doOnNext(modelData -> System.out.println(String.format("Retrieved model: %s, display name '%s', upload time '%s' and decommissioned '%s'",
modelData.getId(), modelData.getDisplayName().get("en"), modelData.getUploadTime(), modelData.isDecommissioned())))
.doOnError(throwable -> System.err.println("List models error: " + throwable))
.doOnTerminate(listModelsLatch::countDown)
.subscribe();
listModelsLatch.await(MaxWaitTimeAsyncOperationsInSeconds, TimeUnit.SECONDS);
}
/**
* Creates all twins specified in the DTDL->DigitalTwins directory.
* @throws IOException If an I/O error is thrown when accessing the starting file.
* @throws InterruptedException If the current thread is interrupted while waiting to acquire latch.
*/
public static void createAllTwins() throws IOException, InterruptedException {
System.out.println("CREATE DIGITAL TWINS");
Map<String, String> twins = FileHelper.loadAllFilesInPath(TwinsPath);
final CountDownLatch createTwinsLatch = new CountDownLatch(twins.size());
twins
.forEach((twinId, twinContent) -> client.createDigitalTwin(twinId, twinContent)
.subscribe(
twin -> System.out.println("Created digital twin: " + twinId + "\n\t Body: " + twin),
throwable -> System.err.println("Could not create digital twin " + twinId + " due to " + throwable),
createTwinsLatch::countDown));
createTwinsLatch.await(MaxWaitTimeAsyncOperationsInSeconds, TimeUnit.SECONDS);
}
public static void connectTwinsTogether() throws IOException, InterruptedException {
System.out.println("CONNECT DIGITAL TWINS");
Map<String, String> allRelationships = FileHelper.loadAllFilesInPath(RelationshipsPath);
final CountDownLatch connectTwinsLatch = new CountDownLatch(4);
allRelationships.values().forEach(
relationshipContent -> {
try {
List<BasicRelationship> relationships = mapper.readValue(relationshipContent, new TypeReference<List<BasicRelationship>>() { });
relationships
.forEach(relationship -> {
try {
client.createRelationship(relationship.getSourceId(), relationship.getId(), mapper.writeValueAsString(relationship))
.doOnSuccess(s -> System.out.println("Linked twin " + relationship.getSourceId() + " to twin " + relationship.getTargetId() + " as " + relationship.getName()))
.doOnError(IgnoreConflictError)
.doOnTerminate(connectTwinsLatch::countDown)
.subscribe();
} catch (JsonProcessingException e) {
throw new RuntimeException("JsonProcessingException while serializing relationship string from BasicRelationship: ", e);
}
});
} catch (JsonProcessingException e) {
throw new RuntimeException("JsonProcessingException while deserializing relationship string to BasicRelationship: ", e);
}
}
);
connectTwinsLatch.await(MaxWaitTimeAsyncOperationsInSeconds, TimeUnit.SECONDS);
}
} | class DigitalTwinsLifecycleAsyncSample {
private static final String tenantId = System.getenv("TENANT_ID");
private static final String clientId = System.getenv("CLIENT_ID");
private static final String clientSecret = System.getenv("CLIENT_SECRET");
private static final String endpoint = System.getenv("DIGITAL_TWINS_ENDPOINT");
private static final int MaxWaitTimeAsyncOperationsInSeconds = 10;
private static final ObjectMapper mapper = new ObjectMapper();
private static final URL DtdlDirectoryUrl = DigitalTwinsLifecycleAsyncSample.class.getClassLoader().getResource("DTDL");
private static final Path DtDlDirectoryPath;
private static final Path TwinsPath;
private static final Path ModelsPath;
private static final Path RelationshipsPath;
private static final DigitalTwinsAsyncClient client;
static {
try {
assert DtdlDirectoryUrl != null;
DtDlDirectoryPath = Paths.get(DtdlDirectoryUrl.toURI());
} catch (URISyntaxException e) {
throw new RuntimeException("Unable to convert the DTDL directory URL to URI", e);
}
TwinsPath = Paths.get(DtDlDirectoryPath.toString(), "DigitalTwins");
ModelsPath = Paths.get(DtDlDirectoryPath.toString(), "Models");
RelationshipsPath = Paths.get(DtDlDirectoryPath.toString(), "Relationships");
client = new DigitalTwinsClientBuilder()
.tokenCredential(
new ClientSecretCredentialBuilder()
.tenantId(tenantId)
.clientId(clientId)
.clientSecret(clientSecret)
.build()
)
.endpoint(endpoint)
.httpLogOptions(
new HttpLogOptions()
.setLogLevel(HttpLogDetailLevel.NONE))
.buildAsyncClient();
}
public static void main(String[] args) throws IOException, InterruptedException {
deleteTwins();
deleteAllModels();
createAllModels();
listAllModels();
createAllTwins();
connectTwinsTogether();
}
/**
* Delete a twin, and any relationships it might have.
* @throws IOException If an I/O error is thrown when accessing the starting file.
* @throws InterruptedException If the current thread is interrupted while waiting to acquire latch.
*/
/**
* Delete models created by FullLifecycleSample for the ADT service instance.
* @throws InterruptedException If the current thread is interrupted while waiting to acquire latch.
*/
public static void deleteAllModels() throws InterruptedException {
System.out.println("DELETING MODELS");
List<String> models = asList(RoomModelId, WifiModelId, BuildingModelId, FloorModelId, HvacModelId);
models
.forEach(modelId -> {
try {
client.deleteModel(modelId).block();
System.out.println("Deleted model: " + modelId);
} catch (ErrorResponseException ex) {
if (ex.getResponse().getStatusCode() != HttpStatus.SC_NOT_FOUND) {
System.err.println("Could not delete model " + modelId + " due to " + ex);
}
}
});
}
/**
* Loads all the models found in the Models directory into memory and uses CreateModelsAsync API to create all the models in the ADT service instance.
* @throws IOException If an I/O error is thrown when accessing the starting file.
* @throws InterruptedException If the current thread is interrupted while waiting to acquire latch.
*/
public static void createAllModels() throws IOException, InterruptedException {
System.out.println("CREATING MODELS");
List<String> modelsToCreate = new ArrayList<>(FileHelper.loadAllFilesInPath(ModelsPath).values());
final CountDownLatch createModelsLatch = new CountDownLatch(1);
client.createModels(modelsToCreate)
.doOnNext(modelData -> System.out.println("Created model: " + modelData.getId()))
.doOnError(IgnoreConflictError)
.doOnTerminate(createModelsLatch::countDown)
.subscribe();
createModelsLatch.await(MaxWaitTimeAsyncOperationsInSeconds, TimeUnit.SECONDS);
}
/**
* Gets all the models within the ADT service instance.
* @throws InterruptedException If the current thread is interrupted while waiting to acquire latch.
*/
public static void listAllModels() throws InterruptedException {
System.out.println("LISTING MODELS");
final CountDownLatch listModelsLatch = new CountDownLatch(1);
client.listModels()
.doOnNext(modelData -> System.out.println("Retrieved model: " + modelData.getId() + ", display name '" + modelData.getDisplayName().get("en") + "'," +
" upload time '" + modelData.getUploadTime() + "' and decommissioned '" + modelData.isDecommissioned() + "'"))
.doOnError(throwable -> System.err.println("List models error: " + throwable))
.doOnTerminate(listModelsLatch::countDown)
.subscribe();
listModelsLatch.await(MaxWaitTimeAsyncOperationsInSeconds, TimeUnit.SECONDS);
}
/**
* Creates all twins specified in the DTDL->DigitalTwins directory.
* @throws IOException If an I/O error is thrown when accessing the starting file.
* @throws InterruptedException If the current thread is interrupted while waiting to acquire latch.
*/
public static void createAllTwins() throws IOException, InterruptedException {
System.out.println("CREATE DIGITAL TWINS");
Map<String, String> twins = FileHelper.loadAllFilesInPath(TwinsPath);
final CountDownLatch createTwinsLatch = new CountDownLatch(twins.size());
twins
.forEach((twinId, twinContent) -> client.createDigitalTwin(twinId, twinContent)
.subscribe(
twin -> System.out.println("Created digital twin: " + twinId + "\n\t Body: " + twin),
throwable -> System.err.println("Could not create digital twin " + twinId + " due to " + throwable),
createTwinsLatch::countDown));
createTwinsLatch.await(MaxWaitTimeAsyncOperationsInSeconds, TimeUnit.SECONDS);
}
/**
* Creates all the relationships defined in the DTDL->Relationships directory
* @throws IOException If an I/O error is thrown when accessing the starting file.
* @throws InterruptedException If the current thread is interrupted while waiting to acquire latch.
*/
public static void connectTwinsTogether() throws IOException, InterruptedException {
System.out.println("CONNECT DIGITAL TWINS");
Map<String, String> allRelationships = FileHelper.loadAllFilesInPath(RelationshipsPath);
final CountDownLatch connectTwinsLatch = new CountDownLatch(4);
allRelationships.values().forEach(
relationshipContent -> {
try {
List<BasicRelationship> relationships = mapper.readValue(relationshipContent, new TypeReference<List<BasicRelationship>>() { });
relationships
.forEach(relationship -> {
try {
client.createRelationship(relationship.getSourceId(), relationship.getId(), mapper.writeValueAsString(relationship))
.doOnSuccess(s -> System.out.println("Linked twin " + relationship.getSourceId() + " to twin " + relationship.getTargetId() + " as " + relationship.getName()))
.doOnError(IgnoreConflictError)
.doOnTerminate(connectTwinsLatch::countDown)
.subscribe();
} catch (JsonProcessingException e) {
throw new RuntimeException("JsonProcessingException while serializing relationship string from BasicRelationship: ", e);
}
});
} catch (JsonProcessingException e) {
throw new RuntimeException("JsonProcessingException while deserializing relationship string to BasicRelationship: ", e);
}
}
);
connectTwinsLatch.await(MaxWaitTimeAsyncOperationsInSeconds, TimeUnit.SECONDS);
}
} |
Ah, is there no way to set it inline during initialization? Or some annotation perhaps? | public SamplesArguments(String[] args) {
Options options = new Options();
Option input = new Option("d", DIGITALTWINS_URL, false, "DigitalTwins endpoint URL");
Option tenantId = new Option("t", TENANT_ID, false, "AAD Tenant Id");
Option clientId = new Option("c", CLIENT_ID, false, "AAD Client Id");
Option clientSecret = new Option("s", CLIENT_SECRET, false, "AAD Client Secret");
input.setRequired(true);
tenantId.setRequired(true);
clientId.setRequired(true);
clientSecret.setRequired(true);
options.addOption(input);
options.addOption(tenantId);
options.addOption(clientId);
options.addOption(clientSecret);
CommandLineParser parser = new DefaultParser();
HelpFormatter formatter = new HelpFormatter();
CommandLine cmd = null;
try {
cmd = parser.parse(options, args);
}
catch (ParseException e) {
System.out.println(e.getMessage());
formatter.printHelp("java <sampleClass>.jar", options);
System.exit(1);
}
this.digitalTwinUrl = cmd.getOptionValue(DIGITALTWINS_URL);
this.tenantId = cmd.getOptionValue(TENANT_ID);
this.clientId = cmd.getOptionValue(CLIENT_ID);
this.clientSecret = cmd.getOptionValue(CLIENT_SECRET);
} | input.setRequired(true); | public SamplesArguments(String[] args) {
Option endpoint = new Option("d", DIGITALTWINS_URL, true, "DigitalTwins endpoint URL");
Option tenantId = new Option("t", TENANT_ID, true, "AAD Tenant Id");
Option clientId = new Option("c", CLIENT_ID, true, "AAD Client Id");
Option clientSecret = new Option("s", CLIENT_SECRET, true, "AAD Client Secret");
Option logLevel = new Option("l", LOG_DETAIL_LEVEL, true, "Http logging detail level \n 0 -> NONE \n 1 -> BASIC \n 2 -> HEADERS \n 3 -> BODY \n 4 -> BODY_AND_HEADERS");
endpoint.setRequired(true);
tenantId.setRequired(true);
clientId.setRequired(true);
clientSecret.setRequired(true);
logLevel.setRequired(false);
Options options = new Options()
.addOption(endpoint)
.addOption(tenantId)
.addOption(clientId)
.addOption(clientSecret)
.addOption(logLevel);
CommandLineParser parser = new DefaultParser();
HelpFormatter formatter = new HelpFormatter();
CommandLine cmd = null;
try {
cmd = parser.parse(options, args);
}
catch (ParseException e) {
System.out.println(e.getMessage());
formatter.printHelp("java <sampleClass>.jar", options);
System.exit(1);
}
this.digitalTwinEndpoint = cmd.getOptionValue(DIGITALTWINS_URL);
this.tenantId = cmd.getOptionValue(TENANT_ID);
this.clientId = cmd.getOptionValue(CLIENT_ID);
this.clientSecret = cmd.getOptionValue(CLIENT_SECRET);
String inputLogLevel = cmd.getOptionValue(LOG_DETAIL_LEVEL);
if (inputLogLevel != null && inputLogLevel.trim().length() > 0) {
try {
int providedLogDetailLevel = Integer.parseInt(inputLogLevel);
this.httpLogDetailLevel = convertFromInt(providedLogDetailLevel);
}
catch (NumberFormatException e) {
System.out.println("Provided log detail level must be an integer ranging from 0 - 4");
formatter.printHelp("java <sampleClass>.jar", options);
System.exit(1);
}
}
} | class SamplesArguments {
private final String DIGITALTWINS_URL = "DigitalTwinsEndpoint";
private final String TENANT_ID = "tenantId";
private final String CLIENT_ID = "clientId";
private final String CLIENT_SECRET = "clientSecret";
private String digitalTwinUrl;
private String tenantId;
private String clientId;
private String clientSecret;
public String getDigitalTwinUrl() {
return this.digitalTwinUrl;
}
public String getTenantId() {
return this.tenantId;
}
public String getClientId() {
return this.clientId;
}
public String getClientSecret() {
return this.clientSecret;
}
} | class SamplesArguments {
private final String DIGITALTWINS_URL = "DigitalTwinsEndpoint";
private final String TENANT_ID = "tenantId";
private final String CLIENT_ID = "clientId";
private final String CLIENT_SECRET = "clientSecret";
private final String LOG_DETAIL_LEVEL = "logLevel";
private String digitalTwinEndpoint;
private String tenantId;
private String clientId;
private String clientSecret;
private HttpLogDetailLevel httpLogDetailLevel = HttpLogDetailLevel.NONE;
public String getDigitalTwinEndpoint() {
return this.digitalTwinEndpoint;
}
public String getTenantId() {
return this.tenantId;
}
public String getClientId() {
return this.clientId;
}
public String getClientSecret() {
return this.clientSecret;
}
public HttpLogDetailLevel getHttpLogDetailLevel() {
return this.httpLogDetailLevel;
}
private static HttpLogDetailLevel convertFromInt(int input) throws NumberFormatException {
switch (input)
{
case 0:
return HttpLogDetailLevel.NONE;
case 1:
return HttpLogDetailLevel.BASIC;
case 2:
return HttpLogDetailLevel.HEADERS;
case 3:
return HttpLogDetailLevel.BODY;
case 4:
return HttpLogDetailLevel.BODY_AND_HEADERS;
}
throw new NumberFormatException("Provided log detail level must be an integer ranging from 0 - 4");
}
} |
unfortunately not :( | public SamplesArguments(String[] args) {
Options options = new Options();
Option input = new Option("d", DIGITALTWINS_URL, false, "DigitalTwins endpoint URL");
Option tenantId = new Option("t", TENANT_ID, false, "AAD Tenant Id");
Option clientId = new Option("c", CLIENT_ID, false, "AAD Client Id");
Option clientSecret = new Option("s", CLIENT_SECRET, false, "AAD Client Secret");
input.setRequired(true);
tenantId.setRequired(true);
clientId.setRequired(true);
clientSecret.setRequired(true);
options.addOption(input);
options.addOption(tenantId);
options.addOption(clientId);
options.addOption(clientSecret);
CommandLineParser parser = new DefaultParser();
HelpFormatter formatter = new HelpFormatter();
CommandLine cmd = null;
try {
cmd = parser.parse(options, args);
}
catch (ParseException e) {
System.out.println(e.getMessage());
formatter.printHelp("java <sampleClass>.jar", options);
System.exit(1);
}
this.digitalTwinUrl = cmd.getOptionValue(DIGITALTWINS_URL);
this.tenantId = cmd.getOptionValue(TENANT_ID);
this.clientId = cmd.getOptionValue(CLIENT_ID);
this.clientSecret = cmd.getOptionValue(CLIENT_SECRET);
} | input.setRequired(true); | public SamplesArguments(String[] args) {
Option endpoint = new Option("d", DIGITALTWINS_URL, true, "DigitalTwins endpoint URL");
Option tenantId = new Option("t", TENANT_ID, true, "AAD Tenant Id");
Option clientId = new Option("c", CLIENT_ID, true, "AAD Client Id");
Option clientSecret = new Option("s", CLIENT_SECRET, true, "AAD Client Secret");
Option logLevel = new Option("l", LOG_DETAIL_LEVEL, true, "Http logging detail level \n 0 -> NONE \n 1 -> BASIC \n 2 -> HEADERS \n 3 -> BODY \n 4 -> BODY_AND_HEADERS");
endpoint.setRequired(true);
tenantId.setRequired(true);
clientId.setRequired(true);
clientSecret.setRequired(true);
logLevel.setRequired(false);
Options options = new Options()
.addOption(endpoint)
.addOption(tenantId)
.addOption(clientId)
.addOption(clientSecret)
.addOption(logLevel);
CommandLineParser parser = new DefaultParser();
HelpFormatter formatter = new HelpFormatter();
CommandLine cmd = null;
try {
cmd = parser.parse(options, args);
}
catch (ParseException e) {
System.out.println(e.getMessage());
formatter.printHelp("java <sampleClass>.jar", options);
System.exit(1);
}
this.digitalTwinEndpoint = cmd.getOptionValue(DIGITALTWINS_URL);
this.tenantId = cmd.getOptionValue(TENANT_ID);
this.clientId = cmd.getOptionValue(CLIENT_ID);
this.clientSecret = cmd.getOptionValue(CLIENT_SECRET);
String inputLogLevel = cmd.getOptionValue(LOG_DETAIL_LEVEL);
if (inputLogLevel != null && inputLogLevel.trim().length() > 0) {
try {
int providedLogDetailLevel = Integer.parseInt(inputLogLevel);
this.httpLogDetailLevel = convertFromInt(providedLogDetailLevel);
}
catch (NumberFormatException e) {
System.out.println("Provided log detail level must be an integer ranging from 0 - 4");
formatter.printHelp("java <sampleClass>.jar", options);
System.exit(1);
}
}
} | class SamplesArguments {
private final String DIGITALTWINS_URL = "DigitalTwinsEndpoint";
private final String TENANT_ID = "tenantId";
private final String CLIENT_ID = "clientId";
private final String CLIENT_SECRET = "clientSecret";
private String digitalTwinUrl;
private String tenantId;
private String clientId;
private String clientSecret;
public String getDigitalTwinUrl() {
return this.digitalTwinUrl;
}
public String getTenantId() {
return this.tenantId;
}
public String getClientId() {
return this.clientId;
}
public String getClientSecret() {
return this.clientSecret;
}
} | class SamplesArguments {
private final String DIGITALTWINS_URL = "DigitalTwinsEndpoint";
private final String TENANT_ID = "tenantId";
private final String CLIENT_ID = "clientId";
private final String CLIENT_SECRET = "clientSecret";
private final String LOG_DETAIL_LEVEL = "logLevel";
private String digitalTwinEndpoint;
private String tenantId;
private String clientId;
private String clientSecret;
private HttpLogDetailLevel httpLogDetailLevel = HttpLogDetailLevel.NONE;
public String getDigitalTwinEndpoint() {
return this.digitalTwinEndpoint;
}
public String getTenantId() {
return this.tenantId;
}
public String getClientId() {
return this.clientId;
}
public String getClientSecret() {
return this.clientSecret;
}
public HttpLogDetailLevel getHttpLogDetailLevel() {
return this.httpLogDetailLevel;
}
private static HttpLogDetailLevel convertFromInt(int input) throws NumberFormatException {
switch (input)
{
case 0:
return HttpLogDetailLevel.NONE;
case 1:
return HttpLogDetailLevel.BASIC;
case 2:
return HttpLogDetailLevel.HEADERS;
case 3:
return HttpLogDetailLevel.BODY;
case 4:
return HttpLogDetailLevel.BODY_AND_HEADERS;
}
throw new NumberFormatException("Provided log detail level must be an integer ranging from 0 - 4");
}
} |
nit: Can we do an inline addition to `options`? Just trying to reduce the lines of code here! | public SamplesArguments(String[] args) {
Options options = new Options();
Option input = new Option("d", DIGITALTWINS_URL, false, "DigitalTwins endpoint URL");
Option tenantId = new Option("t", TENANT_ID, false, "AAD Tenant Id");
Option clientId = new Option("c", CLIENT_ID, false, "AAD Client Id");
Option clientSecret = new Option("s", CLIENT_SECRET, false, "AAD Client Secret");
input.setRequired(true);
tenantId.setRequired(true);
clientId.setRequired(true);
clientSecret.setRequired(true);
options.addOption(input);
options.addOption(tenantId);
options.addOption(clientId);
options.addOption(clientSecret);
CommandLineParser parser = new DefaultParser();
HelpFormatter formatter = new HelpFormatter();
CommandLine cmd = null;
try {
cmd = parser.parse(options, args);
}
catch (ParseException e) {
System.out.println(e.getMessage());
formatter.printHelp("java <sampleClass>.jar", options);
System.exit(1);
}
this.digitalTwinUrl = cmd.getOptionValue(DIGITALTWINS_URL);
this.tenantId = cmd.getOptionValue(TENANT_ID);
this.clientId = cmd.getOptionValue(CLIENT_ID);
this.clientSecret = cmd.getOptionValue(CLIENT_SECRET);
} | options.addOption(input); | public SamplesArguments(String[] args) {
Option endpoint = new Option("d", DIGITALTWINS_URL, true, "DigitalTwins endpoint URL");
Option tenantId = new Option("t", TENANT_ID, true, "AAD Tenant Id");
Option clientId = new Option("c", CLIENT_ID, true, "AAD Client Id");
Option clientSecret = new Option("s", CLIENT_SECRET, true, "AAD Client Secret");
Option logLevel = new Option("l", LOG_DETAIL_LEVEL, true, "Http logging detail level \n 0 -> NONE \n 1 -> BASIC \n 2 -> HEADERS \n 3 -> BODY \n 4 -> BODY_AND_HEADERS");
endpoint.setRequired(true);
tenantId.setRequired(true);
clientId.setRequired(true);
clientSecret.setRequired(true);
logLevel.setRequired(false);
Options options = new Options()
.addOption(endpoint)
.addOption(tenantId)
.addOption(clientId)
.addOption(clientSecret)
.addOption(logLevel);
CommandLineParser parser = new DefaultParser();
HelpFormatter formatter = new HelpFormatter();
CommandLine cmd = null;
try {
cmd = parser.parse(options, args);
}
catch (ParseException e) {
System.out.println(e.getMessage());
formatter.printHelp("java <sampleClass>.jar", options);
System.exit(1);
}
this.digitalTwinEndpoint = cmd.getOptionValue(DIGITALTWINS_URL);
this.tenantId = cmd.getOptionValue(TENANT_ID);
this.clientId = cmd.getOptionValue(CLIENT_ID);
this.clientSecret = cmd.getOptionValue(CLIENT_SECRET);
String inputLogLevel = cmd.getOptionValue(LOG_DETAIL_LEVEL);
if (inputLogLevel != null && inputLogLevel.trim().length() > 0) {
try {
int providedLogDetailLevel = Integer.parseInt(inputLogLevel);
this.httpLogDetailLevel = convertFromInt(providedLogDetailLevel);
}
catch (NumberFormatException e) {
System.out.println("Provided log detail level must be an integer ranging from 0 - 4");
formatter.printHelp("java <sampleClass>.jar", options);
System.exit(1);
}
}
} | class SamplesArguments {
private final String DIGITALTWINS_URL = "DigitalTwinsEndpoint";
private final String TENANT_ID = "tenantId";
private final String CLIENT_ID = "clientId";
private final String CLIENT_SECRET = "clientSecret";
private String digitalTwinUrl;
private String tenantId;
private String clientId;
private String clientSecret;
public String getDigitalTwinUrl() {
return this.digitalTwinUrl;
}
public String getTenantId() {
return this.tenantId;
}
public String getClientId() {
return this.clientId;
}
public String getClientSecret() {
return this.clientSecret;
}
} | class SamplesArguments {
private final String DIGITALTWINS_URL = "DigitalTwinsEndpoint";
private final String TENANT_ID = "tenantId";
private final String CLIENT_ID = "clientId";
private final String CLIENT_SECRET = "clientSecret";
private final String LOG_DETAIL_LEVEL = "logLevel";
private String digitalTwinEndpoint;
private String tenantId;
private String clientId;
private String clientSecret;
private HttpLogDetailLevel httpLogDetailLevel = HttpLogDetailLevel.NONE;
public String getDigitalTwinEndpoint() {
return this.digitalTwinEndpoint;
}
public String getTenantId() {
return this.tenantId;
}
public String getClientId() {
return this.clientId;
}
public String getClientSecret() {
return this.clientSecret;
}
public HttpLogDetailLevel getHttpLogDetailLevel() {
return this.httpLogDetailLevel;
}
private static HttpLogDetailLevel convertFromInt(int input) throws NumberFormatException {
switch (input)
{
case 0:
return HttpLogDetailLevel.NONE;
case 1:
return HttpLogDetailLevel.BASIC;
case 2:
return HttpLogDetailLevel.HEADERS;
case 3:
return HttpLogDetailLevel.BODY;
case 4:
return HttpLogDetailLevel.BODY_AND_HEADERS;
}
throw new NumberFormatException("Provided log detail level must be an integer ranging from 0 - 4");
}
} |
sure, but won't save that much space :)) | public SamplesArguments(String[] args) {
Options options = new Options();
Option input = new Option("d", DIGITALTWINS_URL, false, "DigitalTwins endpoint URL");
Option tenantId = new Option("t", TENANT_ID, false, "AAD Tenant Id");
Option clientId = new Option("c", CLIENT_ID, false, "AAD Client Id");
Option clientSecret = new Option("s", CLIENT_SECRET, false, "AAD Client Secret");
input.setRequired(true);
tenantId.setRequired(true);
clientId.setRequired(true);
clientSecret.setRequired(true);
options.addOption(input);
options.addOption(tenantId);
options.addOption(clientId);
options.addOption(clientSecret);
CommandLineParser parser = new DefaultParser();
HelpFormatter formatter = new HelpFormatter();
CommandLine cmd = null;
try {
cmd = parser.parse(options, args);
}
catch (ParseException e) {
System.out.println(e.getMessage());
formatter.printHelp("java <sampleClass>.jar", options);
System.exit(1);
}
this.digitalTwinUrl = cmd.getOptionValue(DIGITALTWINS_URL);
this.tenantId = cmd.getOptionValue(TENANT_ID);
this.clientId = cmd.getOptionValue(CLIENT_ID);
this.clientSecret = cmd.getOptionValue(CLIENT_SECRET);
} | options.addOption(input); | public SamplesArguments(String[] args) {
Option endpoint = new Option("d", DIGITALTWINS_URL, true, "DigitalTwins endpoint URL");
Option tenantId = new Option("t", TENANT_ID, true, "AAD Tenant Id");
Option clientId = new Option("c", CLIENT_ID, true, "AAD Client Id");
Option clientSecret = new Option("s", CLIENT_SECRET, true, "AAD Client Secret");
Option logLevel = new Option("l", LOG_DETAIL_LEVEL, true, "Http logging detail level \n 0 -> NONE \n 1 -> BASIC \n 2 -> HEADERS \n 3 -> BODY \n 4 -> BODY_AND_HEADERS");
endpoint.setRequired(true);
tenantId.setRequired(true);
clientId.setRequired(true);
clientSecret.setRequired(true);
logLevel.setRequired(false);
Options options = new Options()
.addOption(endpoint)
.addOption(tenantId)
.addOption(clientId)
.addOption(clientSecret)
.addOption(logLevel);
CommandLineParser parser = new DefaultParser();
HelpFormatter formatter = new HelpFormatter();
CommandLine cmd = null;
try {
cmd = parser.parse(options, args);
}
catch (ParseException e) {
System.out.println(e.getMessage());
formatter.printHelp("java <sampleClass>.jar", options);
System.exit(1);
}
this.digitalTwinEndpoint = cmd.getOptionValue(DIGITALTWINS_URL);
this.tenantId = cmd.getOptionValue(TENANT_ID);
this.clientId = cmd.getOptionValue(CLIENT_ID);
this.clientSecret = cmd.getOptionValue(CLIENT_SECRET);
String inputLogLevel = cmd.getOptionValue(LOG_DETAIL_LEVEL);
if (inputLogLevel != null && inputLogLevel.trim().length() > 0) {
try {
int providedLogDetailLevel = Integer.parseInt(inputLogLevel);
this.httpLogDetailLevel = convertFromInt(providedLogDetailLevel);
}
catch (NumberFormatException e) {
System.out.println("Provided log detail level must be an integer ranging from 0 - 4");
formatter.printHelp("java <sampleClass>.jar", options);
System.exit(1);
}
}
} | class SamplesArguments {
private final String DIGITALTWINS_URL = "DigitalTwinsEndpoint";
private final String TENANT_ID = "tenantId";
private final String CLIENT_ID = "clientId";
private final String CLIENT_SECRET = "clientSecret";
private String digitalTwinUrl;
private String tenantId;
private String clientId;
private String clientSecret;
public String getDigitalTwinUrl() {
return this.digitalTwinUrl;
}
public String getTenantId() {
return this.tenantId;
}
public String getClientId() {
return this.clientId;
}
public String getClientSecret() {
return this.clientSecret;
}
} | class SamplesArguments {
private final String DIGITALTWINS_URL = "DigitalTwinsEndpoint";
private final String TENANT_ID = "tenantId";
private final String CLIENT_ID = "clientId";
private final String CLIENT_SECRET = "clientSecret";
private final String LOG_DETAIL_LEVEL = "logLevel";
private String digitalTwinEndpoint;
private String tenantId;
private String clientId;
private String clientSecret;
private HttpLogDetailLevel httpLogDetailLevel = HttpLogDetailLevel.NONE;
public String getDigitalTwinEndpoint() {
return this.digitalTwinEndpoint;
}
public String getTenantId() {
return this.tenantId;
}
public String getClientId() {
return this.clientId;
}
public String getClientSecret() {
return this.clientSecret;
}
public HttpLogDetailLevel getHttpLogDetailLevel() {
return this.httpLogDetailLevel;
}
private static HttpLogDetailLevel convertFromInt(int input) throws NumberFormatException {
switch (input)
{
case 0:
return HttpLogDetailLevel.NONE;
case 1:
return HttpLogDetailLevel.BASIC;
case 2:
return HttpLogDetailLevel.HEADERS;
case 3:
return HttpLogDetailLevel.BODY;
case 4:
return HttpLogDetailLevel.BODY_AND_HEADERS;
}
throw new NumberFormatException("Provided log detail level must be an integer ranging from 0 - 4");
}
} |
``` Options options = new Options() .addOption(input) .addOption(tenantId) .addOption(clientId) .addOption(clientSecret); ``` | public SamplesArguments(String[] args) {
Options options = new Options();
Option input = new Option("d", DIGITALTWINS_URL, false, "DigitalTwins endpoint URL");
Option tenantId = new Option("t", TENANT_ID, false, "AAD Tenant Id");
Option clientId = new Option("c", CLIENT_ID, false, "AAD Client Id");
Option clientSecret = new Option("s", CLIENT_SECRET, false, "AAD Client Secret");
input.setRequired(true);
tenantId.setRequired(true);
clientId.setRequired(true);
clientSecret.setRequired(true);
options.addOption(input);
options.addOption(tenantId);
options.addOption(clientId);
options.addOption(clientSecret);
CommandLineParser parser = new DefaultParser();
HelpFormatter formatter = new HelpFormatter();
CommandLine cmd = null;
try {
cmd = parser.parse(options, args);
}
catch (ParseException e) {
System.out.println(e.getMessage());
formatter.printHelp("java <sampleClass>.jar", options);
System.exit(1);
}
this.digitalTwinUrl = cmd.getOptionValue(DIGITALTWINS_URL);
this.tenantId = cmd.getOptionValue(TENANT_ID);
this.clientId = cmd.getOptionValue(CLIENT_ID);
this.clientSecret = cmd.getOptionValue(CLIENT_SECRET);
} | options.addOption(input); | public SamplesArguments(String[] args) {
Option endpoint = new Option("d", DIGITALTWINS_URL, true, "DigitalTwins endpoint URL");
Option tenantId = new Option("t", TENANT_ID, true, "AAD Tenant Id");
Option clientId = new Option("c", CLIENT_ID, true, "AAD Client Id");
Option clientSecret = new Option("s", CLIENT_SECRET, true, "AAD Client Secret");
Option logLevel = new Option("l", LOG_DETAIL_LEVEL, true, "Http logging detail level \n 0 -> NONE \n 1 -> BASIC \n 2 -> HEADERS \n 3 -> BODY \n 4 -> BODY_AND_HEADERS");
endpoint.setRequired(true);
tenantId.setRequired(true);
clientId.setRequired(true);
clientSecret.setRequired(true);
logLevel.setRequired(false);
Options options = new Options()
.addOption(endpoint)
.addOption(tenantId)
.addOption(clientId)
.addOption(clientSecret)
.addOption(logLevel);
CommandLineParser parser = new DefaultParser();
HelpFormatter formatter = new HelpFormatter();
CommandLine cmd = null;
try {
cmd = parser.parse(options, args);
}
catch (ParseException e) {
System.out.println(e.getMessage());
formatter.printHelp("java <sampleClass>.jar", options);
System.exit(1);
}
this.digitalTwinEndpoint = cmd.getOptionValue(DIGITALTWINS_URL);
this.tenantId = cmd.getOptionValue(TENANT_ID);
this.clientId = cmd.getOptionValue(CLIENT_ID);
this.clientSecret = cmd.getOptionValue(CLIENT_SECRET);
String inputLogLevel = cmd.getOptionValue(LOG_DETAIL_LEVEL);
if (inputLogLevel != null && inputLogLevel.trim().length() > 0) {
try {
int providedLogDetailLevel = Integer.parseInt(inputLogLevel);
this.httpLogDetailLevel = convertFromInt(providedLogDetailLevel);
}
catch (NumberFormatException e) {
System.out.println("Provided log detail level must be an integer ranging from 0 - 4");
formatter.printHelp("java <sampleClass>.jar", options);
System.exit(1);
}
}
} | class SamplesArguments {
private final String DIGITALTWINS_URL = "DigitalTwinsEndpoint";
private final String TENANT_ID = "tenantId";
private final String CLIENT_ID = "clientId";
private final String CLIENT_SECRET = "clientSecret";
private String digitalTwinUrl;
private String tenantId;
private String clientId;
private String clientSecret;
public String getDigitalTwinUrl() {
return this.digitalTwinUrl;
}
public String getTenantId() {
return this.tenantId;
}
public String getClientId() {
return this.clientId;
}
public String getClientSecret() {
return this.clientSecret;
}
} | class SamplesArguments {
private final String DIGITALTWINS_URL = "DigitalTwinsEndpoint";
private final String TENANT_ID = "tenantId";
private final String CLIENT_ID = "clientId";
private final String CLIENT_SECRET = "clientSecret";
private final String LOG_DETAIL_LEVEL = "logLevel";
private String digitalTwinEndpoint;
private String tenantId;
private String clientId;
private String clientSecret;
private HttpLogDetailLevel httpLogDetailLevel = HttpLogDetailLevel.NONE;
public String getDigitalTwinEndpoint() {
return this.digitalTwinEndpoint;
}
public String getTenantId() {
return this.tenantId;
}
public String getClientId() {
return this.clientId;
}
public String getClientSecret() {
return this.clientSecret;
}
public HttpLogDetailLevel getHttpLogDetailLevel() {
return this.httpLogDetailLevel;
}
private static HttpLogDetailLevel convertFromInt(int input) throws NumberFormatException {
switch (input)
{
case 0:
return HttpLogDetailLevel.NONE;
case 1:
return HttpLogDetailLevel.BASIC;
case 2:
return HttpLogDetailLevel.HEADERS;
case 3:
return HttpLogDetailLevel.BODY;
case 4:
return HttpLogDetailLevel.BODY_AND_HEADERS;
}
throw new NumberFormatException("Provided log detail level must be an integer ranging from 0 - 4");
}
} |
How about: ```java Options options = new Options() .addOption(new Option("d", DIGITALTWINS_URL, false, "DigitalTwins endpoint URL")) .addOption(new Option("t", TENANT_ID, false, "AAD Tenant Id")) .addOption(new Option("c", CLIENT_ID, false, "AAD Client Id")) .addOption(new Option("s", CLIENT_SECRET, false, "AAD Client Secret")); ``` There also seems to be a builder options: ```java new Options() .addOption(Option.builder("d") .required() .hasArg(true) .argName(DIGITALTWINS_URL) .desc("DigitalTwins endpoint URL") .build()) (...) .addOption(Option.builder("t") .required() .hasArg(true) .argName(TENANT_ID) .desc("AAD Tenant Id") .build()); ``` However, I am not too particular about it, just giving you options :) | public SamplesArguments(String[] args) {
Options options = new Options();
Option input = new Option("d", DIGITALTWINS_URL, false, "DigitalTwins endpoint URL");
Option tenantId = new Option("t", TENANT_ID, false, "AAD Tenant Id");
Option clientId = new Option("c", CLIENT_ID, false, "AAD Client Id");
Option clientSecret = new Option("s", CLIENT_SECRET, false, "AAD Client Secret");
input.setRequired(true);
tenantId.setRequired(true);
clientId.setRequired(true);
clientSecret.setRequired(true);
options.addOption(input);
options.addOption(tenantId);
options.addOption(clientId);
options.addOption(clientSecret);
CommandLineParser parser = new DefaultParser();
HelpFormatter formatter = new HelpFormatter();
CommandLine cmd = null;
try {
cmd = parser.parse(options, args);
}
catch (ParseException e) {
System.out.println(e.getMessage());
formatter.printHelp("java <sampleClass>.jar", options);
System.exit(1);
}
this.digitalTwinUrl = cmd.getOptionValue(DIGITALTWINS_URL);
this.tenantId = cmd.getOptionValue(TENANT_ID);
this.clientId = cmd.getOptionValue(CLIENT_ID);
this.clientSecret = cmd.getOptionValue(CLIENT_SECRET);
} | options.addOption(input); | public SamplesArguments(String[] args) {
Option endpoint = new Option("d", DIGITALTWINS_URL, true, "DigitalTwins endpoint URL");
Option tenantId = new Option("t", TENANT_ID, true, "AAD Tenant Id");
Option clientId = new Option("c", CLIENT_ID, true, "AAD Client Id");
Option clientSecret = new Option("s", CLIENT_SECRET, true, "AAD Client Secret");
Option logLevel = new Option("l", LOG_DETAIL_LEVEL, true, "Http logging detail level \n 0 -> NONE \n 1 -> BASIC \n 2 -> HEADERS \n 3 -> BODY \n 4 -> BODY_AND_HEADERS");
endpoint.setRequired(true);
tenantId.setRequired(true);
clientId.setRequired(true);
clientSecret.setRequired(true);
logLevel.setRequired(false);
Options options = new Options()
.addOption(endpoint)
.addOption(tenantId)
.addOption(clientId)
.addOption(clientSecret)
.addOption(logLevel);
CommandLineParser parser = new DefaultParser();
HelpFormatter formatter = new HelpFormatter();
CommandLine cmd = null;
try {
cmd = parser.parse(options, args);
}
catch (ParseException e) {
System.out.println(e.getMessage());
formatter.printHelp("java <sampleClass>.jar", options);
System.exit(1);
}
this.digitalTwinEndpoint = cmd.getOptionValue(DIGITALTWINS_URL);
this.tenantId = cmd.getOptionValue(TENANT_ID);
this.clientId = cmd.getOptionValue(CLIENT_ID);
this.clientSecret = cmd.getOptionValue(CLIENT_SECRET);
String inputLogLevel = cmd.getOptionValue(LOG_DETAIL_LEVEL);
if (inputLogLevel != null && inputLogLevel.trim().length() > 0) {
try {
int providedLogDetailLevel = Integer.parseInt(inputLogLevel);
this.httpLogDetailLevel = convertFromInt(providedLogDetailLevel);
}
catch (NumberFormatException e) {
System.out.println("Provided log detail level must be an integer ranging from 0 - 4");
formatter.printHelp("java <sampleClass>.jar", options);
System.exit(1);
}
}
} | class SamplesArguments {
private final String DIGITALTWINS_URL = "DigitalTwinsEndpoint";
private final String TENANT_ID = "tenantId";
private final String CLIENT_ID = "clientId";
private final String CLIENT_SECRET = "clientSecret";
private String digitalTwinUrl;
private String tenantId;
private String clientId;
private String clientSecret;
public String getDigitalTwinUrl() {
return this.digitalTwinUrl;
}
public String getTenantId() {
return this.tenantId;
}
public String getClientId() {
return this.clientId;
}
public String getClientSecret() {
return this.clientSecret;
}
} | class SamplesArguments {
private final String DIGITALTWINS_URL = "DigitalTwinsEndpoint";
private final String TENANT_ID = "tenantId";
private final String CLIENT_ID = "clientId";
private final String CLIENT_SECRET = "clientSecret";
private final String LOG_DETAIL_LEVEL = "logLevel";
private String digitalTwinEndpoint;
private String tenantId;
private String clientId;
private String clientSecret;
private HttpLogDetailLevel httpLogDetailLevel = HttpLogDetailLevel.NONE;
public String getDigitalTwinEndpoint() {
return this.digitalTwinEndpoint;
}
public String getTenantId() {
return this.tenantId;
}
public String getClientId() {
return this.clientId;
}
public String getClientSecret() {
return this.clientSecret;
}
public HttpLogDetailLevel getHttpLogDetailLevel() {
return this.httpLogDetailLevel;
}
private static HttpLogDetailLevel convertFromInt(int input) throws NumberFormatException {
switch (input)
{
case 0:
return HttpLogDetailLevel.NONE;
case 1:
return HttpLogDetailLevel.BASIC;
case 2:
return HttpLogDetailLevel.HEADERS;
case 3:
return HttpLogDetailLevel.BODY;
case 4:
return HttpLogDetailLevel.BODY_AND_HEADERS;
}
throw new NumberFormatException("Provided log detail level must be an integer ranging from 0 - 4");
}
} |
I am not sure I follow this - aren't the created models returned as a result of this API call - `PagedFlux<ModelData>`? | public void modelLifecycleTest(HttpClient httpClient, DigitalTwinsServiceVersion serviceVersion) {
DigitalTwinsAsyncClient asyncClient = getAsyncClient(httpClient, serviceVersion);
List<ModelData> createdModels = new ArrayList<>();
createModelsRunner(asyncClient, (modelsList) -> {
StepVerifier.create(asyncClient.createModels(modelsList))
.assertNext(createdModel -> {
createdModel.setModel(modelsList.get(0));
createdModels.add(createdModel);
})
.assertNext(createdModel -> {
createdModel.setModel(modelsList.get(1));
createdModels.add(createdModel);
})
.assertNext(createdModel -> {
createdModel.setModel(modelsList.get(2));
createdModels.add(createdModel);
})
.verifyComplete();
});
for (int modelIndex = 0; modelIndex < createdModels.size(); modelIndex++) {
final ModelData expected = createdModels.get(modelIndex);
getModelRunner(expected.getId(), (modelId) -> {
StepVerifier.create(asyncClient.getModelWithResponse(modelId))
.assertNext(retrievedModel -> {
assertModelDataAreEqual(expected, retrievedModel.getValue());
})
.verifyComplete();
});
decommissionModelRunner(expected.getId(), (modelId) -> {
StepVerifier.create(asyncClient.decommissionModel(modelId))
.verifyComplete();
});
getModelRunner(expected.getId(), (modelId) -> {
StepVerifier.create(asyncClient.getModel(modelId))
.assertNext(retrievedModel -> {
assertTrue(retrievedModel.isDecommissioned());
})
.verifyComplete();
});
deleteModelRunner(expected.getId(), (modelId) -> {
StepVerifier.create(asyncClient.deleteModel(modelId))
.verifyComplete();
});
}
} | public void modelLifecycleTest(HttpClient httpClient, DigitalTwinsServiceVersion serviceVersion) {
DigitalTwinsAsyncClient asyncClient = getAsyncClient(httpClient, serviceVersion);
List<ModelData> createdModels = new ArrayList<>();
createModelsRunner(asyncClient, (modelsList) -> {
StepVerifier.create(asyncClient.createModels(modelsList))
.assertNext(createdModelsResponseList -> {
createdModels.addAll(createdModelsResponseList);
logger.info("Created {} models successfully", createdModelsResponseList.size());
})
.verifyComplete();
});
for (int modelIndex = 0; modelIndex < createdModels.size(); modelIndex++) {
final ModelData expected = createdModels.get(modelIndex);
getModelRunner(expected.getId(), (modelId) -> {
StepVerifier.create(asyncClient.getModelWithResponse(modelId))
.assertNext(retrievedModel -> {
assertModelDataAreEqual(expected, retrievedModel.getValue(), false);
})
.verifyComplete();
logger.info("Model {} matched expectations", modelId);
});
decommissionModelRunner(expected.getId(), (modelId) -> {
logger.info("Decommissioning model {}", modelId);
StepVerifier.create(asyncClient.decommissionModel(modelId))
.verifyComplete();
});
getModelRunner(expected.getId(), (modelId) -> {
StepVerifier.create(asyncClient.getModel(modelId))
.assertNext(retrievedModel -> {
assertTrue(retrievedModel.isDecommissioned());
})
.verifyComplete();
logger.info("Model {} was decommissioned successfully", modelId);
});
deleteModelRunner(expected.getId(), (modelId) -> {
logger.info("Deleting model {}", modelId);
StepVerifier.create(asyncClient.deleteModel(modelId))
.verifyComplete();
});
}
} | class ModelsAsyncTest extends ModelsTestBase {
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.digitaltwins.core.TestHelper
@Override
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.digitaltwins.core.TestHelper
@Override
public void getModelThrowsIfModelDoesNotExist(HttpClient httpClient, DigitalTwinsServiceVersion serviceVersion) {
DigitalTwinsAsyncClient asyncClient = getAsyncClient(httpClient, serviceVersion);
final String nonExistantModelId = "urn:doesnotexist:fakemodel:1000";
StepVerifier.create(asyncClient.getModel(nonExistantModelId))
.verifyErrorSatisfies(ex -> assertRestException(ex, HttpURLConnection.HTTP_NOT_FOUND));
}
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.digitaltwins.core.TestHelper
@Override
public void createModelThrowsIfModelAlreadyExists(HttpClient httpClient, DigitalTwinsServiceVersion serviceVersion) {
DigitalTwinsAsyncClient asyncClient = getAsyncClient(httpClient, serviceVersion);
final List<String> modelsToCreate = new ArrayList<>();
final String wardModelId = TestAssetsHelper.getUniqueModelId(asyncClient, TestAssetDefaults.wardModelId);
final String wardModelPayload = TestAssetsHelper.getWardModelPayload(wardModelId);
modelsToCreate.add(wardModelPayload);
StepVerifier.create(asyncClient.createModels(modelsToCreate))
.assertNext((modelData -> {
assertNotNull(modelData);
}))
.verifyComplete();
StepVerifier.create(asyncClient.createModels(modelsToCreate))
.verifyErrorSatisfies(ex -> assertRestException(ex, HttpURLConnection.HTTP_CONFLICT));
}
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.digitaltwins.core.TestHelper
@Override
public void getModelThrowsIfModelIdInvalid(HttpClient httpClient, DigitalTwinsServiceVersion serviceVersion) {
DigitalTwinsAsyncClient asyncClient = getAsyncClient(httpClient, serviceVersion);
final String malformedModelId = "thisIsNotAValidModelId";
StepVerifier.create(asyncClient.getModel(malformedModelId))
.verifyErrorSatisfies(ex -> assertRestException(ex, HttpURLConnection.HTTP_BAD_REQUEST));
}
private static void createModelsRunner(DigitalTwinsAsyncClient asyncClient, Consumer<List<String>> createModelsTestRunner) {
String buildingModelId = TestAssetsHelper.getUniqueModelId(asyncClient, TestAssetDefaults.buildingModelId);
String floorModelId = TestAssetsHelper.getUniqueModelId(asyncClient, TestAssetDefaults.floorModelId);
String hvacModelId = TestAssetsHelper.getUniqueModelId(asyncClient, TestAssetDefaults.hvacModelId);
String wardModelId = TestAssetsHelper.getUniqueModelId(asyncClient, TestAssetDefaults.wardModelId);
createModelsRunner(buildingModelId, floorModelId, hvacModelId, wardModelId, createModelsTestRunner);
}
private DigitalTwinsAsyncClient getAsyncClient(HttpClient httpClient, DigitalTwinsServiceVersion serviceVersion) {
return getDigitalTwinsClientBuilder().serviceVersion(serviceVersion).httpClient(httpClient).buildAsyncClient();
}
} | class ModelsAsyncTest extends ModelsTestBase {
private final ClientLogger logger = new ClientLogger(ModelsAsyncTest.class);
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.digitaltwins.core.TestHelper
@Override
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.digitaltwins.core.TestHelper
@Override
public void getModelThrowsIfModelDoesNotExist(HttpClient httpClient, DigitalTwinsServiceVersion serviceVersion) {
DigitalTwinsAsyncClient asyncClient = getAsyncClient(httpClient, serviceVersion);
final String nonExistantModelId = "urn:doesnotexist:fakemodel:1000";
StepVerifier.create(asyncClient.getModel(nonExistantModelId))
.verifyErrorSatisfies(ex -> assertRestException(ex, HttpURLConnection.HTTP_NOT_FOUND));
}
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.digitaltwins.core.TestHelper
@Override
public void createModelThrowsIfModelAlreadyExists(HttpClient httpClient, DigitalTwinsServiceVersion serviceVersion) {
DigitalTwinsAsyncClient asyncClient = getAsyncClient(httpClient, serviceVersion);
final List<String> modelsToCreate = new ArrayList<>();
final String wardModelId = UniqueIdHelper.getUniqueModelId(TestAssetDefaults.WARD_MODEL_ID, asyncClient, this.randomIntegerStringGenerator);
final String wardModelPayload = TestAssetsHelper.getWardModelPayload(wardModelId);
modelsToCreate.add(wardModelPayload);
StepVerifier.create(asyncClient.createModels(modelsToCreate))
.assertNext((modelData -> {
assertNotNull(modelData);
}))
.verifyComplete();
StepVerifier.create(asyncClient.createModels(modelsToCreate))
.verifyErrorSatisfies(ex -> assertRestException(ex, HttpURLConnection.HTTP_CONFLICT));
}
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.digitaltwins.core.TestHelper
@Override
public void getModelThrowsIfModelIdInvalid(HttpClient httpClient, DigitalTwinsServiceVersion serviceVersion) {
DigitalTwinsAsyncClient asyncClient = getAsyncClient(httpClient, serviceVersion);
final String malformedModelId = "thisIsNotAValidModelId";
StepVerifier.create(asyncClient.getModel(malformedModelId))
.verifyErrorSatisfies(ex -> assertRestException(ex, HttpURLConnection.HTTP_BAD_REQUEST));
}
private void createModelsRunner(DigitalTwinsAsyncClient asyncClient, Consumer<List<String>> createModelsTestRunner) {
String buildingModelId = UniqueIdHelper.getUniqueModelId(TestAssetDefaults.BUILDING_MODEL_ID, asyncClient, this.randomIntegerStringGenerator);
String floorModelId = UniqueIdHelper.getUniqueModelId(TestAssetDefaults.FLOOR_MODEL_ID, asyncClient, this.randomIntegerStringGenerator);
String hvacModelId = UniqueIdHelper.getUniqueModelId(TestAssetDefaults.HVAC_MODEL_ID, asyncClient, this.randomIntegerStringGenerator);
String wardModelId = UniqueIdHelper.getUniqueModelId(TestAssetDefaults.WARD_MODEL_ID, asyncClient, this.randomIntegerStringGenerator);
createModelsRunner(buildingModelId, floorModelId, hvacModelId, wardModelId, createModelsTestRunner);
}
private DigitalTwinsAsyncClient getAsyncClient(HttpClient httpClient, DigitalTwinsServiceVersion serviceVersion) {
return getDigitalTwinsClientBuilder(httpClient, serviceVersion)
.buildAsyncClient();
}
} | |
Or is it that `ModelData.model` is null? | public void modelLifecycleTest(HttpClient httpClient, DigitalTwinsServiceVersion serviceVersion) {
DigitalTwinsAsyncClient asyncClient = getAsyncClient(httpClient, serviceVersion);
List<ModelData> createdModels = new ArrayList<>();
createModelsRunner(asyncClient, (modelsList) -> {
StepVerifier.create(asyncClient.createModels(modelsList))
.assertNext(createdModel -> {
createdModel.setModel(modelsList.get(0));
createdModels.add(createdModel);
})
.assertNext(createdModel -> {
createdModel.setModel(modelsList.get(1));
createdModels.add(createdModel);
})
.assertNext(createdModel -> {
createdModel.setModel(modelsList.get(2));
createdModels.add(createdModel);
})
.verifyComplete();
});
for (int modelIndex = 0; modelIndex < createdModels.size(); modelIndex++) {
final ModelData expected = createdModels.get(modelIndex);
getModelRunner(expected.getId(), (modelId) -> {
StepVerifier.create(asyncClient.getModelWithResponse(modelId))
.assertNext(retrievedModel -> {
assertModelDataAreEqual(expected, retrievedModel.getValue());
})
.verifyComplete();
});
decommissionModelRunner(expected.getId(), (modelId) -> {
StepVerifier.create(asyncClient.decommissionModel(modelId))
.verifyComplete();
});
getModelRunner(expected.getId(), (modelId) -> {
StepVerifier.create(asyncClient.getModel(modelId))
.assertNext(retrievedModel -> {
assertTrue(retrievedModel.isDecommissioned());
})
.verifyComplete();
});
deleteModelRunner(expected.getId(), (modelId) -> {
StepVerifier.create(asyncClient.deleteModel(modelId))
.verifyComplete();
});
}
} | public void modelLifecycleTest(HttpClient httpClient, DigitalTwinsServiceVersion serviceVersion) {
DigitalTwinsAsyncClient asyncClient = getAsyncClient(httpClient, serviceVersion);
List<ModelData> createdModels = new ArrayList<>();
createModelsRunner(asyncClient, (modelsList) -> {
StepVerifier.create(asyncClient.createModels(modelsList))
.assertNext(createdModelsResponseList -> {
createdModels.addAll(createdModelsResponseList);
logger.info("Created {} models successfully", createdModelsResponseList.size());
})
.verifyComplete();
});
for (int modelIndex = 0; modelIndex < createdModels.size(); modelIndex++) {
final ModelData expected = createdModels.get(modelIndex);
getModelRunner(expected.getId(), (modelId) -> {
StepVerifier.create(asyncClient.getModelWithResponse(modelId))
.assertNext(retrievedModel -> {
assertModelDataAreEqual(expected, retrievedModel.getValue(), false);
})
.verifyComplete();
logger.info("Model {} matched expectations", modelId);
});
decommissionModelRunner(expected.getId(), (modelId) -> {
logger.info("Decommissioning model {}", modelId);
StepVerifier.create(asyncClient.decommissionModel(modelId))
.verifyComplete();
});
getModelRunner(expected.getId(), (modelId) -> {
StepVerifier.create(asyncClient.getModel(modelId))
.assertNext(retrievedModel -> {
assertTrue(retrievedModel.isDecommissioned());
})
.verifyComplete();
logger.info("Model {} was decommissioned successfully", modelId);
});
deleteModelRunner(expected.getId(), (modelId) -> {
logger.info("Deleting model {}", modelId);
StepVerifier.create(asyncClient.deleteModel(modelId))
.verifyComplete();
});
}
} | class ModelsAsyncTest extends ModelsTestBase {
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.digitaltwins.core.TestHelper
@Override
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.digitaltwins.core.TestHelper
@Override
public void getModelThrowsIfModelDoesNotExist(HttpClient httpClient, DigitalTwinsServiceVersion serviceVersion) {
DigitalTwinsAsyncClient asyncClient = getAsyncClient(httpClient, serviceVersion);
final String nonExistantModelId = "urn:doesnotexist:fakemodel:1000";
StepVerifier.create(asyncClient.getModel(nonExistantModelId))
.verifyErrorSatisfies(ex -> assertRestException(ex, HttpURLConnection.HTTP_NOT_FOUND));
}
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.digitaltwins.core.TestHelper
@Override
public void createModelThrowsIfModelAlreadyExists(HttpClient httpClient, DigitalTwinsServiceVersion serviceVersion) {
DigitalTwinsAsyncClient asyncClient = getAsyncClient(httpClient, serviceVersion);
final List<String> modelsToCreate = new ArrayList<>();
final String wardModelId = TestAssetsHelper.getUniqueModelId(asyncClient, TestAssetDefaults.wardModelId);
final String wardModelPayload = TestAssetsHelper.getWardModelPayload(wardModelId);
modelsToCreate.add(wardModelPayload);
StepVerifier.create(asyncClient.createModels(modelsToCreate))
.assertNext((modelData -> {
assertNotNull(modelData);
}))
.verifyComplete();
StepVerifier.create(asyncClient.createModels(modelsToCreate))
.verifyErrorSatisfies(ex -> assertRestException(ex, HttpURLConnection.HTTP_CONFLICT));
}
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.digitaltwins.core.TestHelper
@Override
public void getModelThrowsIfModelIdInvalid(HttpClient httpClient, DigitalTwinsServiceVersion serviceVersion) {
DigitalTwinsAsyncClient asyncClient = getAsyncClient(httpClient, serviceVersion);
final String malformedModelId = "thisIsNotAValidModelId";
StepVerifier.create(asyncClient.getModel(malformedModelId))
.verifyErrorSatisfies(ex -> assertRestException(ex, HttpURLConnection.HTTP_BAD_REQUEST));
}
private static void createModelsRunner(DigitalTwinsAsyncClient asyncClient, Consumer<List<String>> createModelsTestRunner) {
String buildingModelId = TestAssetsHelper.getUniqueModelId(asyncClient, TestAssetDefaults.buildingModelId);
String floorModelId = TestAssetsHelper.getUniqueModelId(asyncClient, TestAssetDefaults.floorModelId);
String hvacModelId = TestAssetsHelper.getUniqueModelId(asyncClient, TestAssetDefaults.hvacModelId);
String wardModelId = TestAssetsHelper.getUniqueModelId(asyncClient, TestAssetDefaults.wardModelId);
createModelsRunner(buildingModelId, floorModelId, hvacModelId, wardModelId, createModelsTestRunner);
}
private DigitalTwinsAsyncClient getAsyncClient(HttpClient httpClient, DigitalTwinsServiceVersion serviceVersion) {
return getDigitalTwinsClientBuilder().serviceVersion(serviceVersion).httpClient(httpClient).buildAsyncClient();
}
} | class ModelsAsyncTest extends ModelsTestBase {
private final ClientLogger logger = new ClientLogger(ModelsAsyncTest.class);
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.digitaltwins.core.TestHelper
@Override
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.digitaltwins.core.TestHelper
@Override
public void getModelThrowsIfModelDoesNotExist(HttpClient httpClient, DigitalTwinsServiceVersion serviceVersion) {
DigitalTwinsAsyncClient asyncClient = getAsyncClient(httpClient, serviceVersion);
final String nonExistantModelId = "urn:doesnotexist:fakemodel:1000";
StepVerifier.create(asyncClient.getModel(nonExistantModelId))
.verifyErrorSatisfies(ex -> assertRestException(ex, HttpURLConnection.HTTP_NOT_FOUND));
}
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.digitaltwins.core.TestHelper
@Override
public void createModelThrowsIfModelAlreadyExists(HttpClient httpClient, DigitalTwinsServiceVersion serviceVersion) {
DigitalTwinsAsyncClient asyncClient = getAsyncClient(httpClient, serviceVersion);
final List<String> modelsToCreate = new ArrayList<>();
final String wardModelId = UniqueIdHelper.getUniqueModelId(TestAssetDefaults.WARD_MODEL_ID, asyncClient, this.randomIntegerStringGenerator);
final String wardModelPayload = TestAssetsHelper.getWardModelPayload(wardModelId);
modelsToCreate.add(wardModelPayload);
StepVerifier.create(asyncClient.createModels(modelsToCreate))
.assertNext((modelData -> {
assertNotNull(modelData);
}))
.verifyComplete();
StepVerifier.create(asyncClient.createModels(modelsToCreate))
.verifyErrorSatisfies(ex -> assertRestException(ex, HttpURLConnection.HTTP_CONFLICT));
}
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.digitaltwins.core.TestHelper
@Override
public void getModelThrowsIfModelIdInvalid(HttpClient httpClient, DigitalTwinsServiceVersion serviceVersion) {
DigitalTwinsAsyncClient asyncClient = getAsyncClient(httpClient, serviceVersion);
final String malformedModelId = "thisIsNotAValidModelId";
StepVerifier.create(asyncClient.getModel(malformedModelId))
.verifyErrorSatisfies(ex -> assertRestException(ex, HttpURLConnection.HTTP_BAD_REQUEST));
}
private void createModelsRunner(DigitalTwinsAsyncClient asyncClient, Consumer<List<String>> createModelsTestRunner) {
String buildingModelId = UniqueIdHelper.getUniqueModelId(TestAssetDefaults.BUILDING_MODEL_ID, asyncClient, this.randomIntegerStringGenerator);
String floorModelId = UniqueIdHelper.getUniqueModelId(TestAssetDefaults.FLOOR_MODEL_ID, asyncClient, this.randomIntegerStringGenerator);
String hvacModelId = UniqueIdHelper.getUniqueModelId(TestAssetDefaults.HVAC_MODEL_ID, asyncClient, this.randomIntegerStringGenerator);
String wardModelId = UniqueIdHelper.getUniqueModelId(TestAssetDefaults.WARD_MODEL_ID, asyncClient, this.randomIntegerStringGenerator);
createModelsRunner(buildingModelId, floorModelId, hvacModelId, wardModelId, createModelsTestRunner);
}
private DigitalTwinsAsyncClient getAsyncClient(HttpClient httpClient, DigitalTwinsServiceVersion serviceVersion) {
return getDigitalTwinsClientBuilder(httpClient, serviceVersion)
.buildAsyncClient();
}
} | |
I had been using `org.apache.http.HttpStatus` in the sample, but I like `java.net.HttpURLConnection` better; I'll make the switch. | public void getModelThrowsIfModelDoesNotExist(HttpClient httpClient, DigitalTwinsServiceVersion serviceVersion) {
DigitalTwinsAsyncClient asyncClient = getAsyncClient(httpClient, serviceVersion);
final String nonExistantModelId = "urn:doesnotexist:fakemodel:1000";
StepVerifier.create(asyncClient.getModel(nonExistantModelId))
.verifyErrorSatisfies(ex -> assertRestException(ex, HttpURLConnection.HTTP_NOT_FOUND));
} | StepVerifier.create(asyncClient.getModel(nonExistantModelId)) | public void getModelThrowsIfModelDoesNotExist(HttpClient httpClient, DigitalTwinsServiceVersion serviceVersion) {
DigitalTwinsAsyncClient asyncClient = getAsyncClient(httpClient, serviceVersion);
final String nonExistantModelId = "urn:doesnotexist:fakemodel:1000";
StepVerifier.create(asyncClient.getModel(nonExistantModelId))
.verifyErrorSatisfies(ex -> assertRestException(ex, HttpURLConnection.HTTP_NOT_FOUND));
} | class ModelsAsyncTest extends ModelsTestBase {
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.digitaltwins.core.TestHelper
@Override
public void modelLifecycleTest(HttpClient httpClient, DigitalTwinsServiceVersion serviceVersion) {
DigitalTwinsAsyncClient asyncClient = getAsyncClient(httpClient, serviceVersion);
List<ModelData> createdModels = new ArrayList<>();
createModelsRunner(asyncClient, (modelsList) -> {
StepVerifier.create(asyncClient.createModels(modelsList))
.assertNext(createdModel -> {
createdModel.setModel(modelsList.get(0));
createdModels.add(createdModel);
})
.assertNext(createdModel -> {
createdModel.setModel(modelsList.get(1));
createdModels.add(createdModel);
})
.assertNext(createdModel -> {
createdModel.setModel(modelsList.get(2));
createdModels.add(createdModel);
})
.verifyComplete();
});
for (int modelIndex = 0; modelIndex < createdModels.size(); modelIndex++) {
final ModelData expected = createdModels.get(modelIndex);
getModelRunner(expected.getId(), (modelId) -> {
StepVerifier.create(asyncClient.getModelWithResponse(modelId))
.assertNext(retrievedModel -> {
assertModelDataAreEqual(expected, retrievedModel.getValue());
})
.verifyComplete();
});
decommissionModelRunner(expected.getId(), (modelId) -> {
StepVerifier.create(asyncClient.decommissionModel(modelId))
.verifyComplete();
});
getModelRunner(expected.getId(), (modelId) -> {
StepVerifier.create(asyncClient.getModel(modelId))
.assertNext(retrievedModel -> {
assertTrue(retrievedModel.isDecommissioned());
})
.verifyComplete();
});
deleteModelRunner(expected.getId(), (modelId) -> {
StepVerifier.create(asyncClient.deleteModel(modelId))
.verifyComplete();
});
}
}
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.digitaltwins.core.TestHelper
@Override
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.digitaltwins.core.TestHelper
@Override
public void createModelThrowsIfModelAlreadyExists(HttpClient httpClient, DigitalTwinsServiceVersion serviceVersion) {
DigitalTwinsAsyncClient asyncClient = getAsyncClient(httpClient, serviceVersion);
final List<String> modelsToCreate = new ArrayList<>();
final String wardModelId = TestAssetsHelper.getUniqueModelId(asyncClient, TestAssetDefaults.wardModelId);
final String wardModelPayload = TestAssetsHelper.getWardModelPayload(wardModelId);
modelsToCreate.add(wardModelPayload);
StepVerifier.create(asyncClient.createModels(modelsToCreate))
.assertNext((modelData -> {
assertNotNull(modelData);
}))
.verifyComplete();
StepVerifier.create(asyncClient.createModels(modelsToCreate))
.verifyErrorSatisfies(ex -> assertRestException(ex, HttpURLConnection.HTTP_CONFLICT));
}
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.digitaltwins.core.TestHelper
@Override
public void getModelThrowsIfModelIdInvalid(HttpClient httpClient, DigitalTwinsServiceVersion serviceVersion) {
DigitalTwinsAsyncClient asyncClient = getAsyncClient(httpClient, serviceVersion);
final String malformedModelId = "thisIsNotAValidModelId";
StepVerifier.create(asyncClient.getModel(malformedModelId))
.verifyErrorSatisfies(ex -> assertRestException(ex, HttpURLConnection.HTTP_BAD_REQUEST));
}
private static void createModelsRunner(DigitalTwinsAsyncClient asyncClient, Consumer<List<String>> createModelsTestRunner) {
String buildingModelId = TestAssetsHelper.getUniqueModelId(asyncClient, TestAssetDefaults.buildingModelId);
String floorModelId = TestAssetsHelper.getUniqueModelId(asyncClient, TestAssetDefaults.floorModelId);
String hvacModelId = TestAssetsHelper.getUniqueModelId(asyncClient, TestAssetDefaults.hvacModelId);
String wardModelId = TestAssetsHelper.getUniqueModelId(asyncClient, TestAssetDefaults.wardModelId);
createModelsRunner(buildingModelId, floorModelId, hvacModelId, wardModelId, createModelsTestRunner);
}
private DigitalTwinsAsyncClient getAsyncClient(HttpClient httpClient, DigitalTwinsServiceVersion serviceVersion) {
return getDigitalTwinsClientBuilder().serviceVersion(serviceVersion).httpClient(httpClient).buildAsyncClient();
}
} | class ModelsAsyncTest extends ModelsTestBase {
private final ClientLogger logger = new ClientLogger(ModelsAsyncTest.class);
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.digitaltwins.core.TestHelper
@Override
public void modelLifecycleTest(HttpClient httpClient, DigitalTwinsServiceVersion serviceVersion) {
DigitalTwinsAsyncClient asyncClient = getAsyncClient(httpClient, serviceVersion);
List<ModelData> createdModels = new ArrayList<>();
createModelsRunner(asyncClient, (modelsList) -> {
StepVerifier.create(asyncClient.createModels(modelsList))
.assertNext(createdModelsResponseList -> {
createdModels.addAll(createdModelsResponseList);
logger.info("Created {} models successfully", createdModelsResponseList.size());
})
.verifyComplete();
});
for (int modelIndex = 0; modelIndex < createdModels.size(); modelIndex++) {
final ModelData expected = createdModels.get(modelIndex);
getModelRunner(expected.getId(), (modelId) -> {
StepVerifier.create(asyncClient.getModelWithResponse(modelId))
.assertNext(retrievedModel -> {
assertModelDataAreEqual(expected, retrievedModel.getValue(), false);
})
.verifyComplete();
logger.info("Model {} matched expectations", modelId);
});
decommissionModelRunner(expected.getId(), (modelId) -> {
logger.info("Decommissioning model {}", modelId);
StepVerifier.create(asyncClient.decommissionModel(modelId))
.verifyComplete();
});
getModelRunner(expected.getId(), (modelId) -> {
StepVerifier.create(asyncClient.getModel(modelId))
.assertNext(retrievedModel -> {
assertTrue(retrievedModel.isDecommissioned());
})
.verifyComplete();
logger.info("Model {} was decommissioned successfully", modelId);
});
deleteModelRunner(expected.getId(), (modelId) -> {
logger.info("Deleting model {}", modelId);
StepVerifier.create(asyncClient.deleteModel(modelId))
.verifyComplete();
});
}
}
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.digitaltwins.core.TestHelper
@Override
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.digitaltwins.core.TestHelper
@Override
public void createModelThrowsIfModelAlreadyExists(HttpClient httpClient, DigitalTwinsServiceVersion serviceVersion) {
DigitalTwinsAsyncClient asyncClient = getAsyncClient(httpClient, serviceVersion);
final List<String> modelsToCreate = new ArrayList<>();
final String wardModelId = UniqueIdHelper.getUniqueModelId(TestAssetDefaults.WARD_MODEL_ID, asyncClient, this.randomIntegerStringGenerator);
final String wardModelPayload = TestAssetsHelper.getWardModelPayload(wardModelId);
modelsToCreate.add(wardModelPayload);
StepVerifier.create(asyncClient.createModels(modelsToCreate))
.assertNext((modelData -> {
assertNotNull(modelData);
}))
.verifyComplete();
StepVerifier.create(asyncClient.createModels(modelsToCreate))
.verifyErrorSatisfies(ex -> assertRestException(ex, HttpURLConnection.HTTP_CONFLICT));
}
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.digitaltwins.core.TestHelper
@Override
public void getModelThrowsIfModelIdInvalid(HttpClient httpClient, DigitalTwinsServiceVersion serviceVersion) {
DigitalTwinsAsyncClient asyncClient = getAsyncClient(httpClient, serviceVersion);
final String malformedModelId = "thisIsNotAValidModelId";
StepVerifier.create(asyncClient.getModel(malformedModelId))
.verifyErrorSatisfies(ex -> assertRestException(ex, HttpURLConnection.HTTP_BAD_REQUEST));
}
private void createModelsRunner(DigitalTwinsAsyncClient asyncClient, Consumer<List<String>> createModelsTestRunner) {
String buildingModelId = UniqueIdHelper.getUniqueModelId(TestAssetDefaults.BUILDING_MODEL_ID, asyncClient, this.randomIntegerStringGenerator);
String floorModelId = UniqueIdHelper.getUniqueModelId(TestAssetDefaults.FLOOR_MODEL_ID, asyncClient, this.randomIntegerStringGenerator);
String hvacModelId = UniqueIdHelper.getUniqueModelId(TestAssetDefaults.HVAC_MODEL_ID, asyncClient, this.randomIntegerStringGenerator);
String wardModelId = UniqueIdHelper.getUniqueModelId(TestAssetDefaults.WARD_MODEL_ID, asyncClient, this.randomIntegerStringGenerator);
createModelsRunner(buildingModelId, floorModelId, hvacModelId, wardModelId, createModelsTestRunner);
}
private DigitalTwinsAsyncClient getAsyncClient(HttpClient httpClient, DigitalTwinsServiceVersion serviceVersion) {
return getDigitalTwinsClientBuilder(httpClient, serviceVersion)
.buildAsyncClient();
}
} |
I see that this is an azure-core helper, so they maintain the list of http clients they test against; nice! | static Stream<Arguments> getTestParameters() {
List<Arguments> argumentsList = new ArrayList<>();
getHttpClients()
.forEach(httpClient -> {
Arrays.stream(DigitalTwinsServiceVersion.values()).filter(TestHelper::shouldServiceVersionBeTested)
.forEach(serviceVersion -> argumentsList.add(Arguments.of(httpClient, serviceVersion)));
});
return argumentsList.stream();
} | List<Arguments> argumentsList = new ArrayList<>(); | static Stream<Arguments> getTestParameters() {
List<Arguments> argumentsList = new ArrayList<>();
getHttpClients()
.forEach(httpClient -> {
Arrays.stream(DigitalTwinsServiceVersion.values()).filter(TestHelper::shouldServiceVersionBeTested)
.forEach(serviceVersion -> argumentsList.add(Arguments.of(httpClient, serviceVersion)));
});
return argumentsList.stream();
} | class TestHelper {
public static final String DISPLAY_NAME_WITH_ARGUMENTS = "{displayName} with [{arguments}]";
private static final String AZURE_DIGITALTWINS_TEST_SERVICE_VERSIONS = "AZURE_DIGITALTWINS_TEST_SERVICE_VERSIONS";
private static final String SERVICE_VERSION_FROM_ENV =
Configuration.getGlobalConfiguration().get(AZURE_DIGITALTWINS_TEST_SERVICE_VERSIONS);
static void assertRestException(Runnable exceptionThrower, int expectedStatusCode) {
assertRestException(exceptionThrower, ErrorResponseException.class, expectedStatusCode);
}
static void assertRestException(Runnable exceptionThrower, Class<? extends ErrorResponseException> expectedExceptionType, int expectedStatusCode) {
try {
exceptionThrower.run();
fail();
} catch (Throwable ex) {
assertRestException(ex, expectedExceptionType, expectedStatusCode);
}
}
static void assertRestException(Throwable exception, int expectedStatusCode) {
assertRestException(exception, ErrorResponseException.class, expectedStatusCode);
}
static void assertRestException(Throwable exception, Class<? extends ErrorResponseException> expectedExceptionType, int expectedStatusCode) {
assertEquals(expectedExceptionType, exception.getClass());
assertEquals(expectedStatusCode, ((ErrorResponseException) exception).getResponse().getStatusCode());
}
/**
* Returns a stream of arguments that includes all combinations of eligible {@link HttpClient HttpClients} and
* service versions that should be tested.
*
* @return A stream of HttpClient and service version combinations to test.
*/
/**
* Returns whether the given service version match the rules of test framework.
*
* <ul>
* <li>Using latest service version as default if no environment variable is set.</li>
* <li>If it's set to ALL, all Service versions in {@link DigitalTwinsServiceVersion} will be tested.</li>
* <li>Otherwise, Service version string should match env variable.</li>
* </ul>
*
* Environment values currently supported are: "ALL", "${version}".
* Use comma to separate http clients want to test.
* e.g. {@code set AZURE_TEST_SERVICE_VERSIONS = V1_0, V2_0}
*
* @param serviceVersion ServiceVersion needs to check
* @return Boolean indicates whether filters out the service version or not.
*/
private static boolean shouldServiceVersionBeTested(DigitalTwinsServiceVersion serviceVersion) {
if (CoreUtils.isNullOrEmpty(SERVICE_VERSION_FROM_ENV)) {
return DigitalTwinsServiceVersion.getLatest().equals(serviceVersion);
}
if (AZURE_TEST_SERVICE_VERSIONS_VALUE_ALL.equalsIgnoreCase(SERVICE_VERSION_FROM_ENV)) {
return true;
}
String[] configuredServiceVersionList = SERVICE_VERSION_FROM_ENV.split(",");
return Arrays.stream(configuredServiceVersionList).anyMatch(configuredServiceVersion ->
serviceVersion.getVersion().equals(configuredServiceVersion.trim()));
}
} | class TestHelper {
public static final String DISPLAY_NAME_WITH_ARGUMENTS = "{displayName} with [{arguments}]";
private static final String AZURE_DIGITALTWINS_TEST_SERVICE_VERSIONS = "AZURE_DIGITALTWINS_TEST_SERVICE_VERSIONS";
private static final String SERVICE_VERSION_FROM_ENV =
Configuration.getGlobalConfiguration().get(AZURE_DIGITALTWINS_TEST_SERVICE_VERSIONS);
static void assertRestException(Runnable exceptionThrower, int expectedStatusCode) {
assertRestException(exceptionThrower, ErrorResponseException.class, expectedStatusCode);
}
static void assertRestException(Runnable exceptionThrower, Class<? extends ErrorResponseException> expectedExceptionType, int expectedStatusCode) {
try {
exceptionThrower.run();
fail("Expected exception was not thrown");
} catch (Throwable ex) {
assertRestException(ex, expectedExceptionType, expectedStatusCode);
}
}
static void assertRestException(Throwable exception, int expectedStatusCode) {
assertRestException(exception, ErrorResponseException.class, expectedStatusCode);
}
static void assertRestException(Throwable exception, Class<? extends ErrorResponseException> expectedExceptionType, int expectedStatusCode) {
assertEquals(expectedExceptionType, exception.getClass());
assertEquals(expectedStatusCode, ((ErrorResponseException) exception).getResponse().getStatusCode());
}
/**
* Returns a stream of arguments that includes all combinations of eligible {@link HttpClient HttpClients} and
* service versions that should be tested.
*
* @return A stream of HttpClient and service version combinations to test.
*/
/**
* Returns whether the given service version match the rules of test framework.
*
* <ul>
* <li>Using latest service version as default if no environment variable is set.</li>
* <li>If it's set to ALL, all Service versions in {@link DigitalTwinsServiceVersion} will be tested.</li>
* <li>Otherwise, Service version string should match env variable.</li>
* </ul>
*
* Environment values currently supported are: "ALL", "${version}".
* Use comma to separate http clients want to test.
* e.g. {@code set AZURE_TEST_SERVICE_VERSIONS = V1_0, V2_0}
*
* @param serviceVersion ServiceVersion needs to check
* @return Boolean indicates whether filters out the service version or not.
*/
private static boolean shouldServiceVersionBeTested(DigitalTwinsServiceVersion serviceVersion) {
if (CoreUtils.isNullOrEmpty(SERVICE_VERSION_FROM_ENV)) {
return DigitalTwinsServiceVersion.getLatest().equals(serviceVersion);
}
if (AZURE_TEST_SERVICE_VERSIONS_VALUE_ALL.equalsIgnoreCase(SERVICE_VERSION_FROM_ENV)) {
return true;
}
String[] configuredServiceVersionList = SERVICE_VERSION_FROM_ENV.split(",");
return Arrays.stream(configuredServiceVersionList).anyMatch(configuredServiceVersion ->
serviceVersion.getVersion().equals(configuredServiceVersion.trim()));
}
} |
consider adding a check to verify there is content in the property and then print it | public static void main(String[] args) {
TextAnalyticsClient client = new TextAnalyticsClientBuilder()
.credential(new AzureKeyCredential("{key}"))
.endpoint("{endpoint}")
.buildClient();
String document = "Old Faithful is a geyser at Yellowstone Park.";
client.recognizeLinkedEntities(document).forEach(linkedEntity -> {
System.out.println("Linked Entities:");
System.out.printf("Name: %s, entity ID in data source: %s, URL: %s, data source: %s,"
+ " Bing Entity Search API ID: %s.%n",
linkedEntity.getName(), linkedEntity.getDataSourceEntityId(), linkedEntity.getUrl(),
linkedEntity.getDataSource(), linkedEntity.getBingEntitySearchApiId());
linkedEntity.getMatches().forEach(entityMatch -> System.out.printf(
"Matched entity: %s, confidence score: %f.%n",
entityMatch.getText(), entityMatch.getConfidenceScore()));
});
} | + " Bing Entity Search API ID: %s.%n", | public static void main(String[] args) {
TextAnalyticsClient client = new TextAnalyticsClientBuilder()
.credential(new AzureKeyCredential("{key}"))
.endpoint("{endpoint}")
.buildClient();
String document = "Old Faithful is a geyser at Yellowstone Park.";
client.recognizeLinkedEntities(document).forEach(linkedEntity -> {
System.out.println("Linked Entities:");
System.out.printf("Name: %s, entity ID in data source: %s, URL: %s, data source: %s,"
+ " Bing Entity Search API ID: %s.%n",
linkedEntity.getName(), linkedEntity.getDataSourceEntityId(), linkedEntity.getUrl(),
linkedEntity.getDataSource(), linkedEntity.getBingEntitySearchApiId());
linkedEntity.getMatches().forEach(entityMatch -> System.out.printf(
"Matched entity: %s, confidence score: %f.%n",
entityMatch.getText(), entityMatch.getConfidenceScore()));
});
} | class RecognizeLinkedEntities {
/**
* Main method to invoke this demo about how to recognize the linked entities of document.
*
* @param args Unused arguments to the program.
*/
} | class RecognizeLinkedEntities {
/**
* Main method to invoke this demo about how to recognize the linked entities of document.
*
* @param args Unused arguments to the program.
*/
} |
ModelData.model is null when the service returns it from a createModel call. I'm reworking this code a bit | public void modelLifecycleTest(HttpClient httpClient, DigitalTwinsServiceVersion serviceVersion) {
DigitalTwinsAsyncClient asyncClient = getAsyncClient(httpClient, serviceVersion);
List<ModelData> createdModels = new ArrayList<>();
createModelsRunner(asyncClient, (modelsList) -> {
StepVerifier.create(asyncClient.createModels(modelsList))
.assertNext(createdModel -> {
createdModel.setModel(modelsList.get(0));
createdModels.add(createdModel);
})
.assertNext(createdModel -> {
createdModel.setModel(modelsList.get(1));
createdModels.add(createdModel);
})
.assertNext(createdModel -> {
createdModel.setModel(modelsList.get(2));
createdModels.add(createdModel);
})
.verifyComplete();
});
for (int modelIndex = 0; modelIndex < createdModels.size(); modelIndex++) {
final ModelData expected = createdModels.get(modelIndex);
getModelRunner(expected.getId(), (modelId) -> {
StepVerifier.create(asyncClient.getModelWithResponse(modelId))
.assertNext(retrievedModel -> {
assertModelDataAreEqual(expected, retrievedModel.getValue());
})
.verifyComplete();
});
decommissionModelRunner(expected.getId(), (modelId) -> {
StepVerifier.create(asyncClient.decommissionModel(modelId))
.verifyComplete();
});
getModelRunner(expected.getId(), (modelId) -> {
StepVerifier.create(asyncClient.getModel(modelId))
.assertNext(retrievedModel -> {
assertTrue(retrievedModel.isDecommissioned());
})
.verifyComplete();
});
deleteModelRunner(expected.getId(), (modelId) -> {
StepVerifier.create(asyncClient.deleteModel(modelId))
.verifyComplete();
});
}
} | public void modelLifecycleTest(HttpClient httpClient, DigitalTwinsServiceVersion serviceVersion) {
DigitalTwinsAsyncClient asyncClient = getAsyncClient(httpClient, serviceVersion);
List<ModelData> createdModels = new ArrayList<>();
createModelsRunner(asyncClient, (modelsList) -> {
StepVerifier.create(asyncClient.createModels(modelsList))
.assertNext(createdModelsResponseList -> {
createdModels.addAll(createdModelsResponseList);
logger.info("Created {} models successfully", createdModelsResponseList.size());
})
.verifyComplete();
});
for (int modelIndex = 0; modelIndex < createdModels.size(); modelIndex++) {
final ModelData expected = createdModels.get(modelIndex);
getModelRunner(expected.getId(), (modelId) -> {
StepVerifier.create(asyncClient.getModelWithResponse(modelId))
.assertNext(retrievedModel -> {
assertModelDataAreEqual(expected, retrievedModel.getValue(), false);
})
.verifyComplete();
logger.info("Model {} matched expectations", modelId);
});
decommissionModelRunner(expected.getId(), (modelId) -> {
logger.info("Decommissioning model {}", modelId);
StepVerifier.create(asyncClient.decommissionModel(modelId))
.verifyComplete();
});
getModelRunner(expected.getId(), (modelId) -> {
StepVerifier.create(asyncClient.getModel(modelId))
.assertNext(retrievedModel -> {
assertTrue(retrievedModel.isDecommissioned());
})
.verifyComplete();
logger.info("Model {} was decommissioned successfully", modelId);
});
deleteModelRunner(expected.getId(), (modelId) -> {
logger.info("Deleting model {}", modelId);
StepVerifier.create(asyncClient.deleteModel(modelId))
.verifyComplete();
});
}
} | class ModelsAsyncTest extends ModelsTestBase {
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.digitaltwins.core.TestHelper
@Override
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.digitaltwins.core.TestHelper
@Override
public void getModelThrowsIfModelDoesNotExist(HttpClient httpClient, DigitalTwinsServiceVersion serviceVersion) {
DigitalTwinsAsyncClient asyncClient = getAsyncClient(httpClient, serviceVersion);
final String nonExistantModelId = "urn:doesnotexist:fakemodel:1000";
StepVerifier.create(asyncClient.getModel(nonExistantModelId))
.verifyErrorSatisfies(ex -> assertRestException(ex, HttpURLConnection.HTTP_NOT_FOUND));
}
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.digitaltwins.core.TestHelper
@Override
public void createModelThrowsIfModelAlreadyExists(HttpClient httpClient, DigitalTwinsServiceVersion serviceVersion) {
DigitalTwinsAsyncClient asyncClient = getAsyncClient(httpClient, serviceVersion);
final List<String> modelsToCreate = new ArrayList<>();
final String wardModelId = TestAssetsHelper.getUniqueModelId(asyncClient, TestAssetDefaults.wardModelId);
final String wardModelPayload = TestAssetsHelper.getWardModelPayload(wardModelId);
modelsToCreate.add(wardModelPayload);
StepVerifier.create(asyncClient.createModels(modelsToCreate))
.assertNext((modelData -> {
assertNotNull(modelData);
}))
.verifyComplete();
StepVerifier.create(asyncClient.createModels(modelsToCreate))
.verifyErrorSatisfies(ex -> assertRestException(ex, HttpURLConnection.HTTP_CONFLICT));
}
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.digitaltwins.core.TestHelper
@Override
public void getModelThrowsIfModelIdInvalid(HttpClient httpClient, DigitalTwinsServiceVersion serviceVersion) {
DigitalTwinsAsyncClient asyncClient = getAsyncClient(httpClient, serviceVersion);
final String malformedModelId = "thisIsNotAValidModelId";
StepVerifier.create(asyncClient.getModel(malformedModelId))
.verifyErrorSatisfies(ex -> assertRestException(ex, HttpURLConnection.HTTP_BAD_REQUEST));
}
private static void createModelsRunner(DigitalTwinsAsyncClient asyncClient, Consumer<List<String>> createModelsTestRunner) {
String buildingModelId = TestAssetsHelper.getUniqueModelId(asyncClient, TestAssetDefaults.buildingModelId);
String floorModelId = TestAssetsHelper.getUniqueModelId(asyncClient, TestAssetDefaults.floorModelId);
String hvacModelId = TestAssetsHelper.getUniqueModelId(asyncClient, TestAssetDefaults.hvacModelId);
String wardModelId = TestAssetsHelper.getUniqueModelId(asyncClient, TestAssetDefaults.wardModelId);
createModelsRunner(buildingModelId, floorModelId, hvacModelId, wardModelId, createModelsTestRunner);
}
private DigitalTwinsAsyncClient getAsyncClient(HttpClient httpClient, DigitalTwinsServiceVersion serviceVersion) {
return getDigitalTwinsClientBuilder().serviceVersion(serviceVersion).httpClient(httpClient).buildAsyncClient();
}
} | class ModelsAsyncTest extends ModelsTestBase {
private final ClientLogger logger = new ClientLogger(ModelsAsyncTest.class);
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.digitaltwins.core.TestHelper
@Override
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.digitaltwins.core.TestHelper
@Override
public void getModelThrowsIfModelDoesNotExist(HttpClient httpClient, DigitalTwinsServiceVersion serviceVersion) {
DigitalTwinsAsyncClient asyncClient = getAsyncClient(httpClient, serviceVersion);
final String nonExistantModelId = "urn:doesnotexist:fakemodel:1000";
StepVerifier.create(asyncClient.getModel(nonExistantModelId))
.verifyErrorSatisfies(ex -> assertRestException(ex, HttpURLConnection.HTTP_NOT_FOUND));
}
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.digitaltwins.core.TestHelper
@Override
public void createModelThrowsIfModelAlreadyExists(HttpClient httpClient, DigitalTwinsServiceVersion serviceVersion) {
DigitalTwinsAsyncClient asyncClient = getAsyncClient(httpClient, serviceVersion);
final List<String> modelsToCreate = new ArrayList<>();
final String wardModelId = UniqueIdHelper.getUniqueModelId(TestAssetDefaults.WARD_MODEL_ID, asyncClient, this.randomIntegerStringGenerator);
final String wardModelPayload = TestAssetsHelper.getWardModelPayload(wardModelId);
modelsToCreate.add(wardModelPayload);
StepVerifier.create(asyncClient.createModels(modelsToCreate))
.assertNext((modelData -> {
assertNotNull(modelData);
}))
.verifyComplete();
StepVerifier.create(asyncClient.createModels(modelsToCreate))
.verifyErrorSatisfies(ex -> assertRestException(ex, HttpURLConnection.HTTP_CONFLICT));
}
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.digitaltwins.core.TestHelper
@Override
public void getModelThrowsIfModelIdInvalid(HttpClient httpClient, DigitalTwinsServiceVersion serviceVersion) {
DigitalTwinsAsyncClient asyncClient = getAsyncClient(httpClient, serviceVersion);
final String malformedModelId = "thisIsNotAValidModelId";
StepVerifier.create(asyncClient.getModel(malformedModelId))
.verifyErrorSatisfies(ex -> assertRestException(ex, HttpURLConnection.HTTP_BAD_REQUEST));
}
private void createModelsRunner(DigitalTwinsAsyncClient asyncClient, Consumer<List<String>> createModelsTestRunner) {
String buildingModelId = UniqueIdHelper.getUniqueModelId(TestAssetDefaults.BUILDING_MODEL_ID, asyncClient, this.randomIntegerStringGenerator);
String floorModelId = UniqueIdHelper.getUniqueModelId(TestAssetDefaults.FLOOR_MODEL_ID, asyncClient, this.randomIntegerStringGenerator);
String hvacModelId = UniqueIdHelper.getUniqueModelId(TestAssetDefaults.HVAC_MODEL_ID, asyncClient, this.randomIntegerStringGenerator);
String wardModelId = UniqueIdHelper.getUniqueModelId(TestAssetDefaults.WARD_MODEL_ID, asyncClient, this.randomIntegerStringGenerator);
createModelsRunner(buildingModelId, floorModelId, hvacModelId, wardModelId, createModelsTestRunner);
}
private DigitalTwinsAsyncClient getAsyncClient(HttpClient httpClient, DigitalTwinsServiceVersion serviceVersion) {
return getDigitalTwinsClientBuilder(httpClient, serviceVersion)
.buildAsyncClient();
}
} | |
I see ```java.net.HttpURLConnection``` used in the app configuration SDK code, so I'd recommend it | public void getModelThrowsIfModelDoesNotExist(HttpClient httpClient, DigitalTwinsServiceVersion serviceVersion) {
DigitalTwinsAsyncClient asyncClient = getAsyncClient(httpClient, serviceVersion);
final String nonExistantModelId = "urn:doesnotexist:fakemodel:1000";
StepVerifier.create(asyncClient.getModel(nonExistantModelId))
.verifyErrorSatisfies(ex -> assertRestException(ex, HttpURLConnection.HTTP_NOT_FOUND));
} | StepVerifier.create(asyncClient.getModel(nonExistantModelId)) | public void getModelThrowsIfModelDoesNotExist(HttpClient httpClient, DigitalTwinsServiceVersion serviceVersion) {
DigitalTwinsAsyncClient asyncClient = getAsyncClient(httpClient, serviceVersion);
final String nonExistantModelId = "urn:doesnotexist:fakemodel:1000";
StepVerifier.create(asyncClient.getModel(nonExistantModelId))
.verifyErrorSatisfies(ex -> assertRestException(ex, HttpURLConnection.HTTP_NOT_FOUND));
} | class ModelsAsyncTest extends ModelsTestBase {
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.digitaltwins.core.TestHelper
@Override
public void modelLifecycleTest(HttpClient httpClient, DigitalTwinsServiceVersion serviceVersion) {
DigitalTwinsAsyncClient asyncClient = getAsyncClient(httpClient, serviceVersion);
List<ModelData> createdModels = new ArrayList<>();
createModelsRunner(asyncClient, (modelsList) -> {
StepVerifier.create(asyncClient.createModels(modelsList))
.assertNext(createdModel -> {
createdModel.setModel(modelsList.get(0));
createdModels.add(createdModel);
})
.assertNext(createdModel -> {
createdModel.setModel(modelsList.get(1));
createdModels.add(createdModel);
})
.assertNext(createdModel -> {
createdModel.setModel(modelsList.get(2));
createdModels.add(createdModel);
})
.verifyComplete();
});
for (int modelIndex = 0; modelIndex < createdModels.size(); modelIndex++) {
final ModelData expected = createdModels.get(modelIndex);
getModelRunner(expected.getId(), (modelId) -> {
StepVerifier.create(asyncClient.getModelWithResponse(modelId))
.assertNext(retrievedModel -> {
assertModelDataAreEqual(expected, retrievedModel.getValue());
})
.verifyComplete();
});
decommissionModelRunner(expected.getId(), (modelId) -> {
StepVerifier.create(asyncClient.decommissionModel(modelId))
.verifyComplete();
});
getModelRunner(expected.getId(), (modelId) -> {
StepVerifier.create(asyncClient.getModel(modelId))
.assertNext(retrievedModel -> {
assertTrue(retrievedModel.isDecommissioned());
})
.verifyComplete();
});
deleteModelRunner(expected.getId(), (modelId) -> {
StepVerifier.create(asyncClient.deleteModel(modelId))
.verifyComplete();
});
}
}
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.digitaltwins.core.TestHelper
@Override
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.digitaltwins.core.TestHelper
@Override
public void createModelThrowsIfModelAlreadyExists(HttpClient httpClient, DigitalTwinsServiceVersion serviceVersion) {
DigitalTwinsAsyncClient asyncClient = getAsyncClient(httpClient, serviceVersion);
final List<String> modelsToCreate = new ArrayList<>();
final String wardModelId = TestAssetsHelper.getUniqueModelId(asyncClient, TestAssetDefaults.wardModelId);
final String wardModelPayload = TestAssetsHelper.getWardModelPayload(wardModelId);
modelsToCreate.add(wardModelPayload);
StepVerifier.create(asyncClient.createModels(modelsToCreate))
.assertNext((modelData -> {
assertNotNull(modelData);
}))
.verifyComplete();
StepVerifier.create(asyncClient.createModels(modelsToCreate))
.verifyErrorSatisfies(ex -> assertRestException(ex, HttpURLConnection.HTTP_CONFLICT));
}
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.digitaltwins.core.TestHelper
@Override
public void getModelThrowsIfModelIdInvalid(HttpClient httpClient, DigitalTwinsServiceVersion serviceVersion) {
DigitalTwinsAsyncClient asyncClient = getAsyncClient(httpClient, serviceVersion);
final String malformedModelId = "thisIsNotAValidModelId";
StepVerifier.create(asyncClient.getModel(malformedModelId))
.verifyErrorSatisfies(ex -> assertRestException(ex, HttpURLConnection.HTTP_BAD_REQUEST));
}
private static void createModelsRunner(DigitalTwinsAsyncClient asyncClient, Consumer<List<String>> createModelsTestRunner) {
String buildingModelId = TestAssetsHelper.getUniqueModelId(asyncClient, TestAssetDefaults.buildingModelId);
String floorModelId = TestAssetsHelper.getUniqueModelId(asyncClient, TestAssetDefaults.floorModelId);
String hvacModelId = TestAssetsHelper.getUniqueModelId(asyncClient, TestAssetDefaults.hvacModelId);
String wardModelId = TestAssetsHelper.getUniqueModelId(asyncClient, TestAssetDefaults.wardModelId);
createModelsRunner(buildingModelId, floorModelId, hvacModelId, wardModelId, createModelsTestRunner);
}
private DigitalTwinsAsyncClient getAsyncClient(HttpClient httpClient, DigitalTwinsServiceVersion serviceVersion) {
return getDigitalTwinsClientBuilder().serviceVersion(serviceVersion).httpClient(httpClient).buildAsyncClient();
}
} | class ModelsAsyncTest extends ModelsTestBase {
private final ClientLogger logger = new ClientLogger(ModelsAsyncTest.class);
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.digitaltwins.core.TestHelper
@Override
public void modelLifecycleTest(HttpClient httpClient, DigitalTwinsServiceVersion serviceVersion) {
DigitalTwinsAsyncClient asyncClient = getAsyncClient(httpClient, serviceVersion);
List<ModelData> createdModels = new ArrayList<>();
createModelsRunner(asyncClient, (modelsList) -> {
StepVerifier.create(asyncClient.createModels(modelsList))
.assertNext(createdModelsResponseList -> {
createdModels.addAll(createdModelsResponseList);
logger.info("Created {} models successfully", createdModelsResponseList.size());
})
.verifyComplete();
});
for (int modelIndex = 0; modelIndex < createdModels.size(); modelIndex++) {
final ModelData expected = createdModels.get(modelIndex);
getModelRunner(expected.getId(), (modelId) -> {
StepVerifier.create(asyncClient.getModelWithResponse(modelId))
.assertNext(retrievedModel -> {
assertModelDataAreEqual(expected, retrievedModel.getValue(), false);
})
.verifyComplete();
logger.info("Model {} matched expectations", modelId);
});
decommissionModelRunner(expected.getId(), (modelId) -> {
logger.info("Decommissioning model {}", modelId);
StepVerifier.create(asyncClient.decommissionModel(modelId))
.verifyComplete();
});
getModelRunner(expected.getId(), (modelId) -> {
StepVerifier.create(asyncClient.getModel(modelId))
.assertNext(retrievedModel -> {
assertTrue(retrievedModel.isDecommissioned());
})
.verifyComplete();
logger.info("Model {} was decommissioned successfully", modelId);
});
deleteModelRunner(expected.getId(), (modelId) -> {
logger.info("Deleting model {}", modelId);
StepVerifier.create(asyncClient.deleteModel(modelId))
.verifyComplete();
});
}
}
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.digitaltwins.core.TestHelper
@Override
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.digitaltwins.core.TestHelper
@Override
public void createModelThrowsIfModelAlreadyExists(HttpClient httpClient, DigitalTwinsServiceVersion serviceVersion) {
DigitalTwinsAsyncClient asyncClient = getAsyncClient(httpClient, serviceVersion);
final List<String> modelsToCreate = new ArrayList<>();
final String wardModelId = UniqueIdHelper.getUniqueModelId(TestAssetDefaults.WARD_MODEL_ID, asyncClient, this.randomIntegerStringGenerator);
final String wardModelPayload = TestAssetsHelper.getWardModelPayload(wardModelId);
modelsToCreate.add(wardModelPayload);
StepVerifier.create(asyncClient.createModels(modelsToCreate))
.assertNext((modelData -> {
assertNotNull(modelData);
}))
.verifyComplete();
StepVerifier.create(asyncClient.createModels(modelsToCreate))
.verifyErrorSatisfies(ex -> assertRestException(ex, HttpURLConnection.HTTP_CONFLICT));
}
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.digitaltwins.core.TestHelper
@Override
public void getModelThrowsIfModelIdInvalid(HttpClient httpClient, DigitalTwinsServiceVersion serviceVersion) {
DigitalTwinsAsyncClient asyncClient = getAsyncClient(httpClient, serviceVersion);
final String malformedModelId = "thisIsNotAValidModelId";
StepVerifier.create(asyncClient.getModel(malformedModelId))
.verifyErrorSatisfies(ex -> assertRestException(ex, HttpURLConnection.HTTP_BAD_REQUEST));
}
private void createModelsRunner(DigitalTwinsAsyncClient asyncClient, Consumer<List<String>> createModelsTestRunner) {
String buildingModelId = UniqueIdHelper.getUniqueModelId(TestAssetDefaults.BUILDING_MODEL_ID, asyncClient, this.randomIntegerStringGenerator);
String floorModelId = UniqueIdHelper.getUniqueModelId(TestAssetDefaults.FLOOR_MODEL_ID, asyncClient, this.randomIntegerStringGenerator);
String hvacModelId = UniqueIdHelper.getUniqueModelId(TestAssetDefaults.HVAC_MODEL_ID, asyncClient, this.randomIntegerStringGenerator);
String wardModelId = UniqueIdHelper.getUniqueModelId(TestAssetDefaults.WARD_MODEL_ID, asyncClient, this.randomIntegerStringGenerator);
createModelsRunner(buildingModelId, floorModelId, hvacModelId, wardModelId, createModelsTestRunner);
}
private DigitalTwinsAsyncClient getAsyncClient(HttpClient httpClient, DigitalTwinsServiceVersion serviceVersion) {
return getDigitalTwinsClientBuilder(httpClient, serviceVersion)
.buildAsyncClient();
}
} |
we might not to do this for-each iteration, create models does not return a pageable anymore, so the blocking call should directly complete with result. | public void createModelThrowsIfModelAlreadyExists(HttpClient httpClient, DigitalTwinsServiceVersion serviceVersion) {
DigitalTwinsClient client = getClient(httpClient, serviceVersion);
final List<String> modelsToCreate = new ArrayList<>();
final String wardModelId = UniqueIdHelper.getUniqueModelId(TestAssetDefaults.WARD_MODEL_ID, client, randomIntegerStringGenerator);
final String wardModelPayload = TestAssetsHelper.getWardModelPayload(wardModelId);
modelsToCreate.add(wardModelPayload);
List<ModelData> createdModels = client.createModels(modelsToCreate);
createdModels.forEach((modelData) -> {
assertNotNull(modelData);
});
assertRestException(
() -> client.createModels(modelsToCreate).forEach((modelData) -> {
}),
HttpURLConnection.HTTP_CONFLICT);
} | () -> client.createModels(modelsToCreate).forEach((modelData) -> { | public void createModelThrowsIfModelAlreadyExists(HttpClient httpClient, DigitalTwinsServiceVersion serviceVersion) {
DigitalTwinsClient client = getClient(httpClient, serviceVersion);
final List<String> modelsToCreate = new ArrayList<>();
final String wardModelId = UniqueIdHelper.getUniqueModelId(TestAssetDefaults.WARD_MODEL_ID, client, randomIntegerStringGenerator);
final String wardModelPayload = TestAssetsHelper.getWardModelPayload(wardModelId);
modelsToCreate.add(wardModelPayload);
List<ModelData> createdModels = client.createModels(modelsToCreate);
createdModels.forEach((modelData) -> {
assertNotNull(modelData);
});
assertRestException(
() -> client.createModels(modelsToCreate),
HttpURLConnection.HTTP_CONFLICT);
} | class ModelsTest extends ModelsTestBase {
private final ClientLogger logger = new ClientLogger(ModelsTestBase.class);
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.digitaltwins.core.TestHelper
@Override
public void modelLifecycleTest(HttpClient httpClient, DigitalTwinsServiceVersion serviceVersion) {
DigitalTwinsClient client = getClient(httpClient, serviceVersion);
final List<ModelData> createdModels = new ArrayList<>();
createModelsRunner(client, (modelsList) -> {
List<ModelData> createdModelsResponseList = client.createModels(modelsList);
createdModelsResponseList.forEach((modelData) -> {
createdModels.add(modelData);
logger.info("Created {} models successfully", createdModelsResponseList.size());
});
});
for (int modelIndex = 0; modelIndex < createdModels.size(); modelIndex++) {
final ModelData expected = createdModels.get(modelIndex);
getModelRunner(expected.getId(), (modelId) -> {
ModelData actual = client.getModel(modelId);
assertModelDataAreEqual(expected, actual, false);
logger.info("Model {} matched expectations", modelId);
});
decommissionModelRunner(expected.getId(), (modelId) -> {
logger.info("Decommissioning model {}", modelId);
client.decommissionModel(modelId);
});
getModelRunner(expected.getId(), (modelId) -> {
ModelData actual = client.getModel(modelId);
assertTrue(actual.isDecommissioned());
logger.info("Model {} was decommissioned successfully", modelId);
});
deleteModelRunner(expected.getId(), (modelId) -> {
logger.info("Deleting model {}", modelId);
client.deleteModel(modelId);
});
}
}
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.digitaltwins.core.TestHelper
@Override
public void getModelThrowsIfModelDoesNotExist(HttpClient httpClient, DigitalTwinsServiceVersion serviceVersion) {
DigitalTwinsClient client = getClient(httpClient, serviceVersion);
final String nonExistantModelId = "urn:doesnotexist:fakemodel:1000";
getModelRunner(nonExistantModelId, (modelId) -> {
assertRestException(() -> client.getModel(modelId), HttpURLConnection.HTTP_NOT_FOUND);
});
}
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.digitaltwins.core.TestHelper
@Override
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.digitaltwins.core.TestHelper
@Override
public void getModelThrowsIfModelIdInvalid(HttpClient httpClient, DigitalTwinsServiceVersion serviceVersion) {
DigitalTwinsClient client = getClient(httpClient, serviceVersion);
final String malformedModelId = "thisIsNotAValidModelId";
getModelRunner(malformedModelId, (modelId) -> {
assertRestException(() -> client.getModel(modelId), HttpURLConnection.HTTP_BAD_REQUEST);
});
}
private void createModelsRunner(DigitalTwinsClient client, Consumer<List<String>> createModelsTestRunner) {
String buildingModelId = UniqueIdHelper.getUniqueModelId(TestAssetDefaults.BUILDING_MODEL_ID, client, randomIntegerStringGenerator);
String floorModelId = UniqueIdHelper.getUniqueModelId(TestAssetDefaults.FLOOR_MODEL_ID, client, randomIntegerStringGenerator);
String hvacModelId = UniqueIdHelper.getUniqueModelId(TestAssetDefaults.HVAC_MODEL_ID, client, randomIntegerStringGenerator);
String wardModelId = UniqueIdHelper.getUniqueModelId(TestAssetDefaults.WARD_MODEL_ID, client, randomIntegerStringGenerator);
createModelsRunner(buildingModelId, floorModelId, hvacModelId, wardModelId, createModelsTestRunner);
}
private DigitalTwinsClient getClient(HttpClient httpClient, DigitalTwinsServiceVersion serviceVersion) {
return getDigitalTwinsClientBuilder(httpClient, serviceVersion)
.buildClient();
}
} | class ModelsTest extends ModelsTestBase {
private final ClientLogger logger = new ClientLogger(ModelsTestBase.class);
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.digitaltwins.core.TestHelper
@Override
public void modelLifecycleTest(HttpClient httpClient, DigitalTwinsServiceVersion serviceVersion) {
DigitalTwinsClient client = getClient(httpClient, serviceVersion);
final List<ModelData> createdModels = new ArrayList<>();
createModelsRunner(client, (modelsList) -> {
List<ModelData> createdModelsResponseList = client.createModels(modelsList);
createdModelsResponseList.forEach((modelData) -> {
createdModels.add(modelData);
logger.info("Created {} models successfully", createdModelsResponseList.size());
});
});
for (int modelIndex = 0; modelIndex < createdModels.size(); modelIndex++) {
final ModelData expected = createdModels.get(modelIndex);
getModelRunner(expected.getId(), (modelId) -> {
ModelData actual = client.getModel(modelId);
assertModelDataAreEqual(expected, actual, false);
logger.info("Model {} matched expectations", modelId);
});
decommissionModelRunner(expected.getId(), (modelId) -> {
logger.info("Decommissioning model {}", modelId);
client.decommissionModel(modelId);
});
getModelRunner(expected.getId(), (modelId) -> {
ModelData actual = client.getModel(modelId);
assertTrue(actual.isDecommissioned());
logger.info("Model {} was decommissioned successfully", modelId);
});
deleteModelRunner(expected.getId(), (modelId) -> {
logger.info("Deleting model {}", modelId);
client.deleteModel(modelId);
});
}
}
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.digitaltwins.core.TestHelper
@Override
public void getModelThrowsIfModelDoesNotExist(HttpClient httpClient, DigitalTwinsServiceVersion serviceVersion) {
DigitalTwinsClient client = getClient(httpClient, serviceVersion);
final String nonExistantModelId = "urn:doesnotexist:fakemodel:1000";
getModelRunner(nonExistantModelId, (modelId) -> {
assertRestException(() -> client.getModel(modelId), HttpURLConnection.HTTP_NOT_FOUND);
});
}
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.digitaltwins.core.TestHelper
@Override
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.digitaltwins.core.TestHelper
@Override
public void getModelThrowsIfModelIdInvalid(HttpClient httpClient, DigitalTwinsServiceVersion serviceVersion) {
DigitalTwinsClient client = getClient(httpClient, serviceVersion);
final String malformedModelId = "thisIsNotAValidModelId";
getModelRunner(malformedModelId, (modelId) -> {
assertRestException(() -> client.getModel(modelId), HttpURLConnection.HTTP_BAD_REQUEST);
});
}
private void createModelsRunner(DigitalTwinsClient client, Consumer<List<String>> createModelsTestRunner) {
String buildingModelId = UniqueIdHelper.getUniqueModelId(TestAssetDefaults.BUILDING_MODEL_ID, client, randomIntegerStringGenerator);
String floorModelId = UniqueIdHelper.getUniqueModelId(TestAssetDefaults.FLOOR_MODEL_ID, client, randomIntegerStringGenerator);
String hvacModelId = UniqueIdHelper.getUniqueModelId(TestAssetDefaults.HVAC_MODEL_ID, client, randomIntegerStringGenerator);
String wardModelId = UniqueIdHelper.getUniqueModelId(TestAssetDefaults.WARD_MODEL_ID, client, randomIntegerStringGenerator);
createModelsRunner(buildingModelId, floorModelId, hvacModelId, wardModelId, createModelsTestRunner);
}
private DigitalTwinsClient getClient(HttpClient httpClient, DigitalTwinsServiceVersion serviceVersion) {
return getDigitalTwinsClientBuilder(httpClient, serviceVersion)
.buildClient();
}
} |
hmm and actually, it might be better not to include it in the samples as this is a super specific property that will only be used by advanced customers... so better if we don't confuse our normal users | public static void main(String[] args) {
TextAnalyticsClient client = new TextAnalyticsClientBuilder()
.credential(new AzureKeyCredential("{key}"))
.endpoint("{endpoint}")
.buildClient();
String document = "Old Faithful is a geyser at Yellowstone Park.";
client.recognizeLinkedEntities(document).forEach(linkedEntity -> {
System.out.println("Linked Entities:");
System.out.printf("Name: %s, entity ID in data source: %s, URL: %s, data source: %s,"
+ " Bing Entity Search API ID: %s.%n",
linkedEntity.getName(), linkedEntity.getDataSourceEntityId(), linkedEntity.getUrl(),
linkedEntity.getDataSource(), linkedEntity.getBingEntitySearchApiId());
linkedEntity.getMatches().forEach(entityMatch -> System.out.printf(
"Matched entity: %s, confidence score: %f.%n",
entityMatch.getText(), entityMatch.getConfidenceScore()));
});
} | + " Bing Entity Search API ID: %s.%n", | public static void main(String[] args) {
TextAnalyticsClient client = new TextAnalyticsClientBuilder()
.credential(new AzureKeyCredential("{key}"))
.endpoint("{endpoint}")
.buildClient();
String document = "Old Faithful is a geyser at Yellowstone Park.";
client.recognizeLinkedEntities(document).forEach(linkedEntity -> {
System.out.println("Linked Entities:");
System.out.printf("Name: %s, entity ID in data source: %s, URL: %s, data source: %s,"
+ " Bing Entity Search API ID: %s.%n",
linkedEntity.getName(), linkedEntity.getDataSourceEntityId(), linkedEntity.getUrl(),
linkedEntity.getDataSource(), linkedEntity.getBingEntitySearchApiId());
linkedEntity.getMatches().forEach(entityMatch -> System.out.printf(
"Matched entity: %s, confidence score: %f.%n",
entityMatch.getText(), entityMatch.getConfidenceScore()));
});
} | class RecognizeLinkedEntities {
/**
* Main method to invoke this demo about how to recognize the linked entities of document.
*
* @param args Unused arguments to the program.
*/
} | class RecognizeLinkedEntities {
/**
* Main method to invoke this demo about how to recognize the linked entities of document.
*
* @param args Unused arguments to the program.
*/
} |
Can we split this into another test case and disable it? I feel it'll get lost as a comment since there is no issue or TODO tracking this. | 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();
}
} | StepVerifier.create(tableClient.updateEntityWithResponse(createdEntity, true, mode)) | 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();
}
} | 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))
.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 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))
.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 updateEntityWithResponseReplaceAsync() {
updateEntityWithResponseAsync(UpdateMode.REPLACE);
}
@Test
void updateEntityWithResponseMergeAsync() {
updateEntityWithResponseAsync(UpdateMode.MERGE);
}
/**
* In the case of {@link UpdateMode
* In the case of {@link UpdateMode
*/
@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();
}
} | 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))
.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 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))
.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 updateEntityWithResponseReplaceAsync() {
updateEntityWithResponseAsync(UpdateMode.REPLACE);
}
@Test
void updateEntityWithResponseMergeAsync() {
updateEntityWithResponseAsync(UpdateMode.MERGE);
}
/**
* In the case of {@link UpdateMode
* In the case of {@link UpdateMode
*/
@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();
}
} |
Is there a reason for splitting this into three sequential blocks rather than running them concurrently? | void serviceListTablesWithTopAsync() {
final String tableName = testResourceNamer.randomName("test", 20);
final String tableName2 = testResourceNamer.randomName("test", 20);
final String tableName3 = testResourceNamer.randomName("test", 20);
ListTablesOptions options = new ListTablesOptions().setTop(2);
serviceClient.createTable(tableName).block(TIMEOUT);
serviceClient.createTable(tableName2).block(TIMEOUT);
serviceClient.createTable(tableName3).block(TIMEOUT);
StepVerifier.create(serviceClient.listTables(options))
.expectNextCount(2)
.thenConsumeWhile(x -> true)
.expectComplete()
.verify();
} | serviceClient.createTable(tableName).block(TIMEOUT); | void serviceListTablesWithTopAsync() {
final String tableName = testResourceNamer.randomName("test", 20);
final String tableName2 = testResourceNamer.randomName("test", 20);
final String tableName3 = testResourceNamer.randomName("test", 20);
ListTablesOptions options = new ListTablesOptions().setTop(2);
serviceClient.createTable(tableName).block(TIMEOUT);
serviceClient.createTable(tableName2).block(TIMEOUT);
serviceClient.createTable(tableName3).block(TIMEOUT);
StepVerifier.create(serviceClient.listTables(options))
.expectNextCount(2)
.thenConsumeWhile(x -> true)
.expectComplete()
.verify();
} | class TableServiceAsyncClientTest extends TestBase {
private static final Duration TIMEOUT = Duration.ofSeconds(100);
private TableServiceAsyncClient serviceClient;
@BeforeAll
static void beforeAll() {
StepVerifier.setDefaultTimeout(TIMEOUT);
}
@AfterAll
static void afterAll() {
StepVerifier.resetDefaultTimeout();
}
@Override
protected void beforeTest() {
final String connectionString = TestUtils.getConnectionString(interceptorManager.isPlaybackMode());
final TableServiceClientBuilder builder = new TableServiceClientBuilder()
.connectionString(connectionString)
.httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS));
if (interceptorManager.isPlaybackMode()) {
builder.httpClient(interceptorManager.getPlaybackClient());
} else {
builder.httpClient(HttpClient.createDefault());
if (!interceptorManager.isLiveMode()) {
builder.addPolicy(interceptorManager.getRecordPolicy());
}
builder.addPolicy(new RetryPolicy(new ExponentialBackoff(6, Duration.ofMillis(1500),
Duration.ofSeconds(100))));
}
serviceClient = builder.buildAsyncClient();
}
@Test
void serviceCreateTableAsync() {
String tableName = testResourceNamer.randomName("test", 20);
StepVerifier.create(serviceClient.createTable(tableName))
.expectComplete()
.verify();
}
@Test
void serviceCreateTableFailsIfExistsAsync() {
String tableName = testResourceNamer.randomName("test", 20);
serviceClient.createTable(tableName).block(TIMEOUT);
StepVerifier.create(serviceClient.createTable(tableName))
.expectErrorMatches(e -> e instanceof TableServiceErrorException
&& ((TableServiceErrorException) e).getResponse().getStatusCode() == 409)
.verify();
}
@Test
void serviceCreateTableWithResponseAsync() {
String tableName = testResourceNamer.randomName("test", 20);
int expectedStatusCode = 204;
StepVerifier.create(serviceClient.createTableWithResponse(tableName))
.assertNext(response -> {
Assertions.assertEquals(expectedStatusCode, response.getStatusCode());
})
.expectComplete()
.verify();
}
@Test
void serviceCreateTableIfNotExistsAsync() {
String tableName = testResourceNamer.randomName("test", 20);
StepVerifier.create(serviceClient.createTableIfNotExists(tableName))
.expectComplete()
.verify();
}
@Test
void serviceCreateTableIfNotExistsSucceedsIfExistsAsync() {
String tableName = testResourceNamer.randomName("test", 20);
serviceClient.createTable(tableName).block(TIMEOUT);
StepVerifier.create(serviceClient.createTableIfNotExists(tableName))
.expectComplete()
.verify();
}
@Test
void serviceCreateTableIfNotExistsWithResponseAsync() {
String tableName = testResourceNamer.randomName("test", 20);
int expectedStatusCode = 204;
StepVerifier.create(serviceClient.createTableIfNotExistsWithResponse(tableName))
.assertNext(response -> {
Assertions.assertEquals(expectedStatusCode, response.getStatusCode());
})
.expectComplete()
.verify();
}
@Test
void serviceCreateTableIfNotExistsWithResponseSucceedsIfExistsAsync() {
String tableName = testResourceNamer.randomName("test", 20);
int expectedStatusCode = 409;
serviceClient.createTable(tableName).block(TIMEOUT);
StepVerifier.create(serviceClient.createTableIfNotExistsWithResponse(tableName))
.assertNext(response -> {
Assertions.assertEquals(expectedStatusCode, response.getStatusCode());
})
.expectComplete()
.verify();
}
@Test
void serviceDeleteTableAsync() {
final String tableName = testResourceNamer.randomName("test", 20);
serviceClient.createTable(tableName).block(TIMEOUT);
StepVerifier.create(serviceClient.deleteTable(tableName))
.expectComplete()
.verify();
}
@Test
void serviceDeleteTableWithResponseAsync() {
String tableName = testResourceNamer.randomName("test", 20);
int expectedStatusCode = 204;
serviceClient.createTable(tableName).block();
StepVerifier.create(serviceClient.deleteTableWithResponse(tableName))
.assertNext(response -> {
Assertions.assertEquals(expectedStatusCode, response.getStatusCode());
})
.expectComplete()
.verify();
}
@Test
@Tag("ListTables")
void serviceListTablesAsync() {
final String tableName = testResourceNamer.randomName("test", 20);
final String tableName2 = testResourceNamer.randomName("test", 20);
serviceClient.createTable(tableName).block(TIMEOUT);
serviceClient.createTable(tableName2).block(TIMEOUT);
StepVerifier.create(serviceClient.listTables())
.expectNextCount(2)
.thenConsumeWhile(x -> true)
.expectComplete()
.verify();
}
@Test
@Tag("ListTables")
void serviceListTablesWithFilterAsync() {
final String tableName = testResourceNamer.randomName("test", 20);
final String tableName2 = testResourceNamer.randomName("test", 20);
ListTablesOptions options = new ListTablesOptions().setFilter("TableName eq '" + tableName + "'");
serviceClient.createTable(tableName).block(TIMEOUT);
serviceClient.createTable(tableName2).block(TIMEOUT);
StepVerifier.create(serviceClient.listTables(options))
.assertNext(table -> {
assertEquals(tableName, table.getName());
})
.expectNextCount(0)
.thenConsumeWhile(x -> true)
.expectComplete()
.verify();
}
@Test
@Tag("ListTables")
} | class TableServiceAsyncClientTest extends TestBase {
private static final Duration TIMEOUT = Duration.ofSeconds(100);
private TableServiceAsyncClient serviceClient;
@BeforeAll
static void beforeAll() {
StepVerifier.setDefaultTimeout(TIMEOUT);
}
@AfterAll
static void afterAll() {
StepVerifier.resetDefaultTimeout();
}
@Override
protected void beforeTest() {
final String connectionString = TestUtils.getConnectionString(interceptorManager.isPlaybackMode());
final TableServiceClientBuilder builder = new TableServiceClientBuilder()
.connectionString(connectionString)
.httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS));
if (interceptorManager.isPlaybackMode()) {
builder.httpClient(interceptorManager.getPlaybackClient());
} else {
builder.httpClient(HttpClient.createDefault());
if (!interceptorManager.isLiveMode()) {
builder.addPolicy(interceptorManager.getRecordPolicy());
}
builder.addPolicy(new RetryPolicy(new ExponentialBackoff(6, Duration.ofMillis(1500),
Duration.ofSeconds(100))));
}
serviceClient = builder.buildAsyncClient();
}
@Test
void serviceCreateTableAsync() {
String tableName = testResourceNamer.randomName("test", 20);
StepVerifier.create(serviceClient.createTable(tableName))
.expectComplete()
.verify();
}
@Test
void serviceCreateTableFailsIfExistsAsync() {
String tableName = testResourceNamer.randomName("test", 20);
serviceClient.createTable(tableName).block(TIMEOUT);
StepVerifier.create(serviceClient.createTable(tableName))
.expectErrorMatches(e -> e instanceof TableServiceErrorException
&& ((TableServiceErrorException) e).getResponse().getStatusCode() == 409)
.verify();
}
@Test
void serviceCreateTableWithResponseAsync() {
String tableName = testResourceNamer.randomName("test", 20);
int expectedStatusCode = 204;
StepVerifier.create(serviceClient.createTableWithResponse(tableName))
.assertNext(response -> {
Assertions.assertEquals(expectedStatusCode, response.getStatusCode());
})
.expectComplete()
.verify();
}
@Test
void serviceCreateTableIfNotExistsAsync() {
String tableName = testResourceNamer.randomName("test", 20);
StepVerifier.create(serviceClient.createTableIfNotExists(tableName))
.expectComplete()
.verify();
}
@Test
void serviceCreateTableIfNotExistsSucceedsIfExistsAsync() {
String tableName = testResourceNamer.randomName("test", 20);
serviceClient.createTable(tableName).block(TIMEOUT);
StepVerifier.create(serviceClient.createTableIfNotExists(tableName))
.expectComplete()
.verify();
}
@Test
void serviceCreateTableIfNotExistsWithResponseAsync() {
String tableName = testResourceNamer.randomName("test", 20);
int expectedStatusCode = 204;
StepVerifier.create(serviceClient.createTableIfNotExistsWithResponse(tableName))
.assertNext(response -> {
Assertions.assertEquals(expectedStatusCode, response.getStatusCode());
})
.expectComplete()
.verify();
}
@Test
void serviceCreateTableIfNotExistsWithResponseSucceedsIfExistsAsync() {
String tableName = testResourceNamer.randomName("test", 20);
int expectedStatusCode = 409;
serviceClient.createTable(tableName).block(TIMEOUT);
StepVerifier.create(serviceClient.createTableIfNotExistsWithResponse(tableName))
.assertNext(response -> {
Assertions.assertEquals(expectedStatusCode, response.getStatusCode());
})
.expectComplete()
.verify();
}
@Test
void serviceDeleteTableAsync() {
final String tableName = testResourceNamer.randomName("test", 20);
serviceClient.createTable(tableName).block(TIMEOUT);
StepVerifier.create(serviceClient.deleteTable(tableName))
.expectComplete()
.verify();
}
@Test
void serviceDeleteTableWithResponseAsync() {
String tableName = testResourceNamer.randomName("test", 20);
int expectedStatusCode = 204;
serviceClient.createTable(tableName).block();
StepVerifier.create(serviceClient.deleteTableWithResponse(tableName))
.assertNext(response -> {
Assertions.assertEquals(expectedStatusCode, response.getStatusCode());
})
.expectComplete()
.verify();
}
@Test
@Tag("ListTables")
void serviceListTablesAsync() {
final String tableName = testResourceNamer.randomName("test", 20);
final String tableName2 = testResourceNamer.randomName("test", 20);
serviceClient.createTable(tableName).block(TIMEOUT);
serviceClient.createTable(tableName2).block(TIMEOUT);
StepVerifier.create(serviceClient.listTables())
.expectNextCount(2)
.thenConsumeWhile(x -> true)
.expectComplete()
.verify();
}
@Test
@Tag("ListTables")
void serviceListTablesWithFilterAsync() {
final String tableName = testResourceNamer.randomName("test", 20);
final String tableName2 = testResourceNamer.randomName("test", 20);
ListTablesOptions options = new ListTablesOptions().setFilter("TableName eq '" + tableName + "'");
serviceClient.createTable(tableName).block(TIMEOUT);
serviceClient.createTable(tableName2).block(TIMEOUT);
StepVerifier.create(serviceClient.listTables(options))
.assertNext(table -> {
assertEquals(tableName, table.getName());
})
.expectNextCount(0)
.thenConsumeWhile(x -> true)
.expectComplete()
.verify();
}
@Test
@Tag("ListTables")
} |
Yes, once support is merged for multiple tests with the same name (#14801) I will separate these into two test classes, one for Cosmos and one for Storage, each with their own recordings. | 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();
}
} | StepVerifier.create(tableClient.updateEntityWithResponse(createdEntity, true, mode)) | 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();
}
} | 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))
.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 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))
.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 updateEntityWithResponseReplaceAsync() {
updateEntityWithResponseAsync(UpdateMode.REPLACE);
}
@Test
void updateEntityWithResponseMergeAsync() {
updateEntityWithResponseAsync(UpdateMode.MERGE);
}
/**
* In the case of {@link UpdateMode
* In the case of {@link UpdateMode
*/
@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();
}
} | 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))
.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 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))
.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 updateEntityWithResponseReplaceAsync() {
updateEntityWithResponseAsync(UpdateMode.REPLACE);
}
@Test
void updateEntityWithResponseMergeAsync() {
updateEntityWithResponseAsync(UpdateMode.MERGE);
}
/**
* In the case of {@link UpdateMode
* In the case of {@link UpdateMode
*/
@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();
}
} |
Tracking this work in #14930 | 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();
}
} | StepVerifier.create(tableClient.updateEntityWithResponse(createdEntity, true, mode)) | 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();
}
} | 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))
.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 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))
.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 updateEntityWithResponseReplaceAsync() {
updateEntityWithResponseAsync(UpdateMode.REPLACE);
}
@Test
void updateEntityWithResponseMergeAsync() {
updateEntityWithResponseAsync(UpdateMode.MERGE);
}
/**
* In the case of {@link UpdateMode
* In the case of {@link UpdateMode
*/
@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();
}
} | 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))
.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 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))
.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 updateEntityWithResponseReplaceAsync() {
updateEntityWithResponseAsync(UpdateMode.REPLACE);
}
@Test
void updateEntityWithResponseMergeAsync() {
updateEntityWithResponseAsync(UpdateMode.MERGE);
}
/**
* In the case of {@link UpdateMode
* In the case of {@link UpdateMode
*/
@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();
}
} |
If playbackRecordName is null, should this fallback to `testName`? | private InterceptorManager(String testName, String playbackRecordName, TestMode testMode, boolean doNotRecord) {
Objects.requireNonNull(testName, "'testName' cannot be null.");
this.testName = testName;
this.playbackRecordName = playbackRecordName;
this.testMode = testMode;
this.textReplacementRules = new HashMap<>();
this.allowedToReadRecordedValues = (testMode == TestMode.PLAYBACK && !doNotRecord);
this.allowedToRecordValues = (testMode == TestMode.RECORD && !doNotRecord);
if (allowedToReadRecordedValues) {
this.recordedData = readDataFromFile();
} else if (allowedToRecordValues) {
this.recordedData = new RecordedData();
} else {
this.recordedData = null;
}
} | this.playbackRecordName = playbackRecordName; | private InterceptorManager(String testName, String playbackRecordName, TestMode testMode, boolean doNotRecord) {
Objects.requireNonNull(testName, "'testName' cannot be null.");
this.testName = testName;
this.playbackRecordName = CoreUtils.isNullOrEmpty(playbackRecordName) ? testName : playbackRecordName;
this.testMode = testMode;
this.textReplacementRules = new HashMap<>();
this.allowedToReadRecordedValues = (testMode == TestMode.PLAYBACK && !doNotRecord);
this.allowedToRecordValues = (testMode == TestMode.RECORD && !doNotRecord);
if (allowedToReadRecordedValues) {
this.recordedData = readDataFromFile();
} else if (allowedToRecordValues) {
this.recordedData = new RecordedData();
} else {
this.recordedData = null;
}
} | class InterceptorManager implements AutoCloseable {
private static final String RECORD_FOLDER = "session-records/";
private static final ObjectMapper RECORD_MAPPER = new ObjectMapper().enable(SerializationFeature.INDENT_OUTPUT);
private final ClientLogger logger = new ClientLogger(InterceptorManager.class);
private final Map<String, String> textReplacementRules;
private final String testName;
private final String playbackRecordName;
private final TestMode testMode;
private final boolean allowedToReadRecordedValues;
private final boolean allowedToRecordValues;
private final RecordedData recordedData;
/**
* Creates a new InterceptorManager that either replays test-session records or saves them.
*
* <ul>
* <li>If {@code testMode} is {@link TestMode
* record to read network calls from.</li>
* <li>If {@code testMode} is {@link TestMode
* all the network calls to it.</li>
* </ul>
*
* The test session records are persisted in the path: "<i>session-records/{@code testName}.json</i>"
*
* @param testName Name of the test session record.
* @param testMode The {@link TestMode} for this interceptor.
* @throws UncheckedIOException If {@code testMode} is {@link TestMode
* could not be located or the data could not be deserialized into an instance of {@link RecordedData}.
* @throws NullPointerException If {@code testName} is {@code null}.
* @deprecated Use {@link
*/
@Deprecated
public InterceptorManager(String testName, TestMode testMode) {
this(testName, testName, testMode, false);
}
/**
* Creates a new InterceptorManager that either replays test-session records or saves them.
*
* <ul>
* <li>If {@code testMode} is {@link TestMode
* record to read network calls from.</li>
* <li>If {@code testMode} is {@link TestMode
* all the network calls to it.</li>
* <li>If {@code testMode} is {@link TestMode
* record.</li>
* </ul>
*
* The test session records are persisted in the path: "<i>session-records/{@code testName}.json</i>"
*
* @param testContextManager Contextual information about the test being ran, such as test name, {@link TestMode},
* and others.
* @throws UncheckedIOException If {@code testMode} is {@link TestMode
* could not be located or the data could not be deserialized into an instance of {@link RecordedData}.
* @throws NullPointerException If {@code testName} is {@code null}.
*/
public InterceptorManager(TestContextManager testContextManager) {
this(testContextManager.getTestName(), testContextManager.getTestPlaybackRecordingName(),
testContextManager.getTestMode(), testContextManager.doNotRecordTest());
}
/**
* Creates a new InterceptorManager that replays test session records. It takes a set of {@code
* textReplacementRules}, that can be used by {@link PlaybackClient} to replace values in a {@link
* NetworkCallRecord
*
* The test session records are read from: "<i>session-records/{@code testName}.json</i>"
*
* @param testName Name of the test session record.
* @param textReplacementRules A set of rules to replace text in {@link NetworkCallRecord
* playing back network calls.
* @throws UncheckedIOException An existing test session record could not be located or the data could not be
* deserialized into an instance of {@link RecordedData}.
* @throws NullPointerException If {@code testName} or {@code textReplacementRules} is {@code null}.
* @deprecated Use {@link
*/
@Deprecated
public InterceptorManager(String testName, Map<String, String> textReplacementRules) {
this(testName, testName, textReplacementRules, false);
}
/**
* Creates a new InterceptorManager that replays test session records. It takes a set of {@code
* textReplacementRules}, that can be used by {@link PlaybackClient} to replace values in a {@link
* NetworkCallRecord
*
* The test session records are read from: "<i>session-records/{@code testName}.json</i>"
*
* @param testName Name of the test session record.
* @param textReplacementRules A set of rules to replace text in {@link NetworkCallRecord
* playing back network calls.
* @param doNotRecord Flag indicating whether network calls should be record or played back.
* @throws UncheckedIOException An existing test session record could not be located or the data could not be
* deserialized into an instance of {@link RecordedData}.
* @throws NullPointerException If {@code testName} or {@code textReplacementRules} is {@code null}.
* @deprecated Use {@link
*/
@Deprecated
public InterceptorManager(String testName, Map<String, String> textReplacementRules, boolean doNotRecord) {
this(testName, testName, textReplacementRules, doNotRecord);
}
/**
* Creates a new InterceptorManager that replays test session records. It takes a set of {@code
* textReplacementRules}, that can be used by {@link PlaybackClient} to replace values in a {@link
* NetworkCallRecord
*
* The test session records are read from: "<i>session-records/{@code testName}.json</i>"
*
* @param testName Name of the test.
* @param playbackRecordName Full name of the test including its iteration, used as the playback record name.
* @param textReplacementRules A set of rules to replace text in {@link NetworkCallRecord
* playing back network calls.
* @param doNotRecord Flag indicating whether network calls should be record or played back.
* @throws UncheckedIOException An existing test session record could not be located or the data could not be
* deserialized into an instance of {@link RecordedData}.
* @throws NullPointerException If {@code testName} or {@code textReplacementRules} is {@code null}.
*/
public InterceptorManager(String testName, String playbackRecordName, Map<String, String> textReplacementRules,
boolean doNotRecord) {
Objects.requireNonNull(testName, "'testName' cannot be null.");
Objects.requireNonNull(textReplacementRules, "'textReplacementRules' cannot be null.");
this.testName = testName;
this.playbackRecordName = playbackRecordName;
this.testMode = TestMode.PLAYBACK;
this.allowedToReadRecordedValues = !doNotRecord;
this.allowedToRecordValues = false;
this.recordedData = allowedToReadRecordedValues ? readDataFromFile() : null;
this.textReplacementRules = textReplacementRules;
}
/**
* Gets whether this InterceptorManager is in playback mode.
*
* @return true if the InterceptorManager is in playback mode and false otherwise.
*/
public boolean isPlaybackMode() {
return testMode == TestMode.PLAYBACK;
}
/**
* Gets whether this InterceptorManager is in live mode.
*
* @return true if the InterceptorManager is in live mode and false otherwise.
*/
public boolean isLiveMode() {
return testMode == TestMode.LIVE;
}
/**
* Gets the recorded data InterceptorManager is keeping track of.
*
* @return The recorded data managed by InterceptorManager.
*/
public RecordedData getRecordedData() {
return recordedData;
}
/**
* Gets a new HTTP pipeline policy that records network calls and its data is managed by {@link
* InterceptorManager}.
*
* @return HttpPipelinePolicy to record network calls.
*/
public HttpPipelinePolicy getRecordPolicy() {
return new RecordNetworkCallPolicy(recordedData);
}
/**
* Gets a new HTTP client that plays back test session records managed by {@link InterceptorManager}.
*
* @return An HTTP client that plays back network calls from its recorded data.
*/
public HttpClient getPlaybackClient() {
return new PlaybackClient(recordedData, textReplacementRules);
}
/**
* Disposes of resources used by this InterceptorManager.
*
* If {@code testMode} is {@link TestMode
* "<i>session-records/{@code testName}.json</i>"
*/
@Override
public void close() {
if (allowedToRecordValues) {
writeDataToFile();
}
}
private RecordedData readDataFromFile() {
File recordFile = getRecordFile();
try {
return RECORD_MAPPER.readValue(recordFile, RecordedData.class);
} catch (IOException ex) {
throw logger.logExceptionAsWarning(new UncheckedIOException(ex));
}
}
/*
* Creates a File which is the session-records folder.
*/
private File getRecordFolder() {
URL folderUrl = InterceptorManager.class.getClassLoader().getResource(".");
return new File(folderUrl.getPath(), RECORD_FOLDER);
}
/*
* Attempts to retrieve the playback file, if it is not found an exception is thrown as playback can't continue.
*/
private File getRecordFile() {
File playbackFile = new File(getRecordFolder(), playbackRecordName + ".json");
File oldPlaybackFile = new File(getRecordFolder(), testName + ".json");
if (!playbackFile.exists() && oldPlaybackFile.exists()) {
throw logger.logExceptionAsError(new RuntimeException(String.format(
"Missing both new and old playback files. Files are %s and %s.", playbackFile.getPath(),
oldPlaybackFile.getPath())));
}
if (playbackFile.exists()) {
logger.info("==> Playback file path: {}", playbackFile.getPath());
return playbackFile;
} else {
logger.info("==> Playback file path: {}", oldPlaybackFile.getPath());
return oldPlaybackFile;
}
}
private void writeDataToFile() {
try {
RECORD_MAPPER.writeValue(createRecordFile(playbackRecordName), recordedData);
} catch (IOException ex) {
throw logger.logExceptionAsError(new UncheckedIOException("Unable to write data to playback file.", ex));
}
}
/*
* Retrieves or creates the file that will be used to store the recorded test values.
*/
private File createRecordFile(String testName) throws IOException {
File recordFolder = getRecordFolder();
if (!recordFolder.exists()) {
if (recordFolder.mkdir()) {
logger.verbose("Created directory: {}", recordFolder.getPath());
}
}
File recordFile = new File(recordFolder, testName + ".json");
if (recordFile.createNewFile()) {
logger.verbose("Created record file: {}", recordFile.getPath());
}
logger.info("==> Playback file path: " + recordFile);
return recordFile;
}
/**
* Add text replacement rule (regex as key, the replacement text as value) into {@link
* InterceptorManager
*
* @param regex the pattern to locate the position of replacement
* @param replacement the replacement text
*/
public void addTextReplacementRule(String regex, String replacement) {
textReplacementRules.put(regex, replacement);
}
} | class InterceptorManager implements AutoCloseable {
private static final String RECORD_FOLDER = "session-records/";
private static final ObjectMapper RECORD_MAPPER = new ObjectMapper().enable(SerializationFeature.INDENT_OUTPUT);
private final ClientLogger logger = new ClientLogger(InterceptorManager.class);
private final Map<String, String> textReplacementRules;
private final String testName;
private final String playbackRecordName;
private final TestMode testMode;
private final boolean allowedToReadRecordedValues;
private final boolean allowedToRecordValues;
private final RecordedData recordedData;
/**
* Creates a new InterceptorManager that either replays test-session records or saves them.
*
* <ul>
* <li>If {@code testMode} is {@link TestMode
* record to read network calls from.</li>
* <li>If {@code testMode} is {@link TestMode
* all the network calls to it.</li>
* </ul>
*
* The test session records are persisted in the path: "<i>session-records/{@code testName}.json</i>"
*
* @param testName Name of the test session record.
* @param testMode The {@link TestMode} for this interceptor.
* @throws UncheckedIOException If {@code testMode} is {@link TestMode
* could not be located or the data could not be deserialized into an instance of {@link RecordedData}.
* @throws NullPointerException If {@code testName} is {@code null}.
* @deprecated Use {@link
*/
@Deprecated
public InterceptorManager(String testName, TestMode testMode) {
this(testName, testName, testMode, false);
}
/**
* Creates a new InterceptorManager that either replays test-session records or saves them.
*
* <ul>
* <li>If {@code testMode} is {@link TestMode
* record to read network calls from.</li>
* <li>If {@code testMode} is {@link TestMode
* all the network calls to it.</li>
* <li>If {@code testMode} is {@link TestMode
* record.</li>
* </ul>
*
* The test session records are persisted in the path: "<i>session-records/{@code testName}.json</i>"
*
* @param testContextManager Contextual information about the test being ran, such as test name, {@link TestMode},
* and others.
* @throws UncheckedIOException If {@code testMode} is {@link TestMode
* could not be located or the data could not be deserialized into an instance of {@link RecordedData}.
* @throws NullPointerException If {@code testName} is {@code null}.
*/
public InterceptorManager(TestContextManager testContextManager) {
this(testContextManager.getTestName(), testContextManager.getTestPlaybackRecordingName(),
testContextManager.getTestMode(), testContextManager.doNotRecordTest());
}
/**
* Creates a new InterceptorManager that replays test session records. It takes a set of {@code
* textReplacementRules}, that can be used by {@link PlaybackClient} to replace values in a {@link
* NetworkCallRecord
*
* The test session records are read from: "<i>session-records/{@code testName}.json</i>"
*
* @param testName Name of the test session record.
* @param textReplacementRules A set of rules to replace text in {@link NetworkCallRecord
* playing back network calls.
* @throws UncheckedIOException An existing test session record could not be located or the data could not be
* deserialized into an instance of {@link RecordedData}.
* @throws NullPointerException If {@code testName} or {@code textReplacementRules} is {@code null}.
* @deprecated Use {@link
*/
@Deprecated
public InterceptorManager(String testName, Map<String, String> textReplacementRules) {
this(testName, textReplacementRules, false, testName);
}
/**
* Creates a new InterceptorManager that replays test session records. It takes a set of {@code
* textReplacementRules}, that can be used by {@link PlaybackClient} to replace values in a {@link
* NetworkCallRecord
*
* The test session records are read from: "<i>session-records/{@code testName}.json</i>"
*
* @param testName Name of the test session record.
* @param textReplacementRules A set of rules to replace text in {@link NetworkCallRecord
* playing back network calls.
* @param doNotRecord Flag indicating whether network calls should be record or played back.
* @throws UncheckedIOException An existing test session record could not be located or the data could not be
* deserialized into an instance of {@link RecordedData}.
* @throws NullPointerException If {@code testName} or {@code textReplacementRules} is {@code null}.
* @deprecated Use {@link
*/
@Deprecated
public InterceptorManager(String testName, Map<String, String> textReplacementRules, boolean doNotRecord) {
this(testName, textReplacementRules, doNotRecord, testName);
}
/**
* Creates a new InterceptorManager that replays test session records. It takes a set of {@code
* textReplacementRules}, that can be used by {@link PlaybackClient} to replace values in a {@link
* NetworkCallRecord
*
* The test session records are read from: "<i>session-records/{@code testName}.json</i>"
*
* @param testName Name of the test.
* @param textReplacementRules A set of rules to replace text in {@link NetworkCallRecord
* playing back network calls.
* @param doNotRecord Flag indicating whether network calls should be record or played back.
* @param playbackRecordName Full name of the test including its iteration, used as the playback record name.
* @throws UncheckedIOException An existing test session record could not be located or the data could not be
* deserialized into an instance of {@link RecordedData}.
* @throws NullPointerException If {@code testName} or {@code textReplacementRules} is {@code null}.
*/
public InterceptorManager(String testName, Map<String, String> textReplacementRules, boolean doNotRecord,
String playbackRecordName) {
Objects.requireNonNull(testName, "'testName' cannot be null.");
Objects.requireNonNull(textReplacementRules, "'textReplacementRules' cannot be null.");
this.testName = testName;
this.playbackRecordName = CoreUtils.isNullOrEmpty(playbackRecordName) ? testName : playbackRecordName;
this.testMode = TestMode.PLAYBACK;
this.allowedToReadRecordedValues = !doNotRecord;
this.allowedToRecordValues = false;
this.recordedData = allowedToReadRecordedValues ? readDataFromFile() : null;
this.textReplacementRules = textReplacementRules;
}
/**
* Gets whether this InterceptorManager is in playback mode.
*
* @return true if the InterceptorManager is in playback mode and false otherwise.
*/
public boolean isPlaybackMode() {
return testMode == TestMode.PLAYBACK;
}
/**
* Gets whether this InterceptorManager is in live mode.
*
* @return true if the InterceptorManager is in live mode and false otherwise.
*/
public boolean isLiveMode() {
return testMode == TestMode.LIVE;
}
/**
* Gets the recorded data InterceptorManager is keeping track of.
*
* @return The recorded data managed by InterceptorManager.
*/
public RecordedData getRecordedData() {
return recordedData;
}
/**
* Gets a new HTTP pipeline policy that records network calls and its data is managed by {@link
* InterceptorManager}.
*
* @return HttpPipelinePolicy to record network calls.
*/
public HttpPipelinePolicy getRecordPolicy() {
return new RecordNetworkCallPolicy(recordedData);
}
/**
* Gets a new HTTP client that plays back test session records managed by {@link InterceptorManager}.
*
* @return An HTTP client that plays back network calls from its recorded data.
*/
public HttpClient getPlaybackClient() {
return new PlaybackClient(recordedData, textReplacementRules);
}
/**
* Disposes of resources used by this InterceptorManager.
*
* If {@code testMode} is {@link TestMode
* "<i>session-records/{@code testName}.json</i>"
*/
@Override
public void close() {
if (allowedToRecordValues) {
try {
RECORD_MAPPER.writeValue(createRecordFile(playbackRecordName), recordedData);
} catch (IOException ex) {
throw logger.logExceptionAsError(
new UncheckedIOException("Unable to write data to playback file.", ex));
}
}
}
private RecordedData readDataFromFile() {
File recordFile = getRecordFile();
try {
return RECORD_MAPPER.readValue(recordFile, RecordedData.class);
} catch (IOException ex) {
throw logger.logExceptionAsWarning(new UncheckedIOException(ex));
}
}
/*
* Creates a File which is the session-records folder.
*/
private File getRecordFolder() {
URL folderUrl = InterceptorManager.class.getClassLoader().getResource(".");
return new File(folderUrl.getPath(), RECORD_FOLDER);
}
/*
* Attempts to retrieve the playback file, if it is not found an exception is thrown as playback can't continue.
*/
private File getRecordFile() {
File recordFolder = getRecordFolder();
File playbackFile = new File(recordFolder, playbackRecordName + ".json");
File oldPlaybackFile = new File(recordFolder, testName + ".json");
if (!playbackFile.exists() && !oldPlaybackFile.exists()) {
throw logger.logExceptionAsError(new RuntimeException(String.format(
"Missing both new and old playback files. Files are %s and %s.", playbackFile.getPath(),
oldPlaybackFile.getPath())));
}
if (playbackFile.exists()) {
logger.info("==> Playback file path: {}", playbackFile.getPath());
return playbackFile;
} else {
logger.info("==> Playback file path: {}", oldPlaybackFile.getPath());
return oldPlaybackFile;
}
}
/*
* Retrieves or creates the file that will be used to store the recorded test values.
*/
private File createRecordFile(String testName) throws IOException {
File recordFolder = getRecordFolder();
if (!recordFolder.exists()) {
if (recordFolder.mkdir()) {
logger.verbose("Created directory: {}", recordFolder.getPath());
}
}
File recordFile = new File(recordFolder, testName + ".json");
if (recordFile.createNewFile()) {
logger.verbose("Created record file: {}", recordFile.getPath());
}
logger.info("==> Playback file path: " + recordFile);
return recordFile;
}
/**
* Add text replacement rule (regex as key, the replacement text as value) into {@link
* InterceptorManager
*
* @param regex the pattern to locate the position of replacement
* @param replacement the replacement text
*/
public void addTextReplacementRule(String regex, String replacement) {
textReplacementRules.put(regex, replacement);
}
} |
Yes, everything calling into this should be passing `testName` for `playbackRecordName` though. | private InterceptorManager(String testName, String playbackRecordName, TestMode testMode, boolean doNotRecord) {
Objects.requireNonNull(testName, "'testName' cannot be null.");
this.testName = testName;
this.playbackRecordName = playbackRecordName;
this.testMode = testMode;
this.textReplacementRules = new HashMap<>();
this.allowedToReadRecordedValues = (testMode == TestMode.PLAYBACK && !doNotRecord);
this.allowedToRecordValues = (testMode == TestMode.RECORD && !doNotRecord);
if (allowedToReadRecordedValues) {
this.recordedData = readDataFromFile();
} else if (allowedToRecordValues) {
this.recordedData = new RecordedData();
} else {
this.recordedData = null;
}
} | this.playbackRecordName = playbackRecordName; | private InterceptorManager(String testName, String playbackRecordName, TestMode testMode, boolean doNotRecord) {
Objects.requireNonNull(testName, "'testName' cannot be null.");
this.testName = testName;
this.playbackRecordName = CoreUtils.isNullOrEmpty(playbackRecordName) ? testName : playbackRecordName;
this.testMode = testMode;
this.textReplacementRules = new HashMap<>();
this.allowedToReadRecordedValues = (testMode == TestMode.PLAYBACK && !doNotRecord);
this.allowedToRecordValues = (testMode == TestMode.RECORD && !doNotRecord);
if (allowedToReadRecordedValues) {
this.recordedData = readDataFromFile();
} else if (allowedToRecordValues) {
this.recordedData = new RecordedData();
} else {
this.recordedData = null;
}
} | class InterceptorManager implements AutoCloseable {
private static final String RECORD_FOLDER = "session-records/";
private static final ObjectMapper RECORD_MAPPER = new ObjectMapper().enable(SerializationFeature.INDENT_OUTPUT);
private final ClientLogger logger = new ClientLogger(InterceptorManager.class);
private final Map<String, String> textReplacementRules;
private final String testName;
private final String playbackRecordName;
private final TestMode testMode;
private final boolean allowedToReadRecordedValues;
private final boolean allowedToRecordValues;
private final RecordedData recordedData;
/**
* Creates a new InterceptorManager that either replays test-session records or saves them.
*
* <ul>
* <li>If {@code testMode} is {@link TestMode
* record to read network calls from.</li>
* <li>If {@code testMode} is {@link TestMode
* all the network calls to it.</li>
* </ul>
*
* The test session records are persisted in the path: "<i>session-records/{@code testName}.json</i>"
*
* @param testName Name of the test session record.
* @param testMode The {@link TestMode} for this interceptor.
* @throws UncheckedIOException If {@code testMode} is {@link TestMode
* could not be located or the data could not be deserialized into an instance of {@link RecordedData}.
* @throws NullPointerException If {@code testName} is {@code null}.
* @deprecated Use {@link
*/
@Deprecated
public InterceptorManager(String testName, TestMode testMode) {
this(testName, testName, testMode, false);
}
/**
* Creates a new InterceptorManager that either replays test-session records or saves them.
*
* <ul>
* <li>If {@code testMode} is {@link TestMode
* record to read network calls from.</li>
* <li>If {@code testMode} is {@link TestMode
* all the network calls to it.</li>
* <li>If {@code testMode} is {@link TestMode
* record.</li>
* </ul>
*
* The test session records are persisted in the path: "<i>session-records/{@code testName}.json</i>"
*
* @param testContextManager Contextual information about the test being ran, such as test name, {@link TestMode},
* and others.
* @throws UncheckedIOException If {@code testMode} is {@link TestMode
* could not be located or the data could not be deserialized into an instance of {@link RecordedData}.
* @throws NullPointerException If {@code testName} is {@code null}.
*/
public InterceptorManager(TestContextManager testContextManager) {
this(testContextManager.getTestName(), testContextManager.getTestPlaybackRecordingName(),
testContextManager.getTestMode(), testContextManager.doNotRecordTest());
}
/**
* Creates a new InterceptorManager that replays test session records. It takes a set of {@code
* textReplacementRules}, that can be used by {@link PlaybackClient} to replace values in a {@link
* NetworkCallRecord
*
* The test session records are read from: "<i>session-records/{@code testName}.json</i>"
*
* @param testName Name of the test session record.
* @param textReplacementRules A set of rules to replace text in {@link NetworkCallRecord
* playing back network calls.
* @throws UncheckedIOException An existing test session record could not be located or the data could not be
* deserialized into an instance of {@link RecordedData}.
* @throws NullPointerException If {@code testName} or {@code textReplacementRules} is {@code null}.
* @deprecated Use {@link
*/
@Deprecated
public InterceptorManager(String testName, Map<String, String> textReplacementRules) {
this(testName, testName, textReplacementRules, false);
}
/**
* Creates a new InterceptorManager that replays test session records. It takes a set of {@code
* textReplacementRules}, that can be used by {@link PlaybackClient} to replace values in a {@link
* NetworkCallRecord
*
* The test session records are read from: "<i>session-records/{@code testName}.json</i>"
*
* @param testName Name of the test session record.
* @param textReplacementRules A set of rules to replace text in {@link NetworkCallRecord
* playing back network calls.
* @param doNotRecord Flag indicating whether network calls should be record or played back.
* @throws UncheckedIOException An existing test session record could not be located or the data could not be
* deserialized into an instance of {@link RecordedData}.
* @throws NullPointerException If {@code testName} or {@code textReplacementRules} is {@code null}.
* @deprecated Use {@link
*/
@Deprecated
public InterceptorManager(String testName, Map<String, String> textReplacementRules, boolean doNotRecord) {
this(testName, testName, textReplacementRules, doNotRecord);
}
/**
* Creates a new InterceptorManager that replays test session records. It takes a set of {@code
* textReplacementRules}, that can be used by {@link PlaybackClient} to replace values in a {@link
* NetworkCallRecord
*
* The test session records are read from: "<i>session-records/{@code testName}.json</i>"
*
* @param testName Name of the test.
* @param playbackRecordName Full name of the test including its iteration, used as the playback record name.
* @param textReplacementRules A set of rules to replace text in {@link NetworkCallRecord
* playing back network calls.
* @param doNotRecord Flag indicating whether network calls should be record or played back.
* @throws UncheckedIOException An existing test session record could not be located or the data could not be
* deserialized into an instance of {@link RecordedData}.
* @throws NullPointerException If {@code testName} or {@code textReplacementRules} is {@code null}.
*/
public InterceptorManager(String testName, String playbackRecordName, Map<String, String> textReplacementRules,
boolean doNotRecord) {
Objects.requireNonNull(testName, "'testName' cannot be null.");
Objects.requireNonNull(textReplacementRules, "'textReplacementRules' cannot be null.");
this.testName = testName;
this.playbackRecordName = playbackRecordName;
this.testMode = TestMode.PLAYBACK;
this.allowedToReadRecordedValues = !doNotRecord;
this.allowedToRecordValues = false;
this.recordedData = allowedToReadRecordedValues ? readDataFromFile() : null;
this.textReplacementRules = textReplacementRules;
}
/**
* Gets whether this InterceptorManager is in playback mode.
*
* @return true if the InterceptorManager is in playback mode and false otherwise.
*/
public boolean isPlaybackMode() {
return testMode == TestMode.PLAYBACK;
}
/**
* Gets whether this InterceptorManager is in live mode.
*
* @return true if the InterceptorManager is in live mode and false otherwise.
*/
public boolean isLiveMode() {
return testMode == TestMode.LIVE;
}
/**
* Gets the recorded data InterceptorManager is keeping track of.
*
* @return The recorded data managed by InterceptorManager.
*/
public RecordedData getRecordedData() {
return recordedData;
}
/**
* Gets a new HTTP pipeline policy that records network calls and its data is managed by {@link
* InterceptorManager}.
*
* @return HttpPipelinePolicy to record network calls.
*/
public HttpPipelinePolicy getRecordPolicy() {
return new RecordNetworkCallPolicy(recordedData);
}
/**
* Gets a new HTTP client that plays back test session records managed by {@link InterceptorManager}.
*
* @return An HTTP client that plays back network calls from its recorded data.
*/
public HttpClient getPlaybackClient() {
return new PlaybackClient(recordedData, textReplacementRules);
}
/**
* Disposes of resources used by this InterceptorManager.
*
* If {@code testMode} is {@link TestMode
* "<i>session-records/{@code testName}.json</i>"
*/
@Override
public void close() {
if (allowedToRecordValues) {
writeDataToFile();
}
}
private RecordedData readDataFromFile() {
File recordFile = getRecordFile();
try {
return RECORD_MAPPER.readValue(recordFile, RecordedData.class);
} catch (IOException ex) {
throw logger.logExceptionAsWarning(new UncheckedIOException(ex));
}
}
/*
* Creates a File which is the session-records folder.
*/
private File getRecordFolder() {
URL folderUrl = InterceptorManager.class.getClassLoader().getResource(".");
return new File(folderUrl.getPath(), RECORD_FOLDER);
}
/*
* Attempts to retrieve the playback file, if it is not found an exception is thrown as playback can't continue.
*/
private File getRecordFile() {
File playbackFile = new File(getRecordFolder(), playbackRecordName + ".json");
File oldPlaybackFile = new File(getRecordFolder(), testName + ".json");
if (!playbackFile.exists() && oldPlaybackFile.exists()) {
throw logger.logExceptionAsError(new RuntimeException(String.format(
"Missing both new and old playback files. Files are %s and %s.", playbackFile.getPath(),
oldPlaybackFile.getPath())));
}
if (playbackFile.exists()) {
logger.info("==> Playback file path: {}", playbackFile.getPath());
return playbackFile;
} else {
logger.info("==> Playback file path: {}", oldPlaybackFile.getPath());
return oldPlaybackFile;
}
}
private void writeDataToFile() {
try {
RECORD_MAPPER.writeValue(createRecordFile(playbackRecordName), recordedData);
} catch (IOException ex) {
throw logger.logExceptionAsError(new UncheckedIOException("Unable to write data to playback file.", ex));
}
}
/*
* Retrieves or creates the file that will be used to store the recorded test values.
*/
private File createRecordFile(String testName) throws IOException {
File recordFolder = getRecordFolder();
if (!recordFolder.exists()) {
if (recordFolder.mkdir()) {
logger.verbose("Created directory: {}", recordFolder.getPath());
}
}
File recordFile = new File(recordFolder, testName + ".json");
if (recordFile.createNewFile()) {
logger.verbose("Created record file: {}", recordFile.getPath());
}
logger.info("==> Playback file path: " + recordFile);
return recordFile;
}
/**
* Add text replacement rule (regex as key, the replacement text as value) into {@link
* InterceptorManager
*
* @param regex the pattern to locate the position of replacement
* @param replacement the replacement text
*/
public void addTextReplacementRule(String regex, String replacement) {
textReplacementRules.put(regex, replacement);
}
} | class InterceptorManager implements AutoCloseable {
private static final String RECORD_FOLDER = "session-records/";
private static final ObjectMapper RECORD_MAPPER = new ObjectMapper().enable(SerializationFeature.INDENT_OUTPUT);
private final ClientLogger logger = new ClientLogger(InterceptorManager.class);
private final Map<String, String> textReplacementRules;
private final String testName;
private final String playbackRecordName;
private final TestMode testMode;
private final boolean allowedToReadRecordedValues;
private final boolean allowedToRecordValues;
private final RecordedData recordedData;
/**
* Creates a new InterceptorManager that either replays test-session records or saves them.
*
* <ul>
* <li>If {@code testMode} is {@link TestMode
* record to read network calls from.</li>
* <li>If {@code testMode} is {@link TestMode
* all the network calls to it.</li>
* </ul>
*
* The test session records are persisted in the path: "<i>session-records/{@code testName}.json</i>"
*
* @param testName Name of the test session record.
* @param testMode The {@link TestMode} for this interceptor.
* @throws UncheckedIOException If {@code testMode} is {@link TestMode
* could not be located or the data could not be deserialized into an instance of {@link RecordedData}.
* @throws NullPointerException If {@code testName} is {@code null}.
* @deprecated Use {@link
*/
@Deprecated
public InterceptorManager(String testName, TestMode testMode) {
this(testName, testName, testMode, false);
}
/**
* Creates a new InterceptorManager that either replays test-session records or saves them.
*
* <ul>
* <li>If {@code testMode} is {@link TestMode
* record to read network calls from.</li>
* <li>If {@code testMode} is {@link TestMode
* all the network calls to it.</li>
* <li>If {@code testMode} is {@link TestMode
* record.</li>
* </ul>
*
* The test session records are persisted in the path: "<i>session-records/{@code testName}.json</i>"
*
* @param testContextManager Contextual information about the test being ran, such as test name, {@link TestMode},
* and others.
* @throws UncheckedIOException If {@code testMode} is {@link TestMode
* could not be located or the data could not be deserialized into an instance of {@link RecordedData}.
* @throws NullPointerException If {@code testName} is {@code null}.
*/
public InterceptorManager(TestContextManager testContextManager) {
this(testContextManager.getTestName(), testContextManager.getTestPlaybackRecordingName(),
testContextManager.getTestMode(), testContextManager.doNotRecordTest());
}
/**
* Creates a new InterceptorManager that replays test session records. It takes a set of {@code
* textReplacementRules}, that can be used by {@link PlaybackClient} to replace values in a {@link
* NetworkCallRecord
*
* The test session records are read from: "<i>session-records/{@code testName}.json</i>"
*
* @param testName Name of the test session record.
* @param textReplacementRules A set of rules to replace text in {@link NetworkCallRecord
* playing back network calls.
* @throws UncheckedIOException An existing test session record could not be located or the data could not be
* deserialized into an instance of {@link RecordedData}.
* @throws NullPointerException If {@code testName} or {@code textReplacementRules} is {@code null}.
* @deprecated Use {@link
*/
@Deprecated
public InterceptorManager(String testName, Map<String, String> textReplacementRules) {
this(testName, textReplacementRules, false, testName);
}
/**
* Creates a new InterceptorManager that replays test session records. It takes a set of {@code
* textReplacementRules}, that can be used by {@link PlaybackClient} to replace values in a {@link
* NetworkCallRecord
*
* The test session records are read from: "<i>session-records/{@code testName}.json</i>"
*
* @param testName Name of the test session record.
* @param textReplacementRules A set of rules to replace text in {@link NetworkCallRecord
* playing back network calls.
* @param doNotRecord Flag indicating whether network calls should be record or played back.
* @throws UncheckedIOException An existing test session record could not be located or the data could not be
* deserialized into an instance of {@link RecordedData}.
* @throws NullPointerException If {@code testName} or {@code textReplacementRules} is {@code null}.
* @deprecated Use {@link
*/
@Deprecated
public InterceptorManager(String testName, Map<String, String> textReplacementRules, boolean doNotRecord) {
this(testName, textReplacementRules, doNotRecord, testName);
}
/**
* Creates a new InterceptorManager that replays test session records. It takes a set of {@code
* textReplacementRules}, that can be used by {@link PlaybackClient} to replace values in a {@link
* NetworkCallRecord
*
* The test session records are read from: "<i>session-records/{@code testName}.json</i>"
*
* @param testName Name of the test.
* @param textReplacementRules A set of rules to replace text in {@link NetworkCallRecord
* playing back network calls.
* @param doNotRecord Flag indicating whether network calls should be record or played back.
* @param playbackRecordName Full name of the test including its iteration, used as the playback record name.
* @throws UncheckedIOException An existing test session record could not be located or the data could not be
* deserialized into an instance of {@link RecordedData}.
* @throws NullPointerException If {@code testName} or {@code textReplacementRules} is {@code null}.
*/
public InterceptorManager(String testName, Map<String, String> textReplacementRules, boolean doNotRecord,
String playbackRecordName) {
Objects.requireNonNull(testName, "'testName' cannot be null.");
Objects.requireNonNull(textReplacementRules, "'textReplacementRules' cannot be null.");
this.testName = testName;
this.playbackRecordName = CoreUtils.isNullOrEmpty(playbackRecordName) ? testName : playbackRecordName;
this.testMode = TestMode.PLAYBACK;
this.allowedToReadRecordedValues = !doNotRecord;
this.allowedToRecordValues = false;
this.recordedData = allowedToReadRecordedValues ? readDataFromFile() : null;
this.textReplacementRules = textReplacementRules;
}
/**
* Gets whether this InterceptorManager is in playback mode.
*
* @return true if the InterceptorManager is in playback mode and false otherwise.
*/
public boolean isPlaybackMode() {
return testMode == TestMode.PLAYBACK;
}
/**
* Gets whether this InterceptorManager is in live mode.
*
* @return true if the InterceptorManager is in live mode and false otherwise.
*/
public boolean isLiveMode() {
return testMode == TestMode.LIVE;
}
/**
* Gets the recorded data InterceptorManager is keeping track of.
*
* @return The recorded data managed by InterceptorManager.
*/
public RecordedData getRecordedData() {
return recordedData;
}
/**
* Gets a new HTTP pipeline policy that records network calls and its data is managed by {@link
* InterceptorManager}.
*
* @return HttpPipelinePolicy to record network calls.
*/
public HttpPipelinePolicy getRecordPolicy() {
return new RecordNetworkCallPolicy(recordedData);
}
/**
* Gets a new HTTP client that plays back test session records managed by {@link InterceptorManager}.
*
* @return An HTTP client that plays back network calls from its recorded data.
*/
public HttpClient getPlaybackClient() {
return new PlaybackClient(recordedData, textReplacementRules);
}
/**
* Disposes of resources used by this InterceptorManager.
*
* If {@code testMode} is {@link TestMode
* "<i>session-records/{@code testName}.json</i>"
*/
@Override
public void close() {
if (allowedToRecordValues) {
try {
RECORD_MAPPER.writeValue(createRecordFile(playbackRecordName), recordedData);
} catch (IOException ex) {
throw logger.logExceptionAsError(
new UncheckedIOException("Unable to write data to playback file.", ex));
}
}
}
private RecordedData readDataFromFile() {
File recordFile = getRecordFile();
try {
return RECORD_MAPPER.readValue(recordFile, RecordedData.class);
} catch (IOException ex) {
throw logger.logExceptionAsWarning(new UncheckedIOException(ex));
}
}
/*
* Creates a File which is the session-records folder.
*/
private File getRecordFolder() {
URL folderUrl = InterceptorManager.class.getClassLoader().getResource(".");
return new File(folderUrl.getPath(), RECORD_FOLDER);
}
/*
* Attempts to retrieve the playback file, if it is not found an exception is thrown as playback can't continue.
*/
private File getRecordFile() {
File recordFolder = getRecordFolder();
File playbackFile = new File(recordFolder, playbackRecordName + ".json");
File oldPlaybackFile = new File(recordFolder, testName + ".json");
if (!playbackFile.exists() && !oldPlaybackFile.exists()) {
throw logger.logExceptionAsError(new RuntimeException(String.format(
"Missing both new and old playback files. Files are %s and %s.", playbackFile.getPath(),
oldPlaybackFile.getPath())));
}
if (playbackFile.exists()) {
logger.info("==> Playback file path: {}", playbackFile.getPath());
return playbackFile;
} else {
logger.info("==> Playback file path: {}", oldPlaybackFile.getPath());
return oldPlaybackFile;
}
}
/*
* Retrieves or creates the file that will be used to store the recorded test values.
*/
private File createRecordFile(String testName) throws IOException {
File recordFolder = getRecordFolder();
if (!recordFolder.exists()) {
if (recordFolder.mkdir()) {
logger.verbose("Created directory: {}", recordFolder.getPath());
}
}
File recordFile = new File(recordFolder, testName + ".json");
if (recordFile.createNewFile()) {
logger.verbose("Created record file: {}", recordFile.getPath());
}
logger.info("==> Playback file path: " + recordFile);
return recordFile;
}
/**
* Add text replacement rule (regex as key, the replacement text as value) into {@link
* InterceptorManager
*
* @param regex the pattern to locate the position of replacement
* @param replacement the replacement text
*/
public void addTextReplacementRule(String regex, String replacement) {
textReplacementRules.put(regex, replacement);
}
} |
why add two commented statement? | private Mono<Void> withRetry(Mono<Void> observable) {
return observable
.retryWhen(
flux ->
flux
.zipWith(
Flux.range(1, 6),
(Throwable throwable, Integer integer) -> {
if (throwable instanceof ManagementException
&& ((ManagementException) throwable).getResponse().getStatusCode() == 502
|| throwable instanceof JsonParseException
) {
return integer;
} else {
throw logger.logExceptionAsError(Exceptions.propagate(throwable));
}
})
.flatMap(i -> Mono.delay(Duration.ofSeconds(i * 10))));
} | private Mono<Void> withRetry(Mono<Void> observable) {
return observable
.retryWhen(
flux ->
flux
.zipWith(
Flux.range(1, 6),
(Throwable throwable, Integer integer) -> {
if (throwable instanceof ManagementException
&& ((ManagementException) throwable).getResponse().getStatusCode() == 502
|| throwable instanceof JsonParseException
) {
return integer;
} else {
throw logger.logExceptionAsError(Exceptions.propagate(throwable));
}
})
.flatMap(i -> Mono.delay(Duration.ofSeconds(((long) i) * 10))));
} | class InputStreamFlux {
private Flux<ByteBuffer> flux;
private byte[] bytes;
private long size;
} | class InputStreamFlux {
private Flux<ByteBuffer> flux;
private byte[] bytes;
private long size;
} | |
Timeout exception from netty/okhttp respectively. But I cannot reproduce it in track2, so just keep them commented. | private Mono<Void> withRetry(Mono<Void> observable) {
return observable
.retryWhen(
flux ->
flux
.zipWith(
Flux.range(1, 6),
(Throwable throwable, Integer integer) -> {
if (throwable instanceof ManagementException
&& ((ManagementException) throwable).getResponse().getStatusCode() == 502
|| throwable instanceof JsonParseException
) {
return integer;
} else {
throw logger.logExceptionAsError(Exceptions.propagate(throwable));
}
})
.flatMap(i -> Mono.delay(Duration.ofSeconds(i * 10))));
} | private Mono<Void> withRetry(Mono<Void> observable) {
return observable
.retryWhen(
flux ->
flux
.zipWith(
Flux.range(1, 6),
(Throwable throwable, Integer integer) -> {
if (throwable instanceof ManagementException
&& ((ManagementException) throwable).getResponse().getStatusCode() == 502
|| throwable instanceof JsonParseException
) {
return integer;
} else {
throw logger.logExceptionAsError(Exceptions.propagate(throwable));
}
})
.flatMap(i -> Mono.delay(Duration.ofSeconds(((long) i) * 10))));
} | class InputStreamFlux {
private Flux<ByteBuffer> flux;
private byte[] bytes;
private long size;
} | class InputStreamFlux {
private Flux<ByteBuffer> flux;
private byte[] bytes;
private long size;
} | |
The body type is always data, you can return the enum rather than creating a new field variable for it for every instance. | public AmqpBodyType getBodyType() {
return bodyType;
} | return bodyType; | public AmqpBodyType getBodyType() {
return AmqpBodyType.DATA;
} | class AmqpDataBody implements AmqpMessageBody {
private final AmqpBodyType bodyType;
private final IterableStream<BinaryData> data;
/**
* @param data to be set.
*/
public AmqpDataBody(Iterable<BinaryData> data) {
Objects.requireNonNull(data, "'data' cannot be null.");
this.data = new IterableStream<>(data);
this.bodyType = AmqpBodyType.DATA;
}
@Override
/**
* @return data.
*/
public IterableStream<BinaryData> getData() {
return data;
}
} | class AmqpDataBody implements AmqpMessageBody {
private final IterableStream<BinaryData> data;
/**
* Creates instance of {@link AmqpDataBody} with given {@link Iterable} of {@link BinaryData}.
*
* @param data to be set on amqp body.
*
* @throws NullPointerException if {@code data} is null.
*/
public AmqpDataBody(Iterable<BinaryData> data) {
Objects.requireNonNull(data, "'data' cannot be null.");
this.data = new IterableStream<>(data);
}
@Override
/**
* Gets {@link BinaryData} set on this {@link AmqpDataBody}.
*
* @return data set on {@link AmqpDataBody}.
*/
public IterableStream<BinaryData> getData() {
return data;
}
} |
The arrangement should be the first set of `new` operators. And act would be the creation of the message. | public void constructorValidValues() {
AmqpAnnotatedMessage actual = new AmqpAnnotatedMessage(new AmqpDataBody(Collections.singletonList(new BinaryData(CONTENTS_BYTES))));
Assertions.assertEquals(AmqpBodyType.DATA, actual.getBody().getBodyType());
Assertions.assertNotNull(actual.getProperties());
Assertions.assertNotNull(actual.getHeader());
Assertions.assertNotNull(actual.getFooter());
Assertions.assertNotNull(actual.getApplicationProperties());
Assertions.assertNotNull(actual.getDeliveryAnnotations());
Assertions.assertNotNull(actual.getMessageAnnotations());
Assertions.assertNotNull(actual.getApplicationProperties());
Assertions.assertNotNull(actual.getBody());
List<BinaryData> dataList = ((AmqpDataBody) actual.getBody()).getData().stream().collect(Collectors.toList());
assertEquals(1, dataList.size());
byte[] actualData = dataList.get(0).getData();
assertArrayEquals(CONTENTS_BYTES, actualData);
} | AmqpAnnotatedMessage actual = new AmqpAnnotatedMessage(new AmqpDataBody(Collections.singletonList(new BinaryData(CONTENTS_BYTES)))); | public void constructorValidValues() {
final List<BinaryData> expectedBinaryData = Collections.singletonList(DATA_BYTES);
final AmqpDataBody amqpDataBody = new AmqpDataBody(expectedBinaryData);
final AmqpAnnotatedMessage actual = new AmqpAnnotatedMessage(amqpDataBody);
assertMessageCreation(AmqpBodyType.DATA, expectedBinaryData.size(), actual);
} | class AmqpAnnotatedMessageTest {
private static final byte[] CONTENTS_BYTES = "Some-contents".getBytes(StandardCharsets.UTF_8);
/**
* Verifies we correctly set values via constructor for {@link AmqpAnnotatedMessage}.
*/
@Test
/**
* Verifies {@link AmqpAnnotatedMessage} constructor for null valeus.
*/
@Test
public void constructorNullValidValues() {
AmqpDataBody body = null;
Assertions.assertThrows(NullPointerException.class, () -> new AmqpAnnotatedMessage(body));
}
} | class AmqpAnnotatedMessageTest {
private static final byte[] CONTENTS_BYTES = "Some-contents".getBytes(StandardCharsets.UTF_8);
private static final BinaryData DATA_BYTES = new BinaryData(CONTENTS_BYTES);
private final ClientLogger logger = new ClientLogger(AmqpAnnotatedMessageTest.class);
/**
* Verifies we correctly set values via copy constructor for {@link AmqpAnnotatedMessage} and create new
* instances of the properties.
*/
@Test
public void copyConstructorTest() {
final int expectedBinaryDataSize = 1;
List<BinaryData> expectedBinaryData = new ArrayList<>();
expectedBinaryData.add(DATA_BYTES);
final AmqpDataBody amqpDataBody = new AmqpDataBody(expectedBinaryData);
final AmqpAnnotatedMessage expected = new AmqpAnnotatedMessage(amqpDataBody);
final Map<String, Object> expectedMessageAnnotations = expected.getMessageAnnotations();
expectedMessageAnnotations.put("ma-1", "ma-value1");
final Map<String, Object> expectedDeliveryAnnotations = expected.getDeliveryAnnotations();
expectedDeliveryAnnotations.put("da-1", "da-value1");
final Map<String, Object> expectedApplicationProperties = expected.getApplicationProperties();
expectedApplicationProperties.put("ap-1", "ap-value1");
final Map<String, Object> expectedFooter = expected.getFooter();
expectedFooter.put("foo-1", "foo-value1");
final AmqpMessageProperties expectedMessageProperties = expected.getProperties();
expectedMessageProperties.setGroupSequence(2L);
expectedMessageProperties.setContentEncoding("content-enc");
expectedMessageProperties.setReplyToGroupId("a");
expectedMessageProperties.setReplyTo("b");
expectedMessageProperties.setCorrelationId("c");
expectedMessageProperties.setSubject("d");
expectedMessageProperties.setMessageId("id");
final AmqpMessageHeader expectedMessageHeader = expected.getHeader();
expectedMessageHeader.setDeliveryCount(5L);
expectedMessageHeader.setTimeToLive(Duration.ofSeconds(20));
expectedMessageHeader.setPriority(Short.valueOf("4"));
final AmqpAnnotatedMessage actual = new AmqpAnnotatedMessage(expected);
expectedDeliveryAnnotations.remove("da-1");
expectedApplicationProperties.put("ap-2", "ap-value2");
expectedFooter.remove("foo-1");
expected.getHeader().setDeliveryCount(Long.valueOf(100));
expectedBinaryData = new ArrayList<>();
assertNotSame(expected.getProperties(), actual.getProperties());
assertNotSame(expected.getApplicationProperties(), actual.getApplicationProperties());
assertNotSame(expected.getDeliveryAnnotations(), actual.getDeliveryAnnotations());
assertNotSame(expected.getFooter(), actual.getFooter());
assertNotSame(expected.getHeader(), actual.getHeader());
assertNotSame(expected.getMessageAnnotations(), actual.getMessageAnnotations());
assertNotSame(expected.getProperties().getUserId(), actual.getProperties().getUserId());
assertNotSame(expected.getHeader().getDeliveryCount(), actual.getHeader().getDeliveryCount());
assertEquals(1, actual.getDeliveryAnnotations().size());
assertEquals(1, actual.getApplicationProperties().size());
assertEquals(1, actual.getFooter().size());
assertEquals(expectedMessageProperties.getGroupSequence(), actual.getProperties().getGroupSequence());
assertEquals(expectedMessageProperties.getContentEncoding(), actual.getProperties().getContentEncoding());
assertEquals(expectedMessageProperties.getReplyToGroupId(), actual.getProperties().getReplyToGroupId());
assertEquals(expectedMessageProperties.getReplyTo(), actual.getProperties().getReplyTo());
assertEquals(expectedMessageProperties.getCorrelationId(), actual.getProperties().getCorrelationId());
assertEquals(expectedMessageProperties.getSubject(), actual.getProperties().getSubject());
assertEquals(expectedMessageProperties.getMessageId(), actual.getProperties().getMessageId());
assertEquals(expectedMessageHeader.getTimeToLive(), actual.getHeader().getTimeToLive());
assertEquals(expectedMessageHeader.getPriority(), actual.getHeader().getPriority());
assertMessageBody(expectedBinaryDataSize, CONTENTS_BYTES, actual);
}
/**
* Verifies we correctly set values via constructor for {@link AmqpAnnotatedMessage}.
*/
@Test
/**
* Verifies we correctly set values via constructor for {@link AmqpAnnotatedMessage}.
*/
@Test
public void constructorAmqpValidValues() {
final List<BinaryData> expectedBinaryData = Collections.singletonList(DATA_BYTES);
final AmqpDataBody amqpDataBody = new AmqpDataBody(expectedBinaryData);
final AmqpAnnotatedMessage expected = new AmqpAnnotatedMessage(amqpDataBody);
final AmqpAnnotatedMessage actual = new AmqpAnnotatedMessage(expected);
assertMessageCreation(AmqpBodyType.DATA, expectedBinaryData.size(), actual);
}
/**
* Verifies {@link AmqpAnnotatedMessage} constructor for null values.
*/
@Test
public void constructorNullValidValues() {
final AmqpDataBody body = null;
Assertions.assertThrows(NullPointerException.class, () -> new AmqpAnnotatedMessage(body));
}
private void assertMessageCreation(AmqpBodyType expectedType, int expectedMessageSize, AmqpAnnotatedMessage actual) {
assertEquals(expectedType, actual.getBody().getBodyType());
assertNotNull(actual.getProperties());
assertNotNull(actual.getHeader());
assertNotNull(actual.getFooter());
assertNotNull(actual.getApplicationProperties());
assertNotNull(actual.getDeliveryAnnotations());
assertNotNull(actual.getMessageAnnotations());
assertNotNull(actual.getApplicationProperties());
assertNotNull(actual.getBody());
assertMessageBody(expectedMessageSize, CONTENTS_BYTES, actual);
}
private void assertMessageBody(int expectedMessageSize, byte[] expectedbody, AmqpAnnotatedMessage actual) {
final AmqpBodyType actualType = actual.getBody().getBodyType();
switch (actualType) {
case DATA:
List<BinaryData> actualData = ((AmqpDataBody) actual.getBody()).getData().stream().collect(Collectors.toList());
assertEquals(expectedMessageSize, actualData.size());
assertArrayEquals(expectedbody, actualData.get(0).getData());
break;
case VALUE:
case SEQUENCE:
throw logger.logExceptionAsError(new UnsupportedOperationException("type not supported yet :" + actualType));
default:
throw logger.logExceptionAsError(new IllegalStateException("Invalid type :" + actualType));
}
}
} |
in general, I'd be consistent about when you're using "final" or not. This applies to all other areas of your code. | public void constructorAmqpValidValues() {
final List<BinaryData> listBinaryData = Collections.singletonList(DATA_BYTES);
final AmqpDataBody amqpDataBody = new AmqpDataBody(listBinaryData);
AmqpAnnotatedMessage expected = new AmqpAnnotatedMessage(amqpDataBody);
AmqpAnnotatedMessage actual = new AmqpAnnotatedMessage(expected);
assertMessageCreation(actual, AmqpBodyType.DATA, listBinaryData.size());
} | AmqpAnnotatedMessage expected = new AmqpAnnotatedMessage(amqpDataBody); | public void constructorAmqpValidValues() {
final List<BinaryData> expectedBinaryData = Collections.singletonList(DATA_BYTES);
final AmqpDataBody amqpDataBody = new AmqpDataBody(expectedBinaryData);
final AmqpAnnotatedMessage expected = new AmqpAnnotatedMessage(amqpDataBody);
final AmqpAnnotatedMessage actual = new AmqpAnnotatedMessage(expected);
assertMessageCreation(AmqpBodyType.DATA, expectedBinaryData.size(), actual);
} | class AmqpAnnotatedMessageTest {
private static final byte[] CONTENTS_BYTES = "Some-contents".getBytes(StandardCharsets.UTF_8);
private static final BinaryData DATA_BYTES = new BinaryData(CONTENTS_BYTES);
/**
* Verifies we correctly set values via constructor for {@link AmqpAnnotatedMessage}.
*/
@Test
public void constructorValidValues() {
final List<BinaryData> binaryDataList = Collections.singletonList(DATA_BYTES);
final AmqpDataBody amqpDataBody = new AmqpDataBody(binaryDataList);
AmqpAnnotatedMessage actual = new AmqpAnnotatedMessage(amqpDataBody);
assertMessageCreation(actual, AmqpBodyType.DATA, binaryDataList.size());
}
/**
* Verifies we correctly set values via constructor for {@link AmqpAnnotatedMessage}.
*/
@Test
/**
* Verifies {@link AmqpAnnotatedMessage} constructor for null values.
*/
@Test
public void constructorNullValidValues() {
AmqpDataBody body = null;
Assertions.assertThrows(NullPointerException.class, () -> new AmqpAnnotatedMessage(body));
}
private void assertMessageCreation(AmqpAnnotatedMessage actual, AmqpBodyType expectedType,
int messageSizeExpected) {
assertEquals(expectedType, actual.getBody().getBodyType());
assertNotNull(actual.getProperties());
assertNotNull(actual.getHeader());
assertNotNull(actual.getFooter());
assertNotNull(actual.getApplicationProperties());
assertNotNull(actual.getDeliveryAnnotations());
assertNotNull(actual.getMessageAnnotations());
assertNotNull(actual.getApplicationProperties());
assertNotNull(actual.getBody());
List<BinaryData> dataList = ((AmqpDataBody) actual.getBody()).getData().stream().collect(Collectors.toList());
assertEquals(messageSizeExpected, dataList.size());
byte[] actualData = dataList.get(0).getData();
assertArrayEquals(CONTENTS_BYTES, actualData);
}
} | class AmqpAnnotatedMessageTest {
private static final byte[] CONTENTS_BYTES = "Some-contents".getBytes(StandardCharsets.UTF_8);
private static final BinaryData DATA_BYTES = new BinaryData(CONTENTS_BYTES);
private final ClientLogger logger = new ClientLogger(AmqpAnnotatedMessageTest.class);
/**
* Verifies we correctly set values via copy constructor for {@link AmqpAnnotatedMessage} and create new
* instances of the properties.
*/
@Test
public void copyConstructorTest() {
final int expectedBinaryDataSize = 1;
List<BinaryData> expectedBinaryData = new ArrayList<>();
expectedBinaryData.add(DATA_BYTES);
final AmqpDataBody amqpDataBody = new AmqpDataBody(expectedBinaryData);
final AmqpAnnotatedMessage expected = new AmqpAnnotatedMessage(amqpDataBody);
final Map<String, Object> expectedMessageAnnotations = expected.getMessageAnnotations();
expectedMessageAnnotations.put("ma-1", "ma-value1");
final Map<String, Object> expectedDeliveryAnnotations = expected.getDeliveryAnnotations();
expectedDeliveryAnnotations.put("da-1", "da-value1");
final Map<String, Object> expectedApplicationProperties = expected.getApplicationProperties();
expectedApplicationProperties.put("ap-1", "ap-value1");
final Map<String, Object> expectedFooter = expected.getFooter();
expectedFooter.put("foo-1", "foo-value1");
final AmqpMessageProperties expectedMessageProperties = expected.getProperties();
expectedMessageProperties.setGroupSequence(2L);
expectedMessageProperties.setContentEncoding("content-enc");
expectedMessageProperties.setReplyToGroupId("a");
expectedMessageProperties.setReplyTo("b");
expectedMessageProperties.setCorrelationId("c");
expectedMessageProperties.setSubject("d");
expectedMessageProperties.setMessageId("id");
final AmqpMessageHeader expectedMessageHeader = expected.getHeader();
expectedMessageHeader.setDeliveryCount(5L);
expectedMessageHeader.setTimeToLive(Duration.ofSeconds(20));
expectedMessageHeader.setPriority(Short.valueOf("4"));
final AmqpAnnotatedMessage actual = new AmqpAnnotatedMessage(expected);
expectedDeliveryAnnotations.remove("da-1");
expectedApplicationProperties.put("ap-2", "ap-value2");
expectedFooter.remove("foo-1");
expected.getHeader().setDeliveryCount(Long.valueOf(100));
expectedBinaryData = new ArrayList<>();
assertNotSame(expected.getProperties(), actual.getProperties());
assertNotSame(expected.getApplicationProperties(), actual.getApplicationProperties());
assertNotSame(expected.getDeliveryAnnotations(), actual.getDeliveryAnnotations());
assertNotSame(expected.getFooter(), actual.getFooter());
assertNotSame(expected.getHeader(), actual.getHeader());
assertNotSame(expected.getMessageAnnotations(), actual.getMessageAnnotations());
assertNotSame(expected.getProperties().getUserId(), actual.getProperties().getUserId());
assertNotSame(expected.getHeader().getDeliveryCount(), actual.getHeader().getDeliveryCount());
assertEquals(1, actual.getDeliveryAnnotations().size());
assertEquals(1, actual.getApplicationProperties().size());
assertEquals(1, actual.getFooter().size());
assertEquals(expectedMessageProperties.getGroupSequence(), actual.getProperties().getGroupSequence());
assertEquals(expectedMessageProperties.getContentEncoding(), actual.getProperties().getContentEncoding());
assertEquals(expectedMessageProperties.getReplyToGroupId(), actual.getProperties().getReplyToGroupId());
assertEquals(expectedMessageProperties.getReplyTo(), actual.getProperties().getReplyTo());
assertEquals(expectedMessageProperties.getCorrelationId(), actual.getProperties().getCorrelationId());
assertEquals(expectedMessageProperties.getSubject(), actual.getProperties().getSubject());
assertEquals(expectedMessageProperties.getMessageId(), actual.getProperties().getMessageId());
assertEquals(expectedMessageHeader.getTimeToLive(), actual.getHeader().getTimeToLive());
assertEquals(expectedMessageHeader.getPriority(), actual.getHeader().getPriority());
assertMessageBody(expectedBinaryDataSize, CONTENTS_BYTES, actual);
}
/**
* Verifies we correctly set values via constructor for {@link AmqpAnnotatedMessage}.
*/
@Test
public void constructorValidValues() {
final List<BinaryData> expectedBinaryData = Collections.singletonList(DATA_BYTES);
final AmqpDataBody amqpDataBody = new AmqpDataBody(expectedBinaryData);
final AmqpAnnotatedMessage actual = new AmqpAnnotatedMessage(amqpDataBody);
assertMessageCreation(AmqpBodyType.DATA, expectedBinaryData.size(), actual);
}
/**
* Verifies we correctly set values via constructor for {@link AmqpAnnotatedMessage}.
*/
@Test
/**
* Verifies {@link AmqpAnnotatedMessage} constructor for null values.
*/
@Test
public void constructorNullValidValues() {
final AmqpDataBody body = null;
Assertions.assertThrows(NullPointerException.class, () -> new AmqpAnnotatedMessage(body));
}
private void assertMessageCreation(AmqpBodyType expectedType, int expectedMessageSize, AmqpAnnotatedMessage actual) {
assertEquals(expectedType, actual.getBody().getBodyType());
assertNotNull(actual.getProperties());
assertNotNull(actual.getHeader());
assertNotNull(actual.getFooter());
assertNotNull(actual.getApplicationProperties());
assertNotNull(actual.getDeliveryAnnotations());
assertNotNull(actual.getMessageAnnotations());
assertNotNull(actual.getApplicationProperties());
assertNotNull(actual.getBody());
assertMessageBody(expectedMessageSize, CONTENTS_BYTES, actual);
}
private void assertMessageBody(int expectedMessageSize, byte[] expectedbody, AmqpAnnotatedMessage actual) {
final AmqpBodyType actualType = actual.getBody().getBodyType();
switch (actualType) {
case DATA:
List<BinaryData> actualData = ((AmqpDataBody) actual.getBody()).getData().stream().collect(Collectors.toList());
assertEquals(expectedMessageSize, actualData.size());
assertArrayEquals(expectedbody, actualData.get(0).getData());
break;
case VALUE:
case SEQUENCE:
throw logger.logExceptionAsError(new UnsupportedOperationException("type not supported yet :" + actualType));
default:
throw logger.logExceptionAsError(new IllegalStateException("Invalid type :" + actualType));
}
}
} |
It's always a single item collection. Why not add another one even though our current implementation layer does not support it. | public void constructorValidValues() {
final List<BinaryData> binaryDataList = Collections.singletonList(DATA_BYTES);
AmqpDataBody actual = new AmqpDataBody(binaryDataList);
assertEquals(AmqpBodyType.DATA, actual.getBodyType());
List<BinaryData> dataList = actual.getData().stream().collect(Collectors.toList());
assertEquals(binaryDataList.size(), dataList.size());
byte[] actualData = dataList.get(0).getData();
assertArrayEquals(CONTENTS_BYTES, actualData);
} | final List<BinaryData> binaryDataList = Collections.singletonList(DATA_BYTES); | public void constructorValidValues() {
final List<BinaryData> expectedDataList = new ArrayList<>();
expectedDataList.add(new BinaryData("some data 1".getBytes()));
expectedDataList.add(new BinaryData("some data 2".getBytes()));
final AmqpDataBody actual = new AmqpDataBody(expectedDataList);
assertEquals(AmqpBodyType.DATA, actual.getBodyType());
final List<BinaryData> dataList = actual.getData().stream().collect(Collectors.toList());
assertEquals(expectedDataList.size(), dataList.size());
assertArrayEquals(expectedDataList.toArray(), dataList.toArray());
} | class AmqpDataBodyTest {
private static final byte[] CONTENTS_BYTES = "Some-contents".getBytes(StandardCharsets.UTF_8);
private static final BinaryData DATA_BYTES = new BinaryData(CONTENTS_BYTES);
/**
* Verifies we correctly set values via constructor for {@link AmqpAnnotatedMessage}.
*/
@Test
/**
* Verifies {@link BinaryData} constructor for null values.
*/
@Test
public void constructorNullValidValues() {
final List<BinaryData> listBinaryData = null;
Assertions.assertThrows(NullPointerException.class, () -> new AmqpDataBody(listBinaryData));
}
} | class AmqpDataBodyTest {
/**
* Verifies we correctly set values via constructor for {@link AmqpAnnotatedMessage}.
*/
@Test
/**
* Verifies {@link BinaryData} constructor for null values.
*/
@Test
public void constructorNullValidValues() {
final List<BinaryData> listBinaryData = null;
Assertions.assertThrows(NullPointerException.class, () -> new AmqpDataBody(listBinaryData));
}
} |
This is common, you can create a private method to aggregate these copied lines. | public String getDeadLetterReason() {
final Map<String, Object> properties = amqpAnnotatedMessage.getApplicationProperties();
if (properties.containsKey(DEAD_LETTER_REASON)) {
return String.valueOf(properties.get(DEAD_LETTER_REASON));
}
return null;
} | final Map<String, Object> properties = amqpAnnotatedMessage.getApplicationProperties(); | public String getDeadLetterReason() {
return getStringValue(amqpAnnotatedMessage.getApplicationProperties(),
DEAD_LETTER_REASON_ANNOTATION_NAME.getValue());
} | class ServiceBusReceivedMessage {
private final ClientLogger logger = new ClientLogger(ServiceBusReceivedMessage.class);
private static final String DEAD_LETTER_DESCRIPTION = "DeadLetterErrorDescription";
private static final String DEAD_LETTER_REASON = "DeadLetterReason";
private static final String ENQUEUED_SEQUENCE_NUMBER = "x-opt-enqueue-sequence-number";
private final AmqpAnnotatedMessage amqpAnnotatedMessage;
private UUID lockToken;
/**
* The representation of message as defined by AMQP protocol.
*
* @see <a href="http:
* Amqp Message Format.</a>
*
* @return the {@link AmqpAnnotatedMessage} representing amqp message.
*/
public AmqpAnnotatedMessage getAmqpAnnotatedMessage() {
return amqpAnnotatedMessage;
}
ServiceBusReceivedMessage(byte[] body) {
Objects.requireNonNull(body, "'body' cannot be null.");
amqpAnnotatedMessage = new AmqpAnnotatedMessage(new AmqpDataBody(new BinaryData(body)));
}
/**
* Gets the actual payload/data wrapped by the {@link ServiceBusReceivedMessage}.
*
* <p>
* If the means for deserializing the raw data is not apparent to consumers, a common technique is to make use of
* {@link | class ServiceBusReceivedMessage {
private final ClientLogger logger = new ClientLogger(ServiceBusReceivedMessage.class);
private final AmqpAnnotatedMessage amqpAnnotatedMessage;
private final byte[] binaryData;
private UUID lockToken;
/**
* The representation of message as defined by AMQP protocol.
*
* @see <a href="http:
* Amqp Message Format.</a>
*
* @return the {@link AmqpAnnotatedMessage} representing amqp message.
*/
public AmqpAnnotatedMessage getAmqpAnnotatedMessage() {
return amqpAnnotatedMessage;
}
ServiceBusReceivedMessage(byte[] body) {
binaryData = Objects.requireNonNull(body, "'body' cannot be null.");
amqpAnnotatedMessage = new AmqpAnnotatedMessage(new AmqpDataBody(Collections.singletonList(
new BinaryData(binaryData))));
}
/**
* Gets the actual payload/data wrapped by the {@link ServiceBusReceivedMessage}.
*
* <p>
* If the means for deserializing the raw data is not apparent to consumers, a common technique is to make use of
* {@link
* consumers who wish to deserialize the binary data.
* </p>
*
* @return A byte array representing the data.
*/
public byte[] getBody() {
final AmqpBodyType bodyType = amqpAnnotatedMessage.getBody().getBodyType();
switch (bodyType) {
case DATA:
return Arrays.copyOf(binaryData, binaryData.length);
case SEQUENCE:
case VALUE:
throw logger.logExceptionAsError(new UnsupportedOperationException("Body type not supported yet "
+ bodyType.toString()));
default:
logger.warning("Invalid body type {}.", bodyType);
throw logger.logExceptionAsError(new IllegalStateException("Body type not valid "
+ bodyType.toString()));
}
}
/**
* Gets the content type of the message.
*
* @return the contentType of the {@link ServiceBusReceivedMessage}.
*/
public String getContentType() {
return amqpAnnotatedMessage.getProperties().getContentType();
}
/**
* Gets a correlation identifier.
* <p>
* Allows an application to specify a context for the message for the purposes of correlation, for example
* reflecting the MessageId of a message that is being replied to.
* </p>
*
* @return correlation id of this message
*
* @see <a href="https:
* Routing and Correlation</a>
*/
public String getCorrelationId() {
return amqpAnnotatedMessage.getProperties().getCorrelationId();
}
/**
* Gets the description for a message that has been dead-lettered.
*
* @return The description for a message that has been dead-lettered.
*/
public String getDeadLetterErrorDescription() {
return getStringValue(amqpAnnotatedMessage.getApplicationProperties(),
DEAD_LETTER_DESCRIPTION_ANNOTATION_NAME.getValue());
}
/**
* Gets the reason for a message that has been dead-lettered.
*
* @return The reason for a message that has been dead-lettered.
*/
/**
* Gets the name of the queue or subscription that this message was enqueued on, before it was
* deadlettered.
* <p>
* This value is only set in messages that have been dead-lettered and subsequently auto-forwarded
* from the dead-letter queue to another entity. Indicates the entity in which the message
* was dead-lettered. This property is read-only.
*
* @return dead letter source of this message
*
* @see <a href="https:
* queues</a>
*/
public String getDeadLetterSource() {
return getStringValue(amqpAnnotatedMessage.getMessageAnnotations(),
DEAD_LETTER_SOURCE_KEY_ANNOTATION_NAME.getValue());
}
/**
* Gets the number of the times this message was delivered to clients.
* <p>
* The count is incremented when a message lock expires, or the message is explicitly abandoned by
* the receiver. This property is read-only.
*
* @return delivery count of this message.
*
* @see <a href="https:
* transfers, locks, and settlement.</a>
*/
public long getDeliveryCount() {
return amqpAnnotatedMessage.getHeader().getDeliveryCount();
}
/**
* Gets the enqueued sequence number assigned to a message by Service Bus.
* <p>
* The sequence number is a unique 64-bit integer first assigned to a message as it is accepted at its original
* point of submission.
*
* @return enqueued sequence number of this message
*
* @see <a href="https:
* Timestamps</a>
*/
public long getEnqueuedSequenceNumber() {
return getLongValue(amqpAnnotatedMessage.getMessageAnnotations(),
ENQUEUED_SEQUENCE_NUMBER_ANNOTATION_NAME.getValue());
}
/**
* Gets the datetime at which this message was enqueued in Azure Service Bus.
* <p>
* The UTC datetime at which the message has been accepted and stored in the entity. For scheduled messages, this
* reflects the time when the message was activated. This value can be used as an authoritative and neutral arrival
* time indicator when the receiver does not want to trust the sender's clock. This property is read-only.
*
* @return the datetime at which the message was enqueued in Azure Service Bus
*
* @see <a href="https:
* Timestamps</a>
*/
public OffsetDateTime getEnqueuedTime() {
return getOffsetDateTimeValue(amqpAnnotatedMessage.getMessageAnnotations(),
ENQUEUED_TIME_UTC_ANNOTATION_NAME.getValue());
}
/**
* Gets the datetime at which this message will expire.
* <p>
* The value is the UTC datetime for when the message is scheduled for removal and will no longer available for
* retrieval from the entity due to expiration. Expiry is controlled by the {@link
* property. This property is computed from {@link
* TimeToLive}.
*
* @return {@link OffsetDateTime} at which this message expires
*
* @see <a href="https:
*/
public OffsetDateTime getExpiresAt() {
final Duration timeToLive = getTimeToLive();
final OffsetDateTime enqueuedTime = getEnqueuedTime();
return enqueuedTime != null && timeToLive != null
? enqueuedTime.plus(timeToLive)
: null;
}
/**
* Gets the label for the message.
*
* @return The label for the message.
*/
public String getLabel() {
return amqpAnnotatedMessage.getProperties().getSubject();
}
/**
* Gets the lock token for the current message.
* <p>
* The lock token is a reference to the lock that is being held by the broker in
* {@link ReceiveMode
* Locks are used to explicitly settle messages as explained in the
* <a href="https:
* documentation in more detail</a>. The token can also be used to pin the lock permanently
* through the <a
* href="https:
* take the message out of the regular delivery state flow. This property is read-only.
*
* @return Lock-token for this message. Could return {@code null} for {@link ReceiveMode
*
* @see <a href="https:
* transfers, locks, and settlement</a>
*/
public String getLockToken() {
return lockToken != null ? lockToken.toString() : null;
}
/**
* Gets the datetime at which the lock of this message expires.
* <p>
* For messages retrieved under a lock (peek-lock receive mode, not pre-settled) this property reflects the UTC
* datetime until which the message is held locked in the queue/subscription. When the lock expires, the {@link
*
* is read-only.
*
* @return the datetime at which the lock of this message expires if the message is received using {@link
* ReceiveMode
*
* @see <a href="https:
* transfers, locks, and settlement</a>
*/
public OffsetDateTime getLockedUntil() {
return getOffsetDateTimeValue(amqpAnnotatedMessage.getMessageAnnotations(),
LOCKED_UNTIL_KEY_ANNOTATION_NAME.getValue());
}
/**
* @return Id of the {@link ServiceBusReceivedMessage}.
*/
public String getMessageId() {
return amqpAnnotatedMessage.getProperties().getMessageId();
}
/**
* Gets the partition key for sending a message to a partitioned entity.
* <p>
* For <a href="https:
* entities</a>, setting this value enables assigning related messages to the same internal partition, so that
* submission sequence order is correctly recorded. The partition is chosen by a hash function over this value and
* cannot be chosen directly. For session-aware entities, the {@link
* this value.
*
* @return The partition key of this message
*
* @see <a href="https:
* entities</a>
*/
public String getPartitionKey() {
return getStringValue(amqpAnnotatedMessage.getMessageAnnotations(),
PARTITION_KEY_ANNOTATION_NAME.getValue());
}
/**
* Gets the set of free-form {@link ServiceBusReceivedMessage} properties which may be used for passing metadata
* associated with the {@link ServiceBusReceivedMessage} during Service Bus operations. A common use-case for
* {@code properties()} is to associate serialization hints for the {@link
* who wish to deserialize the binary data.
*
* @return Application properties associated with this {@link ServiceBusReceivedMessage}.
*/
public Map<String, Object> getApplicationProperties() {
return amqpAnnotatedMessage.getApplicationProperties();
}
/**
* Gets the address of an entity to send replies to.
* <p>
* This optional and application-defined value is a standard way to express a reply path to the receiver of the
* message. When a sender expects a reply, it sets the value to the absolute or relative path of the queue or topic
* it expects the reply to be sent to.
*
* @return ReplyTo property value of this message
*
* @see <a href="https:
* Routing and Correlation</a>
*/
public String getReplyTo() {
return amqpAnnotatedMessage.getProperties().getReplyTo();
}
/**
* Gets or sets a session identifier augmenting the {@link
* <p>
* This value augments the ReplyTo information and specifies which SessionId should be set for the reply when sent
* to the reply entity.
*
* @return ReplyToSessionId property value of this message
*
* @see <a href="https:
* Routing and Correlation</a>
*/
public String getReplyToSessionId() {
return amqpAnnotatedMessage.getProperties().getReplyToGroupId();
}
/**
* Gets the scheduled enqueue time of this message.
* <p>
* This value is used for delayed message availability. The message is safely added to the queue, but is not
* considered active and therefore not retrievable until the scheduled enqueue time. Mind that the message may not
* be activated (enqueued) at the exact given datetime; the actual activation time depends on the queue's workload
* and its state.
* </p>
*
* @return the datetime at which the message will be enqueued in Azure Service Bus
*
* @see <a href="https:
* Timestamps</a>
*/
public OffsetDateTime getScheduledEnqueueTime() {
return getOffsetDateTimeValue(amqpAnnotatedMessage.getMessageAnnotations(),
SCHEDULED_ENQUEUE_UTC_TIME_NAME.getValue());
}
/**
* Gets the unique number assigned to a message by Service Bus.
* <p>
* The sequence number is a unique 64-bit integer assigned to a message as it is accepted and stored by the broker
* and functions as its true identifier. For partitioned entities, the topmost 16 bits reflect the partition
* identifier. Sequence numbers monotonically increase and are gapless. They roll over to 0 when the 48-64 bit range
* is exhausted. This property is read-only.
*
* @return sequence number of this message
*
* @see <a href="https:
* Timestamps</a>
*/
public long getSequenceNumber() {
return getLongValue(amqpAnnotatedMessage.getMessageAnnotations(),
SEQUENCE_NUMBER_ANNOTATION_NAME.getValue());
}
/**
* Gets the session id of the message.
*
* @return Session Id of the {@link ServiceBusReceivedMessage}.
*/
public String getSessionId() {
return amqpAnnotatedMessage.getProperties().getGroupId();
}
/**
* Gets the duration before this message expires.
* <p>
* This value is the relative duration after which the message expires, starting from the datetime the message has
* been accepted and stored by the broker, as captured in {@link
* explicitly, the assumed value is the DefaultTimeToLive set for the respective queue or topic. A message-level
* TimeToLive value cannot be longer than the entity's DefaultTimeToLive setting and it is silently adjusted if it
* does.
*
* @return Time to live duration of this message
*
* @see <a href="https:
*/
public Duration getTimeToLive() {
return amqpAnnotatedMessage.getHeader().getTimeToLive();
}
/**
* Gets the "to" address.
*
* @return "To" property value of this message
*/
public String getTo() {
return amqpAnnotatedMessage.getProperties().getTo();
}
/**
* Gets the partition key for sending a message to a entity via another partitioned transfer entity.
*
* If a message is sent via a transfer queue in the scope of a transaction, this value selects the
* transfer queue partition: This is functionally equivalent to {@link
* messages are kept together and in order as they are transferred.
*
* @return partition key on the via queue.
*
* @see <a href="https:
*/
public String getViaPartitionKey() {
return getStringValue(amqpAnnotatedMessage.getMessageAnnotations(),
VIA_PARTITION_KEY_ANNOTATION_NAME.getValue());
}
/**
* Sets a correlation identifier.
*
* @param correlationId correlation id of this message
*
* @see
*/
void setCorrelationId(String correlationId) {
amqpAnnotatedMessage.getProperties().setCorrelationId(correlationId);
}
/**
* Sets the content type of the {@link ServiceBusReceivedMessage}.
*
* @param contentType of the message.
*/
void setContentType(String contentType) {
amqpAnnotatedMessage.getProperties().setContentType(contentType);
}
/**
* Sets the dead letter description.
*
* @param deadLetterErrorDescription Dead letter description.
*/
void setDeadLetterErrorDescription(String deadLetterErrorDescription) {
amqpAnnotatedMessage.getApplicationProperties().put(DEAD_LETTER_DESCRIPTION_ANNOTATION_NAME.getValue(),
deadLetterErrorDescription);
}
/**
* Sets the dead letter reason.
*
* @param deadLetterReason Dead letter reason.
*/
void setDeadLetterReason(String deadLetterReason) {
amqpAnnotatedMessage.getApplicationProperties().put(DEAD_LETTER_REASON_ANNOTATION_NAME.getValue(),
deadLetterReason);
}
/**
* Sets the name of the queue or subscription that this message was enqueued on, before it was
* deadlettered.
*
* @param deadLetterSource the name of the queue or subscription that this message was enqueued on,
* before it was deadlettered.
*/
void setDeadLetterSource(String deadLetterSource) {
amqpAnnotatedMessage.getMessageAnnotations().put(DEAD_LETTER_SOURCE_KEY_ANNOTATION_NAME.getValue(),
deadLetterSource);
}
/**
* Sets the number of the times this message was delivered to clients.
*
* @param deliveryCount the number of the times this message was delivered to clients.
*/
void setDeliveryCount(long deliveryCount) {
amqpAnnotatedMessage.getHeader().setDeliveryCount(deliveryCount);
}
void setEnqueuedSequenceNumber(long enqueuedSequenceNumber) {
amqpAnnotatedMessage.getMessageAnnotations().put(ENQUEUED_SEQUENCE_NUMBER_ANNOTATION_NAME.getValue(),
enqueuedSequenceNumber);
}
/**
* Sets the datetime at which this message was enqueued in Azure Service Bus.
*
* @param enqueuedTime the datetime at which this message was enqueued in Azure Service Bus.
*/
void setEnqueuedTime(OffsetDateTime enqueuedTime) {
setValue(amqpAnnotatedMessage.getMessageAnnotations(), ENQUEUED_TIME_UTC_ANNOTATION_NAME, enqueuedTime);
}
/**
* Sets the subject for the message.
*
* @param subject The subject to set.
*/
void setSubject(String subject) {
amqpAnnotatedMessage.getProperties().setSubject(subject);
}
/**
* Sets the lock token for the current message.
*
* @param lockToken the lock token for the current message.
*/
void setLockToken(UUID lockToken) {
this.lockToken = lockToken;
}
/**
* Sets the datetime at which the lock of this message expires.
*
* @param lockedUntil the datetime at which the lock of this message expires.
*/
void setLockedUntil(OffsetDateTime lockedUntil) {
setValue(amqpAnnotatedMessage.getMessageAnnotations(), LOCKED_UNTIL_KEY_ANNOTATION_NAME, lockedUntil);
}
/**
* Sets the message id.
*
* @param messageId to be set.
*/
void setMessageId(String messageId) {
amqpAnnotatedMessage.getProperties().setMessageId(messageId);
}
/**
* Sets a partition key for sending a message to a partitioned entity
*
* @param partitionKey partition key of this message
*
* @see
*/
void setPartitionKey(String partitionKey) {
amqpAnnotatedMessage.getMessageAnnotations().put(PARTITION_KEY_ANNOTATION_NAME.getValue(), partitionKey);
}
/**
* Sets the scheduled enqueue time of this message.
*
* @param scheduledEnqueueTime the datetime at which this message should be enqueued in Azure Service Bus.
*
* @see
*/
void setScheduledEnqueueTime(OffsetDateTime scheduledEnqueueTime) {
setValue(amqpAnnotatedMessage.getMessageAnnotations(), SCHEDULED_ENQUEUE_UTC_TIME_NAME, scheduledEnqueueTime);
}
/**
* Sets the unique number assigned to a message by Service Bus.
*
* @param sequenceNumber the unique number assigned to a message by Service Bus.
*/
void setSequenceNumber(long sequenceNumber) {
amqpAnnotatedMessage.getMessageAnnotations().put(SEQUENCE_NUMBER_ANNOTATION_NAME.getValue(), sequenceNumber);
}
/**
* Sets the session id.
*
* @param sessionId to be set.
*/
void setSessionId(String sessionId) {
amqpAnnotatedMessage.getProperties().setGroupId(sessionId);
}
/**
* Sets the duration of time before this message expires.
*
* @param timeToLive Time to Live duration of this message
*
* @see
*/
void setTimeToLive(Duration timeToLive) {
amqpAnnotatedMessage.getHeader().setTimeToLive(timeToLive);
}
/**
* Sets the address of an entity to send replies to.
*
* @param replyTo ReplyTo property value of this message
*
* @see
*/
void setReplyTo(String replyTo) {
amqpAnnotatedMessage.getProperties().setReplyTo(replyTo);
}
/**
* Gets or sets a session identifier augmenting the {@link
*
* @param replyToSessionId ReplyToSessionId property value of this message
*/
void setReplyToSessionId(String replyToSessionId) {
amqpAnnotatedMessage.getProperties().setReplyToGroupId(replyToSessionId);
}
/**
* Sets the "to" address.
* <p>
* This property is reserved for future use in routing scenarios and presently ignored by the broker itself.
* Applications can use this value in rule-driven
* <a href="https:
* chaining</a> scenarios to indicate the intended logical destination of the message.
*
* @param to To property value of this message
*/
void setTo(String to) {
amqpAnnotatedMessage.getProperties().setTo(to);
}
/**
* Sets a via-partition key for sending a message to a destination entity via another partitioned entity
*
* @param viaPartitionKey via-partition key of this message
*
* @see
*/
void setViaPartitionKey(String viaPartitionKey) {
amqpAnnotatedMessage.getMessageAnnotations().put(VIA_PARTITION_KEY_ANNOTATION_NAME.getValue(), viaPartitionKey);
}
/*
* Gets String value from given map and null if key does not exists.
*/
private String getStringValue(Map<String, Object> dataMap, String key) {
return (String) dataMap.get(key);
}
/*
* Gets long value from given map and 0 if key does not exists.
*/
private long getLongValue(Map<String, Object> dataMap, String key) {
return dataMap.containsKey(key) ? (long) dataMap.get(key) : 0;
}
/*
* Gets OffsetDateTime value from given map and null if key does not exists.
*/
private OffsetDateTime getOffsetDateTimeValue(Map<String, Object> dataMap, String key) {
return dataMap.containsKey(key) ? ((Date) dataMap.get(key)).toInstant().atOffset(ZoneOffset.UTC) : null;
}
private void setValue(Map<String, Object> dataMap, AmqpMessageConstant key, OffsetDateTime value) {
if (value != null) {
amqpAnnotatedMessage.getMessageAnnotations().put(key.getValue(),
new Date(value.toInstant().toEpochMilli()));
}
}
} |
The point I was trying to make is that you know this data in the constructor. You can do this logic in the constructor and simply return a copy of the binary data. Before, you were iterating through the Iterable of BinaryData each time, creating a new List object and then throwing it away to get the first item before copying it. | public byte[] getBody() {
byte[] body = null;
final AmqpBodyType bodyType = amqpAnnotatedMessage.getBody().getBodyType();
switch (bodyType) {
case DATA:
final BinaryData binaryData = ((AmqpDataBody) amqpAnnotatedMessage.getBody()).getBinaryData();
if (binaryData != null) {
body = binaryData.getData();
}
break;
case SEQUENCE:
case VALUE:
throw logger.logExceptionAsError(new UnsupportedOperationException("Body type not supported yet "
+ bodyType.toString()));
default:
logger.warning("Invalid body type {}.", bodyType);
throw logger.logExceptionAsError(new IllegalStateException("Body type not valid "
+ bodyType.toString()));
}
return body;
} | byte[] body = null; | public byte[] getBody() {
final AmqpBodyType bodyType = amqpAnnotatedMessage.getBody().getBodyType();
switch (bodyType) {
case DATA:
return Arrays.copyOf(binaryData, binaryData.length);
case SEQUENCE:
case VALUE:
throw logger.logExceptionAsError(new UnsupportedOperationException("Body type not supported yet "
+ bodyType.toString()));
default:
logger.warning("Invalid body type {}.", bodyType);
throw logger.logExceptionAsError(new IllegalStateException("Body type not valid "
+ bodyType.toString()));
}
} | class ServiceBusReceivedMessage {
private final ClientLogger logger = new ClientLogger(ServiceBusReceivedMessage.class);
private static final String DEAD_LETTER_DESCRIPTION = "DeadLetterErrorDescription";
private static final String DEAD_LETTER_REASON = "DeadLetterReason";
private static final String ENQUEUED_SEQUENCE_NUMBER = "x-opt-enqueue-sequence-number";
private final AmqpAnnotatedMessage amqpAnnotatedMessage;
private UUID lockToken;
/**
* The representation of message as defined by AMQP protocol.
*
* @see <a href="http:
* Amqp Message Format.</a>
*
* @return the {@link AmqpAnnotatedMessage} representing amqp message.
*/
public AmqpAnnotatedMessage getAmqpAnnotatedMessage() {
return amqpAnnotatedMessage;
}
ServiceBusReceivedMessage(byte[] body) {
Objects.requireNonNull(body, "'body' cannot be null.");
amqpAnnotatedMessage = new AmqpAnnotatedMessage(new AmqpDataBody(new BinaryData(body)));
}
/**
* Gets the actual payload/data wrapped by the {@link ServiceBusReceivedMessage}.
*
* <p>
* If the means for deserializing the raw data is not apparent to consumers, a common technique is to make use of
* {@link | class ServiceBusReceivedMessage {
private final ClientLogger logger = new ClientLogger(ServiceBusReceivedMessage.class);
private final AmqpAnnotatedMessage amqpAnnotatedMessage;
private final byte[] binaryData;
private UUID lockToken;
/**
* The representation of message as defined by AMQP protocol.
*
* @see <a href="http:
* Amqp Message Format.</a>
*
* @return the {@link AmqpAnnotatedMessage} representing amqp message.
*/
public AmqpAnnotatedMessage getAmqpAnnotatedMessage() {
return amqpAnnotatedMessage;
}
ServiceBusReceivedMessage(byte[] body) {
binaryData = Objects.requireNonNull(body, "'body' cannot be null.");
amqpAnnotatedMessage = new AmqpAnnotatedMessage(new AmqpDataBody(Collections.singletonList(
new BinaryData(binaryData))));
}
/**
* Gets the actual payload/data wrapped by the {@link ServiceBusReceivedMessage}.
*
* <p>
* If the means for deserializing the raw data is not apparent to consumers, a common technique is to make use of
* {@link
* consumers who wish to deserialize the binary data.
* </p>
*
* @return A byte array representing the data.
*/
/**
* Gets the content type of the message.
*
* @return the contentType of the {@link ServiceBusReceivedMessage}.
*/
public String getContentType() {
return amqpAnnotatedMessage.getProperties().getContentType();
}
/**
* Gets a correlation identifier.
* <p>
* Allows an application to specify a context for the message for the purposes of correlation, for example
* reflecting the MessageId of a message that is being replied to.
* </p>
*
* @return correlation id of this message
*
* @see <a href="https:
* Routing and Correlation</a>
*/
public String getCorrelationId() {
return amqpAnnotatedMessage.getProperties().getCorrelationId();
}
/**
* Gets the description for a message that has been dead-lettered.
*
* @return The description for a message that has been dead-lettered.
*/
public String getDeadLetterErrorDescription() {
return getStringValue(amqpAnnotatedMessage.getApplicationProperties(),
DEAD_LETTER_DESCRIPTION_ANNOTATION_NAME.getValue());
}
/**
* Gets the reason for a message that has been dead-lettered.
*
* @return The reason for a message that has been dead-lettered.
*/
public String getDeadLetterReason() {
return getStringValue(amqpAnnotatedMessage.getApplicationProperties(),
DEAD_LETTER_REASON_ANNOTATION_NAME.getValue());
}
/**
* Gets the name of the queue or subscription that this message was enqueued on, before it was
* deadlettered.
* <p>
* This value is only set in messages that have been dead-lettered and subsequently auto-forwarded
* from the dead-letter queue to another entity. Indicates the entity in which the message
* was dead-lettered. This property is read-only.
*
* @return dead letter source of this message
*
* @see <a href="https:
* queues</a>
*/
public String getDeadLetterSource() {
return getStringValue(amqpAnnotatedMessage.getMessageAnnotations(),
DEAD_LETTER_SOURCE_KEY_ANNOTATION_NAME.getValue());
}
/**
* Gets the number of the times this message was delivered to clients.
* <p>
* The count is incremented when a message lock expires, or the message is explicitly abandoned by
* the receiver. This property is read-only.
*
* @return delivery count of this message.
*
* @see <a href="https:
* transfers, locks, and settlement.</a>
*/
public long getDeliveryCount() {
return amqpAnnotatedMessage.getHeader().getDeliveryCount();
}
/**
* Gets the enqueued sequence number assigned to a message by Service Bus.
* <p>
* The sequence number is a unique 64-bit integer first assigned to a message as it is accepted at its original
* point of submission.
*
* @return enqueued sequence number of this message
*
* @see <a href="https:
* Timestamps</a>
*/
public long getEnqueuedSequenceNumber() {
return getLongValue(amqpAnnotatedMessage.getMessageAnnotations(),
ENQUEUED_SEQUENCE_NUMBER_ANNOTATION_NAME.getValue());
}
/**
* Gets the datetime at which this message was enqueued in Azure Service Bus.
* <p>
* The UTC datetime at which the message has been accepted and stored in the entity. For scheduled messages, this
* reflects the time when the message was activated. This value can be used as an authoritative and neutral arrival
* time indicator when the receiver does not want to trust the sender's clock. This property is read-only.
*
* @return the datetime at which the message was enqueued in Azure Service Bus
*
* @see <a href="https:
* Timestamps</a>
*/
public OffsetDateTime getEnqueuedTime() {
return getOffsetDateTimeValue(amqpAnnotatedMessage.getMessageAnnotations(),
ENQUEUED_TIME_UTC_ANNOTATION_NAME.getValue());
}
/**
* Gets the datetime at which this message will expire.
* <p>
* The value is the UTC datetime for when the message is scheduled for removal and will no longer available for
* retrieval from the entity due to expiration. Expiry is controlled by the {@link
* property. This property is computed from {@link
* TimeToLive}.
*
* @return {@link OffsetDateTime} at which this message expires
*
* @see <a href="https:
*/
public OffsetDateTime getExpiresAt() {
final Duration timeToLive = getTimeToLive();
final OffsetDateTime enqueuedTime = getEnqueuedTime();
return enqueuedTime != null && timeToLive != null
? enqueuedTime.plus(timeToLive)
: null;
}
/**
* Gets the label for the message.
*
* @return The label for the message.
*/
public String getLabel() {
return amqpAnnotatedMessage.getProperties().getSubject();
}
/**
* Gets the lock token for the current message.
* <p>
* The lock token is a reference to the lock that is being held by the broker in
* {@link ReceiveMode
* Locks are used to explicitly settle messages as explained in the
* <a href="https:
* documentation in more detail</a>. The token can also be used to pin the lock permanently
* through the <a
* href="https:
* take the message out of the regular delivery state flow. This property is read-only.
*
* @return Lock-token for this message. Could return {@code null} for {@link ReceiveMode
*
* @see <a href="https:
* transfers, locks, and settlement</a>
*/
public String getLockToken() {
return lockToken != null ? lockToken.toString() : null;
}
/**
* Gets the datetime at which the lock of this message expires.
* <p>
* For messages retrieved under a lock (peek-lock receive mode, not pre-settled) this property reflects the UTC
* datetime until which the message is held locked in the queue/subscription. When the lock expires, the {@link
*
* is read-only.
*
* @return the datetime at which the lock of this message expires if the message is received using {@link
* ReceiveMode
*
* @see <a href="https:
* transfers, locks, and settlement</a>
*/
public OffsetDateTime getLockedUntil() {
return getOffsetDateTimeValue(amqpAnnotatedMessage.getMessageAnnotations(),
LOCKED_UNTIL_KEY_ANNOTATION_NAME.getValue());
}
/**
* @return Id of the {@link ServiceBusReceivedMessage}.
*/
public String getMessageId() {
return amqpAnnotatedMessage.getProperties().getMessageId();
}
/**
* Gets the partition key for sending a message to a partitioned entity.
* <p>
* For <a href="https:
* entities</a>, setting this value enables assigning related messages to the same internal partition, so that
* submission sequence order is correctly recorded. The partition is chosen by a hash function over this value and
* cannot be chosen directly. For session-aware entities, the {@link
* this value.
*
* @return The partition key of this message
*
* @see <a href="https:
* entities</a>
*/
public String getPartitionKey() {
return getStringValue(amqpAnnotatedMessage.getMessageAnnotations(),
PARTITION_KEY_ANNOTATION_NAME.getValue());
}
/**
* Gets the set of free-form {@link ServiceBusReceivedMessage} properties which may be used for passing metadata
* associated with the {@link ServiceBusReceivedMessage} during Service Bus operations. A common use-case for
* {@code properties()} is to associate serialization hints for the {@link
* who wish to deserialize the binary data.
*
* @return Application properties associated with this {@link ServiceBusReceivedMessage}.
*/
public Map<String, Object> getApplicationProperties() {
return amqpAnnotatedMessage.getApplicationProperties();
}
/**
* Gets the address of an entity to send replies to.
* <p>
* This optional and application-defined value is a standard way to express a reply path to the receiver of the
* message. When a sender expects a reply, it sets the value to the absolute or relative path of the queue or topic
* it expects the reply to be sent to.
*
* @return ReplyTo property value of this message
*
* @see <a href="https:
* Routing and Correlation</a>
*/
public String getReplyTo() {
return amqpAnnotatedMessage.getProperties().getReplyTo();
}
/**
* Gets or sets a session identifier augmenting the {@link
* <p>
* This value augments the ReplyTo information and specifies which SessionId should be set for the reply when sent
* to the reply entity.
*
* @return ReplyToSessionId property value of this message
*
* @see <a href="https:
* Routing and Correlation</a>
*/
public String getReplyToSessionId() {
return amqpAnnotatedMessage.getProperties().getReplyToGroupId();
}
/**
* Gets the scheduled enqueue time of this message.
* <p>
* This value is used for delayed message availability. The message is safely added to the queue, but is not
* considered active and therefore not retrievable until the scheduled enqueue time. Mind that the message may not
* be activated (enqueued) at the exact given datetime; the actual activation time depends on the queue's workload
* and its state.
* </p>
*
* @return the datetime at which the message will be enqueued in Azure Service Bus
*
* @see <a href="https:
* Timestamps</a>
*/
public OffsetDateTime getScheduledEnqueueTime() {
return getOffsetDateTimeValue(amqpAnnotatedMessage.getMessageAnnotations(),
SCHEDULED_ENQUEUE_UTC_TIME_NAME.getValue());
}
/**
* Gets the unique number assigned to a message by Service Bus.
* <p>
* The sequence number is a unique 64-bit integer assigned to a message as it is accepted and stored by the broker
* and functions as its true identifier. For partitioned entities, the topmost 16 bits reflect the partition
* identifier. Sequence numbers monotonically increase and are gapless. They roll over to 0 when the 48-64 bit range
* is exhausted. This property is read-only.
*
* @return sequence number of this message
*
* @see <a href="https:
* Timestamps</a>
*/
public long getSequenceNumber() {
return getLongValue(amqpAnnotatedMessage.getMessageAnnotations(),
SEQUENCE_NUMBER_ANNOTATION_NAME.getValue());
}
/**
* Gets the session id of the message.
*
* @return Session Id of the {@link ServiceBusReceivedMessage}.
*/
public String getSessionId() {
return amqpAnnotatedMessage.getProperties().getGroupId();
}
/**
* Gets the duration before this message expires.
* <p>
* This value is the relative duration after which the message expires, starting from the datetime the message has
* been accepted and stored by the broker, as captured in {@link
* explicitly, the assumed value is the DefaultTimeToLive set for the respective queue or topic. A message-level
* TimeToLive value cannot be longer than the entity's DefaultTimeToLive setting and it is silently adjusted if it
* does.
*
* @return Time to live duration of this message
*
* @see <a href="https:
*/
public Duration getTimeToLive() {
return amqpAnnotatedMessage.getHeader().getTimeToLive();
}
/**
* Gets the "to" address.
*
* @return "To" property value of this message
*/
public String getTo() {
return amqpAnnotatedMessage.getProperties().getTo();
}
/**
* Gets the partition key for sending a message to a entity via another partitioned transfer entity.
*
* If a message is sent via a transfer queue in the scope of a transaction, this value selects the
* transfer queue partition: This is functionally equivalent to {@link
* messages are kept together and in order as they are transferred.
*
* @return partition key on the via queue.
*
* @see <a href="https:
*/
public String getViaPartitionKey() {
return getStringValue(amqpAnnotatedMessage.getMessageAnnotations(),
VIA_PARTITION_KEY_ANNOTATION_NAME.getValue());
}
/**
* Sets a correlation identifier.
*
* @param correlationId correlation id of this message
*
* @see
*/
void setCorrelationId(String correlationId) {
amqpAnnotatedMessage.getProperties().setCorrelationId(correlationId);
}
/**
* Sets the content type of the {@link ServiceBusReceivedMessage}.
*
* @param contentType of the message.
*/
void setContentType(String contentType) {
amqpAnnotatedMessage.getProperties().setContentType(contentType);
}
/**
* Sets the dead letter description.
*
* @param deadLetterErrorDescription Dead letter description.
*/
void setDeadLetterErrorDescription(String deadLetterErrorDescription) {
amqpAnnotatedMessage.getApplicationProperties().put(DEAD_LETTER_DESCRIPTION_ANNOTATION_NAME.getValue(),
deadLetterErrorDescription);
}
/**
* Sets the dead letter reason.
*
* @param deadLetterReason Dead letter reason.
*/
void setDeadLetterReason(String deadLetterReason) {
amqpAnnotatedMessage.getApplicationProperties().put(DEAD_LETTER_REASON_ANNOTATION_NAME.getValue(),
deadLetterReason);
}
/**
* Sets the name of the queue or subscription that this message was enqueued on, before it was
* deadlettered.
*
* @param deadLetterSource the name of the queue or subscription that this message was enqueued on,
* before it was deadlettered.
*/
void setDeadLetterSource(String deadLetterSource) {
amqpAnnotatedMessage.getMessageAnnotations().put(DEAD_LETTER_SOURCE_KEY_ANNOTATION_NAME.getValue(),
deadLetterSource);
}
/**
* Sets the number of the times this message was delivered to clients.
*
* @param deliveryCount the number of the times this message was delivered to clients.
*/
void setDeliveryCount(long deliveryCount) {
amqpAnnotatedMessage.getHeader().setDeliveryCount(deliveryCount);
}
void setEnqueuedSequenceNumber(long enqueuedSequenceNumber) {
amqpAnnotatedMessage.getMessageAnnotations().put(ENQUEUED_SEQUENCE_NUMBER_ANNOTATION_NAME.getValue(),
enqueuedSequenceNumber);
}
/**
* Sets the datetime at which this message was enqueued in Azure Service Bus.
*
* @param enqueuedTime the datetime at which this message was enqueued in Azure Service Bus.
*/
void setEnqueuedTime(OffsetDateTime enqueuedTime) {
setValue(amqpAnnotatedMessage.getMessageAnnotations(), ENQUEUED_TIME_UTC_ANNOTATION_NAME, enqueuedTime);
}
/**
* Sets the subject for the message.
*
* @param subject The subject to set.
*/
void setSubject(String subject) {
amqpAnnotatedMessage.getProperties().setSubject(subject);
}
/**
* Sets the lock token for the current message.
*
* @param lockToken the lock token for the current message.
*/
void setLockToken(UUID lockToken) {
this.lockToken = lockToken;
}
/**
* Sets the datetime at which the lock of this message expires.
*
* @param lockedUntil the datetime at which the lock of this message expires.
*/
void setLockedUntil(OffsetDateTime lockedUntil) {
setValue(amqpAnnotatedMessage.getMessageAnnotations(), LOCKED_UNTIL_KEY_ANNOTATION_NAME, lockedUntil);
}
/**
* Sets the message id.
*
* @param messageId to be set.
*/
void setMessageId(String messageId) {
amqpAnnotatedMessage.getProperties().setMessageId(messageId);
}
/**
* Sets a partition key for sending a message to a partitioned entity
*
* @param partitionKey partition key of this message
*
* @see
*/
void setPartitionKey(String partitionKey) {
amqpAnnotatedMessage.getMessageAnnotations().put(PARTITION_KEY_ANNOTATION_NAME.getValue(), partitionKey);
}
/**
* Sets the scheduled enqueue time of this message.
*
* @param scheduledEnqueueTime the datetime at which this message should be enqueued in Azure Service Bus.
*
* @see
*/
void setScheduledEnqueueTime(OffsetDateTime scheduledEnqueueTime) {
setValue(amqpAnnotatedMessage.getMessageAnnotations(), SCHEDULED_ENQUEUE_UTC_TIME_NAME, scheduledEnqueueTime);
}
/**
* Sets the unique number assigned to a message by Service Bus.
*
* @param sequenceNumber the unique number assigned to a message by Service Bus.
*/
void setSequenceNumber(long sequenceNumber) {
amqpAnnotatedMessage.getMessageAnnotations().put(SEQUENCE_NUMBER_ANNOTATION_NAME.getValue(), sequenceNumber);
}
/**
* Sets the session id.
*
* @param sessionId to be set.
*/
void setSessionId(String sessionId) {
amqpAnnotatedMessage.getProperties().setGroupId(sessionId);
}
/**
* Sets the duration of time before this message expires.
*
* @param timeToLive Time to Live duration of this message
*
* @see
*/
void setTimeToLive(Duration timeToLive) {
amqpAnnotatedMessage.getHeader().setTimeToLive(timeToLive);
}
/**
* Sets the address of an entity to send replies to.
*
* @param replyTo ReplyTo property value of this message
*
* @see
*/
void setReplyTo(String replyTo) {
amqpAnnotatedMessage.getProperties().setReplyTo(replyTo);
}
/**
* Gets or sets a session identifier augmenting the {@link
*
* @param replyToSessionId ReplyToSessionId property value of this message
*/
void setReplyToSessionId(String replyToSessionId) {
amqpAnnotatedMessage.getProperties().setReplyToGroupId(replyToSessionId);
}
/**
* Sets the "to" address.
* <p>
* This property is reserved for future use in routing scenarios and presently ignored by the broker itself.
* Applications can use this value in rule-driven
* <a href="https:
* chaining</a> scenarios to indicate the intended logical destination of the message.
*
* @param to To property value of this message
*/
void setTo(String to) {
amqpAnnotatedMessage.getProperties().setTo(to);
}
/**
* Sets a via-partition key for sending a message to a destination entity via another partitioned entity
*
* @param viaPartitionKey via-partition key of this message
*
* @see
*/
void setViaPartitionKey(String viaPartitionKey) {
amqpAnnotatedMessage.getMessageAnnotations().put(VIA_PARTITION_KEY_ANNOTATION_NAME.getValue(), viaPartitionKey);
}
/*
* Gets String value from given map and null if key does not exists.
*/
private String getStringValue(Map<String, Object> dataMap, String key) {
return (String) dataMap.get(key);
}
/*
* Gets long value from given map and 0 if key does not exists.
*/
private long getLongValue(Map<String, Object> dataMap, String key) {
return dataMap.containsKey(key) ? (long) dataMap.get(key) : 0;
}
/*
* Gets OffsetDateTime value from given map and null if key does not exists.
*/
private OffsetDateTime getOffsetDateTimeValue(Map<String, Object> dataMap, String key) {
return dataMap.containsKey(key) ? ((Date) dataMap.get(key)).toInstant().atOffset(ZoneOffset.UTC) : null;
}
private void setValue(Map<String, Object> dataMap, AmqpMessageConstant key, OffsetDateTime value) {
if (value != null) {
amqpAnnotatedMessage.getMessageAnnotations().put(key.getValue(),
new Date(value.toInstant().toEpochMilli()));
}
}
} |
The extra message is not necessary. If this fails, we'll know the line that it failed at. | void receiveAndValidateProperties(MessagingEntityType entityType) {
final boolean isSessionEnabled = false;
final String subject = "subject";
final Map<String, Object> footer = new HashMap<>();
footer.put("footer-key-1", "footer-value-1");
footer.put("footer-key-2", "footer-value-2");
final Map<String, Object> aplicaitonProperties = new HashMap<>();
aplicaitonProperties.put("ap-key-1", "ap-value-1");
aplicaitonProperties.put("ap-key-2", "ap-value-2");
final Map<String, Object> deliveryAnnotation = new HashMap<>();
deliveryAnnotation.put("delivery-annotations-key-1", "delivery-annotations-value-1");
deliveryAnnotation.put("delivery-annotations-key-2", "delivery-annotations-value-2");
setSenderAndReceiver(entityType, TestUtils.USE_CASE_VALIDATE_AMQP_PROPERTIES, isSessionEnabled);
final String messageId = UUID.randomUUID().toString();
final AmqpAnnotatedMessage expectedAmqpProperties = new AmqpAnnotatedMessage(new AmqpDataBody(Collections.singletonList(new BinaryData(CONTENTS_BYTES))));
expectedAmqpProperties.getProperties().setSubject(subject);
expectedAmqpProperties.getProperties().setReplyToGroupId("r-gid");
expectedAmqpProperties.getProperties().setReplyTo("replyto");
expectedAmqpProperties.getProperties().setContentType("content-type");
expectedAmqpProperties.getProperties().setCorrelationId("corelation-id");
expectedAmqpProperties.getProperties().setTo("to");
expectedAmqpProperties.getProperties().setAbsoluteExpiryTime(OffsetDateTime.now().plusSeconds(60));
expectedAmqpProperties.getProperties().setUserId("user-id-1".getBytes());
expectedAmqpProperties.getProperties().setContentEncoding("string");
expectedAmqpProperties.getProperties().setGroupSequence(Long.valueOf(2));
expectedAmqpProperties.getProperties().setCreationTime(OffsetDateTime.now().plusSeconds(30));
expectedAmqpProperties.getHeader().setPriority(Short.valueOf((short) 2));
expectedAmqpProperties.getHeader().setFirstAcquirer(true);
expectedAmqpProperties.getHeader().setDurable(true);
expectedAmqpProperties.getFooter().putAll(footer);
expectedAmqpProperties.getDeliveryAnnotations().putAll(deliveryAnnotation);
expectedAmqpProperties.getApplicationProperties().putAll(aplicaitonProperties);
final ServiceBusMessage message = getMessage(messageId, isSessionEnabled, expectedAmqpProperties);
sendMessage(message).block(TIMEOUT);
StepVerifier.create(receiver.receiveMessages().map(ServiceBusReceivedMessageContext::getMessage))
.assertNext(received -> {
assertNotNull(received.getLockToken());
AmqpAnnotatedMessage actual = received.getAmqpAnnotatedMessage();
try {
assertArrayEquals(CONTENTS_BYTES, message.getBody());
assertEquals(expectedAmqpProperties.getHeader().getPriority(), actual.getHeader().getPriority(), "Header.priority is not equal.");
assertEquals(expectedAmqpProperties.getHeader().isFirstAcquirer(), actual.getHeader().isFirstAcquirer(), "Header.FirstAcquirer is not equal.");
assertEquals(expectedAmqpProperties.getHeader().isDurable(), actual.getHeader().isDurable(), "Header.Durable is not equal.");
assertEquals(expectedAmqpProperties.getProperties().getSubject(), actual.getProperties().getSubject(), "Properties.subject is not equal.");
assertEquals(expectedAmqpProperties.getProperties().getReplyToGroupId(), actual.getProperties().getReplyToGroupId(), "Properties.ReplyToGroupId is not equal.");
assertEquals(expectedAmqpProperties.getProperties().getReplyTo(), actual.getProperties().getReplyTo(), "Properties.replyTo is not equal.");
assertEquals(expectedAmqpProperties.getProperties().getContentType(), actual.getProperties().getContentType(), "Properties.contentType is not equal.");
assertEquals(expectedAmqpProperties.getProperties().getCorrelationId(), actual.getProperties().getCorrelationId(), "Properties.correlationId is not equal.");
assertEquals(expectedAmqpProperties.getProperties().getTo(), actual.getProperties().getTo(), "Properties.to is not equal.");
assertEquals(expectedAmqpProperties.getProperties().getAbsoluteExpiryTime().toEpochSecond(), actual.getProperties().getAbsoluteExpiryTime().toEpochSecond(), "Properties.absoluteExpiryTime is not equal.");
assertEquals(expectedAmqpProperties.getProperties().getSubject(), actual.getProperties().getSubject(), "Properties.subject is not equal.");
assertEquals(expectedAmqpProperties.getProperties().getContentEncoding(), actual.getProperties().getContentEncoding(), "Properties.contentEncoding is not equal.");
assertEquals(expectedAmqpProperties.getProperties().getGroupSequence(), actual.getProperties().getGroupSequence(), "Properties.groupSequence is not equal.");
assertEquals(expectedAmqpProperties.getProperties().getCreationTime().toEpochSecond(), actual.getProperties().getCreationTime().toEpochSecond(), "Properties.absoluteExpiryTime is not equal.");
assertArrayEquals(expectedAmqpProperties.getProperties().getUserId(), actual.getProperties().getUserId(), "Properties.userId is not equal.");
assertMapValues(expectedAmqpProperties.getDeliveryAnnotations(), actual.getDeliveryAnnotations());
assertMapValues(expectedAmqpProperties.getMessageAnnotations(), actual.getMessageAnnotations());
assertMapValues(expectedAmqpProperties.getApplicationProperties(), actual.getApplicationProperties());
assertMapValues(expectedAmqpProperties.getFooter(), actual.getFooter());
} finally {
logger.info("Completing message.");
receiver.complete(received).block(Duration.ofSeconds(15));
messagesPending.decrementAndGet();
}
})
.thenCancel()
.verify(Duration.ofMinutes(2));
} | assertEquals(expectedAmqpProperties.getHeader().getPriority(), actual.getHeader().getPriority(), "Header.priority is not equal."); | void receiveAndValidateProperties(MessagingEntityType entityType) {
final boolean isSessionEnabled = false;
final String subject = "subject";
final Map<String, Object> footer = new HashMap<>();
footer.put("footer-key-1", "footer-value-1");
footer.put("footer-key-2", "footer-value-2");
final Map<String, Object> aplicaitonProperties = new HashMap<>();
aplicaitonProperties.put("ap-key-1", "ap-value-1");
aplicaitonProperties.put("ap-key-2", "ap-value-2");
final Map<String, Object> deliveryAnnotation = new HashMap<>();
deliveryAnnotation.put("delivery-annotations-key-1", "delivery-annotations-value-1");
deliveryAnnotation.put("delivery-annotations-key-2", "delivery-annotations-value-2");
setSenderAndReceiver(entityType, TestUtils.USE_CASE_VALIDATE_AMQP_PROPERTIES, isSessionEnabled);
final String messageId = UUID.randomUUID().toString();
final AmqpAnnotatedMessage expectedAmqpProperties = new AmqpAnnotatedMessage(new AmqpDataBody(Collections.singletonList(new BinaryData(CONTENTS_BYTES))));
expectedAmqpProperties.getProperties().setSubject(subject);
expectedAmqpProperties.getProperties().setReplyToGroupId("r-gid");
expectedAmqpProperties.getProperties().setReplyTo("replyto");
expectedAmqpProperties.getProperties().setContentType("content-type");
expectedAmqpProperties.getProperties().setCorrelationId("corelation-id");
expectedAmqpProperties.getProperties().setTo("to");
expectedAmqpProperties.getProperties().setAbsoluteExpiryTime(OffsetDateTime.now().plusSeconds(60));
expectedAmqpProperties.getProperties().setUserId("user-id-1".getBytes());
expectedAmqpProperties.getProperties().setContentEncoding("string");
expectedAmqpProperties.getProperties().setGroupSequence(Long.valueOf(2));
expectedAmqpProperties.getProperties().setCreationTime(OffsetDateTime.now().plusSeconds(30));
expectedAmqpProperties.getHeader().setPriority(Short.valueOf((short) 2));
expectedAmqpProperties.getHeader().setFirstAcquirer(true);
expectedAmqpProperties.getHeader().setDurable(true);
expectedAmqpProperties.getFooter().putAll(footer);
expectedAmqpProperties.getDeliveryAnnotations().putAll(deliveryAnnotation);
expectedAmqpProperties.getApplicationProperties().putAll(aplicaitonProperties);
final ServiceBusMessage message = TestUtils.getServiceBusMessage(CONTENTS_BYTES, messageId);
final AmqpAnnotatedMessage amqpAnnotatedMessage = message.getAmqpAnnotatedMessage();
amqpAnnotatedMessage.getMessageAnnotations().putAll(expectedAmqpProperties.getMessageAnnotations());
amqpAnnotatedMessage.getApplicationProperties().putAll(expectedAmqpProperties.getApplicationProperties());
amqpAnnotatedMessage.getDeliveryAnnotations().putAll(expectedAmqpProperties.getDeliveryAnnotations());
amqpAnnotatedMessage.getFooter().putAll(expectedAmqpProperties.getFooter());
final AmqpMessageHeader header = amqpAnnotatedMessage.getHeader();
header.setFirstAcquirer(expectedAmqpProperties.getHeader().isFirstAcquirer());
header.setTimeToLive(expectedAmqpProperties.getHeader().getTimeToLive());
header.setDurable(expectedAmqpProperties.getHeader().isDurable());
header.setDeliveryCount(expectedAmqpProperties.getHeader().getDeliveryCount());
header.setPriority(expectedAmqpProperties.getHeader().getPriority());
final AmqpMessageProperties amqpMessageProperties = amqpAnnotatedMessage.getProperties();
amqpMessageProperties.setReplyTo((expectedAmqpProperties.getProperties().getReplyTo()));
amqpMessageProperties.setContentEncoding((expectedAmqpProperties.getProperties().getContentEncoding()));
amqpMessageProperties.setAbsoluteExpiryTime((expectedAmqpProperties.getProperties().getAbsoluteExpiryTime()));
amqpMessageProperties.setSubject((expectedAmqpProperties.getProperties().getSubject()));
amqpMessageProperties.setContentType(expectedAmqpProperties.getProperties().getContentType());
amqpMessageProperties.setCorrelationId(expectedAmqpProperties.getProperties().getCorrelationId());
amqpMessageProperties.setTo(expectedAmqpProperties.getProperties().getTo());
amqpMessageProperties.setGroupSequence(expectedAmqpProperties.getProperties().getGroupSequence());
amqpMessageProperties.setUserId(expectedAmqpProperties.getProperties().getUserId());
amqpMessageProperties.setAbsoluteExpiryTime(expectedAmqpProperties.getProperties().getAbsoluteExpiryTime());
amqpMessageProperties.setCreationTime(expectedAmqpProperties.getProperties().getCreationTime());
amqpMessageProperties.setReplyToGroupId(expectedAmqpProperties.getProperties().getReplyToGroupId());
sendMessage(message).block(TIMEOUT);
StepVerifier.create(receiver.receiveMessages().map(ServiceBusReceivedMessageContext::getMessage))
.assertNext(received -> {
assertNotNull(received.getLockToken());
AmqpAnnotatedMessage actual = received.getAmqpAnnotatedMessage();
try {
assertArrayEquals(CONTENTS_BYTES, message.getBody());
assertEquals(expectedAmqpProperties.getHeader().getPriority(), actual.getHeader().getPriority());
assertEquals(expectedAmqpProperties.getHeader().isFirstAcquirer(), actual.getHeader().isFirstAcquirer());
assertEquals(expectedAmqpProperties.getHeader().isDurable(), actual.getHeader().isDurable());
assertEquals(expectedAmqpProperties.getProperties().getSubject(), actual.getProperties().getSubject());
assertEquals(expectedAmqpProperties.getProperties().getReplyToGroupId(), actual.getProperties().getReplyToGroupId());
assertEquals(expectedAmqpProperties.getProperties().getReplyTo(), actual.getProperties().getReplyTo());
assertEquals(expectedAmqpProperties.getProperties().getContentType(), actual.getProperties().getContentType());
assertEquals(expectedAmqpProperties.getProperties().getCorrelationId(), actual.getProperties().getCorrelationId());
assertEquals(expectedAmqpProperties.getProperties().getTo(), actual.getProperties().getTo());
assertEquals(expectedAmqpProperties.getProperties().getAbsoluteExpiryTime().toEpochSecond(), actual.getProperties().getAbsoluteExpiryTime().toEpochSecond());
assertEquals(expectedAmqpProperties.getProperties().getSubject(), actual.getProperties().getSubject());
assertEquals(expectedAmqpProperties.getProperties().getContentEncoding(), actual.getProperties().getContentEncoding());
assertEquals(expectedAmqpProperties.getProperties().getGroupSequence(), actual.getProperties().getGroupSequence());
assertEquals(expectedAmqpProperties.getProperties().getCreationTime().toEpochSecond(), actual.getProperties().getCreationTime().toEpochSecond());
assertArrayEquals(expectedAmqpProperties.getProperties().getUserId(), actual.getProperties().getUserId());
assertMapValues(expectedAmqpProperties.getDeliveryAnnotations(), actual.getDeliveryAnnotations());
assertMapValues(expectedAmqpProperties.getMessageAnnotations(), actual.getMessageAnnotations());
assertMapValues(expectedAmqpProperties.getApplicationProperties(), actual.getApplicationProperties());
assertMapValues(expectedAmqpProperties.getFooter(), actual.getFooter());
} finally {
logger.info("Completing message.");
receiver.complete(received).block(Duration.ofSeconds(15));
messagesPending.decrementAndGet();
}
})
.thenCancel()
.verify(Duration.ofMinutes(2));
} | class ServiceBusReceiverAsyncClientIntegrationTest extends IntegrationTestBase {
private final ClientLogger logger = new ClientLogger(ServiceBusReceiverAsyncClientIntegrationTest.class);
private final AtomicInteger messagesPending = new AtomicInteger();
private final List<Long> messagesDeferredPending = new ArrayList<>();
private final boolean isSessionEnabled = false;
private ServiceBusReceiverAsyncClient receiver;
private ServiceBusSenderAsyncClient sender;
/**
* Receiver used to clean up resources in {@link
*/
private ServiceBusReceiverAsyncClient receiveAndDeleteReceiver;
ServiceBusReceiverAsyncClientIntegrationTest() {
super(new ClientLogger(ServiceBusReceiverAsyncClientIntegrationTest.class));
}
@Override
protected void beforeTest() {
sessionId = UUID.randomUUID().toString();
}
@Override
protected void afterTest() {
sharedBuilder = null;
final int pending = messagesPending.get();
final int pendingDeferred = messagesDeferredPending.size();
if (pending < 1 && pendingDeferred < 1) {
dispose(receiver, sender, receiveAndDeleteReceiver);
return;
}
try {
if (pending > 0) {
receiveAndDeleteReceiver.receiveMessages()
.map(message -> {
logger.info("Message received: {}", message.getMessage().getSequenceNumber());
return message;
})
.timeout(Duration.ofSeconds(15), Mono.empty())
.blockLast();
}
} catch (Exception e) {
logger.warning("Error occurred when draining queue.", e);
}
try {
if (pendingDeferred > 0) {
for (Long sequenceNumber : messagesDeferredPending) {
receiveAndDeleteReceiver.receiveDeferredMessage(sequenceNumber)
.map(message -> {
logger.info("Message received: {}", message.getSequenceNumber());
return message;
})
.timeout(Duration.ofSeconds(15), Mono.empty())
.block();
}
}
} catch (Exception e) {
logger.warning("Error occurred when draining for deferred messages.", e);
} finally {
dispose(receiver, sender, receiveAndDeleteReceiver);
}
}
/**
* Verifies that we can create multiple transaction using sender and receiver.
*/
@Test
void createMultipleTransactionTest() {
setSenderAndReceiver(MessagingEntityType.QUEUE, 0, isSessionEnabled);
StepVerifier.create(receiver.createTransaction())
.assertNext(Assertions::assertNotNull)
.verifyComplete();
StepVerifier.create(receiver.createTransaction())
.assertNext(Assertions::assertNotNull)
.verifyComplete();
}
/**
* Verifies that we can create transaction and complete.
*/
@MethodSource("com.azure.messaging.servicebus.IntegrationTestBase
@ParameterizedTest
void createTransactionAndRollbackMessagesTest(MessagingEntityType entityType) {
setSenderAndReceiver(entityType, 0, isSessionEnabled);
final String messageId = UUID.randomUUID().toString();
final ServiceBusMessage message = getMessage(messageId, isSessionEnabled);
sendMessage(message).block(OPERATION_TIMEOUT);
AtomicReference<ServiceBusTransactionContext> transaction = new AtomicReference<>();
StepVerifier.create(receiver.createTransaction())
.assertNext(txn -> {
transaction.set(txn);
assertNotNull(transaction);
})
.verifyComplete();
final ServiceBusReceivedMessageContext receivedContext = receiver.receiveMessages().next().block(OPERATION_TIMEOUT);
assertNotNull(receivedContext);
final ServiceBusReceivedMessage receivedMessage = receivedContext.getMessage();
assertNotNull(receivedMessage);
StepVerifier.create(receiver.complete(receivedMessage, transaction.get()))
.verifyComplete();
StepVerifier.create(receiver.rollbackTransaction(transaction.get()))
.verifyComplete();
}
/**
* Verifies that we can do following using shared connection and on non session entity. 1. create transaction 2.
* receive and settle with transactionContext. 3. commit Rollback this transaction.
*/
@ParameterizedTest
@EnumSource(DispositionStatus.class)
void transactionSendReceiveAndCommit(DispositionStatus dispositionStatus) {
final MessagingEntityType entityType = MessagingEntityType.QUEUE;
setSenderAndReceiver(entityType, TestUtils.USE_CASE_PEEK_TRANSACTION_SENDRECEIVE_AND_COMPLETE, isSessionEnabled);
final String messageId1 = UUID.randomUUID().toString();
final ServiceBusMessage message1 = getMessage(messageId1, isSessionEnabled);
final String deadLetterReason = "test reason";
sendMessage(message1).block(TIMEOUT);
AtomicReference<ServiceBusTransactionContext> transaction = new AtomicReference<>();
StepVerifier.create(receiver.createTransaction())
.assertNext(txn -> {
transaction.set(txn);
assertNotNull(transaction);
})
.verifyComplete();
assertNotNull(transaction.get());
final ServiceBusReceivedMessageContext receivedContext = receiver.receiveMessages().next().block(TIMEOUT);
assertNotNull(receivedContext);
final ServiceBusReceivedMessage receivedMessage = receivedContext.getMessage();
assertNotNull(receivedMessage);
final Mono<Void> operation;
switch (dispositionStatus) {
case COMPLETED:
operation = receiver.complete(receivedMessage, transaction.get());
messagesPending.decrementAndGet();
break;
case ABANDONED:
operation = receiver.abandon(receivedMessage, null, transaction.get());
break;
case SUSPENDED:
DeadLetterOptions deadLetterOptions = new DeadLetterOptions().setDeadLetterReason(deadLetterReason);
operation = receiver.deadLetter(receivedMessage, deadLetterOptions, transaction.get());
messagesPending.decrementAndGet();
break;
case DEFERRED:
operation = receiver.defer(receivedMessage, null, transaction.get());
break;
default:
throw logger.logExceptionAsError(new IllegalArgumentException(
"Disposition status not recognized for this test case: " + dispositionStatus));
}
StepVerifier.create(operation)
.verifyComplete();
StepVerifier.create(receiver.commitTransaction(transaction.get()))
.verifyComplete();
if (dispositionStatus == DispositionStatus.DEFERRED) {
messagesDeferredPending.add(receivedMessage.getSequenceNumber());
}
}
/**
* Verifies that we can do following on different clients i.e. sender and receiver. 1. create transaction using
* sender 2. receive and complete with transactionContext. 3. Commit this transaction using sender.
*/
@MethodSource("com.azure.messaging.servicebus.IntegrationTestBase
@ParameterizedTest
@Disabled
void transactionReceiveCompleteCommitMixClient(MessagingEntityType entityType) {
setSenderAndReceiver(entityType, 0, isSessionEnabled, true);
final String messageId = UUID.randomUUID().toString();
final ServiceBusMessage message = getMessage(messageId, isSessionEnabled);
sendMessage(message).block(TIMEOUT);
AtomicReference<ServiceBusTransactionContext> transaction = new AtomicReference<>();
StepVerifier.create(sender.createTransaction())
.assertNext(txn -> {
transaction.set(txn);
assertNotNull(transaction);
})
.verifyComplete();
assertNotNull(transaction.get());
final ServiceBusReceivedMessageContext receivedContext = receiver.receiveMessages().next().block(TIMEOUT);
assertNotNull(receivedContext);
final ServiceBusReceivedMessage receivedMessage = receivedContext.getMessage();
assertNotNull(receivedMessage);
StepVerifier.create(receiver.complete(receivedMessage, transaction.get()))
.verifyComplete();
StepVerifier.create(sender.commitTransaction(transaction.get()))
.verifyComplete();
}
/**
* Verifies that we can send and receive two messages.
*/
@MethodSource("com.azure.messaging.servicebus.IntegrationTestBase
@ParameterizedTest
void receiveTwoMessagesAutoComplete(MessagingEntityType entityType, boolean isSessionEnabled) {
setSenderAndReceiver(entityType, 0, isSessionEnabled);
final String messageId = UUID.randomUUID().toString();
final ServiceBusMessage message = getMessage(messageId, isSessionEnabled);
final List<ServiceBusReceivedMessage> receivedMessages = new ArrayList<>();
Mono.when(sendMessage(message), sendMessage(message)).block(TIMEOUT);
try {
StepVerifier.create(receiver.receiveMessages())
.assertNext(receivedMessage -> {
receivedMessages.add(receivedMessage.getMessage());
assertMessageEquals(receivedMessage, messageId, isSessionEnabled);
})
.assertNext(receivedMessage -> {
receivedMessages.add(receivedMessage.getMessage());
assertMessageEquals(receivedMessage, messageId, isSessionEnabled);
})
.thenCancel()
.verify();
} finally {
int numberCompleted = completeMessages(receiver, receivedMessages);
messagesPending.addAndGet(-numberCompleted);
}
}
/**
* Verifies that we can send and receive a message.
*/
@MethodSource("com.azure.messaging.servicebus.IntegrationTestBase
@ParameterizedTest
void receiveMessageAutoComplete(MessagingEntityType entityType, boolean isSessionEnabled) {
setSenderAndReceiver(entityType, 0, isSessionEnabled);
final String messageId = UUID.randomUUID().toString();
final ServiceBusMessage message = getMessage(messageId, isSessionEnabled);
final List<ServiceBusReceivedMessage> receivedMessages = new ArrayList<>();
sendMessage(message).block(TIMEOUT);
try {
StepVerifier.create(receiver.receiveMessages())
.assertNext(receivedMessage -> {
receivedMessages.add(receivedMessage.getMessage());
assertMessageEquals(receivedMessage, messageId, isSessionEnabled);
})
.thenCancel()
.verify();
} finally {
int numberCompleted = completeMessages(receiver, receivedMessages);
messagesPending.addAndGet(-numberCompleted);
}
}
/**
* Verifies that we can send and peek a message.
*/
@MethodSource("com.azure.messaging.servicebus.IntegrationTestBase
@ParameterizedTest
void peekMessage(MessagingEntityType entityType, boolean isSessionEnabled) {
setSenderAndReceiver(entityType, 1, isSessionEnabled);
final String messageId = UUID.randomUUID().toString();
final ServiceBusMessage message = getMessage(messageId, isSessionEnabled);
sendMessage(message).block(TIMEOUT);
StepVerifier.create(receiver.peekMessage())
.assertNext(receivedMessage -> assertMessageEquals(receivedMessage, messageId, isSessionEnabled))
.verifyComplete();
}
/**
* Verifies that we can schedule and receive a message.
*/
@MethodSource("com.azure.messaging.servicebus.IntegrationTestBase
@ParameterizedTest
void sendScheduledMessageAndReceive(MessagingEntityType entityType, boolean isSessionEnabled) {
setSenderAndReceiver(entityType, 0, isSessionEnabled);
final String messageId = UUID.randomUUID().toString();
final ServiceBusMessage message = getMessage(messageId, isSessionEnabled);
final OffsetDateTime scheduledEnqueueTime = OffsetDateTime.now().plusSeconds(2);
sender.scheduleMessage(message, scheduledEnqueueTime).block(TIMEOUT);
StepVerifier.create(Mono.delay(Duration.ofSeconds(3)).then(receiveAndDeleteReceiver.receiveMessages().next()))
.assertNext(receivedMessage -> {
assertMessageEquals(receivedMessage, messageId, isSessionEnabled);
messagesPending.decrementAndGet();
})
.verifyComplete();
}
/**
* Verifies that we can cancel a scheduled message.
*/
@MethodSource("com.azure.messaging.servicebus.IntegrationTestBase
@ParameterizedTest
void cancelScheduledMessage(MessagingEntityType entityType, boolean isSessionEnabled) {
setSenderAndReceiver(entityType, 0, isSessionEnabled);
final String messageId = UUID.randomUUID().toString();
final ServiceBusMessage message = getMessage(messageId, isSessionEnabled);
final OffsetDateTime scheduledEnqueueTime = OffsetDateTime.now().plusSeconds(10);
final Duration delayDuration = Duration.ofSeconds(3);
final Long sequenceNumber = sender.scheduleMessage(message, scheduledEnqueueTime).block(TIMEOUT);
logger.verbose("Scheduled the message, sequence number {}.", sequenceNumber);
assertNotNull(sequenceNumber);
Mono.delay(delayDuration)
.then(sender.cancelScheduledMessage(sequenceNumber))
.block(TIMEOUT);
messagesPending.decrementAndGet();
logger.verbose("Cancelled the scheduled message, sequence number {}.", sequenceNumber);
StepVerifier.create(receiver.receiveMessages().take(1))
.thenAwait(Duration.ofSeconds(5))
.thenCancel()
.verify();
}
/**
* Verifies that we can send and peek a message.
*/
@MethodSource("com.azure.messaging.servicebus.IntegrationTestBase
@ParameterizedTest
void peekFromSequenceNumberMessage(MessagingEntityType entityType, boolean isSessionEnabled) {
setSenderAndReceiver(entityType, 3, isSessionEnabled);
final String messageId = UUID.randomUUID().toString();
final ServiceBusMessage message = getMessage(messageId, isSessionEnabled);
sendMessage(message).block(TIMEOUT);
final ServiceBusReceivedMessageContext receivedContext = receiver.receiveMessages().next().block(TIMEOUT);
assertNotNull(receivedContext);
final ServiceBusReceivedMessage receivedMessage = receivedContext.getMessage();
assertNotNull(receivedMessage);
try {
StepVerifier.create(receiver.peekMessageAt(receivedMessage.getSequenceNumber()))
.assertNext(m -> {
assertEquals(receivedMessage.getSequenceNumber(), m.getSequenceNumber());
assertMessageEquals(m, messageId, isSessionEnabled);
})
.verifyComplete();
} finally {
receiver.complete(receivedMessage)
.block(Duration.ofSeconds(10));
messagesPending.decrementAndGet();
}
}
/**
* Verifies that we can send and peek a batch of messages and the sequence number is tracked correctly.
*/
@MethodSource("com.azure.messaging.servicebus.IntegrationTestBase
@ParameterizedTest
void peekBatchMessages(MessagingEntityType entityType, boolean isSessionEnabled) {
setSenderAndReceiver(entityType, TestUtils.USE_CASE_PEEK_BATCH_MESSAGES, isSessionEnabled);
final BiConsumer<ServiceBusReceivedMessage, Integer> checkCorrectMessage = (message, index) -> {
final Map<String, Object> properties = message.getApplicationProperties();
final Object value = properties.get(MESSAGE_POSITION_ID);
assertTrue(value instanceof Integer, "Did not contain correct position number: " + value);
final int position = (int) value;
assertEquals(index, position);
};
final String messageId = UUID.randomUUID().toString();
final List<ServiceBusMessage> messages = TestUtils.getServiceBusMessages(10, messageId, CONTENTS_BYTES);
if (isSessionEnabled) {
messages.forEach(m -> m.setSessionId(sessionId));
}
sendMessage(messages).block(TIMEOUT);
try {
StepVerifier.create(receiver.peekMessages(3))
.assertNext(message -> checkCorrectMessage.accept(message, 0))
.assertNext(message -> checkCorrectMessage.accept(message, 1))
.assertNext(message -> checkCorrectMessage.accept(message, 2))
.verifyComplete();
StepVerifier.create(receiver.peekMessages(4))
.assertNext(message -> checkCorrectMessage.accept(message, 3))
.assertNext(message -> checkCorrectMessage.accept(message, 4))
.assertNext(message -> checkCorrectMessage.accept(message, 5))
.assertNext(message -> checkCorrectMessage.accept(message, 6))
.verifyComplete();
StepVerifier.create(receiver.peekMessage())
.assertNext(message -> checkCorrectMessage.accept(message, 7))
.verifyComplete();
} finally {
receiveAndDeleteReceiver.receiveMessages()
.take(messages.size())
.blockLast(Duration.ofSeconds(15));
messagesPending.addAndGet(-messages.size());
}
}
/**
* Verifies that we can send and peek a batch of messages.
*/
@MethodSource("com.azure.messaging.servicebus.IntegrationTestBase
@ParameterizedTest
void peekBatchMessagesFromSequence(MessagingEntityType entityType) {
setSenderAndReceiver(entityType, TestUtils.USE_CASE_PEEK_MESSAGE_FROM_SEQUENCE, false);
final String messageId = UUID.randomUUID().toString();
final ServiceBusMessage message = getMessage(messageId, false);
final int maxMessages = 2;
final int fromSequenceNumber = 1;
Mono.when(sendMessage(message), sendMessage(message)).block(TIMEOUT);
StepVerifier.create(receiver.peekMessagesAt(maxMessages, fromSequenceNumber))
.expectNextCount(maxMessages)
.verifyComplete();
}
/**
* Verifies that we can dead-letter a message.
*/
@MethodSource("com.azure.messaging.servicebus.IntegrationTestBase
@ParameterizedTest
void deadLetterMessage(MessagingEntityType entityType, boolean isSessionEnabled) {
setSenderAndReceiver(entityType, 0, isSessionEnabled);
final String messageId = UUID.randomUUID().toString();
final ServiceBusMessage message = getMessage(messageId, isSessionEnabled);
sendMessage(message).block(TIMEOUT);
final ServiceBusReceivedMessageContext receivedContext = receiver.receiveMessages().next().block(TIMEOUT);
assertNotNull(receivedContext);
final ServiceBusReceivedMessage receivedMessage = receivedContext.getMessage();
assertNotNull(receivedMessage);
StepVerifier.create(receiver.deadLetter(receivedMessage))
.verifyComplete();
messagesPending.decrementAndGet();
}
@MethodSource("com.azure.messaging.servicebus.IntegrationTestBase
@ParameterizedTest
void receiveAndComplete(MessagingEntityType entityType, boolean isSessionEnabled) {
setSenderAndReceiver(entityType, 0, isSessionEnabled);
final String messageId = UUID.randomUUID().toString();
final ServiceBusMessage message = getMessage(messageId, isSessionEnabled);
sendMessage(message).block(TIMEOUT);
final ServiceBusReceivedMessageContext receivedContext = receiver.receiveMessages().next().block(TIMEOUT);
assertNotNull(receivedContext);
final ServiceBusReceivedMessage receivedMessage = receivedContext.getMessage();
assertNotNull(receivedMessage);
StepVerifier.create(receiver.complete(receivedMessage))
.verifyComplete();
messagesPending.decrementAndGet();
}
/**
* Verifies that we can renew message lock on a non-session receiver.
*/
@MethodSource("com.azure.messaging.servicebus.IntegrationTestBase
@ParameterizedTest
void receiveAndRenewLock(MessagingEntityType entityType) {
setSenderAndReceiver(entityType, 0, false);
final String messageId = UUID.randomUUID().toString();
final ServiceBusMessage message = getMessage(messageId, false);
sendMessage(message).block(TIMEOUT);
final ServiceBusReceivedMessageContext receivedContext = receiver.receiveMessages().next().block(TIMEOUT);
assertNotNull(receivedContext);
final ServiceBusReceivedMessage receivedMessage = receivedContext.getMessage();
assertNotNull(receivedMessage);
assertNotNull(receivedMessage.getLockedUntil());
final OffsetDateTime initialLock = receivedMessage.getLockedUntil();
logger.info("Received message. Seq: {}. lockedUntil: {}", receivedMessage.getSequenceNumber(), initialLock);
try {
StepVerifier.create(Mono.delay(Duration.ofSeconds(7))
.then(Mono.defer(() -> receiver.renewMessageLock(receivedMessage.getLockToken()))))
.assertNext(lockedUntil -> {
assertTrue(lockedUntil.isAfter(initialLock),
String.format("Updated lock is not after the initial Lock. updated: [%s]. initial:[%s]",
lockedUntil, initialLock));
})
.verifyComplete();
} finally {
logger.info("Completing message. Seq: {}.", receivedMessage.getSequenceNumber());
receiver.complete(receivedMessage)
.doOnSuccess(aVoid -> messagesPending.decrementAndGet())
.block(TIMEOUT);
}
}
/**
* Verifies that the lock can be automatically renewed.
*/
@Disabled("Auto-lock renewal is not enabled.")
@MethodSource("com.azure.messaging.servicebus.IntegrationTestBase
@ParameterizedTest
void autoRenewLockOnReceiveMessage(MessagingEntityType entityType, boolean isSessionEnabled) {
setSenderAndReceiver(entityType, 0, isSessionEnabled);
final String messageId = UUID.randomUUID().toString();
final ServiceBusMessage message = getMessage(messageId, isSessionEnabled);
sendMessage(message).block(TIMEOUT);
StepVerifier.create(receiver.receiveMessages().map(ServiceBusReceivedMessageContext::getMessage))
.assertNext(received -> {
assertNotNull(received.getLockedUntil());
assertNotNull(received.getLockToken());
logger.info("{}: lockToken[{}]. lockedUntil[{}]. now[{}]", received.getSequenceNumber(),
received.getLockToken(), received.getLockedUntil(), OffsetDateTime.now());
final OffsetDateTime initial = received.getLockedUntil();
final OffsetDateTime timeToStop = initial.plusSeconds(5);
OffsetDateTime latest = OffsetDateTime.MIN;
final AtomicInteger iteration = new AtomicInteger();
while (OffsetDateTime.now().isBefore(timeToStop)) {
logger.info("Iteration {}: {}. Time to stop: {}", iteration.incrementAndGet(), OffsetDateTime.now(), timeToStop);
try {
TimeUnit.SECONDS.sleep(4);
} catch (InterruptedException error) {
logger.error("Error occurred while sleeping: " + error);
}
assertNotNull(received.getLockedUntil());
latest = received.getLockedUntil();
}
try {
assertTrue(initial.isBefore(latest), String.format(
"Latest should be after or equal to initial. initial: %s. latest: %s", initial, latest));
} finally {
logger.info("Completing message.");
receiver.complete(received).block(Duration.ofSeconds(15));
messagesPending.decrementAndGet();
}
})
.thenCancel()
.verify(Duration.ofMinutes(2));
}
@MethodSource("com.azure.messaging.servicebus.IntegrationTestBase
@ParameterizedTest
void receiveAndAbandon(MessagingEntityType entityType, boolean isSessionEnabled) {
setSenderAndReceiver(entityType, 0, isSessionEnabled);
final String messageId = UUID.randomUUID().toString();
final ServiceBusMessage message = getMessage(messageId, isSessionEnabled);
sendMessage(message).block(TIMEOUT);
final ServiceBusReceivedMessageContext receivedContext = receiver.receiveMessages().next().block(TIMEOUT);
assertNotNull(receivedContext);
final ServiceBusReceivedMessage receivedMessage = receivedContext.getMessage();
assertNotNull(receivedMessage);
StepVerifier.create(receiver.abandon(receivedMessage))
.verifyComplete();
messagesPending.decrementAndGet();
}
@MethodSource("com.azure.messaging.servicebus.IntegrationTestBase
@ParameterizedTest
void receiveAndDefer(MessagingEntityType entityType, boolean isSessionEnabled) {
setSenderAndReceiver(entityType, TestUtils.USE_CASE_PEEK_RECEIVE_AND_DEFER, isSessionEnabled);
final String messageId = UUID.randomUUID().toString();
final ServiceBusMessage message = getMessage(messageId, isSessionEnabled);
sendMessage(message).block(TIMEOUT);
final ServiceBusReceivedMessageContext receivedContext = receiver.receiveMessages().next().block(TIMEOUT);
assertNotNull(receivedContext);
final ServiceBusReceivedMessage receivedMessage = receivedContext.getMessage();
assertNotNull(receivedMessage);
StepVerifier.create(receiver.defer(receivedMessage))
.verifyComplete();
messagesPending.decrementAndGet();
completeDeferredMessages(receiver, receivedMessage);
}
/**
* Test we can receive a deferred message via sequence number and then perform abandon, suspend, or complete on it.
*/
@MethodSource("com.azure.messaging.servicebus.IntegrationTestBase
@ParameterizedTest
void receiveDeferredMessageBySequenceNumber(MessagingEntityType entityType, DispositionStatus dispositionStatus) {
setSenderAndReceiver(entityType, 0, false);
final String messageId = UUID.randomUUID().toString();
final ServiceBusMessage message = getMessage(messageId, false);
sendMessage(message).block(TIMEOUT);
final ServiceBusReceivedMessageContext receivedContext = receiver.receiveMessages().next().block(TIMEOUT);
assertNotNull(receivedContext);
final ServiceBusReceivedMessage receivedMessage = receivedContext.getMessage();
assertNotNull(receivedMessage);
receiver.defer(receivedMessage).block(TIMEOUT);
final ServiceBusReceivedMessage receivedDeferredMessage = receiver
.receiveDeferredMessage(receivedMessage.getSequenceNumber())
.block(TIMEOUT);
assertNotNull(receivedDeferredMessage);
assertEquals(receivedMessage.getSequenceNumber(), receivedDeferredMessage.getSequenceNumber());
final Mono<Void> operation;
switch (dispositionStatus) {
case ABANDONED:
operation = receiver.abandon(receivedDeferredMessage);
messagesDeferredPending.add(receivedDeferredMessage.getSequenceNumber());
break;
case SUSPENDED:
operation = receiver.deadLetter(receivedDeferredMessage);
break;
case COMPLETED:
operation = receiver.complete(receivedDeferredMessage);
break;
default:
throw logger.logExceptionAsError(new IllegalArgumentException(
"Disposition status not recognized for this test case: " + dispositionStatus));
}
StepVerifier.create(operation)
.expectComplete()
.verify();
if (dispositionStatus != DispositionStatus.COMPLETED) {
messagesPending.decrementAndGet();
}
}
@MethodSource("com.azure.messaging.servicebus.IntegrationTestBase
@ParameterizedTest
void sendReceiveMessageWithVariousPropertyTypes(MessagingEntityType entityType) {
setSenderAndReceiver(entityType, TestUtils.USE_CASE_SEND_RECEIVE_WITH_PROPERTIES, isSessionEnabled);
final boolean isSessionEnabled = true;
final String messageId = UUID.randomUUID().toString();
final ServiceBusMessage messageToSend = getMessage(messageId, isSessionEnabled);
Map<String, Object> sentProperties = messageToSend.getApplicationProperties();
sentProperties.put("NullProperty", null);
sentProperties.put("BooleanProperty", true);
sentProperties.put("ByteProperty", (byte) 1);
sentProperties.put("ShortProperty", (short) 2);
sentProperties.put("IntProperty", 3);
sentProperties.put("LongProperty", 4L);
sentProperties.put("FloatProperty", 5.5f);
sentProperties.put("DoubleProperty", 6.6f);
sentProperties.put("CharProperty", 'z');
sentProperties.put("UUIDProperty", UUID.randomUUID());
sentProperties.put("StringProperty", "string");
sendMessage(messageToSend).block(TIMEOUT);
StepVerifier.create(receiveAndDeleteReceiver.receiveMessages())
.assertNext(receivedMessage -> {
messagesPending.decrementAndGet();
assertMessageEquals(receivedMessage, messageId, isSessionEnabled);
final Map<String, Object> received = receivedMessage.getMessage().getApplicationProperties();
assertEquals(sentProperties.size(), received.size());
for (Map.Entry<String, Object> sentEntry : sentProperties.entrySet()) {
if (sentEntry.getValue() != null && sentEntry.getValue().getClass().isArray()) {
assertArrayEquals((Object[]) sentEntry.getValue(), (Object[]) received.get(sentEntry.getKey()));
} else {
final Object expected = sentEntry.getValue();
final Object actual = received.get(sentEntry.getKey());
assertEquals(expected, actual, String.format(
"Key '%s' does not match. Expected: '%s'. Actual: '%s'", sentEntry.getKey(), expected,
actual));
}
}
})
.thenCancel()
.verify();
}
@MethodSource("com.azure.messaging.servicebus.IntegrationTestBase
@ParameterizedTest
void setAndGetSessionState(MessagingEntityType entityType) {
setSenderAndReceiver(entityType, 0, true);
final byte[] sessionState = "Finished".getBytes(UTF_8);
final String messageId = UUID.randomUUID().toString();
final ServiceBusMessage messageToSend = getMessage(messageId, true);
sendMessage(messageToSend).block(Duration.ofSeconds(10));
AtomicReference<ServiceBusReceivedMessage> receivedMessage = new AtomicReference<>();
StepVerifier.create(receiver.receiveMessages()
.take(1)
.flatMap(m -> {
logger.info("SessionId: {}. LockToken: {}. LockedUntil: {}. Message received.",
m.getSessionId(), m.getMessage().getLockToken(), m.getMessage().getLockedUntil());
receivedMessage.set(m.getMessage());
return receiver.setSessionState(sessionId, sessionState);
}))
.expectComplete()
.verify();
StepVerifier.create(receiver.getSessionState(sessionId))
.assertNext(state -> {
logger.info("State received: {}", new String(state, UTF_8));
assertArrayEquals(sessionState, state);
})
.verifyComplete();
receiver.complete(receivedMessage.get()).block(Duration.ofSeconds(15));
messagesPending.decrementAndGet();
}
/**
* Verifies that we can receive a message from dead letter queue.
*/
@MethodSource("com.azure.messaging.servicebus.IntegrationTestBase
@ParameterizedTest
void receiveFromDeadLetter(MessagingEntityType entityType) {
final boolean isSessionEnabled = false;
setSenderAndReceiver(entityType, 0, isSessionEnabled);
ServiceBusReceiverAsyncClient deadLetterReceiver = getDeadLetterReceiverBuilder(false, entityType,
0, Function.identity())
.buildAsyncClient();
final String messageId = UUID.randomUUID().toString();
final ServiceBusMessage message = getMessage(messageId, isSessionEnabled);
final List<ServiceBusReceivedMessage> receivedMessages = new ArrayList<>();
sendMessage(message).block(TIMEOUT);
final ServiceBusReceivedMessageContext receivedContext = receiver.receiveMessages().next()
.block(OPERATION_TIMEOUT);
assertNotNull(receivedContext);
final ServiceBusReceivedMessage receivedMessage = receivedContext.getMessage();
assertNotNull(receivedMessage);
StepVerifier.create(receiver.deadLetter(receivedMessage))
.verifyComplete();
try {
StepVerifier.create(deadLetterReceiver.receiveMessages().take(1))
.assertNext(messageContext -> {
receivedMessages.add(messageContext.getMessage());
assertMessageEquals(receivedMessage, messageId, isSessionEnabled);
})
.thenCancel()
.verify();
} finally {
int numberCompleted = completeMessages(deadLetterReceiver, receivedMessages);
messagesPending.addAndGet(-numberCompleted);
}
}
@MethodSource("com.azure.messaging.servicebus.IntegrationTestBase
@ParameterizedTest
void renewMessageLock(MessagingEntityType entityType) throws InterruptedException {
final boolean isSessionEnabled = false;
setSenderAndReceiver(entityType, 0, isSessionEnabled);
final Duration maximumDuration = Duration.ofSeconds(35);
final Duration sleepDuration = maximumDuration.plusMillis(500);
final String messageId = UUID.randomUUID().toString();
final ServiceBusMessage message = getMessage(messageId, isSessionEnabled);
final ServiceBusReceivedMessageContext receivedContext = sendMessage(message)
.then(receiver.receiveMessages().next())
.block(TIMEOUT);
assertNotNull(receivedContext);
final ServiceBusReceivedMessage receivedMessage = receivedContext.getMessage();
assertNotNull(receivedMessage);
final OffsetDateTime lockedUntil = receivedMessage.getLockedUntil();
assertNotNull(lockedUntil);
StepVerifier.create(receiver.getAutoRenewMessageLock(receivedMessage.getLockToken(), maximumDuration))
.thenAwait(sleepDuration)
.then(() -> {
logger.info("Completing message.");
int numberCompleted = completeMessages(receiver, Collections.singletonList(receivedMessage));
messagesPending.addAndGet(-numberCompleted);
})
.expectComplete()
.verify(Duration.ofMinutes(3));
}
/**
* Verifies that we can receive a message which have different section set (i.e header, footer, annotations,
* application properties etc).
*/
@MethodSource("com.azure.messaging.servicebus.IntegrationTestBase
@ParameterizedTest
/**
* Asserts the length and values with in the map.
*/
private void assertMapValues(Map<String, Object> expectedMap, Map<String, Object> actualMap) {
assertTrue(actualMap.size() >= expectedMap.size());
Iterator<String> expectedKeys = expectedMap.keySet().iterator();
while (expectedKeys.hasNext()) {
String key = expectedKeys.next();
assertEquals(expectedMap.get(key), actualMap.get(key), "Value is not equal for Key " + key);
}
}
/**
* Sets the sender and receiver. If session is enabled, then a single-named session receiver is created.
*/
private void setSenderAndReceiver(MessagingEntityType entityType, int entityIndex, boolean isSessionEnabled) {
setSenderAndReceiver(entityType, entityIndex, isSessionEnabled, false);
}
/**
* Sets the sender and receiver. If session is enabled, then a single-named session receiver is created with shared
* connection as needed.
*/
private void setSenderAndReceiver(MessagingEntityType entityType, int entityIndex, boolean isSessionEnabled,
boolean shareConnection) {
this.sender = getSenderBuilder(false, entityType, entityIndex, isSessionEnabled, shareConnection)
.buildAsyncClient();
if (isSessionEnabled) {
assertNotNull(sessionId, "'sessionId' should have been set.");
this.receiver = getSessionReceiverBuilder(false, entityType, entityIndex, Function.identity(),
shareConnection)
.sessionId(sessionId)
.buildAsyncClient();
this.receiveAndDeleteReceiver = getSessionReceiverBuilder(false, entityType, entityIndex,
Function.identity(), shareConnection)
.sessionId(sessionId)
.receiveMode(ReceiveMode.RECEIVE_AND_DELETE)
.buildAsyncClient();
} else {
this.receiver = getReceiverBuilder(false, entityType, entityIndex, Function.identity(),
shareConnection)
.buildAsyncClient();
this.receiveAndDeleteReceiver = getReceiverBuilder(false, entityType, entityIndex,
Function.identity(), shareConnection)
.receiveMode(ReceiveMode.RECEIVE_AND_DELETE)
.buildAsyncClient();
}
}
private Mono<Void> sendMessage(ServiceBusMessage message) {
return sender.sendMessage(message).doOnSuccess(aVoid -> {
int number = messagesPending.incrementAndGet();
logger.info("Message Id {}. Number sent: {}", message.getMessageId(), number);
});
}
private Mono<Void> sendMessage(List<ServiceBusMessage> messages) {
return sender.sendMessages(messages).doOnSuccess(aVoid -> {
int number = messagesPending.addAndGet(messages.size());
logger.info("Number of messages sent: {}", number);
});
}
private int completeMessages(ServiceBusReceiverAsyncClient client, List<ServiceBusReceivedMessage> lockTokens) {
Mono.when(lockTokens.stream().map(e -> client.complete(e))
.collect(Collectors.toList()))
.block(TIMEOUT);
return lockTokens.size();
}
private void completeDeferredMessages(ServiceBusReceiverAsyncClient client, ServiceBusReceivedMessage receivedMessage) {
final ServiceBusReceivedMessage receivedDeferredMessage = client
.receiveDeferredMessage(receivedMessage.getSequenceNumber())
.block(TIMEOUT);
assertNotNull(receivedDeferredMessage);
receiver.complete(receivedDeferredMessage).block(TIMEOUT);
}
private ServiceBusClientBuilder.ServiceBusReceiverClientBuilder getDeadLetterReceiverBuilder(boolean useCredentials,
MessagingEntityType entityType, int entityIndex, Function<ServiceBusClientBuilder, ServiceBusClientBuilder> onBuilderCreate) {
ServiceBusClientBuilder builder = getBuilder(useCredentials);
builder = onBuilderCreate.apply(builder);
switch (entityType) {
case QUEUE:
final String queueName = getQueueName(entityIndex);
assertNotNull(queueName, "'queueName' cannot be null.");
return builder.receiver().queueName(queueName).subQueue(SubQueue.DEAD_LETTER_QUEUE);
case SUBSCRIPTION:
final String topicName = getTopicName(entityIndex);
final String subscriptionName = getSubscriptionBaseName();
assertNotNull(topicName, "'topicName' cannot be null.");
assertNotNull(subscriptionName, "'subscriptionName' cannot be null.");
return builder.receiver().topicName(topicName).subscriptionName(subscriptionName).subQueue(SubQueue.DEAD_LETTER_QUEUE);
default:
throw logger.logExceptionAsError(new IllegalArgumentException("Unknown entity type: " + entityType));
}
}
protected ServiceBusMessage getMessage(String messageId, boolean isSessionEnabled, AmqpAnnotatedMessage amqpPropertiesToSet) {
final ServiceBusMessage message = TestUtils.getServiceBusMessage(CONTENTS_BYTES, messageId);
final AmqpAnnotatedMessage amqpAnnotatedMessage = message.getAmqpAnnotatedMessage();
amqpAnnotatedMessage.getMessageAnnotations().putAll(amqpPropertiesToSet.getMessageAnnotations());
amqpAnnotatedMessage.getApplicationProperties().putAll(amqpPropertiesToSet.getApplicationProperties());
amqpAnnotatedMessage.getDeliveryAnnotations().putAll(amqpPropertiesToSet.getDeliveryAnnotations());
amqpAnnotatedMessage.getFooter().putAll(amqpPropertiesToSet.getFooter());
final AmqpMessageHeader header = amqpAnnotatedMessage.getHeader();
header.setFirstAcquirer(amqpPropertiesToSet.getHeader().isFirstAcquirer());
header.setTimeToLive(amqpPropertiesToSet.getHeader().getTimeToLive());
header.setDurable(amqpPropertiesToSet.getHeader().isDurable());
header.setDeliveryCount(amqpPropertiesToSet.getHeader().getDeliveryCount());
header.setPriority(amqpPropertiesToSet.getHeader().getPriority());
final AmqpMessageProperties amqpMessageProperties = amqpAnnotatedMessage.getProperties();
amqpMessageProperties.setReplyTo((amqpPropertiesToSet.getProperties().getReplyTo()));
amqpMessageProperties.setContentEncoding((amqpPropertiesToSet.getProperties().getContentEncoding()));
amqpMessageProperties.setAbsoluteExpiryTime((amqpPropertiesToSet.getProperties().getAbsoluteExpiryTime()));
amqpMessageProperties.setSubject((amqpPropertiesToSet.getProperties().getSubject()));
amqpMessageProperties.setContentType(amqpPropertiesToSet.getProperties().getContentType());
amqpMessageProperties.setCorrelationId(amqpPropertiesToSet.getProperties().getCorrelationId());
amqpMessageProperties.setTo(amqpPropertiesToSet.getProperties().getTo());
amqpMessageProperties.setGroupSequence(amqpPropertiesToSet.getProperties().getGroupSequence());
amqpMessageProperties.setUserId(amqpPropertiesToSet.getProperties().getUserId());
amqpMessageProperties.setAbsoluteExpiryTime(amqpPropertiesToSet.getProperties().getAbsoluteExpiryTime());
amqpMessageProperties.setCreationTime(amqpPropertiesToSet.getProperties().getCreationTime());
amqpMessageProperties.setReplyToGroupId(amqpPropertiesToSet.getProperties().getReplyToGroupId());
logger.verbose("Message id {}.", messageId);
return isSessionEnabled ? message.setSessionId(sessionId) : message;
}
} | class ServiceBusReceiverAsyncClientIntegrationTest extends IntegrationTestBase {
private final ClientLogger logger = new ClientLogger(ServiceBusReceiverAsyncClientIntegrationTest.class);
private final AtomicInteger messagesPending = new AtomicInteger();
private final List<Long> messagesDeferredPending = new ArrayList<>();
private final boolean isSessionEnabled = false;
private ServiceBusReceiverAsyncClient receiver;
private ServiceBusSenderAsyncClient sender;
/**
* Receiver used to clean up resources in {@link
*/
private ServiceBusReceiverAsyncClient receiveAndDeleteReceiver;
ServiceBusReceiverAsyncClientIntegrationTest() {
super(new ClientLogger(ServiceBusReceiverAsyncClientIntegrationTest.class));
}
@Override
protected void beforeTest() {
sessionId = UUID.randomUUID().toString();
}
@Override
protected void afterTest() {
sharedBuilder = null;
final int pending = messagesPending.get();
final int pendingDeferred = messagesDeferredPending.size();
if (pending < 1 && pendingDeferred < 1) {
dispose(receiver, sender, receiveAndDeleteReceiver);
return;
}
try {
if (pending > 0) {
receiveAndDeleteReceiver.receiveMessages()
.map(message -> {
logger.info("Message received: {}", message.getMessage().getSequenceNumber());
return message;
})
.timeout(Duration.ofSeconds(15), Mono.empty())
.blockLast();
}
} catch (Exception e) {
logger.warning("Error occurred when draining queue.", e);
}
try {
if (pendingDeferred > 0) {
for (Long sequenceNumber : messagesDeferredPending) {
receiveAndDeleteReceiver.receiveDeferredMessage(sequenceNumber)
.map(message -> {
logger.info("Message received: {}", message.getSequenceNumber());
return message;
})
.timeout(Duration.ofSeconds(15), Mono.empty())
.block();
}
}
} catch (Exception e) {
logger.warning("Error occurred when draining for deferred messages.", e);
} finally {
dispose(receiver, sender, receiveAndDeleteReceiver);
}
}
/**
* Verifies that we can create multiple transaction using sender and receiver.
*/
@Test
void createMultipleTransactionTest() {
setSenderAndReceiver(MessagingEntityType.QUEUE, 0, isSessionEnabled);
StepVerifier.create(receiver.createTransaction())
.assertNext(Assertions::assertNotNull)
.verifyComplete();
StepVerifier.create(receiver.createTransaction())
.assertNext(Assertions::assertNotNull)
.verifyComplete();
}
/**
* Verifies that we can create transaction and complete.
*/
@MethodSource("com.azure.messaging.servicebus.IntegrationTestBase
@ParameterizedTest
void createTransactionAndRollbackMessagesTest(MessagingEntityType entityType) {
setSenderAndReceiver(entityType, 0, isSessionEnabled);
final String messageId = UUID.randomUUID().toString();
final ServiceBusMessage message = getMessage(messageId, isSessionEnabled);
sendMessage(message).block(OPERATION_TIMEOUT);
AtomicReference<ServiceBusTransactionContext> transaction = new AtomicReference<>();
StepVerifier.create(receiver.createTransaction())
.assertNext(txn -> {
transaction.set(txn);
assertNotNull(transaction);
})
.verifyComplete();
final ServiceBusReceivedMessageContext receivedContext = receiver.receiveMessages().next().block(OPERATION_TIMEOUT);
assertNotNull(receivedContext);
final ServiceBusReceivedMessage receivedMessage = receivedContext.getMessage();
assertNotNull(receivedMessage);
StepVerifier.create(receiver.complete(receivedMessage, transaction.get()))
.verifyComplete();
StepVerifier.create(receiver.rollbackTransaction(transaction.get()))
.verifyComplete();
}
/**
* Verifies that we can do following using shared connection and on non session entity. 1. create transaction 2.
* receive and settle with transactionContext. 3. commit Rollback this transaction.
*/
@ParameterizedTest
@EnumSource(DispositionStatus.class)
void transactionSendReceiveAndCommit(DispositionStatus dispositionStatus) {
final MessagingEntityType entityType = MessagingEntityType.QUEUE;
setSenderAndReceiver(entityType, TestUtils.USE_CASE_PEEK_TRANSACTION_SENDRECEIVE_AND_COMPLETE, isSessionEnabled);
final String messageId1 = UUID.randomUUID().toString();
final ServiceBusMessage message1 = getMessage(messageId1, isSessionEnabled);
final String deadLetterReason = "test reason";
sendMessage(message1).block(TIMEOUT);
AtomicReference<ServiceBusTransactionContext> transaction = new AtomicReference<>();
StepVerifier.create(receiver.createTransaction())
.assertNext(txn -> {
transaction.set(txn);
assertNotNull(transaction);
})
.verifyComplete();
assertNotNull(transaction.get());
final ServiceBusReceivedMessageContext receivedContext = receiver.receiveMessages().next().block(TIMEOUT);
assertNotNull(receivedContext);
final ServiceBusReceivedMessage receivedMessage = receivedContext.getMessage();
assertNotNull(receivedMessage);
final Mono<Void> operation;
switch (dispositionStatus) {
case COMPLETED:
operation = receiver.complete(receivedMessage, transaction.get());
messagesPending.decrementAndGet();
break;
case ABANDONED:
operation = receiver.abandon(receivedMessage, null, transaction.get());
break;
case SUSPENDED:
DeadLetterOptions deadLetterOptions = new DeadLetterOptions().setDeadLetterReason(deadLetterReason);
operation = receiver.deadLetter(receivedMessage, deadLetterOptions, transaction.get());
messagesPending.decrementAndGet();
break;
case DEFERRED:
operation = receiver.defer(receivedMessage, null, transaction.get());
break;
default:
throw logger.logExceptionAsError(new IllegalArgumentException(
"Disposition status not recognized for this test case: " + dispositionStatus));
}
StepVerifier.create(operation)
.verifyComplete();
StepVerifier.create(receiver.commitTransaction(transaction.get()))
.verifyComplete();
if (dispositionStatus == DispositionStatus.DEFERRED) {
messagesDeferredPending.add(receivedMessage.getSequenceNumber());
}
}
/**
* Verifies that we can do following on different clients i.e. sender and receiver. 1. create transaction using
* sender 2. receive and complete with transactionContext. 3. Commit this transaction using sender.
*/
@MethodSource("com.azure.messaging.servicebus.IntegrationTestBase
@ParameterizedTest
@Disabled
void transactionReceiveCompleteCommitMixClient(MessagingEntityType entityType) {
setSenderAndReceiver(entityType, 0, isSessionEnabled, true);
final String messageId = UUID.randomUUID().toString();
final ServiceBusMessage message = getMessage(messageId, isSessionEnabled);
sendMessage(message).block(TIMEOUT);
AtomicReference<ServiceBusTransactionContext> transaction = new AtomicReference<>();
StepVerifier.create(sender.createTransaction())
.assertNext(txn -> {
transaction.set(txn);
assertNotNull(transaction);
})
.verifyComplete();
assertNotNull(transaction.get());
final ServiceBusReceivedMessageContext receivedContext = receiver.receiveMessages().next().block(TIMEOUT);
assertNotNull(receivedContext);
final ServiceBusReceivedMessage receivedMessage = receivedContext.getMessage();
assertNotNull(receivedMessage);
StepVerifier.create(receiver.complete(receivedMessage, transaction.get()))
.verifyComplete();
StepVerifier.create(sender.commitTransaction(transaction.get()))
.verifyComplete();
}
/**
* Verifies that we can send and receive two messages.
*/
@MethodSource("com.azure.messaging.servicebus.IntegrationTestBase
@ParameterizedTest
void receiveTwoMessagesAutoComplete(MessagingEntityType entityType, boolean isSessionEnabled) {
setSenderAndReceiver(entityType, 0, isSessionEnabled);
final String messageId = UUID.randomUUID().toString();
final ServiceBusMessage message = getMessage(messageId, isSessionEnabled);
final List<ServiceBusReceivedMessage> receivedMessages = new ArrayList<>();
Mono.when(sendMessage(message), sendMessage(message)).block(TIMEOUT);
try {
StepVerifier.create(receiver.receiveMessages())
.assertNext(receivedMessage -> {
receivedMessages.add(receivedMessage.getMessage());
assertMessageEquals(receivedMessage, messageId, isSessionEnabled);
})
.assertNext(receivedMessage -> {
receivedMessages.add(receivedMessage.getMessage());
assertMessageEquals(receivedMessage, messageId, isSessionEnabled);
})
.thenCancel()
.verify();
} finally {
int numberCompleted = completeMessages(receiver, receivedMessages);
messagesPending.addAndGet(-numberCompleted);
}
}
/**
* Verifies that we can send and receive a message.
*/
@MethodSource("com.azure.messaging.servicebus.IntegrationTestBase
@ParameterizedTest
void receiveMessageAutoComplete(MessagingEntityType entityType, boolean isSessionEnabled) {
setSenderAndReceiver(entityType, 0, isSessionEnabled);
final String messageId = UUID.randomUUID().toString();
final ServiceBusMessage message = getMessage(messageId, isSessionEnabled);
final List<ServiceBusReceivedMessage> receivedMessages = new ArrayList<>();
sendMessage(message).block(TIMEOUT);
try {
StepVerifier.create(receiver.receiveMessages())
.assertNext(receivedMessage -> {
receivedMessages.add(receivedMessage.getMessage());
assertMessageEquals(receivedMessage, messageId, isSessionEnabled);
})
.thenCancel()
.verify();
} finally {
int numberCompleted = completeMessages(receiver, receivedMessages);
messagesPending.addAndGet(-numberCompleted);
}
}
/**
* Verifies that we can send and peek a message.
*/
@MethodSource("com.azure.messaging.servicebus.IntegrationTestBase
@ParameterizedTest
void peekMessage(MessagingEntityType entityType, boolean isSessionEnabled) {
setSenderAndReceiver(entityType, 1, isSessionEnabled);
final String messageId = UUID.randomUUID().toString();
final ServiceBusMessage message = getMessage(messageId, isSessionEnabled);
sendMessage(message).block(TIMEOUT);
StepVerifier.create(receiver.peekMessage())
.assertNext(receivedMessage -> assertMessageEquals(receivedMessage, messageId, isSessionEnabled))
.verifyComplete();
}
/**
* Verifies that we can schedule and receive a message.
*/
@MethodSource("com.azure.messaging.servicebus.IntegrationTestBase
@ParameterizedTest
void sendScheduledMessageAndReceive(MessagingEntityType entityType, boolean isSessionEnabled) {
setSenderAndReceiver(entityType, 0, isSessionEnabled);
final String messageId = UUID.randomUUID().toString();
final ServiceBusMessage message = getMessage(messageId, isSessionEnabled);
final OffsetDateTime scheduledEnqueueTime = OffsetDateTime.now().plusSeconds(2);
sender.scheduleMessage(message, scheduledEnqueueTime).block(TIMEOUT);
StepVerifier.create(Mono.delay(Duration.ofSeconds(3)).then(receiveAndDeleteReceiver.receiveMessages().next()))
.assertNext(receivedMessage -> {
assertMessageEquals(receivedMessage, messageId, isSessionEnabled);
messagesPending.decrementAndGet();
})
.verifyComplete();
}
/**
* Verifies that we can cancel a scheduled message.
*/
@MethodSource("com.azure.messaging.servicebus.IntegrationTestBase
@ParameterizedTest
void cancelScheduledMessage(MessagingEntityType entityType, boolean isSessionEnabled) {
setSenderAndReceiver(entityType, 0, isSessionEnabled);
final String messageId = UUID.randomUUID().toString();
final ServiceBusMessage message = getMessage(messageId, isSessionEnabled);
final OffsetDateTime scheduledEnqueueTime = OffsetDateTime.now().plusSeconds(10);
final Duration delayDuration = Duration.ofSeconds(3);
final Long sequenceNumber = sender.scheduleMessage(message, scheduledEnqueueTime).block(TIMEOUT);
logger.verbose("Scheduled the message, sequence number {}.", sequenceNumber);
assertNotNull(sequenceNumber);
Mono.delay(delayDuration)
.then(sender.cancelScheduledMessage(sequenceNumber))
.block(TIMEOUT);
messagesPending.decrementAndGet();
logger.verbose("Cancelled the scheduled message, sequence number {}.", sequenceNumber);
StepVerifier.create(receiver.receiveMessages().take(1))
.thenAwait(Duration.ofSeconds(5))
.thenCancel()
.verify();
}
/**
* Verifies that we can send and peek a message.
*/
@MethodSource("com.azure.messaging.servicebus.IntegrationTestBase
@ParameterizedTest
void peekFromSequenceNumberMessage(MessagingEntityType entityType, boolean isSessionEnabled) {
setSenderAndReceiver(entityType, 3, isSessionEnabled);
final String messageId = UUID.randomUUID().toString();
final ServiceBusMessage message = getMessage(messageId, isSessionEnabled);
sendMessage(message).block(TIMEOUT);
final ServiceBusReceivedMessageContext receivedContext = receiver.receiveMessages().next().block(TIMEOUT);
assertNotNull(receivedContext);
final ServiceBusReceivedMessage receivedMessage = receivedContext.getMessage();
assertNotNull(receivedMessage);
try {
StepVerifier.create(receiver.peekMessageAt(receivedMessage.getSequenceNumber()))
.assertNext(m -> {
assertEquals(receivedMessage.getSequenceNumber(), m.getSequenceNumber());
assertMessageEquals(m, messageId, isSessionEnabled);
})
.verifyComplete();
} finally {
receiver.complete(receivedMessage)
.block(Duration.ofSeconds(10));
messagesPending.decrementAndGet();
}
}
/**
* Verifies that we can send and peek a batch of messages and the sequence number is tracked correctly.
*/
@MethodSource("com.azure.messaging.servicebus.IntegrationTestBase
@ParameterizedTest
void peekBatchMessages(MessagingEntityType entityType, boolean isSessionEnabled) {
setSenderAndReceiver(entityType, TestUtils.USE_CASE_PEEK_BATCH_MESSAGES, isSessionEnabled);
final BiConsumer<ServiceBusReceivedMessage, Integer> checkCorrectMessage = (message, index) -> {
final Map<String, Object> properties = message.getApplicationProperties();
final Object value = properties.get(MESSAGE_POSITION_ID);
assertTrue(value instanceof Integer, "Did not contain correct position number: " + value);
final int position = (int) value;
assertEquals(index, position);
};
final String messageId = UUID.randomUUID().toString();
final List<ServiceBusMessage> messages = TestUtils.getServiceBusMessages(10, messageId, CONTENTS_BYTES);
if (isSessionEnabled) {
messages.forEach(m -> m.setSessionId(sessionId));
}
sendMessage(messages).block(TIMEOUT);
try {
StepVerifier.create(receiver.peekMessages(3))
.assertNext(message -> checkCorrectMessage.accept(message, 0))
.assertNext(message -> checkCorrectMessage.accept(message, 1))
.assertNext(message -> checkCorrectMessage.accept(message, 2))
.verifyComplete();
StepVerifier.create(receiver.peekMessages(4))
.assertNext(message -> checkCorrectMessage.accept(message, 3))
.assertNext(message -> checkCorrectMessage.accept(message, 4))
.assertNext(message -> checkCorrectMessage.accept(message, 5))
.assertNext(message -> checkCorrectMessage.accept(message, 6))
.verifyComplete();
StepVerifier.create(receiver.peekMessage())
.assertNext(message -> checkCorrectMessage.accept(message, 7))
.verifyComplete();
} finally {
receiveAndDeleteReceiver.receiveMessages()
.take(messages.size())
.blockLast(Duration.ofSeconds(15));
messagesPending.addAndGet(-messages.size());
}
}
/**
* Verifies that we can send and peek a batch of messages.
*/
@MethodSource("com.azure.messaging.servicebus.IntegrationTestBase
@ParameterizedTest
void peekBatchMessagesFromSequence(MessagingEntityType entityType) {
setSenderAndReceiver(entityType, TestUtils.USE_CASE_PEEK_MESSAGE_FROM_SEQUENCE, false);
final String messageId = UUID.randomUUID().toString();
final ServiceBusMessage message = getMessage(messageId, false);
final int maxMessages = 2;
final int fromSequenceNumber = 1;
Mono.when(sendMessage(message), sendMessage(message)).block(TIMEOUT);
StepVerifier.create(receiver.peekMessagesAt(maxMessages, fromSequenceNumber))
.expectNextCount(maxMessages)
.verifyComplete();
}
/**
* Verifies that we can dead-letter a message.
*/
@MethodSource("com.azure.messaging.servicebus.IntegrationTestBase
@ParameterizedTest
void deadLetterMessage(MessagingEntityType entityType, boolean isSessionEnabled) {
setSenderAndReceiver(entityType, 0, isSessionEnabled);
final String messageId = UUID.randomUUID().toString();
final ServiceBusMessage message = getMessage(messageId, isSessionEnabled);
sendMessage(message).block(TIMEOUT);
final ServiceBusReceivedMessageContext receivedContext = receiver.receiveMessages().next().block(TIMEOUT);
assertNotNull(receivedContext);
final ServiceBusReceivedMessage receivedMessage = receivedContext.getMessage();
assertNotNull(receivedMessage);
StepVerifier.create(receiver.deadLetter(receivedMessage))
.verifyComplete();
messagesPending.decrementAndGet();
}
@MethodSource("com.azure.messaging.servicebus.IntegrationTestBase
@ParameterizedTest
void receiveAndComplete(MessagingEntityType entityType, boolean isSessionEnabled) {
setSenderAndReceiver(entityType, 0, isSessionEnabled);
final String messageId = UUID.randomUUID().toString();
final ServiceBusMessage message = getMessage(messageId, isSessionEnabled);
sendMessage(message).block(TIMEOUT);
final ServiceBusReceivedMessageContext receivedContext = receiver.receiveMessages().next().block(TIMEOUT);
assertNotNull(receivedContext);
final ServiceBusReceivedMessage receivedMessage = receivedContext.getMessage();
assertNotNull(receivedMessage);
StepVerifier.create(receiver.complete(receivedMessage))
.verifyComplete();
messagesPending.decrementAndGet();
}
/**
* Verifies that we can renew message lock on a non-session receiver.
*/
@MethodSource("com.azure.messaging.servicebus.IntegrationTestBase
@ParameterizedTest
void receiveAndRenewLock(MessagingEntityType entityType) {
setSenderAndReceiver(entityType, 0, false);
final String messageId = UUID.randomUUID().toString();
final ServiceBusMessage message = getMessage(messageId, false);
sendMessage(message).block(TIMEOUT);
final ServiceBusReceivedMessageContext receivedContext = receiver.receiveMessages().next().block(TIMEOUT);
assertNotNull(receivedContext);
final ServiceBusReceivedMessage receivedMessage = receivedContext.getMessage();
assertNotNull(receivedMessage);
assertNotNull(receivedMessage.getLockedUntil());
final OffsetDateTime initialLock = receivedMessage.getLockedUntil();
logger.info("Received message. Seq: {}. lockedUntil: {}", receivedMessage.getSequenceNumber(), initialLock);
try {
StepVerifier.create(Mono.delay(Duration.ofSeconds(7))
.then(Mono.defer(() -> receiver.renewMessageLock(receivedMessage.getLockToken()))))
.assertNext(lockedUntil -> {
assertTrue(lockedUntil.isAfter(initialLock),
String.format("Updated lock is not after the initial Lock. updated: [%s]. initial:[%s]",
lockedUntil, initialLock));
})
.verifyComplete();
} finally {
logger.info("Completing message. Seq: {}.", receivedMessage.getSequenceNumber());
receiver.complete(receivedMessage)
.doOnSuccess(aVoid -> messagesPending.decrementAndGet())
.block(TIMEOUT);
}
}
/**
* Verifies that the lock can be automatically renewed.
*/
@Disabled("Auto-lock renewal is not enabled.")
@MethodSource("com.azure.messaging.servicebus.IntegrationTestBase
@ParameterizedTest
void autoRenewLockOnReceiveMessage(MessagingEntityType entityType, boolean isSessionEnabled) {
setSenderAndReceiver(entityType, 0, isSessionEnabled);
final String messageId = UUID.randomUUID().toString();
final ServiceBusMessage message = getMessage(messageId, isSessionEnabled);
sendMessage(message).block(TIMEOUT);
StepVerifier.create(receiver.receiveMessages().map(ServiceBusReceivedMessageContext::getMessage))
.assertNext(received -> {
assertNotNull(received.getLockedUntil());
assertNotNull(received.getLockToken());
logger.info("{}: lockToken[{}]. lockedUntil[{}]. now[{}]", received.getSequenceNumber(),
received.getLockToken(), received.getLockedUntil(), OffsetDateTime.now());
final OffsetDateTime initial = received.getLockedUntil();
final OffsetDateTime timeToStop = initial.plusSeconds(5);
OffsetDateTime latest = OffsetDateTime.MIN;
final AtomicInteger iteration = new AtomicInteger();
while (OffsetDateTime.now().isBefore(timeToStop)) {
logger.info("Iteration {}: {}. Time to stop: {}", iteration.incrementAndGet(), OffsetDateTime.now(), timeToStop);
try {
TimeUnit.SECONDS.sleep(4);
} catch (InterruptedException error) {
logger.error("Error occurred while sleeping: " + error);
}
assertNotNull(received.getLockedUntil());
latest = received.getLockedUntil();
}
try {
assertTrue(initial.isBefore(latest), String.format(
"Latest should be after or equal to initial. initial: %s. latest: %s", initial, latest));
} finally {
logger.info("Completing message.");
receiver.complete(received).block(Duration.ofSeconds(15));
messagesPending.decrementAndGet();
}
})
.thenCancel()
.verify(Duration.ofMinutes(2));
}
@MethodSource("com.azure.messaging.servicebus.IntegrationTestBase
@ParameterizedTest
void receiveAndAbandon(MessagingEntityType entityType, boolean isSessionEnabled) {
setSenderAndReceiver(entityType, 0, isSessionEnabled);
final String messageId = UUID.randomUUID().toString();
final ServiceBusMessage message = getMessage(messageId, isSessionEnabled);
sendMessage(message).block(TIMEOUT);
final ServiceBusReceivedMessageContext receivedContext = receiver.receiveMessages().next().block(TIMEOUT);
assertNotNull(receivedContext);
final ServiceBusReceivedMessage receivedMessage = receivedContext.getMessage();
assertNotNull(receivedMessage);
StepVerifier.create(receiver.abandon(receivedMessage))
.verifyComplete();
messagesPending.decrementAndGet();
}
@MethodSource("com.azure.messaging.servicebus.IntegrationTestBase
@ParameterizedTest
void receiveAndDefer(MessagingEntityType entityType, boolean isSessionEnabled) {
setSenderAndReceiver(entityType, TestUtils.USE_CASE_PEEK_RECEIVE_AND_DEFER, isSessionEnabled);
final String messageId = UUID.randomUUID().toString();
final ServiceBusMessage message = getMessage(messageId, isSessionEnabled);
sendMessage(message).block(TIMEOUT);
final ServiceBusReceivedMessageContext receivedContext = receiver.receiveMessages().next().block(TIMEOUT);
assertNotNull(receivedContext);
final ServiceBusReceivedMessage receivedMessage = receivedContext.getMessage();
assertNotNull(receivedMessage);
StepVerifier.create(receiver.defer(receivedMessage))
.verifyComplete();
messagesPending.decrementAndGet();
completeDeferredMessages(receiver, receivedMessage);
}
/**
* Test we can receive a deferred message via sequence number and then perform abandon, suspend, or complete on it.
*/
@MethodSource("com.azure.messaging.servicebus.IntegrationTestBase
@ParameterizedTest
void receiveDeferredMessageBySequenceNumber(MessagingEntityType entityType, DispositionStatus dispositionStatus) {
setSenderAndReceiver(entityType, 0, false);
final String messageId = UUID.randomUUID().toString();
final ServiceBusMessage message = getMessage(messageId, false);
sendMessage(message).block(TIMEOUT);
final ServiceBusReceivedMessageContext receivedContext = receiver.receiveMessages().next().block(TIMEOUT);
assertNotNull(receivedContext);
final ServiceBusReceivedMessage receivedMessage = receivedContext.getMessage();
assertNotNull(receivedMessage);
receiver.defer(receivedMessage).block(TIMEOUT);
final ServiceBusReceivedMessage receivedDeferredMessage = receiver
.receiveDeferredMessage(receivedMessage.getSequenceNumber())
.block(TIMEOUT);
assertNotNull(receivedDeferredMessage);
assertEquals(receivedMessage.getSequenceNumber(), receivedDeferredMessage.getSequenceNumber());
final Mono<Void> operation;
switch (dispositionStatus) {
case ABANDONED:
operation = receiver.abandon(receivedDeferredMessage);
messagesDeferredPending.add(receivedDeferredMessage.getSequenceNumber());
break;
case SUSPENDED:
operation = receiver.deadLetter(receivedDeferredMessage);
break;
case COMPLETED:
operation = receiver.complete(receivedDeferredMessage);
break;
default:
throw logger.logExceptionAsError(new IllegalArgumentException(
"Disposition status not recognized for this test case: " + dispositionStatus));
}
StepVerifier.create(operation)
.expectComplete()
.verify();
if (dispositionStatus != DispositionStatus.COMPLETED) {
messagesPending.decrementAndGet();
}
}
@MethodSource("com.azure.messaging.servicebus.IntegrationTestBase
@ParameterizedTest
void sendReceiveMessageWithVariousPropertyTypes(MessagingEntityType entityType) {
setSenderAndReceiver(entityType, TestUtils.USE_CASE_SEND_RECEIVE_WITH_PROPERTIES, isSessionEnabled);
final boolean isSessionEnabled = true;
final String messageId = UUID.randomUUID().toString();
final ServiceBusMessage messageToSend = getMessage(messageId, isSessionEnabled);
Map<String, Object> sentProperties = messageToSend.getApplicationProperties();
sentProperties.put("NullProperty", null);
sentProperties.put("BooleanProperty", true);
sentProperties.put("ByteProperty", (byte) 1);
sentProperties.put("ShortProperty", (short) 2);
sentProperties.put("IntProperty", 3);
sentProperties.put("LongProperty", 4L);
sentProperties.put("FloatProperty", 5.5f);
sentProperties.put("DoubleProperty", 6.6f);
sentProperties.put("CharProperty", 'z');
sentProperties.put("UUIDProperty", UUID.randomUUID());
sentProperties.put("StringProperty", "string");
sendMessage(messageToSend).block(TIMEOUT);
StepVerifier.create(receiveAndDeleteReceiver.receiveMessages())
.assertNext(receivedMessage -> {
messagesPending.decrementAndGet();
assertMessageEquals(receivedMessage, messageId, isSessionEnabled);
final Map<String, Object> received = receivedMessage.getMessage().getApplicationProperties();
assertEquals(sentProperties.size(), received.size());
for (Map.Entry<String, Object> sentEntry : sentProperties.entrySet()) {
if (sentEntry.getValue() != null && sentEntry.getValue().getClass().isArray()) {
assertArrayEquals((Object[]) sentEntry.getValue(), (Object[]) received.get(sentEntry.getKey()));
} else {
final Object expected = sentEntry.getValue();
final Object actual = received.get(sentEntry.getKey());
assertEquals(expected, actual, String.format(
"Key '%s' does not match. Expected: '%s'. Actual: '%s'", sentEntry.getKey(), expected,
actual));
}
}
})
.thenCancel()
.verify();
}
@MethodSource("com.azure.messaging.servicebus.IntegrationTestBase
@ParameterizedTest
void setAndGetSessionState(MessagingEntityType entityType) {
setSenderAndReceiver(entityType, 0, true);
final byte[] sessionState = "Finished".getBytes(UTF_8);
final String messageId = UUID.randomUUID().toString();
final ServiceBusMessage messageToSend = getMessage(messageId, true);
sendMessage(messageToSend).block(Duration.ofSeconds(10));
AtomicReference<ServiceBusReceivedMessage> receivedMessage = new AtomicReference<>();
StepVerifier.create(receiver.receiveMessages()
.take(1)
.flatMap(m -> {
logger.info("SessionId: {}. LockToken: {}. LockedUntil: {}. Message received.",
m.getSessionId(), m.getMessage().getLockToken(), m.getMessage().getLockedUntil());
receivedMessage.set(m.getMessage());
return receiver.setSessionState(sessionId, sessionState);
}))
.expectComplete()
.verify();
StepVerifier.create(receiver.getSessionState(sessionId))
.assertNext(state -> {
logger.info("State received: {}", new String(state, UTF_8));
assertArrayEquals(sessionState, state);
})
.verifyComplete();
receiver.complete(receivedMessage.get()).block(Duration.ofSeconds(15));
messagesPending.decrementAndGet();
}
/**
* Verifies that we can receive a message from dead letter queue.
*/
@MethodSource("com.azure.messaging.servicebus.IntegrationTestBase
@ParameterizedTest
void receiveFromDeadLetter(MessagingEntityType entityType) {
final boolean isSessionEnabled = false;
setSenderAndReceiver(entityType, 0, isSessionEnabled);
ServiceBusReceiverAsyncClient deadLetterReceiver = getDeadLetterReceiverBuilder(false, entityType,
0, Function.identity())
.buildAsyncClient();
final String messageId = UUID.randomUUID().toString();
final ServiceBusMessage message = getMessage(messageId, isSessionEnabled);
final List<ServiceBusReceivedMessage> receivedMessages = new ArrayList<>();
sendMessage(message).block(TIMEOUT);
final ServiceBusReceivedMessageContext receivedContext = receiver.receiveMessages().next()
.block(OPERATION_TIMEOUT);
assertNotNull(receivedContext);
final ServiceBusReceivedMessage receivedMessage = receivedContext.getMessage();
assertNotNull(receivedMessage);
StepVerifier.create(receiver.deadLetter(receivedMessage))
.verifyComplete();
try {
StepVerifier.create(deadLetterReceiver.receiveMessages().take(1))
.assertNext(messageContext -> {
receivedMessages.add(messageContext.getMessage());
assertMessageEquals(receivedMessage, messageId, isSessionEnabled);
})
.thenCancel()
.verify();
} finally {
int numberCompleted = completeMessages(deadLetterReceiver, receivedMessages);
messagesPending.addAndGet(-numberCompleted);
}
}
@MethodSource("com.azure.messaging.servicebus.IntegrationTestBase
@ParameterizedTest
void renewMessageLock(MessagingEntityType entityType) throws InterruptedException {
final boolean isSessionEnabled = false;
setSenderAndReceiver(entityType, 0, isSessionEnabled);
final Duration maximumDuration = Duration.ofSeconds(35);
final Duration sleepDuration = maximumDuration.plusMillis(500);
final String messageId = UUID.randomUUID().toString();
final ServiceBusMessage message = getMessage(messageId, isSessionEnabled);
final ServiceBusReceivedMessageContext receivedContext = sendMessage(message)
.then(receiver.receiveMessages().next())
.block(TIMEOUT);
assertNotNull(receivedContext);
final ServiceBusReceivedMessage receivedMessage = receivedContext.getMessage();
assertNotNull(receivedMessage);
final OffsetDateTime lockedUntil = receivedMessage.getLockedUntil();
assertNotNull(lockedUntil);
StepVerifier.create(receiver.getAutoRenewMessageLock(receivedMessage.getLockToken(), maximumDuration))
.thenAwait(sleepDuration)
.then(() -> {
logger.info("Completing message.");
int numberCompleted = completeMessages(receiver, Collections.singletonList(receivedMessage));
messagesPending.addAndGet(-numberCompleted);
})
.expectComplete()
.verify(Duration.ofMinutes(3));
}
/**
* Verifies that we can receive a message which have different section set (i.e header, footer, annotations,
* application properties etc).
*/
@MethodSource("com.azure.messaging.servicebus.IntegrationTestBase
@ParameterizedTest
/**
* Asserts the length and values with in the map.
*/
private void assertMapValues(Map<String, Object> expectedMap, Map<String, Object> actualMap) {
assertTrue(actualMap.size() >= expectedMap.size());
Iterator<String> expectedKeys = expectedMap.keySet().iterator();
while (expectedKeys.hasNext()) {
String key = expectedKeys.next();
assertEquals(expectedMap.get(key), actualMap.get(key), "Value is not equal for Key " + key);
}
}
/**
* Sets the sender and receiver. If session is enabled, then a single-named session receiver is created.
*/
private void setSenderAndReceiver(MessagingEntityType entityType, int entityIndex, boolean isSessionEnabled) {
setSenderAndReceiver(entityType, entityIndex, isSessionEnabled, false);
}
/**
* Sets the sender and receiver. If session is enabled, then a single-named session receiver is created with shared
* connection as needed.
*/
private void setSenderAndReceiver(MessagingEntityType entityType, int entityIndex, boolean isSessionEnabled,
boolean shareConnection) {
this.sender = getSenderBuilder(false, entityType, entityIndex, isSessionEnabled, shareConnection)
.buildAsyncClient();
if (isSessionEnabled) {
assertNotNull(sessionId, "'sessionId' should have been set.");
this.receiver = getSessionReceiverBuilder(false, entityType, entityIndex, Function.identity(),
shareConnection)
.sessionId(sessionId)
.buildAsyncClient();
this.receiveAndDeleteReceiver = getSessionReceiverBuilder(false, entityType, entityIndex,
Function.identity(), shareConnection)
.sessionId(sessionId)
.receiveMode(ReceiveMode.RECEIVE_AND_DELETE)
.buildAsyncClient();
} else {
this.receiver = getReceiverBuilder(false, entityType, entityIndex, Function.identity(),
shareConnection)
.buildAsyncClient();
this.receiveAndDeleteReceiver = getReceiverBuilder(false, entityType, entityIndex,
Function.identity(), shareConnection)
.receiveMode(ReceiveMode.RECEIVE_AND_DELETE)
.buildAsyncClient();
}
}
private Mono<Void> sendMessage(ServiceBusMessage message) {
return sender.sendMessage(message).doOnSuccess(aVoid -> {
int number = messagesPending.incrementAndGet();
logger.info("Message Id {}. Number sent: {}", message.getMessageId(), number);
});
}
private Mono<Void> sendMessage(List<ServiceBusMessage> messages) {
return sender.sendMessages(messages).doOnSuccess(aVoid -> {
int number = messagesPending.addAndGet(messages.size());
logger.info("Number of messages sent: {}", number);
});
}
private int completeMessages(ServiceBusReceiverAsyncClient client, List<ServiceBusReceivedMessage> lockTokens) {
Mono.when(lockTokens.stream().map(e -> client.complete(e))
.collect(Collectors.toList()))
.block(TIMEOUT);
return lockTokens.size();
}
private void completeDeferredMessages(ServiceBusReceiverAsyncClient client, ServiceBusReceivedMessage receivedMessage) {
final ServiceBusReceivedMessage receivedDeferredMessage = client
.receiveDeferredMessage(receivedMessage.getSequenceNumber())
.block(TIMEOUT);
assertNotNull(receivedDeferredMessage);
receiver.complete(receivedDeferredMessage).block(TIMEOUT);
}
private ServiceBusClientBuilder.ServiceBusReceiverClientBuilder getDeadLetterReceiverBuilder(boolean useCredentials,
MessagingEntityType entityType, int entityIndex, Function<ServiceBusClientBuilder, ServiceBusClientBuilder> onBuilderCreate) {
ServiceBusClientBuilder builder = getBuilder(useCredentials);
builder = onBuilderCreate.apply(builder);
switch (entityType) {
case QUEUE:
final String queueName = getQueueName(entityIndex);
assertNotNull(queueName, "'queueName' cannot be null.");
return builder.receiver().queueName(queueName).subQueue(SubQueue.DEAD_LETTER_QUEUE);
case SUBSCRIPTION:
final String topicName = getTopicName(entityIndex);
final String subscriptionName = getSubscriptionBaseName();
assertNotNull(topicName, "'topicName' cannot be null.");
assertNotNull(subscriptionName, "'subscriptionName' cannot be null.");
return builder.receiver().topicName(topicName).subscriptionName(subscriptionName).subQueue(SubQueue.DEAD_LETTER_QUEUE);
default:
throw logger.logExceptionAsError(new IllegalArgumentException("Unknown entity type: " + entityType));
}
}
} |
```suggestion var value = amqpAnnotatedMessage.getMessageAnnotations().get(SCHEDULED_ENQUEUE_UTC_TIME_NAME.getValue()); return value != null ? ((Date) value).toInstant().atOffset(ZoneOffset.UTC) : null; ``` | public OffsetDateTime getScheduledEnqueueTime() {
OffsetDateTime scheduledEnqueueTime = null;
Map<String, Object> messageAnnotationMap = amqpAnnotatedMessage.getMessageAnnotations();
if (messageAnnotationMap.containsKey(SCHEDULED_ENQUEUE_UTC_TIME_NAME.getValue())) {
scheduledEnqueueTime = ((Date) messageAnnotationMap.get(SCHEDULED_ENQUEUE_UTC_TIME_NAME.getValue()))
.toInstant().atOffset(ZoneOffset.UTC);
}
return scheduledEnqueueTime;
} | Map<String, Object> messageAnnotationMap = amqpAnnotatedMessage.getMessageAnnotations(); | public OffsetDateTime getScheduledEnqueueTime() {
Object value = amqpAnnotatedMessage.getMessageAnnotations().get(SCHEDULED_ENQUEUE_UTC_TIME_NAME.getValue());
return value != null
? ((Date) value).toInstant().atOffset(ZoneOffset.UTC)
: null;
} | class ServiceBusMessage {
private final AmqpAnnotatedMessage amqpAnnotatedMessage;
private final ClientLogger logger = new ClientLogger(ServiceBusMessage.class);
private final byte[] binaryData;
private Context context;
/**
* Creates a {@link ServiceBusMessage} with a {@link java.nio.charset.StandardCharsets
*
* @param body The content of the Service bus message.
*
* @throws NullPointerException if {@code body} is null.
*/
public ServiceBusMessage(String body) {
this(Objects.requireNonNull(body, "'body' cannot be null.").getBytes(StandardCharsets.UTF_8));
}
/**
* Creates a {@link ServiceBusMessage} containing the {@code body}.
*
* @param body The data to set for this {@link ServiceBusMessage}.
*
* @throws NullPointerException if {@code body} is {@code null}.
*/
public ServiceBusMessage(byte[] body) {
this.binaryData = Objects.requireNonNull(body, "'body' cannot be null.");
this.context = Context.NONE;
this.amqpAnnotatedMessage = new AmqpAnnotatedMessage(new AmqpDataBody(Collections.singletonList(
new BinaryData(binaryData))));
}
/**
* Creates a {@link ServiceBusMessage} using properties from {@code receivedMessage}. This is normally used when a
* {@link ServiceBusReceivedMessage} needs to be sent to another entity.
*
* @param receivedMessage The received message to create new message from.
*
* @throws NullPointerException if {@code receivedMessage} is {@code null}.
*/
public ServiceBusMessage(ServiceBusReceivedMessage receivedMessage) {
Objects.requireNonNull(receivedMessage, "'receivedMessage' cannot be null.");
this.amqpAnnotatedMessage = new AmqpAnnotatedMessage(receivedMessage.getAmqpAnnotatedMessage());
this.context = Context.NONE;
this.binaryData = receivedMessage.getBody();
amqpAnnotatedMessage.getHeader().setDeliveryCount(null);
removeValues(amqpAnnotatedMessage.getMessageAnnotations(), LOCKED_UNTIL_KEY_ANNOTATION_NAME,
SEQUENCE_NUMBER_ANNOTATION_NAME, DEAD_LETTER_SOURCE_KEY_ANNOTATION_NAME,
ENQUEUED_SEQUENCE_NUMBER_ANNOTATION_NAME, ENQUEUED_TIME_UTC_ANNOTATION_NAME);
removeValues(amqpAnnotatedMessage.getApplicationProperties(), DEAD_LETTER_DESCRIPTION_ANNOTATION_NAME,
DEAD_LETTER_REASON_ANNOTATION_NAME);
}
/**
* Gets the {@link AmqpAnnotatedMessage}.
*
* @return the amqp message.
*/
public AmqpAnnotatedMessage getAmqpAnnotatedMessage() {
return amqpAnnotatedMessage;
}
/**
* Gets the set of free-form {@link ServiceBusMessage} properties which may be used for passing metadata associated
* with the {@link ServiceBusMessage} during Service Bus operations. A common use-case for
* {@code getApplicationProperties()} is to associate serialization hints for the {@link
* consumers who wish to deserialize the binary data.
*
* @return Application properties associated with this {@link ServiceBusMessage}.
*/
public Map<String, Object> getApplicationProperties() {
return amqpAnnotatedMessage.getApplicationProperties();
}
/**
* Gets the actual payload/data wrapped by the {@link ServiceBusMessage}.
*
* <p>
* If the means for deserializing the raw data is not apparent to consumers, a common technique is to make use of
* {@link
* consumers who wish to deserialize the binary data.
* </p>
*
* @return A byte array representing the data.
*/
public byte[] getBody() {
final AmqpBodyType type = amqpAnnotatedMessage.getBody().getBodyType();
switch (type) {
case DATA:
return Arrays.copyOf(binaryData, binaryData.length);
case SEQUENCE:
case VALUE:
throw logger.logExceptionAsError(new UnsupportedOperationException("Not supported AmqpBodyType: "
+ type.toString()));
default:
throw logger.logExceptionAsError(new IllegalArgumentException("Unknown AmqpBodyType: "
+ type.toString()));
}
}
/**
* Gets the content type of the message.
*
* @return the contentType of the {@link ServiceBusMessage}.
*/
public String getContentType() {
return amqpAnnotatedMessage.getProperties().getContentType();
}
/**
* Sets the content type of the {@link ServiceBusMessage}.
*
* @param contentType of the message.
*
* @return The updated {@link ServiceBusMessage}.
*/
public ServiceBusMessage setContentType(String contentType) {
amqpAnnotatedMessage.getProperties().setContentType(contentType);
return this;
}
/**
* Gets a correlation identifier.
* <p>
* Allows an application to specify a context for the message for the purposes of correlation, for example
* reflecting the MessageId of a message that is being replied to.
* </p>
*
* @return correlation id of this message
* @see <a href="https:
* Routing and Correlation</a>
*/
public String getCorrelationId() {
return amqpAnnotatedMessage.getProperties().getCorrelationId();
}
/**
* Sets a correlation identifier.
*
* @param correlationId correlation id of this message
*
* @return The updated {@link ServiceBusMessage}.
* @see
*/
public ServiceBusMessage setCorrelationId(String correlationId) {
amqpAnnotatedMessage.getProperties().setCorrelationId(correlationId);
return this;
}
/**
* Gets the subject for the message.
*
* @return The subject for the message.
*/
public String getSubject() {
return amqpAnnotatedMessage.getProperties().getSubject();
}
/**
* Sets the subject for the message.
*
* @param subject The subject to set.
*
* @return The updated {@link ServiceBusMessage} object.
*/
public ServiceBusMessage setSubject(String subject) {
amqpAnnotatedMessage.getProperties().setSubject(subject);
return this;
}
/**
* @return Id of the {@link ServiceBusMessage}.
*/
public String getMessageId() {
return amqpAnnotatedMessage.getProperties().getMessageId();
}
/**
* Sets the message id.
*
* @param messageId to be set.
*
* @return The updated {@link ServiceBusMessage}.
*/
public ServiceBusMessage setMessageId(String messageId) {
amqpAnnotatedMessage.getProperties().setMessageId(messageId);
return this;
}
/**
* Gets the partition key for sending a message to a partitioned entity.
* <p>
* For <a href="https:
* entities</a>, setting this value enables assigning related messages to the same internal partition, so that
* submission sequence order is correctly recorded. The partition is chosen by a hash function over this value and
* cannot be chosen directly. For session-aware entities, the {@link
* this value.
*
* @return The partition key of this message
* @see <a href="https:
* entities</a>
*/
public String getPartitionKey() {
return (String) amqpAnnotatedMessage.getMessageAnnotations().get(PARTITION_KEY_ANNOTATION_NAME.getValue());
}
/**
* Sets a partition key for sending a message to a partitioned entity
*
* @param partitionKey partition key of this message
*
* @return The updated {@link ServiceBusMessage}.
* @see
*/
public ServiceBusMessage setPartitionKey(String partitionKey) {
amqpAnnotatedMessage.getMessageAnnotations().put(PARTITION_KEY_ANNOTATION_NAME.getValue(), partitionKey);
return this;
}
/**
* Gets the address of an entity to send replies to.
* <p>
* This optional and application-defined value is a standard way to express a reply path to the receiver of the
* message. When a sender expects a reply, it sets the value to the absolute or relative path of the queue or topic
* it expects the reply to be sent to.
*
* @return ReplyTo property value of this message
* @see <a href="https:
* Routing and Correlation</a>
*/
public String getReplyTo() {
return amqpAnnotatedMessage.getProperties().getReplyTo();
}
/**
* Sets the address of an entity to send replies to.
*
* @param replyTo ReplyTo property value of this message
*
* @return The updated {@link ServiceBusMessage}.
* @see
*/
public ServiceBusMessage setReplyTo(String replyTo) {
amqpAnnotatedMessage.getProperties().setReplyTo(replyTo);
return this;
}
/**
* Gets the "to" address.
*
* @return "To" property value of this message
*/
public String getTo() {
return amqpAnnotatedMessage.getProperties().getTo();
}
/**
* Sets the "to" address.
* <p>
* This property is reserved for future use in routing scenarios and presently ignored by the broker itself.
* Applications can use this value in rule-driven
* <a href="https:
* chaining</a> scenarios to indicate the intended logical destination of the message.
*
* @param to To property value of this message
*
* @return The updated {@link ServiceBusMessage}.
*/
public ServiceBusMessage setTo(String to) {
amqpAnnotatedMessage.getProperties().setTo(to);
return this;
}
/**
* Gets the duration before this message expires.
* <p>
* This value is the relative duration after which the message expires, starting from the instant the message has
* been accepted and stored by the broker, as captured in {@link
* explicitly, the assumed value is the DefaultTimeToLive set for the respective queue or topic. A message-level
* TimeToLive value cannot be longer than the entity's DefaultTimeToLive setting and it is silently adjusted if it
* does.
*
* @return Time to live duration of this message
* @see <a href="https:
*/
public Duration getTimeToLive() {
return amqpAnnotatedMessage.getHeader().getTimeToLive();
}
/**
* Sets the duration of time before this message expires.
*
* @param timeToLive Time to Live duration of this message
*
* @return The updated {@link ServiceBusMessage}.
* @see
*/
public ServiceBusMessage setTimeToLive(Duration timeToLive) {
amqpAnnotatedMessage.getHeader().setTimeToLive(timeToLive);
return this;
}
/**
* Gets the scheduled enqueue time of this message.
* <p>
* This value is used for delayed message availability. The message is safely added to the queue, but is not
* considered active and therefore not retrievable until the scheduled enqueue time. Mind that the message may not
* be activated (enqueued) at the exact given datetime; the actual activation time depends on the queue's workload
* and its state.
* </p>
*
* @return the datetime at which the message will be enqueued in Azure Service Bus
* @see <a href="https:
* Timestamps</a>
*/
/**
* Sets the scheduled enqueue time of this message.
*
* @param scheduledEnqueueTime the datetime at which this message should be enqueued in Azure Service Bus.
*
* @return The updated {@link ServiceBusMessage}.
* @see
*/
public ServiceBusMessage setScheduledEnqueueTime(OffsetDateTime scheduledEnqueueTime) {
if (scheduledEnqueueTime != null) {
amqpAnnotatedMessage.getMessageAnnotations().put(SCHEDULED_ENQUEUE_UTC_TIME_NAME.getValue(),
scheduledEnqueueTime);
}
return this;
}
/**
* Gets or sets a session identifier augmenting the {@link
* <p>
* This value augments the ReplyTo information and specifies which SessionId should be set for the reply when sent
* to the reply entity.
*
* @return ReplyToSessionId property value of this message
* @see <a href="https:
* Routing and Correlation</a>
*/
public String getReplyToSessionId() {
return amqpAnnotatedMessage.getProperties().getReplyToGroupId();
}
/**
* Gets or sets a session identifier augmenting the {@link
*
* @param replyToSessionId ReplyToSessionId property value of this message
*
* @return The updated {@link ServiceBusMessage}.
*/
public ServiceBusMessage setReplyToSessionId(String replyToSessionId) {
amqpAnnotatedMessage.getProperties().setReplyToGroupId(replyToSessionId);
return this;
}
/**
* Gets the partition key for sending a message to a entity via another partitioned transfer entity.
*
* If a message is sent via a transfer queue in the scope of a transaction, this value selects the transfer queue
* partition: This is functionally equivalent to {@link
* together and in order as they are transferred.
*
* @return partition key on the via queue.
* @see <a href="https:
* and Send Via</a>
*/
public String getViaPartitionKey() {
return (String) amqpAnnotatedMessage.getMessageAnnotations().get(VIA_PARTITION_KEY_ANNOTATION_NAME.getValue());
}
/**
* Sets a via-partition key for sending a message to a destination entity via another partitioned entity
*
* @param viaPartitionKey via-partition key of this message
*
* @return The updated {@link ServiceBusMessage}.
* @see
*/
public ServiceBusMessage setViaPartitionKey(String viaPartitionKey) {
amqpAnnotatedMessage.getMessageAnnotations().put(VIA_PARTITION_KEY_ANNOTATION_NAME.getValue(), viaPartitionKey);
return this;
}
/**
* Gets the session id of the message.
*
* @return Session Id of the {@link ServiceBusMessage}.
*/
public String getSessionId() {
return amqpAnnotatedMessage.getProperties().getGroupId();
}
/**
* Sets the session id.
*
* @param sessionId to be set.
*
* @return The updated {@link ServiceBusMessage}.
*/
public ServiceBusMessage setSessionId(String sessionId) {
amqpAnnotatedMessage.getProperties().setGroupId(sessionId);
return this;
}
/**
* A specified key-value pair of type {@link Context} to set additional information on the {@link
* ServiceBusMessage}.
*
* @return the {@link Context} object set on the {@link ServiceBusMessage}.
*/
Context getContext() {
return context;
}
/**
* Adds a new key value pair to the existing context on Message.
*
* @param key The key for this context object
* @param value The value for this context object.
*
* @return The updated {@link ServiceBusMessage}.
* @throws NullPointerException if {@code key} or {@code value} is null.
*/
public ServiceBusMessage addContext(String key, Object value) {
Objects.requireNonNull(key, "The 'key' parameter cannot be null.");
Objects.requireNonNull(value, "The 'value' parameter cannot be null.");
this.context = context.addData(key, value);
return this;
}
/*
* Gets value from given map.
*/
private void removeValues(Map<String, Object> dataMap, AmqpMessageConstant... keys) {
for (AmqpMessageConstant key : keys) {
dataMap.remove(key.getValue());
}
}
} | class ServiceBusMessage {
private final AmqpAnnotatedMessage amqpAnnotatedMessage;
private final ClientLogger logger = new ClientLogger(ServiceBusMessage.class);
private final byte[] binaryData;
private Context context;
/**
* Creates a {@link ServiceBusMessage} with a {@link java.nio.charset.StandardCharsets
*
* @param body The content of the Service bus message.
*
* @throws NullPointerException if {@code body} is null.
*/
public ServiceBusMessage(String body) {
this(Objects.requireNonNull(body, "'body' cannot be null.").getBytes(StandardCharsets.UTF_8));
}
/**
* Creates a {@link ServiceBusMessage} containing the {@code body}.
*
* @param body The data to set for this {@link ServiceBusMessage}.
*
* @throws NullPointerException if {@code body} is {@code null}.
*/
public ServiceBusMessage(byte[] body) {
this.binaryData = Objects.requireNonNull(body, "'body' cannot be null.");
this.context = Context.NONE;
this.amqpAnnotatedMessage = new AmqpAnnotatedMessage(new AmqpDataBody(Collections.singletonList(
new BinaryData(binaryData))));
}
/**
* Creates a {@link ServiceBusMessage} using properties from {@code receivedMessage}. This is normally used when a
* {@link ServiceBusReceivedMessage} needs to be sent to another entity.
*
* @param receivedMessage The received message to create new message from.
*
* @throws NullPointerException if {@code receivedMessage} is {@code null}.
*/
public ServiceBusMessage(ServiceBusReceivedMessage receivedMessage) {
Objects.requireNonNull(receivedMessage, "'receivedMessage' cannot be null.");
this.amqpAnnotatedMessage = new AmqpAnnotatedMessage(receivedMessage.getAmqpAnnotatedMessage());
this.context = Context.NONE;
this.binaryData = receivedMessage.getBody();
amqpAnnotatedMessage.getHeader().setDeliveryCount(null);
removeValues(amqpAnnotatedMessage.getMessageAnnotations(), LOCKED_UNTIL_KEY_ANNOTATION_NAME,
SEQUENCE_NUMBER_ANNOTATION_NAME, DEAD_LETTER_SOURCE_KEY_ANNOTATION_NAME,
ENQUEUED_SEQUENCE_NUMBER_ANNOTATION_NAME, ENQUEUED_TIME_UTC_ANNOTATION_NAME);
removeValues(amqpAnnotatedMessage.getApplicationProperties(), DEAD_LETTER_DESCRIPTION_ANNOTATION_NAME,
DEAD_LETTER_REASON_ANNOTATION_NAME);
}
/**
* Gets the {@link AmqpAnnotatedMessage}.
*
* @return the amqp message.
*/
public AmqpAnnotatedMessage getAmqpAnnotatedMessage() {
return amqpAnnotatedMessage;
}
/**
* Gets the set of free-form {@link ServiceBusMessage} properties which may be used for passing metadata associated
* with the {@link ServiceBusMessage} during Service Bus operations. A common use-case for
* {@code getApplicationProperties()} is to associate serialization hints for the {@link
* consumers who wish to deserialize the binary data.
*
* @return Application properties associated with this {@link ServiceBusMessage}.
*/
public Map<String, Object> getApplicationProperties() {
return amqpAnnotatedMessage.getApplicationProperties();
}
/**
* Gets the actual payload/data wrapped by the {@link ServiceBusMessage}.
*
* <p>
* If the means for deserializing the raw data is not apparent to consumers, a common technique is to make use of
* {@link
* consumers who wish to deserialize the binary data.
* </p>
*
* @return A byte array representing the data.
*/
public byte[] getBody() {
final AmqpBodyType type = amqpAnnotatedMessage.getBody().getBodyType();
switch (type) {
case DATA:
return Arrays.copyOf(binaryData, binaryData.length);
case SEQUENCE:
case VALUE:
throw logger.logExceptionAsError(new UnsupportedOperationException("Not supported AmqpBodyType: "
+ type.toString()));
default:
throw logger.logExceptionAsError(new IllegalArgumentException("Unknown AmqpBodyType: "
+ type.toString()));
}
}
/**
* Gets the content type of the message.
*
* @return the contentType of the {@link ServiceBusMessage}.
*/
public String getContentType() {
return amqpAnnotatedMessage.getProperties().getContentType();
}
/**
* Sets the content type of the {@link ServiceBusMessage}.
*
* @param contentType of the message.
*
* @return The updated {@link ServiceBusMessage}.
*/
public ServiceBusMessage setContentType(String contentType) {
amqpAnnotatedMessage.getProperties().setContentType(contentType);
return this;
}
/**
* Gets a correlation identifier.
* <p>
* Allows an application to specify a context for the message for the purposes of correlation, for example
* reflecting the MessageId of a message that is being replied to.
* </p>
*
* @return correlation id of this message
* @see <a href="https:
* Routing and Correlation</a>
*/
public String getCorrelationId() {
return amqpAnnotatedMessage.getProperties().getCorrelationId();
}
/**
* Sets a correlation identifier.
*
* @param correlationId correlation id of this message
*
* @return The updated {@link ServiceBusMessage}.
* @see
*/
public ServiceBusMessage setCorrelationId(String correlationId) {
amqpAnnotatedMessage.getProperties().setCorrelationId(correlationId);
return this;
}
/**
* Gets the subject for the message.
*
* @return The subject for the message.
*/
public String getSubject() {
return amqpAnnotatedMessage.getProperties().getSubject();
}
/**
* Sets the subject for the message.
*
* @param subject The subject to set.
*
* @return The updated {@link ServiceBusMessage} object.
*/
public ServiceBusMessage setSubject(String subject) {
amqpAnnotatedMessage.getProperties().setSubject(subject);
return this;
}
/**
* @return Id of the {@link ServiceBusMessage}.
*/
public String getMessageId() {
return amqpAnnotatedMessage.getProperties().getMessageId();
}
/**
* Sets the message id.
*
* @param messageId to be set.
*
* @return The updated {@link ServiceBusMessage}.
*/
public ServiceBusMessage setMessageId(String messageId) {
amqpAnnotatedMessage.getProperties().setMessageId(messageId);
return this;
}
/**
* Gets the partition key for sending a message to a partitioned entity.
* <p>
* For <a href="https:
* entities</a>, setting this value enables assigning related messages to the same internal partition, so that
* submission sequence order is correctly recorded. The partition is chosen by a hash function over this value and
* cannot be chosen directly. For session-aware entities, the {@link
* this value.
*
* @return The partition key of this message
* @see <a href="https:
* entities</a>
*/
public String getPartitionKey() {
return (String) amqpAnnotatedMessage.getMessageAnnotations().get(PARTITION_KEY_ANNOTATION_NAME.getValue());
}
/**
* Sets a partition key for sending a message to a partitioned entity
*
* @param partitionKey partition key of this message
*
* @return The updated {@link ServiceBusMessage}.
* @see
*/
public ServiceBusMessage setPartitionKey(String partitionKey) {
amqpAnnotatedMessage.getMessageAnnotations().put(PARTITION_KEY_ANNOTATION_NAME.getValue(), partitionKey);
return this;
}
/**
* Gets the address of an entity to send replies to.
* <p>
* This optional and application-defined value is a standard way to express a reply path to the receiver of the
* message. When a sender expects a reply, it sets the value to the absolute or relative path of the queue or topic
* it expects the reply to be sent to.
*
* @return ReplyTo property value of this message
* @see <a href="https:
* Routing and Correlation</a>
*/
public String getReplyTo() {
return amqpAnnotatedMessage.getProperties().getReplyTo();
}
/**
* Sets the address of an entity to send replies to.
*
* @param replyTo ReplyTo property value of this message
*
* @return The updated {@link ServiceBusMessage}.
* @see
*/
public ServiceBusMessage setReplyTo(String replyTo) {
amqpAnnotatedMessage.getProperties().setReplyTo(replyTo);
return this;
}
/**
* Gets the "to" address.
*
* @return "To" property value of this message
*/
public String getTo() {
return amqpAnnotatedMessage.getProperties().getTo();
}
/**
* Sets the "to" address.
* <p>
* This property is reserved for future use in routing scenarios and presently ignored by the broker itself.
* Applications can use this value in rule-driven
* <a href="https:
* chaining</a> scenarios to indicate the intended logical destination of the message.
*
* @param to To property value of this message
*
* @return The updated {@link ServiceBusMessage}.
*/
public ServiceBusMessage setTo(String to) {
amqpAnnotatedMessage.getProperties().setTo(to);
return this;
}
/**
* Gets the duration before this message expires.
* <p>
* This value is the relative duration after which the message expires, starting from the instant the message has
* been accepted and stored by the broker, as captured in {@link
* explicitly, the assumed value is the DefaultTimeToLive set for the respective queue or topic. A message-level
* TimeToLive value cannot be longer than the entity's DefaultTimeToLive setting and it is silently adjusted if it
* does.
*
* @return Time to live duration of this message
* @see <a href="https:
*/
public Duration getTimeToLive() {
return amqpAnnotatedMessage.getHeader().getTimeToLive();
}
/**
* Sets the duration of time before this message expires.
*
* @param timeToLive Time to Live duration of this message
*
* @return The updated {@link ServiceBusMessage}.
* @see
*/
public ServiceBusMessage setTimeToLive(Duration timeToLive) {
amqpAnnotatedMessage.getHeader().setTimeToLive(timeToLive);
return this;
}
/**
* Gets the scheduled enqueue time of this message.
* <p>
* This value is used for delayed message availability. The message is safely added to the queue, but is not
* considered active and therefore not retrievable until the scheduled enqueue time. Mind that the message may not
* be activated (enqueued) at the exact given datetime; the actual activation time depends on the queue's workload
* and its state.
* </p>
*
* @return the datetime at which the message will be enqueued in Azure Service Bus
* @see <a href="https:
* Timestamps</a>
*/
/**
* Sets the scheduled enqueue time of this message. A {@code null} will not be set. If this value needs to be unset
* it could be done by value removing from {@link AmqpAnnotatedMessage
* {@link AmqpMessageConstant
*
* @param scheduledEnqueueTime the datetime at which this message should be enqueued in Azure Service Bus.
*
* @return The updated {@link ServiceBusMessage}.
* @see
*/
public ServiceBusMessage setScheduledEnqueueTime(OffsetDateTime scheduledEnqueueTime) {
if (scheduledEnqueueTime != null) {
amqpAnnotatedMessage.getMessageAnnotations().put(SCHEDULED_ENQUEUE_UTC_TIME_NAME.getValue(),
scheduledEnqueueTime);
}
return this;
}
/**
* Gets or sets a session identifier augmenting the {@link
* <p>
* This value augments the ReplyTo information and specifies which SessionId should be set for the reply when sent
* to the reply entity.
*
* @return ReplyToSessionId property value of this message
* @see <a href="https:
* Routing and Correlation</a>
*/
public String getReplyToSessionId() {
return amqpAnnotatedMessage.getProperties().getReplyToGroupId();
}
/**
* Gets or sets a session identifier augmenting the {@link
*
* @param replyToSessionId ReplyToSessionId property value of this message
*
* @return The updated {@link ServiceBusMessage}.
*/
public ServiceBusMessage setReplyToSessionId(String replyToSessionId) {
amqpAnnotatedMessage.getProperties().setReplyToGroupId(replyToSessionId);
return this;
}
/**
* Gets the partition key for sending a message to a entity via another partitioned transfer entity.
*
* If a message is sent via a transfer queue in the scope of a transaction, this value selects the transfer queue
* partition: This is functionally equivalent to {@link
* together and in order as they are transferred.
*
* @return partition key on the via queue.
* @see <a href="https:
* and Send Via</a>
*/
public String getViaPartitionKey() {
return (String) amqpAnnotatedMessage.getMessageAnnotations().get(VIA_PARTITION_KEY_ANNOTATION_NAME.getValue());
}
/**
* Sets a via-partition key for sending a message to a destination entity via another partitioned entity
*
* @param viaPartitionKey via-partition key of this message
*
* @return The updated {@link ServiceBusMessage}.
* @see
*/
public ServiceBusMessage setViaPartitionKey(String viaPartitionKey) {
amqpAnnotatedMessage.getMessageAnnotations().put(VIA_PARTITION_KEY_ANNOTATION_NAME.getValue(), viaPartitionKey);
return this;
}
/**
* Gets the session id of the message.
*
* @return Session Id of the {@link ServiceBusMessage}.
*/
public String getSessionId() {
return amqpAnnotatedMessage.getProperties().getGroupId();
}
/**
* Sets the session id.
*
* @param sessionId to be set.
*
* @return The updated {@link ServiceBusMessage}.
*/
public ServiceBusMessage setSessionId(String sessionId) {
amqpAnnotatedMessage.getProperties().setGroupId(sessionId);
return this;
}
/**
* A specified key-value pair of type {@link Context} to set additional information on the {@link
* ServiceBusMessage}.
*
* @return the {@link Context} object set on the {@link ServiceBusMessage}.
*/
Context getContext() {
return context;
}
/**
* Adds a new key value pair to the existing context on Message.
*
* @param key The key for this context object
* @param value The value for this context object.
*
* @return The updated {@link ServiceBusMessage}.
* @throws NullPointerException if {@code key} or {@code value} is null.
*/
public ServiceBusMessage addContext(String key, Object value) {
Objects.requireNonNull(key, "The 'key' parameter cannot be null.");
Objects.requireNonNull(value, "The 'value' parameter cannot be null.");
this.context = context.addData(key, value);
return this;
}
/*
* Gets value from given map.
*/
private void removeValues(Map<String, Object> dataMap, AmqpMessageConstant... keys) {
for (AmqpMessageConstant key : keys) {
dataMap.remove(key.getValue());
}
}
} |
The local variable declaration is unnecessary. | public OffsetDateTime getScheduledEnqueueTime() {
OffsetDateTime scheduledEnqueueTime = null;
Map<String, Object> messageAnnotationMap = amqpAnnotatedMessage.getMessageAnnotations();
if (messageAnnotationMap.containsKey(SCHEDULED_ENQUEUE_UTC_TIME_NAME.getValue())) {
scheduledEnqueueTime = ((Date) messageAnnotationMap.get(SCHEDULED_ENQUEUE_UTC_TIME_NAME.getValue()))
.toInstant().atOffset(ZoneOffset.UTC);
}
return scheduledEnqueueTime;
} | Map<String, Object> messageAnnotationMap = amqpAnnotatedMessage.getMessageAnnotations(); | public OffsetDateTime getScheduledEnqueueTime() {
Object value = amqpAnnotatedMessage.getMessageAnnotations().get(SCHEDULED_ENQUEUE_UTC_TIME_NAME.getValue());
return value != null
? ((Date) value).toInstant().atOffset(ZoneOffset.UTC)
: null;
} | class ServiceBusMessage {
private final AmqpAnnotatedMessage amqpAnnotatedMessage;
private final ClientLogger logger = new ClientLogger(ServiceBusMessage.class);
private final byte[] binaryData;
private Context context;
/**
* Creates a {@link ServiceBusMessage} with a {@link java.nio.charset.StandardCharsets
*
* @param body The content of the Service bus message.
*
* @throws NullPointerException if {@code body} is null.
*/
public ServiceBusMessage(String body) {
this(Objects.requireNonNull(body, "'body' cannot be null.").getBytes(StandardCharsets.UTF_8));
}
/**
* Creates a {@link ServiceBusMessage} containing the {@code body}.
*
* @param body The data to set for this {@link ServiceBusMessage}.
*
* @throws NullPointerException if {@code body} is {@code null}.
*/
public ServiceBusMessage(byte[] body) {
this.binaryData = Objects.requireNonNull(body, "'body' cannot be null.");
this.context = Context.NONE;
this.amqpAnnotatedMessage = new AmqpAnnotatedMessage(new AmqpDataBody(Collections.singletonList(
new BinaryData(binaryData))));
}
/**
* Creates a {@link ServiceBusMessage} using properties from {@code receivedMessage}. This is normally used when a
* {@link ServiceBusReceivedMessage} needs to be sent to another entity.
*
* @param receivedMessage The received message to create new message from.
*
* @throws NullPointerException if {@code receivedMessage} is {@code null}.
*/
public ServiceBusMessage(ServiceBusReceivedMessage receivedMessage) {
Objects.requireNonNull(receivedMessage, "'receivedMessage' cannot be null.");
this.amqpAnnotatedMessage = new AmqpAnnotatedMessage(receivedMessage.getAmqpAnnotatedMessage());
this.context = Context.NONE;
this.binaryData = receivedMessage.getBody();
amqpAnnotatedMessage.getHeader().setDeliveryCount(null);
removeValues(amqpAnnotatedMessage.getMessageAnnotations(), LOCKED_UNTIL_KEY_ANNOTATION_NAME,
SEQUENCE_NUMBER_ANNOTATION_NAME, DEAD_LETTER_SOURCE_KEY_ANNOTATION_NAME,
ENQUEUED_SEQUENCE_NUMBER_ANNOTATION_NAME, ENQUEUED_TIME_UTC_ANNOTATION_NAME);
removeValues(amqpAnnotatedMessage.getApplicationProperties(), DEAD_LETTER_DESCRIPTION_ANNOTATION_NAME,
DEAD_LETTER_REASON_ANNOTATION_NAME);
}
/**
* Gets the {@link AmqpAnnotatedMessage}.
*
* @return the amqp message.
*/
public AmqpAnnotatedMessage getAmqpAnnotatedMessage() {
return amqpAnnotatedMessage;
}
/**
* Gets the set of free-form {@link ServiceBusMessage} properties which may be used for passing metadata associated
* with the {@link ServiceBusMessage} during Service Bus operations. A common use-case for
* {@code getApplicationProperties()} is to associate serialization hints for the {@link
* consumers who wish to deserialize the binary data.
*
* @return Application properties associated with this {@link ServiceBusMessage}.
*/
public Map<String, Object> getApplicationProperties() {
return amqpAnnotatedMessage.getApplicationProperties();
}
/**
* Gets the actual payload/data wrapped by the {@link ServiceBusMessage}.
*
* <p>
* If the means for deserializing the raw data is not apparent to consumers, a common technique is to make use of
* {@link
* consumers who wish to deserialize the binary data.
* </p>
*
* @return A byte array representing the data.
*/
public byte[] getBody() {
final AmqpBodyType type = amqpAnnotatedMessage.getBody().getBodyType();
switch (type) {
case DATA:
return Arrays.copyOf(binaryData, binaryData.length);
case SEQUENCE:
case VALUE:
throw logger.logExceptionAsError(new UnsupportedOperationException("Not supported AmqpBodyType: "
+ type.toString()));
default:
throw logger.logExceptionAsError(new IllegalArgumentException("Unknown AmqpBodyType: "
+ type.toString()));
}
}
/**
* Gets the content type of the message.
*
* @return the contentType of the {@link ServiceBusMessage}.
*/
public String getContentType() {
return amqpAnnotatedMessage.getProperties().getContentType();
}
/**
* Sets the content type of the {@link ServiceBusMessage}.
*
* @param contentType of the message.
*
* @return The updated {@link ServiceBusMessage}.
*/
public ServiceBusMessage setContentType(String contentType) {
amqpAnnotatedMessage.getProperties().setContentType(contentType);
return this;
}
/**
* Gets a correlation identifier.
* <p>
* Allows an application to specify a context for the message for the purposes of correlation, for example
* reflecting the MessageId of a message that is being replied to.
* </p>
*
* @return correlation id of this message
* @see <a href="https:
* Routing and Correlation</a>
*/
public String getCorrelationId() {
return amqpAnnotatedMessage.getProperties().getCorrelationId();
}
/**
* Sets a correlation identifier.
*
* @param correlationId correlation id of this message
*
* @return The updated {@link ServiceBusMessage}.
* @see
*/
public ServiceBusMessage setCorrelationId(String correlationId) {
amqpAnnotatedMessage.getProperties().setCorrelationId(correlationId);
return this;
}
/**
* Gets the subject for the message.
*
* @return The subject for the message.
*/
public String getSubject() {
return amqpAnnotatedMessage.getProperties().getSubject();
}
/**
* Sets the subject for the message.
*
* @param subject The subject to set.
*
* @return The updated {@link ServiceBusMessage} object.
*/
public ServiceBusMessage setSubject(String subject) {
amqpAnnotatedMessage.getProperties().setSubject(subject);
return this;
}
/**
* @return Id of the {@link ServiceBusMessage}.
*/
public String getMessageId() {
return amqpAnnotatedMessage.getProperties().getMessageId();
}
/**
* Sets the message id.
*
* @param messageId to be set.
*
* @return The updated {@link ServiceBusMessage}.
*/
public ServiceBusMessage setMessageId(String messageId) {
amqpAnnotatedMessage.getProperties().setMessageId(messageId);
return this;
}
/**
* Gets the partition key for sending a message to a partitioned entity.
* <p>
* For <a href="https:
* entities</a>, setting this value enables assigning related messages to the same internal partition, so that
* submission sequence order is correctly recorded. The partition is chosen by a hash function over this value and
* cannot be chosen directly. For session-aware entities, the {@link
* this value.
*
* @return The partition key of this message
* @see <a href="https:
* entities</a>
*/
public String getPartitionKey() {
return (String) amqpAnnotatedMessage.getMessageAnnotations().get(PARTITION_KEY_ANNOTATION_NAME.getValue());
}
/**
* Sets a partition key for sending a message to a partitioned entity
*
* @param partitionKey partition key of this message
*
* @return The updated {@link ServiceBusMessage}.
* @see
*/
public ServiceBusMessage setPartitionKey(String partitionKey) {
amqpAnnotatedMessage.getMessageAnnotations().put(PARTITION_KEY_ANNOTATION_NAME.getValue(), partitionKey);
return this;
}
/**
* Gets the address of an entity to send replies to.
* <p>
* This optional and application-defined value is a standard way to express a reply path to the receiver of the
* message. When a sender expects a reply, it sets the value to the absolute or relative path of the queue or topic
* it expects the reply to be sent to.
*
* @return ReplyTo property value of this message
* @see <a href="https:
* Routing and Correlation</a>
*/
public String getReplyTo() {
return amqpAnnotatedMessage.getProperties().getReplyTo();
}
/**
* Sets the address of an entity to send replies to.
*
* @param replyTo ReplyTo property value of this message
*
* @return The updated {@link ServiceBusMessage}.
* @see
*/
public ServiceBusMessage setReplyTo(String replyTo) {
amqpAnnotatedMessage.getProperties().setReplyTo(replyTo);
return this;
}
/**
* Gets the "to" address.
*
* @return "To" property value of this message
*/
public String getTo() {
return amqpAnnotatedMessage.getProperties().getTo();
}
/**
* Sets the "to" address.
* <p>
* This property is reserved for future use in routing scenarios and presently ignored by the broker itself.
* Applications can use this value in rule-driven
* <a href="https:
* chaining</a> scenarios to indicate the intended logical destination of the message.
*
* @param to To property value of this message
*
* @return The updated {@link ServiceBusMessage}.
*/
public ServiceBusMessage setTo(String to) {
amqpAnnotatedMessage.getProperties().setTo(to);
return this;
}
/**
* Gets the duration before this message expires.
* <p>
* This value is the relative duration after which the message expires, starting from the instant the message has
* been accepted and stored by the broker, as captured in {@link
* explicitly, the assumed value is the DefaultTimeToLive set for the respective queue or topic. A message-level
* TimeToLive value cannot be longer than the entity's DefaultTimeToLive setting and it is silently adjusted if it
* does.
*
* @return Time to live duration of this message
* @see <a href="https:
*/
public Duration getTimeToLive() {
return amqpAnnotatedMessage.getHeader().getTimeToLive();
}
/**
* Sets the duration of time before this message expires.
*
* @param timeToLive Time to Live duration of this message
*
* @return The updated {@link ServiceBusMessage}.
* @see
*/
public ServiceBusMessage setTimeToLive(Duration timeToLive) {
amqpAnnotatedMessage.getHeader().setTimeToLive(timeToLive);
return this;
}
/**
* Gets the scheduled enqueue time of this message.
* <p>
* This value is used for delayed message availability. The message is safely added to the queue, but is not
* considered active and therefore not retrievable until the scheduled enqueue time. Mind that the message may not
* be activated (enqueued) at the exact given datetime; the actual activation time depends on the queue's workload
* and its state.
* </p>
*
* @return the datetime at which the message will be enqueued in Azure Service Bus
* @see <a href="https:
* Timestamps</a>
*/
/**
* Sets the scheduled enqueue time of this message.
*
* @param scheduledEnqueueTime the datetime at which this message should be enqueued in Azure Service Bus.
*
* @return The updated {@link ServiceBusMessage}.
* @see
*/
public ServiceBusMessage setScheduledEnqueueTime(OffsetDateTime scheduledEnqueueTime) {
if (scheduledEnqueueTime != null) {
amqpAnnotatedMessage.getMessageAnnotations().put(SCHEDULED_ENQUEUE_UTC_TIME_NAME.getValue(),
scheduledEnqueueTime);
}
return this;
}
/**
* Gets or sets a session identifier augmenting the {@link
* <p>
* This value augments the ReplyTo information and specifies which SessionId should be set for the reply when sent
* to the reply entity.
*
* @return ReplyToSessionId property value of this message
* @see <a href="https:
* Routing and Correlation</a>
*/
public String getReplyToSessionId() {
return amqpAnnotatedMessage.getProperties().getReplyToGroupId();
}
/**
* Gets or sets a session identifier augmenting the {@link
*
* @param replyToSessionId ReplyToSessionId property value of this message
*
* @return The updated {@link ServiceBusMessage}.
*/
public ServiceBusMessage setReplyToSessionId(String replyToSessionId) {
amqpAnnotatedMessage.getProperties().setReplyToGroupId(replyToSessionId);
return this;
}
/**
* Gets the partition key for sending a message to a entity via another partitioned transfer entity.
*
* If a message is sent via a transfer queue in the scope of a transaction, this value selects the transfer queue
* partition: This is functionally equivalent to {@link
* together and in order as they are transferred.
*
* @return partition key on the via queue.
* @see <a href="https:
* and Send Via</a>
*/
public String getViaPartitionKey() {
return (String) amqpAnnotatedMessage.getMessageAnnotations().get(VIA_PARTITION_KEY_ANNOTATION_NAME.getValue());
}
/**
* Sets a via-partition key for sending a message to a destination entity via another partitioned entity
*
* @param viaPartitionKey via-partition key of this message
*
* @return The updated {@link ServiceBusMessage}.
* @see
*/
public ServiceBusMessage setViaPartitionKey(String viaPartitionKey) {
amqpAnnotatedMessage.getMessageAnnotations().put(VIA_PARTITION_KEY_ANNOTATION_NAME.getValue(), viaPartitionKey);
return this;
}
/**
* Gets the session id of the message.
*
* @return Session Id of the {@link ServiceBusMessage}.
*/
public String getSessionId() {
return amqpAnnotatedMessage.getProperties().getGroupId();
}
/**
* Sets the session id.
*
* @param sessionId to be set.
*
* @return The updated {@link ServiceBusMessage}.
*/
public ServiceBusMessage setSessionId(String sessionId) {
amqpAnnotatedMessage.getProperties().setGroupId(sessionId);
return this;
}
/**
* A specified key-value pair of type {@link Context} to set additional information on the {@link
* ServiceBusMessage}.
*
* @return the {@link Context} object set on the {@link ServiceBusMessage}.
*/
Context getContext() {
return context;
}
/**
* Adds a new key value pair to the existing context on Message.
*
* @param key The key for this context object
* @param value The value for this context object.
*
* @return The updated {@link ServiceBusMessage}.
* @throws NullPointerException if {@code key} or {@code value} is null.
*/
public ServiceBusMessage addContext(String key, Object value) {
Objects.requireNonNull(key, "The 'key' parameter cannot be null.");
Objects.requireNonNull(value, "The 'value' parameter cannot be null.");
this.context = context.addData(key, value);
return this;
}
/*
* Gets value from given map.
*/
private void removeValues(Map<String, Object> dataMap, AmqpMessageConstant... keys) {
for (AmqpMessageConstant key : keys) {
dataMap.remove(key.getValue());
}
}
} | class ServiceBusMessage {
private final AmqpAnnotatedMessage amqpAnnotatedMessage;
private final ClientLogger logger = new ClientLogger(ServiceBusMessage.class);
private final byte[] binaryData;
private Context context;
/**
* Creates a {@link ServiceBusMessage} with a {@link java.nio.charset.StandardCharsets
*
* @param body The content of the Service bus message.
*
* @throws NullPointerException if {@code body} is null.
*/
public ServiceBusMessage(String body) {
this(Objects.requireNonNull(body, "'body' cannot be null.").getBytes(StandardCharsets.UTF_8));
}
/**
* Creates a {@link ServiceBusMessage} containing the {@code body}.
*
* @param body The data to set for this {@link ServiceBusMessage}.
*
* @throws NullPointerException if {@code body} is {@code null}.
*/
public ServiceBusMessage(byte[] body) {
this.binaryData = Objects.requireNonNull(body, "'body' cannot be null.");
this.context = Context.NONE;
this.amqpAnnotatedMessage = new AmqpAnnotatedMessage(new AmqpDataBody(Collections.singletonList(
new BinaryData(binaryData))));
}
/**
* Creates a {@link ServiceBusMessage} using properties from {@code receivedMessage}. This is normally used when a
* {@link ServiceBusReceivedMessage} needs to be sent to another entity.
*
* @param receivedMessage The received message to create new message from.
*
* @throws NullPointerException if {@code receivedMessage} is {@code null}.
*/
public ServiceBusMessage(ServiceBusReceivedMessage receivedMessage) {
Objects.requireNonNull(receivedMessage, "'receivedMessage' cannot be null.");
this.amqpAnnotatedMessage = new AmqpAnnotatedMessage(receivedMessage.getAmqpAnnotatedMessage());
this.context = Context.NONE;
this.binaryData = receivedMessage.getBody();
amqpAnnotatedMessage.getHeader().setDeliveryCount(null);
removeValues(amqpAnnotatedMessage.getMessageAnnotations(), LOCKED_UNTIL_KEY_ANNOTATION_NAME,
SEQUENCE_NUMBER_ANNOTATION_NAME, DEAD_LETTER_SOURCE_KEY_ANNOTATION_NAME,
ENQUEUED_SEQUENCE_NUMBER_ANNOTATION_NAME, ENQUEUED_TIME_UTC_ANNOTATION_NAME);
removeValues(amqpAnnotatedMessage.getApplicationProperties(), DEAD_LETTER_DESCRIPTION_ANNOTATION_NAME,
DEAD_LETTER_REASON_ANNOTATION_NAME);
}
/**
* Gets the {@link AmqpAnnotatedMessage}.
*
* @return the amqp message.
*/
public AmqpAnnotatedMessage getAmqpAnnotatedMessage() {
return amqpAnnotatedMessage;
}
/**
* Gets the set of free-form {@link ServiceBusMessage} properties which may be used for passing metadata associated
* with the {@link ServiceBusMessage} during Service Bus operations. A common use-case for
* {@code getApplicationProperties()} is to associate serialization hints for the {@link
* consumers who wish to deserialize the binary data.
*
* @return Application properties associated with this {@link ServiceBusMessage}.
*/
public Map<String, Object> getApplicationProperties() {
return amqpAnnotatedMessage.getApplicationProperties();
}
/**
* Gets the actual payload/data wrapped by the {@link ServiceBusMessage}.
*
* <p>
* If the means for deserializing the raw data is not apparent to consumers, a common technique is to make use of
* {@link
* consumers who wish to deserialize the binary data.
* </p>
*
* @return A byte array representing the data.
*/
public byte[] getBody() {
final AmqpBodyType type = amqpAnnotatedMessage.getBody().getBodyType();
switch (type) {
case DATA:
return Arrays.copyOf(binaryData, binaryData.length);
case SEQUENCE:
case VALUE:
throw logger.logExceptionAsError(new UnsupportedOperationException("Not supported AmqpBodyType: "
+ type.toString()));
default:
throw logger.logExceptionAsError(new IllegalArgumentException("Unknown AmqpBodyType: "
+ type.toString()));
}
}
/**
* Gets the content type of the message.
*
* @return the contentType of the {@link ServiceBusMessage}.
*/
public String getContentType() {
return amqpAnnotatedMessage.getProperties().getContentType();
}
/**
* Sets the content type of the {@link ServiceBusMessage}.
*
* @param contentType of the message.
*
* @return The updated {@link ServiceBusMessage}.
*/
public ServiceBusMessage setContentType(String contentType) {
amqpAnnotatedMessage.getProperties().setContentType(contentType);
return this;
}
/**
* Gets a correlation identifier.
* <p>
* Allows an application to specify a context for the message for the purposes of correlation, for example
* reflecting the MessageId of a message that is being replied to.
* </p>
*
* @return correlation id of this message
* @see <a href="https:
* Routing and Correlation</a>
*/
public String getCorrelationId() {
return amqpAnnotatedMessage.getProperties().getCorrelationId();
}
/**
* Sets a correlation identifier.
*
* @param correlationId correlation id of this message
*
* @return The updated {@link ServiceBusMessage}.
* @see
*/
public ServiceBusMessage setCorrelationId(String correlationId) {
amqpAnnotatedMessage.getProperties().setCorrelationId(correlationId);
return this;
}
/**
* Gets the subject for the message.
*
* @return The subject for the message.
*/
public String getSubject() {
return amqpAnnotatedMessage.getProperties().getSubject();
}
/**
* Sets the subject for the message.
*
* @param subject The subject to set.
*
* @return The updated {@link ServiceBusMessage} object.
*/
public ServiceBusMessage setSubject(String subject) {
amqpAnnotatedMessage.getProperties().setSubject(subject);
return this;
}
/**
* @return Id of the {@link ServiceBusMessage}.
*/
public String getMessageId() {
return amqpAnnotatedMessage.getProperties().getMessageId();
}
/**
* Sets the message id.
*
* @param messageId to be set.
*
* @return The updated {@link ServiceBusMessage}.
*/
public ServiceBusMessage setMessageId(String messageId) {
amqpAnnotatedMessage.getProperties().setMessageId(messageId);
return this;
}
/**
* Gets the partition key for sending a message to a partitioned entity.
* <p>
* For <a href="https:
* entities</a>, setting this value enables assigning related messages to the same internal partition, so that
* submission sequence order is correctly recorded. The partition is chosen by a hash function over this value and
* cannot be chosen directly. For session-aware entities, the {@link
* this value.
*
* @return The partition key of this message
* @see <a href="https:
* entities</a>
*/
public String getPartitionKey() {
return (String) amqpAnnotatedMessage.getMessageAnnotations().get(PARTITION_KEY_ANNOTATION_NAME.getValue());
}
/**
* Sets a partition key for sending a message to a partitioned entity
*
* @param partitionKey partition key of this message
*
* @return The updated {@link ServiceBusMessage}.
* @see
*/
public ServiceBusMessage setPartitionKey(String partitionKey) {
amqpAnnotatedMessage.getMessageAnnotations().put(PARTITION_KEY_ANNOTATION_NAME.getValue(), partitionKey);
return this;
}
/**
* Gets the address of an entity to send replies to.
* <p>
* This optional and application-defined value is a standard way to express a reply path to the receiver of the
* message. When a sender expects a reply, it sets the value to the absolute or relative path of the queue or topic
* it expects the reply to be sent to.
*
* @return ReplyTo property value of this message
* @see <a href="https:
* Routing and Correlation</a>
*/
public String getReplyTo() {
return amqpAnnotatedMessage.getProperties().getReplyTo();
}
/**
* Sets the address of an entity to send replies to.
*
* @param replyTo ReplyTo property value of this message
*
* @return The updated {@link ServiceBusMessage}.
* @see
*/
public ServiceBusMessage setReplyTo(String replyTo) {
amqpAnnotatedMessage.getProperties().setReplyTo(replyTo);
return this;
}
/**
* Gets the "to" address.
*
* @return "To" property value of this message
*/
public String getTo() {
return amqpAnnotatedMessage.getProperties().getTo();
}
/**
* Sets the "to" address.
* <p>
* This property is reserved for future use in routing scenarios and presently ignored by the broker itself.
* Applications can use this value in rule-driven
* <a href="https:
* chaining</a> scenarios to indicate the intended logical destination of the message.
*
* @param to To property value of this message
*
* @return The updated {@link ServiceBusMessage}.
*/
public ServiceBusMessage setTo(String to) {
amqpAnnotatedMessage.getProperties().setTo(to);
return this;
}
/**
* Gets the duration before this message expires.
* <p>
* This value is the relative duration after which the message expires, starting from the instant the message has
* been accepted and stored by the broker, as captured in {@link
* explicitly, the assumed value is the DefaultTimeToLive set for the respective queue or topic. A message-level
* TimeToLive value cannot be longer than the entity's DefaultTimeToLive setting and it is silently adjusted if it
* does.
*
* @return Time to live duration of this message
* @see <a href="https:
*/
public Duration getTimeToLive() {
return amqpAnnotatedMessage.getHeader().getTimeToLive();
}
/**
* Sets the duration of time before this message expires.
*
* @param timeToLive Time to Live duration of this message
*
* @return The updated {@link ServiceBusMessage}.
* @see
*/
public ServiceBusMessage setTimeToLive(Duration timeToLive) {
amqpAnnotatedMessage.getHeader().setTimeToLive(timeToLive);
return this;
}
/**
* Gets the scheduled enqueue time of this message.
* <p>
* This value is used for delayed message availability. The message is safely added to the queue, but is not
* considered active and therefore not retrievable until the scheduled enqueue time. Mind that the message may not
* be activated (enqueued) at the exact given datetime; the actual activation time depends on the queue's workload
* and its state.
* </p>
*
* @return the datetime at which the message will be enqueued in Azure Service Bus
* @see <a href="https:
* Timestamps</a>
*/
/**
* Sets the scheduled enqueue time of this message. A {@code null} will not be set. If this value needs to be unset
* it could be done by value removing from {@link AmqpAnnotatedMessage
* {@link AmqpMessageConstant
*
* @param scheduledEnqueueTime the datetime at which this message should be enqueued in Azure Service Bus.
*
* @return The updated {@link ServiceBusMessage}.
* @see
*/
public ServiceBusMessage setScheduledEnqueueTime(OffsetDateTime scheduledEnqueueTime) {
if (scheduledEnqueueTime != null) {
amqpAnnotatedMessage.getMessageAnnotations().put(SCHEDULED_ENQUEUE_UTC_TIME_NAME.getValue(),
scheduledEnqueueTime);
}
return this;
}
/**
* Gets or sets a session identifier augmenting the {@link
* <p>
* This value augments the ReplyTo information and specifies which SessionId should be set for the reply when sent
* to the reply entity.
*
* @return ReplyToSessionId property value of this message
* @see <a href="https:
* Routing and Correlation</a>
*/
public String getReplyToSessionId() {
return amqpAnnotatedMessage.getProperties().getReplyToGroupId();
}
/**
* Gets or sets a session identifier augmenting the {@link
*
* @param replyToSessionId ReplyToSessionId property value of this message
*
* @return The updated {@link ServiceBusMessage}.
*/
public ServiceBusMessage setReplyToSessionId(String replyToSessionId) {
amqpAnnotatedMessage.getProperties().setReplyToGroupId(replyToSessionId);
return this;
}
/**
* Gets the partition key for sending a message to a entity via another partitioned transfer entity.
*
* If a message is sent via a transfer queue in the scope of a transaction, this value selects the transfer queue
* partition: This is functionally equivalent to {@link
* together and in order as they are transferred.
*
* @return partition key on the via queue.
* @see <a href="https:
* and Send Via</a>
*/
public String getViaPartitionKey() {
return (String) amqpAnnotatedMessage.getMessageAnnotations().get(VIA_PARTITION_KEY_ANNOTATION_NAME.getValue());
}
/**
* Sets a via-partition key for sending a message to a destination entity via another partitioned entity
*
* @param viaPartitionKey via-partition key of this message
*
* @return The updated {@link ServiceBusMessage}.
* @see
*/
public ServiceBusMessage setViaPartitionKey(String viaPartitionKey) {
amqpAnnotatedMessage.getMessageAnnotations().put(VIA_PARTITION_KEY_ANNOTATION_NAME.getValue(), viaPartitionKey);
return this;
}
/**
* Gets the session id of the message.
*
* @return Session Id of the {@link ServiceBusMessage}.
*/
public String getSessionId() {
return amqpAnnotatedMessage.getProperties().getGroupId();
}
/**
* Sets the session id.
*
* @param sessionId to be set.
*
* @return The updated {@link ServiceBusMessage}.
*/
public ServiceBusMessage setSessionId(String sessionId) {
amqpAnnotatedMessage.getProperties().setGroupId(sessionId);
return this;
}
/**
* A specified key-value pair of type {@link Context} to set additional information on the {@link
* ServiceBusMessage}.
*
* @return the {@link Context} object set on the {@link ServiceBusMessage}.
*/
Context getContext() {
return context;
}
/**
* Adds a new key value pair to the existing context on Message.
*
* @param key The key for this context object
* @param value The value for this context object.
*
* @return The updated {@link ServiceBusMessage}.
* @throws NullPointerException if {@code key} or {@code value} is null.
*/
public ServiceBusMessage addContext(String key, Object value) {
Objects.requireNonNull(key, "The 'key' parameter cannot be null.");
Objects.requireNonNull(value, "The 'value' parameter cannot be null.");
this.context = context.addData(key, value);
return this;
}
/*
* Gets value from given map.
*/
private void removeValues(Map<String, Object> dataMap, AmqpMessageConstant... keys) {
for (AmqpMessageConstant key : keys) {
dataMap.remove(key.getValue());
}
}
} |
What if they're trying to clear the scheduledEnqueueTime? Isn't null a value option to pass? Same with other instances. | public ServiceBusMessage setScheduledEnqueueTime(OffsetDateTime scheduledEnqueueTime) {
if (scheduledEnqueueTime != null) {
amqpAnnotatedMessage.getMessageAnnotations().put(SCHEDULED_ENQUEUE_UTC_TIME_NAME.getValue(),
scheduledEnqueueTime);
}
return this;
} | if (scheduledEnqueueTime != null) { | public ServiceBusMessage setScheduledEnqueueTime(OffsetDateTime scheduledEnqueueTime) {
if (scheduledEnqueueTime != null) {
amqpAnnotatedMessage.getMessageAnnotations().put(SCHEDULED_ENQUEUE_UTC_TIME_NAME.getValue(),
scheduledEnqueueTime);
}
return this;
} | class ServiceBusMessage {
private final AmqpAnnotatedMessage amqpAnnotatedMessage;
private final ClientLogger logger = new ClientLogger(ServiceBusMessage.class);
private final byte[] binaryData;
private Context context;
/**
* Creates a {@link ServiceBusMessage} with a {@link java.nio.charset.StandardCharsets
*
* @param body The content of the Service bus message.
*
* @throws NullPointerException if {@code body} is null.
*/
public ServiceBusMessage(String body) {
this(Objects.requireNonNull(body, "'body' cannot be null.").getBytes(StandardCharsets.UTF_8));
}
/**
* Creates a {@link ServiceBusMessage} containing the {@code body}.
*
* @param body The data to set for this {@link ServiceBusMessage}.
*
* @throws NullPointerException if {@code body} is {@code null}.
*/
public ServiceBusMessage(byte[] body) {
this.binaryData = Objects.requireNonNull(body, "'body' cannot be null.");
this.context = Context.NONE;
this.amqpAnnotatedMessage = new AmqpAnnotatedMessage(new AmqpDataBody(Collections.singletonList(
new BinaryData(binaryData))));
}
/**
* Creates a {@link ServiceBusMessage} using properties from {@code receivedMessage}. This is normally used when a
* {@link ServiceBusReceivedMessage} needs to be sent to another entity.
*
* @param receivedMessage The received message to create new message from.
*
* @throws NullPointerException if {@code receivedMessage} is {@code null}.
*/
public ServiceBusMessage(ServiceBusReceivedMessage receivedMessage) {
Objects.requireNonNull(receivedMessage, "'receivedMessage' cannot be null.");
this.amqpAnnotatedMessage = new AmqpAnnotatedMessage(receivedMessage.getAmqpAnnotatedMessage());
this.context = Context.NONE;
this.binaryData = receivedMessage.getBody();
amqpAnnotatedMessage.getHeader().setDeliveryCount(null);
removeValues(amqpAnnotatedMessage.getMessageAnnotations(), LOCKED_UNTIL_KEY_ANNOTATION_NAME,
SEQUENCE_NUMBER_ANNOTATION_NAME, DEAD_LETTER_SOURCE_KEY_ANNOTATION_NAME,
ENQUEUED_SEQUENCE_NUMBER_ANNOTATION_NAME, ENQUEUED_TIME_UTC_ANNOTATION_NAME);
removeValues(amqpAnnotatedMessage.getApplicationProperties(), DEAD_LETTER_DESCRIPTION_ANNOTATION_NAME,
DEAD_LETTER_REASON_ANNOTATION_NAME);
}
/**
* Gets the {@link AmqpAnnotatedMessage}.
*
* @return the amqp message.
*/
public AmqpAnnotatedMessage getAmqpAnnotatedMessage() {
return amqpAnnotatedMessage;
}
/**
* Gets the set of free-form {@link ServiceBusMessage} properties which may be used for passing metadata associated
* with the {@link ServiceBusMessage} during Service Bus operations. A common use-case for
* {@code getApplicationProperties()} is to associate serialization hints for the {@link
* consumers who wish to deserialize the binary data.
*
* @return Application properties associated with this {@link ServiceBusMessage}.
*/
public Map<String, Object> getApplicationProperties() {
return amqpAnnotatedMessage.getApplicationProperties();
}
/**
* Gets the actual payload/data wrapped by the {@link ServiceBusMessage}.
*
* <p>
* If the means for deserializing the raw data is not apparent to consumers, a common technique is to make use of
* {@link
* consumers who wish to deserialize the binary data.
* </p>
*
* @return A byte array representing the data.
*/
public byte[] getBody() {
final AmqpBodyType type = amqpAnnotatedMessage.getBody().getBodyType();
switch (type) {
case DATA:
return Arrays.copyOf(binaryData, binaryData.length);
case SEQUENCE:
case VALUE:
throw logger.logExceptionAsError(new UnsupportedOperationException("Not supported AmqpBodyType: "
+ type.toString()));
default:
throw logger.logExceptionAsError(new IllegalArgumentException("Unknown AmqpBodyType: "
+ type.toString()));
}
}
/**
* Gets the content type of the message.
*
* @return the contentType of the {@link ServiceBusMessage}.
*/
public String getContentType() {
return amqpAnnotatedMessage.getProperties().getContentType();
}
/**
* Sets the content type of the {@link ServiceBusMessage}.
*
* @param contentType of the message.
*
* @return The updated {@link ServiceBusMessage}.
*/
public ServiceBusMessage setContentType(String contentType) {
amqpAnnotatedMessage.getProperties().setContentType(contentType);
return this;
}
/**
* Gets a correlation identifier.
* <p>
* Allows an application to specify a context for the message for the purposes of correlation, for example
* reflecting the MessageId of a message that is being replied to.
* </p>
*
* @return correlation id of this message
* @see <a href="https:
* Routing and Correlation</a>
*/
public String getCorrelationId() {
return amqpAnnotatedMessage.getProperties().getCorrelationId();
}
/**
* Sets a correlation identifier.
*
* @param correlationId correlation id of this message
*
* @return The updated {@link ServiceBusMessage}.
* @see
*/
public ServiceBusMessage setCorrelationId(String correlationId) {
amqpAnnotatedMessage.getProperties().setCorrelationId(correlationId);
return this;
}
/**
* Gets the subject for the message.
*
* @return The subject for the message.
*/
public String getSubject() {
return amqpAnnotatedMessage.getProperties().getSubject();
}
/**
* Sets the subject for the message.
*
* @param subject The subject to set.
*
* @return The updated {@link ServiceBusMessage} object.
*/
public ServiceBusMessage setSubject(String subject) {
amqpAnnotatedMessage.getProperties().setSubject(subject);
return this;
}
/**
* @return Id of the {@link ServiceBusMessage}.
*/
public String getMessageId() {
return amqpAnnotatedMessage.getProperties().getMessageId();
}
/**
* Sets the message id.
*
* @param messageId to be set.
*
* @return The updated {@link ServiceBusMessage}.
*/
public ServiceBusMessage setMessageId(String messageId) {
amqpAnnotatedMessage.getProperties().setMessageId(messageId);
return this;
}
/**
* Gets the partition key for sending a message to a partitioned entity.
* <p>
* For <a href="https:
* entities</a>, setting this value enables assigning related messages to the same internal partition, so that
* submission sequence order is correctly recorded. The partition is chosen by a hash function over this value and
* cannot be chosen directly. For session-aware entities, the {@link
* this value.
*
* @return The partition key of this message
* @see <a href="https:
* entities</a>
*/
public String getPartitionKey() {
return (String) amqpAnnotatedMessage.getMessageAnnotations().get(PARTITION_KEY_ANNOTATION_NAME.getValue());
}
/**
* Sets a partition key for sending a message to a partitioned entity
*
* @param partitionKey partition key of this message
*
* @return The updated {@link ServiceBusMessage}.
* @see
*/
public ServiceBusMessage setPartitionKey(String partitionKey) {
amqpAnnotatedMessage.getMessageAnnotations().put(PARTITION_KEY_ANNOTATION_NAME.getValue(), partitionKey);
return this;
}
/**
* Gets the address of an entity to send replies to.
* <p>
* This optional and application-defined value is a standard way to express a reply path to the receiver of the
* message. When a sender expects a reply, it sets the value to the absolute or relative path of the queue or topic
* it expects the reply to be sent to.
*
* @return ReplyTo property value of this message
* @see <a href="https:
* Routing and Correlation</a>
*/
public String getReplyTo() {
return amqpAnnotatedMessage.getProperties().getReplyTo();
}
/**
* Sets the address of an entity to send replies to.
*
* @param replyTo ReplyTo property value of this message
*
* @return The updated {@link ServiceBusMessage}.
* @see
*/
public ServiceBusMessage setReplyTo(String replyTo) {
amqpAnnotatedMessage.getProperties().setReplyTo(replyTo);
return this;
}
/**
* Gets the "to" address.
*
* @return "To" property value of this message
*/
public String getTo() {
return amqpAnnotatedMessage.getProperties().getTo();
}
/**
* Sets the "to" address.
* <p>
* This property is reserved for future use in routing scenarios and presently ignored by the broker itself.
* Applications can use this value in rule-driven
* <a href="https:
* chaining</a> scenarios to indicate the intended logical destination of the message.
*
* @param to To property value of this message
*
* @return The updated {@link ServiceBusMessage}.
*/
public ServiceBusMessage setTo(String to) {
amqpAnnotatedMessage.getProperties().setTo(to);
return this;
}
/**
* Gets the duration before this message expires.
* <p>
* This value is the relative duration after which the message expires, starting from the instant the message has
* been accepted and stored by the broker, as captured in {@link
* explicitly, the assumed value is the DefaultTimeToLive set for the respective queue or topic. A message-level
* TimeToLive value cannot be longer than the entity's DefaultTimeToLive setting and it is silently adjusted if it
* does.
*
* @return Time to live duration of this message
* @see <a href="https:
*/
public Duration getTimeToLive() {
return amqpAnnotatedMessage.getHeader().getTimeToLive();
}
/**
* Sets the duration of time before this message expires.
*
* @param timeToLive Time to Live duration of this message
*
* @return The updated {@link ServiceBusMessage}.
* @see
*/
public ServiceBusMessage setTimeToLive(Duration timeToLive) {
amqpAnnotatedMessage.getHeader().setTimeToLive(timeToLive);
return this;
}
/**
* Gets the scheduled enqueue time of this message.
* <p>
* This value is used for delayed message availability. The message is safely added to the queue, but is not
* considered active and therefore not retrievable until the scheduled enqueue time. Mind that the message may not
* be activated (enqueued) at the exact given datetime; the actual activation time depends on the queue's workload
* and its state.
* </p>
*
* @return the datetime at which the message will be enqueued in Azure Service Bus
* @see <a href="https:
* Timestamps</a>
*/
public OffsetDateTime getScheduledEnqueueTime() {
OffsetDateTime scheduledEnqueueTime = null;
Map<String, Object> messageAnnotationMap = amqpAnnotatedMessage.getMessageAnnotations();
if (messageAnnotationMap.containsKey(SCHEDULED_ENQUEUE_UTC_TIME_NAME.getValue())) {
scheduledEnqueueTime = ((Date) messageAnnotationMap.get(SCHEDULED_ENQUEUE_UTC_TIME_NAME.getValue()))
.toInstant().atOffset(ZoneOffset.UTC);
}
return scheduledEnqueueTime;
}
/**
* Sets the scheduled enqueue time of this message.
*
* @param scheduledEnqueueTime the datetime at which this message should be enqueued in Azure Service Bus.
*
* @return The updated {@link ServiceBusMessage}.
* @see
*/
/**
* Gets or sets a session identifier augmenting the {@link
* <p>
* This value augments the ReplyTo information and specifies which SessionId should be set for the reply when sent
* to the reply entity.
*
* @return ReplyToSessionId property value of this message
* @see <a href="https:
* Routing and Correlation</a>
*/
public String getReplyToSessionId() {
return amqpAnnotatedMessage.getProperties().getReplyToGroupId();
}
/**
* Gets or sets a session identifier augmenting the {@link
*
* @param replyToSessionId ReplyToSessionId property value of this message
*
* @return The updated {@link ServiceBusMessage}.
*/
public ServiceBusMessage setReplyToSessionId(String replyToSessionId) {
amqpAnnotatedMessage.getProperties().setReplyToGroupId(replyToSessionId);
return this;
}
/**
* Gets the partition key for sending a message to a entity via another partitioned transfer entity.
*
* If a message is sent via a transfer queue in the scope of a transaction, this value selects the transfer queue
* partition: This is functionally equivalent to {@link
* together and in order as they are transferred.
*
* @return partition key on the via queue.
* @see <a href="https:
* and Send Via</a>
*/
public String getViaPartitionKey() {
return (String) amqpAnnotatedMessage.getMessageAnnotations().get(VIA_PARTITION_KEY_ANNOTATION_NAME.getValue());
}
/**
* Sets a via-partition key for sending a message to a destination entity via another partitioned entity
*
* @param viaPartitionKey via-partition key of this message
*
* @return The updated {@link ServiceBusMessage}.
* @see
*/
public ServiceBusMessage setViaPartitionKey(String viaPartitionKey) {
amqpAnnotatedMessage.getMessageAnnotations().put(VIA_PARTITION_KEY_ANNOTATION_NAME.getValue(), viaPartitionKey);
return this;
}
/**
* Gets the session id of the message.
*
* @return Session Id of the {@link ServiceBusMessage}.
*/
public String getSessionId() {
return amqpAnnotatedMessage.getProperties().getGroupId();
}
/**
* Sets the session id.
*
* @param sessionId to be set.
*
* @return The updated {@link ServiceBusMessage}.
*/
public ServiceBusMessage setSessionId(String sessionId) {
amqpAnnotatedMessage.getProperties().setGroupId(sessionId);
return this;
}
/**
* A specified key-value pair of type {@link Context} to set additional information on the {@link
* ServiceBusMessage}.
*
* @return the {@link Context} object set on the {@link ServiceBusMessage}.
*/
Context getContext() {
return context;
}
/**
* Adds a new key value pair to the existing context on Message.
*
* @param key The key for this context object
* @param value The value for this context object.
*
* @return The updated {@link ServiceBusMessage}.
* @throws NullPointerException if {@code key} or {@code value} is null.
*/
public ServiceBusMessage addContext(String key, Object value) {
Objects.requireNonNull(key, "The 'key' parameter cannot be null.");
Objects.requireNonNull(value, "The 'value' parameter cannot be null.");
this.context = context.addData(key, value);
return this;
}
/*
* Gets value from given map.
*/
private void removeValues(Map<String, Object> dataMap, AmqpMessageConstant... keys) {
for (AmqpMessageConstant key : keys) {
dataMap.remove(key.getValue());
}
}
} | class ServiceBusMessage {
private final AmqpAnnotatedMessage amqpAnnotatedMessage;
private final ClientLogger logger = new ClientLogger(ServiceBusMessage.class);
private final byte[] binaryData;
private Context context;
/**
* Creates a {@link ServiceBusMessage} with a {@link java.nio.charset.StandardCharsets
*
* @param body The content of the Service bus message.
*
* @throws NullPointerException if {@code body} is null.
*/
public ServiceBusMessage(String body) {
this(Objects.requireNonNull(body, "'body' cannot be null.").getBytes(StandardCharsets.UTF_8));
}
/**
* Creates a {@link ServiceBusMessage} containing the {@code body}.
*
* @param body The data to set for this {@link ServiceBusMessage}.
*
* @throws NullPointerException if {@code body} is {@code null}.
*/
public ServiceBusMessage(byte[] body) {
this.binaryData = Objects.requireNonNull(body, "'body' cannot be null.");
this.context = Context.NONE;
this.amqpAnnotatedMessage = new AmqpAnnotatedMessage(new AmqpDataBody(Collections.singletonList(
new BinaryData(binaryData))));
}
/**
* Creates a {@link ServiceBusMessage} using properties from {@code receivedMessage}. This is normally used when a
* {@link ServiceBusReceivedMessage} needs to be sent to another entity.
*
* @param receivedMessage The received message to create new message from.
*
* @throws NullPointerException if {@code receivedMessage} is {@code null}.
*/
public ServiceBusMessage(ServiceBusReceivedMessage receivedMessage) {
Objects.requireNonNull(receivedMessage, "'receivedMessage' cannot be null.");
this.amqpAnnotatedMessage = new AmqpAnnotatedMessage(receivedMessage.getAmqpAnnotatedMessage());
this.context = Context.NONE;
this.binaryData = receivedMessage.getBody();
amqpAnnotatedMessage.getHeader().setDeliveryCount(null);
removeValues(amqpAnnotatedMessage.getMessageAnnotations(), LOCKED_UNTIL_KEY_ANNOTATION_NAME,
SEQUENCE_NUMBER_ANNOTATION_NAME, DEAD_LETTER_SOURCE_KEY_ANNOTATION_NAME,
ENQUEUED_SEQUENCE_NUMBER_ANNOTATION_NAME, ENQUEUED_TIME_UTC_ANNOTATION_NAME);
removeValues(amqpAnnotatedMessage.getApplicationProperties(), DEAD_LETTER_DESCRIPTION_ANNOTATION_NAME,
DEAD_LETTER_REASON_ANNOTATION_NAME);
}
/**
* Gets the {@link AmqpAnnotatedMessage}.
*
* @return the amqp message.
*/
public AmqpAnnotatedMessage getAmqpAnnotatedMessage() {
return amqpAnnotatedMessage;
}
/**
* Gets the set of free-form {@link ServiceBusMessage} properties which may be used for passing metadata associated
* with the {@link ServiceBusMessage} during Service Bus operations. A common use-case for
* {@code getApplicationProperties()} is to associate serialization hints for the {@link
* consumers who wish to deserialize the binary data.
*
* @return Application properties associated with this {@link ServiceBusMessage}.
*/
public Map<String, Object> getApplicationProperties() {
return amqpAnnotatedMessage.getApplicationProperties();
}
/**
* Gets the actual payload/data wrapped by the {@link ServiceBusMessage}.
*
* <p>
* If the means for deserializing the raw data is not apparent to consumers, a common technique is to make use of
* {@link
* consumers who wish to deserialize the binary data.
* </p>
*
* @return A byte array representing the data.
*/
public byte[] getBody() {
final AmqpBodyType type = amqpAnnotatedMessage.getBody().getBodyType();
switch (type) {
case DATA:
return Arrays.copyOf(binaryData, binaryData.length);
case SEQUENCE:
case VALUE:
throw logger.logExceptionAsError(new UnsupportedOperationException("Not supported AmqpBodyType: "
+ type.toString()));
default:
throw logger.logExceptionAsError(new IllegalArgumentException("Unknown AmqpBodyType: "
+ type.toString()));
}
}
/**
* Gets the content type of the message.
*
* @return the contentType of the {@link ServiceBusMessage}.
*/
public String getContentType() {
return amqpAnnotatedMessage.getProperties().getContentType();
}
/**
* Sets the content type of the {@link ServiceBusMessage}.
*
* @param contentType of the message.
*
* @return The updated {@link ServiceBusMessage}.
*/
public ServiceBusMessage setContentType(String contentType) {
amqpAnnotatedMessage.getProperties().setContentType(contentType);
return this;
}
/**
* Gets a correlation identifier.
* <p>
* Allows an application to specify a context for the message for the purposes of correlation, for example
* reflecting the MessageId of a message that is being replied to.
* </p>
*
* @return correlation id of this message
* @see <a href="https:
* Routing and Correlation</a>
*/
public String getCorrelationId() {
return amqpAnnotatedMessage.getProperties().getCorrelationId();
}
/**
* Sets a correlation identifier.
*
* @param correlationId correlation id of this message
*
* @return The updated {@link ServiceBusMessage}.
* @see
*/
public ServiceBusMessage setCorrelationId(String correlationId) {
amqpAnnotatedMessage.getProperties().setCorrelationId(correlationId);
return this;
}
/**
* Gets the subject for the message.
*
* @return The subject for the message.
*/
public String getSubject() {
return amqpAnnotatedMessage.getProperties().getSubject();
}
/**
* Sets the subject for the message.
*
* @param subject The subject to set.
*
* @return The updated {@link ServiceBusMessage} object.
*/
public ServiceBusMessage setSubject(String subject) {
amqpAnnotatedMessage.getProperties().setSubject(subject);
return this;
}
/**
* @return Id of the {@link ServiceBusMessage}.
*/
public String getMessageId() {
return amqpAnnotatedMessage.getProperties().getMessageId();
}
/**
* Sets the message id.
*
* @param messageId to be set.
*
* @return The updated {@link ServiceBusMessage}.
*/
public ServiceBusMessage setMessageId(String messageId) {
amqpAnnotatedMessage.getProperties().setMessageId(messageId);
return this;
}
/**
* Gets the partition key for sending a message to a partitioned entity.
* <p>
* For <a href="https:
* entities</a>, setting this value enables assigning related messages to the same internal partition, so that
* submission sequence order is correctly recorded. The partition is chosen by a hash function over this value and
* cannot be chosen directly. For session-aware entities, the {@link
* this value.
*
* @return The partition key of this message
* @see <a href="https:
* entities</a>
*/
public String getPartitionKey() {
return (String) amqpAnnotatedMessage.getMessageAnnotations().get(PARTITION_KEY_ANNOTATION_NAME.getValue());
}
/**
* Sets a partition key for sending a message to a partitioned entity
*
* @param partitionKey partition key of this message
*
* @return The updated {@link ServiceBusMessage}.
* @see
*/
public ServiceBusMessage setPartitionKey(String partitionKey) {
amqpAnnotatedMessage.getMessageAnnotations().put(PARTITION_KEY_ANNOTATION_NAME.getValue(), partitionKey);
return this;
}
/**
* Gets the address of an entity to send replies to.
* <p>
* This optional and application-defined value is a standard way to express a reply path to the receiver of the
* message. When a sender expects a reply, it sets the value to the absolute or relative path of the queue or topic
* it expects the reply to be sent to.
*
* @return ReplyTo property value of this message
* @see <a href="https:
* Routing and Correlation</a>
*/
public String getReplyTo() {
return amqpAnnotatedMessage.getProperties().getReplyTo();
}
/**
* Sets the address of an entity to send replies to.
*
* @param replyTo ReplyTo property value of this message
*
* @return The updated {@link ServiceBusMessage}.
* @see
*/
public ServiceBusMessage setReplyTo(String replyTo) {
amqpAnnotatedMessage.getProperties().setReplyTo(replyTo);
return this;
}
/**
* Gets the "to" address.
*
* @return "To" property value of this message
*/
public String getTo() {
return amqpAnnotatedMessage.getProperties().getTo();
}
/**
* Sets the "to" address.
* <p>
* This property is reserved for future use in routing scenarios and presently ignored by the broker itself.
* Applications can use this value in rule-driven
* <a href="https:
* chaining</a> scenarios to indicate the intended logical destination of the message.
*
* @param to To property value of this message
*
* @return The updated {@link ServiceBusMessage}.
*/
public ServiceBusMessage setTo(String to) {
amqpAnnotatedMessage.getProperties().setTo(to);
return this;
}
/**
* Gets the duration before this message expires.
* <p>
* This value is the relative duration after which the message expires, starting from the instant the message has
* been accepted and stored by the broker, as captured in {@link
* explicitly, the assumed value is the DefaultTimeToLive set for the respective queue or topic. A message-level
* TimeToLive value cannot be longer than the entity's DefaultTimeToLive setting and it is silently adjusted if it
* does.
*
* @return Time to live duration of this message
* @see <a href="https:
*/
public Duration getTimeToLive() {
return amqpAnnotatedMessage.getHeader().getTimeToLive();
}
/**
* Sets the duration of time before this message expires.
*
* @param timeToLive Time to Live duration of this message
*
* @return The updated {@link ServiceBusMessage}.
* @see
*/
public ServiceBusMessage setTimeToLive(Duration timeToLive) {
amqpAnnotatedMessage.getHeader().setTimeToLive(timeToLive);
return this;
}
/**
* Gets the scheduled enqueue time of this message.
* <p>
* This value is used for delayed message availability. The message is safely added to the queue, but is not
* considered active and therefore not retrievable until the scheduled enqueue time. Mind that the message may not
* be activated (enqueued) at the exact given datetime; the actual activation time depends on the queue's workload
* and its state.
* </p>
*
* @return the datetime at which the message will be enqueued in Azure Service Bus
* @see <a href="https:
* Timestamps</a>
*/
public OffsetDateTime getScheduledEnqueueTime() {
Object value = amqpAnnotatedMessage.getMessageAnnotations().get(SCHEDULED_ENQUEUE_UTC_TIME_NAME.getValue());
return value != null
? ((Date) value).toInstant().atOffset(ZoneOffset.UTC)
: null;
}
/**
* Sets the scheduled enqueue time of this message. A {@code null} will not be set. If this value needs to be unset
* it could be done by value removing from {@link AmqpAnnotatedMessage
* {@link AmqpMessageConstant
*
* @param scheduledEnqueueTime the datetime at which this message should be enqueued in Azure Service Bus.
*
* @return The updated {@link ServiceBusMessage}.
* @see
*/
/**
* Gets or sets a session identifier augmenting the {@link
* <p>
* This value augments the ReplyTo information and specifies which SessionId should be set for the reply when sent
* to the reply entity.
*
* @return ReplyToSessionId property value of this message
* @see <a href="https:
* Routing and Correlation</a>
*/
public String getReplyToSessionId() {
return amqpAnnotatedMessage.getProperties().getReplyToGroupId();
}
/**
* Gets or sets a session identifier augmenting the {@link
*
* @param replyToSessionId ReplyToSessionId property value of this message
*
* @return The updated {@link ServiceBusMessage}.
*/
public ServiceBusMessage setReplyToSessionId(String replyToSessionId) {
amqpAnnotatedMessage.getProperties().setReplyToGroupId(replyToSessionId);
return this;
}
/**
* Gets the partition key for sending a message to a entity via another partitioned transfer entity.
*
* If a message is sent via a transfer queue in the scope of a transaction, this value selects the transfer queue
* partition: This is functionally equivalent to {@link
* together and in order as they are transferred.
*
* @return partition key on the via queue.
* @see <a href="https:
* and Send Via</a>
*/
public String getViaPartitionKey() {
return (String) amqpAnnotatedMessage.getMessageAnnotations().get(VIA_PARTITION_KEY_ANNOTATION_NAME.getValue());
}
/**
* Sets a via-partition key for sending a message to a destination entity via another partitioned entity
*
* @param viaPartitionKey via-partition key of this message
*
* @return The updated {@link ServiceBusMessage}.
* @see
*/
public ServiceBusMessage setViaPartitionKey(String viaPartitionKey) {
amqpAnnotatedMessage.getMessageAnnotations().put(VIA_PARTITION_KEY_ANNOTATION_NAME.getValue(), viaPartitionKey);
return this;
}
/**
* Gets the session id of the message.
*
* @return Session Id of the {@link ServiceBusMessage}.
*/
public String getSessionId() {
return amqpAnnotatedMessage.getProperties().getGroupId();
}
/**
* Sets the session id.
*
* @param sessionId to be set.
*
* @return The updated {@link ServiceBusMessage}.
*/
public ServiceBusMessage setSessionId(String sessionId) {
amqpAnnotatedMessage.getProperties().setGroupId(sessionId);
return this;
}
/**
* A specified key-value pair of type {@link Context} to set additional information on the {@link
* ServiceBusMessage}.
*
* @return the {@link Context} object set on the {@link ServiceBusMessage}.
*/
Context getContext() {
return context;
}
/**
* Adds a new key value pair to the existing context on Message.
*
* @param key The key for this context object
* @param value The value for this context object.
*
* @return The updated {@link ServiceBusMessage}.
* @throws NullPointerException if {@code key} or {@code value} is null.
*/
public ServiceBusMessage addContext(String key, Object value) {
Objects.requireNonNull(key, "The 'key' parameter cannot be null.");
Objects.requireNonNull(value, "The 'value' parameter cannot be null.");
this.context = context.addData(key, value);
return this;
}
/*
* Gets value from given map.
*/
private void removeValues(Map<String, Object> dataMap, AmqpMessageConstant... keys) {
for (AmqpMessageConstant key : keys) {
dataMap.remove(key.getValue());
}
}
} |
Internally these key,value pair is stored in Map and Null value is not allowed. The code on master is also checking for `null` and not putting in map is user provided null value. User can get `Map` using `amqpAnnotatedMessage.getMessageAnnotations()` and remove a key if they do not want it. | public ServiceBusMessage setScheduledEnqueueTime(OffsetDateTime scheduledEnqueueTime) {
if (scheduledEnqueueTime != null) {
amqpAnnotatedMessage.getMessageAnnotations().put(SCHEDULED_ENQUEUE_UTC_TIME_NAME.getValue(),
scheduledEnqueueTime);
}
return this;
} | if (scheduledEnqueueTime != null) { | public ServiceBusMessage setScheduledEnqueueTime(OffsetDateTime scheduledEnqueueTime) {
if (scheduledEnqueueTime != null) {
amqpAnnotatedMessage.getMessageAnnotations().put(SCHEDULED_ENQUEUE_UTC_TIME_NAME.getValue(),
scheduledEnqueueTime);
}
return this;
} | class ServiceBusMessage {
private final AmqpAnnotatedMessage amqpAnnotatedMessage;
private final ClientLogger logger = new ClientLogger(ServiceBusMessage.class);
private final byte[] binaryData;
private Context context;
/**
* Creates a {@link ServiceBusMessage} with a {@link java.nio.charset.StandardCharsets
*
* @param body The content of the Service bus message.
*
* @throws NullPointerException if {@code body} is null.
*/
public ServiceBusMessage(String body) {
this(Objects.requireNonNull(body, "'body' cannot be null.").getBytes(StandardCharsets.UTF_8));
}
/**
* Creates a {@link ServiceBusMessage} containing the {@code body}.
*
* @param body The data to set for this {@link ServiceBusMessage}.
*
* @throws NullPointerException if {@code body} is {@code null}.
*/
public ServiceBusMessage(byte[] body) {
this.binaryData = Objects.requireNonNull(body, "'body' cannot be null.");
this.context = Context.NONE;
this.amqpAnnotatedMessage = new AmqpAnnotatedMessage(new AmqpDataBody(Collections.singletonList(
new BinaryData(binaryData))));
}
/**
* Creates a {@link ServiceBusMessage} using properties from {@code receivedMessage}. This is normally used when a
* {@link ServiceBusReceivedMessage} needs to be sent to another entity.
*
* @param receivedMessage The received message to create new message from.
*
* @throws NullPointerException if {@code receivedMessage} is {@code null}.
*/
public ServiceBusMessage(ServiceBusReceivedMessage receivedMessage) {
Objects.requireNonNull(receivedMessage, "'receivedMessage' cannot be null.");
this.amqpAnnotatedMessage = new AmqpAnnotatedMessage(receivedMessage.getAmqpAnnotatedMessage());
this.context = Context.NONE;
this.binaryData = receivedMessage.getBody();
amqpAnnotatedMessage.getHeader().setDeliveryCount(null);
removeValues(amqpAnnotatedMessage.getMessageAnnotations(), LOCKED_UNTIL_KEY_ANNOTATION_NAME,
SEQUENCE_NUMBER_ANNOTATION_NAME, DEAD_LETTER_SOURCE_KEY_ANNOTATION_NAME,
ENQUEUED_SEQUENCE_NUMBER_ANNOTATION_NAME, ENQUEUED_TIME_UTC_ANNOTATION_NAME);
removeValues(amqpAnnotatedMessage.getApplicationProperties(), DEAD_LETTER_DESCRIPTION_ANNOTATION_NAME,
DEAD_LETTER_REASON_ANNOTATION_NAME);
}
/**
* Gets the {@link AmqpAnnotatedMessage}.
*
* @return the amqp message.
*/
public AmqpAnnotatedMessage getAmqpAnnotatedMessage() {
return amqpAnnotatedMessage;
}
/**
* Gets the set of free-form {@link ServiceBusMessage} properties which may be used for passing metadata associated
* with the {@link ServiceBusMessage} during Service Bus operations. A common use-case for
* {@code getApplicationProperties()} is to associate serialization hints for the {@link
* consumers who wish to deserialize the binary data.
*
* @return Application properties associated with this {@link ServiceBusMessage}.
*/
public Map<String, Object> getApplicationProperties() {
return amqpAnnotatedMessage.getApplicationProperties();
}
/**
* Gets the actual payload/data wrapped by the {@link ServiceBusMessage}.
*
* <p>
* If the means for deserializing the raw data is not apparent to consumers, a common technique is to make use of
* {@link
* consumers who wish to deserialize the binary data.
* </p>
*
* @return A byte array representing the data.
*/
public byte[] getBody() {
final AmqpBodyType type = amqpAnnotatedMessage.getBody().getBodyType();
switch (type) {
case DATA:
return Arrays.copyOf(binaryData, binaryData.length);
case SEQUENCE:
case VALUE:
throw logger.logExceptionAsError(new UnsupportedOperationException("Not supported AmqpBodyType: "
+ type.toString()));
default:
throw logger.logExceptionAsError(new IllegalArgumentException("Unknown AmqpBodyType: "
+ type.toString()));
}
}
/**
* Gets the content type of the message.
*
* @return the contentType of the {@link ServiceBusMessage}.
*/
public String getContentType() {
return amqpAnnotatedMessage.getProperties().getContentType();
}
/**
* Sets the content type of the {@link ServiceBusMessage}.
*
* @param contentType of the message.
*
* @return The updated {@link ServiceBusMessage}.
*/
public ServiceBusMessage setContentType(String contentType) {
amqpAnnotatedMessage.getProperties().setContentType(contentType);
return this;
}
/**
* Gets a correlation identifier.
* <p>
* Allows an application to specify a context for the message for the purposes of correlation, for example
* reflecting the MessageId of a message that is being replied to.
* </p>
*
* @return correlation id of this message
* @see <a href="https:
* Routing and Correlation</a>
*/
public String getCorrelationId() {
return amqpAnnotatedMessage.getProperties().getCorrelationId();
}
/**
* Sets a correlation identifier.
*
* @param correlationId correlation id of this message
*
* @return The updated {@link ServiceBusMessage}.
* @see
*/
public ServiceBusMessage setCorrelationId(String correlationId) {
amqpAnnotatedMessage.getProperties().setCorrelationId(correlationId);
return this;
}
/**
* Gets the subject for the message.
*
* @return The subject for the message.
*/
public String getSubject() {
return amqpAnnotatedMessage.getProperties().getSubject();
}
/**
* Sets the subject for the message.
*
* @param subject The subject to set.
*
* @return The updated {@link ServiceBusMessage} object.
*/
public ServiceBusMessage setSubject(String subject) {
amqpAnnotatedMessage.getProperties().setSubject(subject);
return this;
}
/**
* @return Id of the {@link ServiceBusMessage}.
*/
public String getMessageId() {
return amqpAnnotatedMessage.getProperties().getMessageId();
}
/**
* Sets the message id.
*
* @param messageId to be set.
*
* @return The updated {@link ServiceBusMessage}.
*/
public ServiceBusMessage setMessageId(String messageId) {
amqpAnnotatedMessage.getProperties().setMessageId(messageId);
return this;
}
/**
* Gets the partition key for sending a message to a partitioned entity.
* <p>
* For <a href="https:
* entities</a>, setting this value enables assigning related messages to the same internal partition, so that
* submission sequence order is correctly recorded. The partition is chosen by a hash function over this value and
* cannot be chosen directly. For session-aware entities, the {@link
* this value.
*
* @return The partition key of this message
* @see <a href="https:
* entities</a>
*/
public String getPartitionKey() {
return (String) amqpAnnotatedMessage.getMessageAnnotations().get(PARTITION_KEY_ANNOTATION_NAME.getValue());
}
/**
* Sets a partition key for sending a message to a partitioned entity
*
* @param partitionKey partition key of this message
*
* @return The updated {@link ServiceBusMessage}.
* @see
*/
public ServiceBusMessage setPartitionKey(String partitionKey) {
amqpAnnotatedMessage.getMessageAnnotations().put(PARTITION_KEY_ANNOTATION_NAME.getValue(), partitionKey);
return this;
}
/**
* Gets the address of an entity to send replies to.
* <p>
* This optional and application-defined value is a standard way to express a reply path to the receiver of the
* message. When a sender expects a reply, it sets the value to the absolute or relative path of the queue or topic
* it expects the reply to be sent to.
*
* @return ReplyTo property value of this message
* @see <a href="https:
* Routing and Correlation</a>
*/
public String getReplyTo() {
return amqpAnnotatedMessage.getProperties().getReplyTo();
}
/**
* Sets the address of an entity to send replies to.
*
* @param replyTo ReplyTo property value of this message
*
* @return The updated {@link ServiceBusMessage}.
* @see
*/
public ServiceBusMessage setReplyTo(String replyTo) {
amqpAnnotatedMessage.getProperties().setReplyTo(replyTo);
return this;
}
/**
* Gets the "to" address.
*
* @return "To" property value of this message
*/
public String getTo() {
return amqpAnnotatedMessage.getProperties().getTo();
}
/**
* Sets the "to" address.
* <p>
* This property is reserved for future use in routing scenarios and presently ignored by the broker itself.
* Applications can use this value in rule-driven
* <a href="https:
* chaining</a> scenarios to indicate the intended logical destination of the message.
*
* @param to To property value of this message
*
* @return The updated {@link ServiceBusMessage}.
*/
public ServiceBusMessage setTo(String to) {
amqpAnnotatedMessage.getProperties().setTo(to);
return this;
}
/**
* Gets the duration before this message expires.
* <p>
* This value is the relative duration after which the message expires, starting from the instant the message has
* been accepted and stored by the broker, as captured in {@link
* explicitly, the assumed value is the DefaultTimeToLive set for the respective queue or topic. A message-level
* TimeToLive value cannot be longer than the entity's DefaultTimeToLive setting and it is silently adjusted if it
* does.
*
* @return Time to live duration of this message
* @see <a href="https:
*/
public Duration getTimeToLive() {
return amqpAnnotatedMessage.getHeader().getTimeToLive();
}
/**
* Sets the duration of time before this message expires.
*
* @param timeToLive Time to Live duration of this message
*
* @return The updated {@link ServiceBusMessage}.
* @see
*/
public ServiceBusMessage setTimeToLive(Duration timeToLive) {
amqpAnnotatedMessage.getHeader().setTimeToLive(timeToLive);
return this;
}
/**
* Gets the scheduled enqueue time of this message.
* <p>
* This value is used for delayed message availability. The message is safely added to the queue, but is not
* considered active and therefore not retrievable until the scheduled enqueue time. Mind that the message may not
* be activated (enqueued) at the exact given datetime; the actual activation time depends on the queue's workload
* and its state.
* </p>
*
* @return the datetime at which the message will be enqueued in Azure Service Bus
* @see <a href="https:
* Timestamps</a>
*/
public OffsetDateTime getScheduledEnqueueTime() {
OffsetDateTime scheduledEnqueueTime = null;
Map<String, Object> messageAnnotationMap = amqpAnnotatedMessage.getMessageAnnotations();
if (messageAnnotationMap.containsKey(SCHEDULED_ENQUEUE_UTC_TIME_NAME.getValue())) {
scheduledEnqueueTime = ((Date) messageAnnotationMap.get(SCHEDULED_ENQUEUE_UTC_TIME_NAME.getValue()))
.toInstant().atOffset(ZoneOffset.UTC);
}
return scheduledEnqueueTime;
}
/**
* Sets the scheduled enqueue time of this message.
*
* @param scheduledEnqueueTime the datetime at which this message should be enqueued in Azure Service Bus.
*
* @return The updated {@link ServiceBusMessage}.
* @see
*/
/**
* Gets or sets a session identifier augmenting the {@link
* <p>
* This value augments the ReplyTo information and specifies which SessionId should be set for the reply when sent
* to the reply entity.
*
* @return ReplyToSessionId property value of this message
* @see <a href="https:
* Routing and Correlation</a>
*/
public String getReplyToSessionId() {
return amqpAnnotatedMessage.getProperties().getReplyToGroupId();
}
/**
* Gets or sets a session identifier augmenting the {@link
*
* @param replyToSessionId ReplyToSessionId property value of this message
*
* @return The updated {@link ServiceBusMessage}.
*/
public ServiceBusMessage setReplyToSessionId(String replyToSessionId) {
amqpAnnotatedMessage.getProperties().setReplyToGroupId(replyToSessionId);
return this;
}
/**
* Gets the partition key for sending a message to a entity via another partitioned transfer entity.
*
* If a message is sent via a transfer queue in the scope of a transaction, this value selects the transfer queue
* partition: This is functionally equivalent to {@link
* together and in order as they are transferred.
*
* @return partition key on the via queue.
* @see <a href="https:
* and Send Via</a>
*/
public String getViaPartitionKey() {
return (String) amqpAnnotatedMessage.getMessageAnnotations().get(VIA_PARTITION_KEY_ANNOTATION_NAME.getValue());
}
/**
* Sets a via-partition key for sending a message to a destination entity via another partitioned entity
*
* @param viaPartitionKey via-partition key of this message
*
* @return The updated {@link ServiceBusMessage}.
* @see
*/
public ServiceBusMessage setViaPartitionKey(String viaPartitionKey) {
amqpAnnotatedMessage.getMessageAnnotations().put(VIA_PARTITION_KEY_ANNOTATION_NAME.getValue(), viaPartitionKey);
return this;
}
/**
* Gets the session id of the message.
*
* @return Session Id of the {@link ServiceBusMessage}.
*/
public String getSessionId() {
return amqpAnnotatedMessage.getProperties().getGroupId();
}
/**
* Sets the session id.
*
* @param sessionId to be set.
*
* @return The updated {@link ServiceBusMessage}.
*/
public ServiceBusMessage setSessionId(String sessionId) {
amqpAnnotatedMessage.getProperties().setGroupId(sessionId);
return this;
}
/**
* A specified key-value pair of type {@link Context} to set additional information on the {@link
* ServiceBusMessage}.
*
* @return the {@link Context} object set on the {@link ServiceBusMessage}.
*/
Context getContext() {
return context;
}
/**
* Adds a new key value pair to the existing context on Message.
*
* @param key The key for this context object
* @param value The value for this context object.
*
* @return The updated {@link ServiceBusMessage}.
* @throws NullPointerException if {@code key} or {@code value} is null.
*/
public ServiceBusMessage addContext(String key, Object value) {
Objects.requireNonNull(key, "The 'key' parameter cannot be null.");
Objects.requireNonNull(value, "The 'value' parameter cannot be null.");
this.context = context.addData(key, value);
return this;
}
/*
* Gets value from given map.
*/
private void removeValues(Map<String, Object> dataMap, AmqpMessageConstant... keys) {
for (AmqpMessageConstant key : keys) {
dataMap.remove(key.getValue());
}
}
} | class ServiceBusMessage {
private final AmqpAnnotatedMessage amqpAnnotatedMessage;
private final ClientLogger logger = new ClientLogger(ServiceBusMessage.class);
private final byte[] binaryData;
private Context context;
/**
* Creates a {@link ServiceBusMessage} with a {@link java.nio.charset.StandardCharsets
*
* @param body The content of the Service bus message.
*
* @throws NullPointerException if {@code body} is null.
*/
public ServiceBusMessage(String body) {
this(Objects.requireNonNull(body, "'body' cannot be null.").getBytes(StandardCharsets.UTF_8));
}
/**
* Creates a {@link ServiceBusMessage} containing the {@code body}.
*
* @param body The data to set for this {@link ServiceBusMessage}.
*
* @throws NullPointerException if {@code body} is {@code null}.
*/
public ServiceBusMessage(byte[] body) {
this.binaryData = Objects.requireNonNull(body, "'body' cannot be null.");
this.context = Context.NONE;
this.amqpAnnotatedMessage = new AmqpAnnotatedMessage(new AmqpDataBody(Collections.singletonList(
new BinaryData(binaryData))));
}
/**
* Creates a {@link ServiceBusMessage} using properties from {@code receivedMessage}. This is normally used when a
* {@link ServiceBusReceivedMessage} needs to be sent to another entity.
*
* @param receivedMessage The received message to create new message from.
*
* @throws NullPointerException if {@code receivedMessage} is {@code null}.
*/
public ServiceBusMessage(ServiceBusReceivedMessage receivedMessage) {
Objects.requireNonNull(receivedMessage, "'receivedMessage' cannot be null.");
this.amqpAnnotatedMessage = new AmqpAnnotatedMessage(receivedMessage.getAmqpAnnotatedMessage());
this.context = Context.NONE;
this.binaryData = receivedMessage.getBody();
amqpAnnotatedMessage.getHeader().setDeliveryCount(null);
removeValues(amqpAnnotatedMessage.getMessageAnnotations(), LOCKED_UNTIL_KEY_ANNOTATION_NAME,
SEQUENCE_NUMBER_ANNOTATION_NAME, DEAD_LETTER_SOURCE_KEY_ANNOTATION_NAME,
ENQUEUED_SEQUENCE_NUMBER_ANNOTATION_NAME, ENQUEUED_TIME_UTC_ANNOTATION_NAME);
removeValues(amqpAnnotatedMessage.getApplicationProperties(), DEAD_LETTER_DESCRIPTION_ANNOTATION_NAME,
DEAD_LETTER_REASON_ANNOTATION_NAME);
}
/**
* Gets the {@link AmqpAnnotatedMessage}.
*
* @return the amqp message.
*/
public AmqpAnnotatedMessage getAmqpAnnotatedMessage() {
return amqpAnnotatedMessage;
}
/**
* Gets the set of free-form {@link ServiceBusMessage} properties which may be used for passing metadata associated
* with the {@link ServiceBusMessage} during Service Bus operations. A common use-case for
* {@code getApplicationProperties()} is to associate serialization hints for the {@link
* consumers who wish to deserialize the binary data.
*
* @return Application properties associated with this {@link ServiceBusMessage}.
*/
public Map<String, Object> getApplicationProperties() {
return amqpAnnotatedMessage.getApplicationProperties();
}
/**
* Gets the actual payload/data wrapped by the {@link ServiceBusMessage}.
*
* <p>
* If the means for deserializing the raw data is not apparent to consumers, a common technique is to make use of
* {@link
* consumers who wish to deserialize the binary data.
* </p>
*
* @return A byte array representing the data.
*/
public byte[] getBody() {
final AmqpBodyType type = amqpAnnotatedMessage.getBody().getBodyType();
switch (type) {
case DATA:
return Arrays.copyOf(binaryData, binaryData.length);
case SEQUENCE:
case VALUE:
throw logger.logExceptionAsError(new UnsupportedOperationException("Not supported AmqpBodyType: "
+ type.toString()));
default:
throw logger.logExceptionAsError(new IllegalArgumentException("Unknown AmqpBodyType: "
+ type.toString()));
}
}
/**
* Gets the content type of the message.
*
* @return the contentType of the {@link ServiceBusMessage}.
*/
public String getContentType() {
return amqpAnnotatedMessage.getProperties().getContentType();
}
/**
* Sets the content type of the {@link ServiceBusMessage}.
*
* @param contentType of the message.
*
* @return The updated {@link ServiceBusMessage}.
*/
public ServiceBusMessage setContentType(String contentType) {
amqpAnnotatedMessage.getProperties().setContentType(contentType);
return this;
}
/**
* Gets a correlation identifier.
* <p>
* Allows an application to specify a context for the message for the purposes of correlation, for example
* reflecting the MessageId of a message that is being replied to.
* </p>
*
* @return correlation id of this message
* @see <a href="https:
* Routing and Correlation</a>
*/
public String getCorrelationId() {
return amqpAnnotatedMessage.getProperties().getCorrelationId();
}
/**
* Sets a correlation identifier.
*
* @param correlationId correlation id of this message
*
* @return The updated {@link ServiceBusMessage}.
* @see
*/
public ServiceBusMessage setCorrelationId(String correlationId) {
amqpAnnotatedMessage.getProperties().setCorrelationId(correlationId);
return this;
}
/**
* Gets the subject for the message.
*
* @return The subject for the message.
*/
public String getSubject() {
return amqpAnnotatedMessage.getProperties().getSubject();
}
/**
* Sets the subject for the message.
*
* @param subject The subject to set.
*
* @return The updated {@link ServiceBusMessage} object.
*/
public ServiceBusMessage setSubject(String subject) {
amqpAnnotatedMessage.getProperties().setSubject(subject);
return this;
}
/**
* @return Id of the {@link ServiceBusMessage}.
*/
public String getMessageId() {
return amqpAnnotatedMessage.getProperties().getMessageId();
}
/**
* Sets the message id.
*
* @param messageId to be set.
*
* @return The updated {@link ServiceBusMessage}.
*/
public ServiceBusMessage setMessageId(String messageId) {
amqpAnnotatedMessage.getProperties().setMessageId(messageId);
return this;
}
/**
* Gets the partition key for sending a message to a partitioned entity.
* <p>
* For <a href="https:
* entities</a>, setting this value enables assigning related messages to the same internal partition, so that
* submission sequence order is correctly recorded. The partition is chosen by a hash function over this value and
* cannot be chosen directly. For session-aware entities, the {@link
* this value.
*
* @return The partition key of this message
* @see <a href="https:
* entities</a>
*/
public String getPartitionKey() {
return (String) amqpAnnotatedMessage.getMessageAnnotations().get(PARTITION_KEY_ANNOTATION_NAME.getValue());
}
/**
* Sets a partition key for sending a message to a partitioned entity
*
* @param partitionKey partition key of this message
*
* @return The updated {@link ServiceBusMessage}.
* @see
*/
public ServiceBusMessage setPartitionKey(String partitionKey) {
amqpAnnotatedMessage.getMessageAnnotations().put(PARTITION_KEY_ANNOTATION_NAME.getValue(), partitionKey);
return this;
}
/**
* Gets the address of an entity to send replies to.
* <p>
* This optional and application-defined value is a standard way to express a reply path to the receiver of the
* message. When a sender expects a reply, it sets the value to the absolute or relative path of the queue or topic
* it expects the reply to be sent to.
*
* @return ReplyTo property value of this message
* @see <a href="https:
* Routing and Correlation</a>
*/
public String getReplyTo() {
return amqpAnnotatedMessage.getProperties().getReplyTo();
}
/**
* Sets the address of an entity to send replies to.
*
* @param replyTo ReplyTo property value of this message
*
* @return The updated {@link ServiceBusMessage}.
* @see
*/
public ServiceBusMessage setReplyTo(String replyTo) {
amqpAnnotatedMessage.getProperties().setReplyTo(replyTo);
return this;
}
/**
* Gets the "to" address.
*
* @return "To" property value of this message
*/
public String getTo() {
return amqpAnnotatedMessage.getProperties().getTo();
}
/**
* Sets the "to" address.
* <p>
* This property is reserved for future use in routing scenarios and presently ignored by the broker itself.
* Applications can use this value in rule-driven
* <a href="https:
* chaining</a> scenarios to indicate the intended logical destination of the message.
*
* @param to To property value of this message
*
* @return The updated {@link ServiceBusMessage}.
*/
public ServiceBusMessage setTo(String to) {
amqpAnnotatedMessage.getProperties().setTo(to);
return this;
}
/**
* Gets the duration before this message expires.
* <p>
* This value is the relative duration after which the message expires, starting from the instant the message has
* been accepted and stored by the broker, as captured in {@link
* explicitly, the assumed value is the DefaultTimeToLive set for the respective queue or topic. A message-level
* TimeToLive value cannot be longer than the entity's DefaultTimeToLive setting and it is silently adjusted if it
* does.
*
* @return Time to live duration of this message
* @see <a href="https:
*/
public Duration getTimeToLive() {
return amqpAnnotatedMessage.getHeader().getTimeToLive();
}
/**
* Sets the duration of time before this message expires.
*
* @param timeToLive Time to Live duration of this message
*
* @return The updated {@link ServiceBusMessage}.
* @see
*/
public ServiceBusMessage setTimeToLive(Duration timeToLive) {
amqpAnnotatedMessage.getHeader().setTimeToLive(timeToLive);
return this;
}
/**
* Gets the scheduled enqueue time of this message.
* <p>
* This value is used for delayed message availability. The message is safely added to the queue, but is not
* considered active and therefore not retrievable until the scheduled enqueue time. Mind that the message may not
* be activated (enqueued) at the exact given datetime; the actual activation time depends on the queue's workload
* and its state.
* </p>
*
* @return the datetime at which the message will be enqueued in Azure Service Bus
* @see <a href="https:
* Timestamps</a>
*/
public OffsetDateTime getScheduledEnqueueTime() {
Object value = amqpAnnotatedMessage.getMessageAnnotations().get(SCHEDULED_ENQUEUE_UTC_TIME_NAME.getValue());
return value != null
? ((Date) value).toInstant().atOffset(ZoneOffset.UTC)
: null;
}
/**
* Sets the scheduled enqueue time of this message. A {@code null} will not be set. If this value needs to be unset
* it could be done by value removing from {@link AmqpAnnotatedMessage
* {@link AmqpMessageConstant
*
* @param scheduledEnqueueTime the datetime at which this message should be enqueued in Azure Service Bus.
*
* @return The updated {@link ServiceBusMessage}.
* @see
*/
/**
* Gets or sets a session identifier augmenting the {@link
* <p>
* This value augments the ReplyTo information and specifies which SessionId should be set for the reply when sent
* to the reply entity.
*
* @return ReplyToSessionId property value of this message
* @see <a href="https:
* Routing and Correlation</a>
*/
public String getReplyToSessionId() {
return amqpAnnotatedMessage.getProperties().getReplyToGroupId();
}
/**
* Gets or sets a session identifier augmenting the {@link
*
* @param replyToSessionId ReplyToSessionId property value of this message
*
* @return The updated {@link ServiceBusMessage}.
*/
public ServiceBusMessage setReplyToSessionId(String replyToSessionId) {
amqpAnnotatedMessage.getProperties().setReplyToGroupId(replyToSessionId);
return this;
}
/**
* Gets the partition key for sending a message to a entity via another partitioned transfer entity.
*
* If a message is sent via a transfer queue in the scope of a transaction, this value selects the transfer queue
* partition: This is functionally equivalent to {@link
* together and in order as they are transferred.
*
* @return partition key on the via queue.
* @see <a href="https:
* and Send Via</a>
*/
public String getViaPartitionKey() {
return (String) amqpAnnotatedMessage.getMessageAnnotations().get(VIA_PARTITION_KEY_ANNOTATION_NAME.getValue());
}
/**
* Sets a via-partition key for sending a message to a destination entity via another partitioned entity
*
* @param viaPartitionKey via-partition key of this message
*
* @return The updated {@link ServiceBusMessage}.
* @see
*/
public ServiceBusMessage setViaPartitionKey(String viaPartitionKey) {
amqpAnnotatedMessage.getMessageAnnotations().put(VIA_PARTITION_KEY_ANNOTATION_NAME.getValue(), viaPartitionKey);
return this;
}
/**
* Gets the session id of the message.
*
* @return Session Id of the {@link ServiceBusMessage}.
*/
public String getSessionId() {
return amqpAnnotatedMessage.getProperties().getGroupId();
}
/**
* Sets the session id.
*
* @param sessionId to be set.
*
* @return The updated {@link ServiceBusMessage}.
*/
public ServiceBusMessage setSessionId(String sessionId) {
amqpAnnotatedMessage.getProperties().setGroupId(sessionId);
return this;
}
/**
* A specified key-value pair of type {@link Context} to set additional information on the {@link
* ServiceBusMessage}.
*
* @return the {@link Context} object set on the {@link ServiceBusMessage}.
*/
Context getContext() {
return context;
}
/**
* Adds a new key value pair to the existing context on Message.
*
* @param key The key for this context object
* @param value The value for this context object.
*
* @return The updated {@link ServiceBusMessage}.
* @throws NullPointerException if {@code key} or {@code value} is null.
*/
public ServiceBusMessage addContext(String key, Object value) {
Objects.requireNonNull(key, "The 'key' parameter cannot be null.");
Objects.requireNonNull(value, "The 'value' parameter cannot be null.");
this.context = context.addData(key, value);
return this;
}
/*
* Gets value from given map.
*/
private void removeValues(Map<String, Object> dataMap, AmqpMessageConstant... keys) {
for (AmqpMessageConstant key : keys) {
dataMap.remove(key.getValue());
}
}
} |
May be worthwhile to document here. it's odd having one method do one thing and then the other do something else. | public ServiceBusMessage setScheduledEnqueueTime(OffsetDateTime scheduledEnqueueTime) {
if (scheduledEnqueueTime != null) {
amqpAnnotatedMessage.getMessageAnnotations().put(SCHEDULED_ENQUEUE_UTC_TIME_NAME.getValue(),
scheduledEnqueueTime);
}
return this;
} | if (scheduledEnqueueTime != null) { | public ServiceBusMessage setScheduledEnqueueTime(OffsetDateTime scheduledEnqueueTime) {
if (scheduledEnqueueTime != null) {
amqpAnnotatedMessage.getMessageAnnotations().put(SCHEDULED_ENQUEUE_UTC_TIME_NAME.getValue(),
scheduledEnqueueTime);
}
return this;
} | class ServiceBusMessage {
private final AmqpAnnotatedMessage amqpAnnotatedMessage;
private final ClientLogger logger = new ClientLogger(ServiceBusMessage.class);
private final byte[] binaryData;
private Context context;
/**
* Creates a {@link ServiceBusMessage} with a {@link java.nio.charset.StandardCharsets
*
* @param body The content of the Service bus message.
*
* @throws NullPointerException if {@code body} is null.
*/
public ServiceBusMessage(String body) {
this(Objects.requireNonNull(body, "'body' cannot be null.").getBytes(StandardCharsets.UTF_8));
}
/**
* Creates a {@link ServiceBusMessage} containing the {@code body}.
*
* @param body The data to set for this {@link ServiceBusMessage}.
*
* @throws NullPointerException if {@code body} is {@code null}.
*/
public ServiceBusMessage(byte[] body) {
this.binaryData = Objects.requireNonNull(body, "'body' cannot be null.");
this.context = Context.NONE;
this.amqpAnnotatedMessage = new AmqpAnnotatedMessage(new AmqpDataBody(Collections.singletonList(
new BinaryData(binaryData))));
}
/**
* Creates a {@link ServiceBusMessage} using properties from {@code receivedMessage}. This is normally used when a
* {@link ServiceBusReceivedMessage} needs to be sent to another entity.
*
* @param receivedMessage The received message to create new message from.
*
* @throws NullPointerException if {@code receivedMessage} is {@code null}.
*/
public ServiceBusMessage(ServiceBusReceivedMessage receivedMessage) {
Objects.requireNonNull(receivedMessage, "'receivedMessage' cannot be null.");
this.amqpAnnotatedMessage = new AmqpAnnotatedMessage(receivedMessage.getAmqpAnnotatedMessage());
this.context = Context.NONE;
this.binaryData = receivedMessage.getBody();
amqpAnnotatedMessage.getHeader().setDeliveryCount(null);
removeValues(amqpAnnotatedMessage.getMessageAnnotations(), LOCKED_UNTIL_KEY_ANNOTATION_NAME,
SEQUENCE_NUMBER_ANNOTATION_NAME, DEAD_LETTER_SOURCE_KEY_ANNOTATION_NAME,
ENQUEUED_SEQUENCE_NUMBER_ANNOTATION_NAME, ENQUEUED_TIME_UTC_ANNOTATION_NAME);
removeValues(amqpAnnotatedMessage.getApplicationProperties(), DEAD_LETTER_DESCRIPTION_ANNOTATION_NAME,
DEAD_LETTER_REASON_ANNOTATION_NAME);
}
/**
* Gets the {@link AmqpAnnotatedMessage}.
*
* @return the amqp message.
*/
public AmqpAnnotatedMessage getAmqpAnnotatedMessage() {
return amqpAnnotatedMessage;
}
/**
* Gets the set of free-form {@link ServiceBusMessage} properties which may be used for passing metadata associated
* with the {@link ServiceBusMessage} during Service Bus operations. A common use-case for
* {@code getApplicationProperties()} is to associate serialization hints for the {@link
* consumers who wish to deserialize the binary data.
*
* @return Application properties associated with this {@link ServiceBusMessage}.
*/
public Map<String, Object> getApplicationProperties() {
return amqpAnnotatedMessage.getApplicationProperties();
}
/**
* Gets the actual payload/data wrapped by the {@link ServiceBusMessage}.
*
* <p>
* If the means for deserializing the raw data is not apparent to consumers, a common technique is to make use of
* {@link
* consumers who wish to deserialize the binary data.
* </p>
*
* @return A byte array representing the data.
*/
public byte[] getBody() {
final AmqpBodyType type = amqpAnnotatedMessage.getBody().getBodyType();
switch (type) {
case DATA:
return Arrays.copyOf(binaryData, binaryData.length);
case SEQUENCE:
case VALUE:
throw logger.logExceptionAsError(new UnsupportedOperationException("Not supported AmqpBodyType: "
+ type.toString()));
default:
throw logger.logExceptionAsError(new IllegalArgumentException("Unknown AmqpBodyType: "
+ type.toString()));
}
}
/**
* Gets the content type of the message.
*
* @return the contentType of the {@link ServiceBusMessage}.
*/
public String getContentType() {
return amqpAnnotatedMessage.getProperties().getContentType();
}
/**
* Sets the content type of the {@link ServiceBusMessage}.
*
* @param contentType of the message.
*
* @return The updated {@link ServiceBusMessage}.
*/
public ServiceBusMessage setContentType(String contentType) {
amqpAnnotatedMessage.getProperties().setContentType(contentType);
return this;
}
/**
* Gets a correlation identifier.
* <p>
* Allows an application to specify a context for the message for the purposes of correlation, for example
* reflecting the MessageId of a message that is being replied to.
* </p>
*
* @return correlation id of this message
* @see <a href="https:
* Routing and Correlation</a>
*/
public String getCorrelationId() {
return amqpAnnotatedMessage.getProperties().getCorrelationId();
}
/**
* Sets a correlation identifier.
*
* @param correlationId correlation id of this message
*
* @return The updated {@link ServiceBusMessage}.
* @see
*/
public ServiceBusMessage setCorrelationId(String correlationId) {
amqpAnnotatedMessage.getProperties().setCorrelationId(correlationId);
return this;
}
/**
* Gets the subject for the message.
*
* @return The subject for the message.
*/
public String getSubject() {
return amqpAnnotatedMessage.getProperties().getSubject();
}
/**
* Sets the subject for the message.
*
* @param subject The subject to set.
*
* @return The updated {@link ServiceBusMessage} object.
*/
public ServiceBusMessage setSubject(String subject) {
amqpAnnotatedMessage.getProperties().setSubject(subject);
return this;
}
/**
* @return Id of the {@link ServiceBusMessage}.
*/
public String getMessageId() {
return amqpAnnotatedMessage.getProperties().getMessageId();
}
/**
* Sets the message id.
*
* @param messageId to be set.
*
* @return The updated {@link ServiceBusMessage}.
*/
public ServiceBusMessage setMessageId(String messageId) {
amqpAnnotatedMessage.getProperties().setMessageId(messageId);
return this;
}
/**
* Gets the partition key for sending a message to a partitioned entity.
* <p>
* For <a href="https:
* entities</a>, setting this value enables assigning related messages to the same internal partition, so that
* submission sequence order is correctly recorded. The partition is chosen by a hash function over this value and
* cannot be chosen directly. For session-aware entities, the {@link
* this value.
*
* @return The partition key of this message
* @see <a href="https:
* entities</a>
*/
public String getPartitionKey() {
return (String) amqpAnnotatedMessage.getMessageAnnotations().get(PARTITION_KEY_ANNOTATION_NAME.getValue());
}
/**
* Sets a partition key for sending a message to a partitioned entity
*
* @param partitionKey partition key of this message
*
* @return The updated {@link ServiceBusMessage}.
* @see
*/
public ServiceBusMessage setPartitionKey(String partitionKey) {
amqpAnnotatedMessage.getMessageAnnotations().put(PARTITION_KEY_ANNOTATION_NAME.getValue(), partitionKey);
return this;
}
/**
* Gets the address of an entity to send replies to.
* <p>
* This optional and application-defined value is a standard way to express a reply path to the receiver of the
* message. When a sender expects a reply, it sets the value to the absolute or relative path of the queue or topic
* it expects the reply to be sent to.
*
* @return ReplyTo property value of this message
* @see <a href="https:
* Routing and Correlation</a>
*/
public String getReplyTo() {
return amqpAnnotatedMessage.getProperties().getReplyTo();
}
/**
* Sets the address of an entity to send replies to.
*
* @param replyTo ReplyTo property value of this message
*
* @return The updated {@link ServiceBusMessage}.
* @see
*/
public ServiceBusMessage setReplyTo(String replyTo) {
amqpAnnotatedMessage.getProperties().setReplyTo(replyTo);
return this;
}
/**
* Gets the "to" address.
*
* @return "To" property value of this message
*/
public String getTo() {
return amqpAnnotatedMessage.getProperties().getTo();
}
/**
* Sets the "to" address.
* <p>
* This property is reserved for future use in routing scenarios and presently ignored by the broker itself.
* Applications can use this value in rule-driven
* <a href="https:
* chaining</a> scenarios to indicate the intended logical destination of the message.
*
* @param to To property value of this message
*
* @return The updated {@link ServiceBusMessage}.
*/
public ServiceBusMessage setTo(String to) {
amqpAnnotatedMessage.getProperties().setTo(to);
return this;
}
/**
* Gets the duration before this message expires.
* <p>
* This value is the relative duration after which the message expires, starting from the instant the message has
* been accepted and stored by the broker, as captured in {@link
* explicitly, the assumed value is the DefaultTimeToLive set for the respective queue or topic. A message-level
* TimeToLive value cannot be longer than the entity's DefaultTimeToLive setting and it is silently adjusted if it
* does.
*
* @return Time to live duration of this message
* @see <a href="https:
*/
public Duration getTimeToLive() {
return amqpAnnotatedMessage.getHeader().getTimeToLive();
}
/**
* Sets the duration of time before this message expires.
*
* @param timeToLive Time to Live duration of this message
*
* @return The updated {@link ServiceBusMessage}.
* @see
*/
public ServiceBusMessage setTimeToLive(Duration timeToLive) {
amqpAnnotatedMessage.getHeader().setTimeToLive(timeToLive);
return this;
}
/**
* Gets the scheduled enqueue time of this message.
* <p>
* This value is used for delayed message availability. The message is safely added to the queue, but is not
* considered active and therefore not retrievable until the scheduled enqueue time. Mind that the message may not
* be activated (enqueued) at the exact given datetime; the actual activation time depends on the queue's workload
* and its state.
* </p>
*
* @return the datetime at which the message will be enqueued in Azure Service Bus
* @see <a href="https:
* Timestamps</a>
*/
public OffsetDateTime getScheduledEnqueueTime() {
OffsetDateTime scheduledEnqueueTime = null;
Map<String, Object> messageAnnotationMap = amqpAnnotatedMessage.getMessageAnnotations();
if (messageAnnotationMap.containsKey(SCHEDULED_ENQUEUE_UTC_TIME_NAME.getValue())) {
scheduledEnqueueTime = ((Date) messageAnnotationMap.get(SCHEDULED_ENQUEUE_UTC_TIME_NAME.getValue()))
.toInstant().atOffset(ZoneOffset.UTC);
}
return scheduledEnqueueTime;
}
/**
* Sets the scheduled enqueue time of this message.
*
* @param scheduledEnqueueTime the datetime at which this message should be enqueued in Azure Service Bus.
*
* @return The updated {@link ServiceBusMessage}.
* @see
*/
/**
* Gets or sets a session identifier augmenting the {@link
* <p>
* This value augments the ReplyTo information and specifies which SessionId should be set for the reply when sent
* to the reply entity.
*
* @return ReplyToSessionId property value of this message
* @see <a href="https:
* Routing and Correlation</a>
*/
public String getReplyToSessionId() {
return amqpAnnotatedMessage.getProperties().getReplyToGroupId();
}
/**
* Gets or sets a session identifier augmenting the {@link
*
* @param replyToSessionId ReplyToSessionId property value of this message
*
* @return The updated {@link ServiceBusMessage}.
*/
public ServiceBusMessage setReplyToSessionId(String replyToSessionId) {
amqpAnnotatedMessage.getProperties().setReplyToGroupId(replyToSessionId);
return this;
}
/**
* Gets the partition key for sending a message to a entity via another partitioned transfer entity.
*
* If a message is sent via a transfer queue in the scope of a transaction, this value selects the transfer queue
* partition: This is functionally equivalent to {@link
* together and in order as they are transferred.
*
* @return partition key on the via queue.
* @see <a href="https:
* and Send Via</a>
*/
public String getViaPartitionKey() {
return (String) amqpAnnotatedMessage.getMessageAnnotations().get(VIA_PARTITION_KEY_ANNOTATION_NAME.getValue());
}
/**
* Sets a via-partition key for sending a message to a destination entity via another partitioned entity
*
* @param viaPartitionKey via-partition key of this message
*
* @return The updated {@link ServiceBusMessage}.
* @see
*/
public ServiceBusMessage setViaPartitionKey(String viaPartitionKey) {
amqpAnnotatedMessage.getMessageAnnotations().put(VIA_PARTITION_KEY_ANNOTATION_NAME.getValue(), viaPartitionKey);
return this;
}
/**
* Gets the session id of the message.
*
* @return Session Id of the {@link ServiceBusMessage}.
*/
public String getSessionId() {
return amqpAnnotatedMessage.getProperties().getGroupId();
}
/**
* Sets the session id.
*
* @param sessionId to be set.
*
* @return The updated {@link ServiceBusMessage}.
*/
public ServiceBusMessage setSessionId(String sessionId) {
amqpAnnotatedMessage.getProperties().setGroupId(sessionId);
return this;
}
/**
* A specified key-value pair of type {@link Context} to set additional information on the {@link
* ServiceBusMessage}.
*
* @return the {@link Context} object set on the {@link ServiceBusMessage}.
*/
Context getContext() {
return context;
}
/**
* Adds a new key value pair to the existing context on Message.
*
* @param key The key for this context object
* @param value The value for this context object.
*
* @return The updated {@link ServiceBusMessage}.
* @throws NullPointerException if {@code key} or {@code value} is null.
*/
public ServiceBusMessage addContext(String key, Object value) {
Objects.requireNonNull(key, "The 'key' parameter cannot be null.");
Objects.requireNonNull(value, "The 'value' parameter cannot be null.");
this.context = context.addData(key, value);
return this;
}
/*
* Gets value from given map.
*/
private void removeValues(Map<String, Object> dataMap, AmqpMessageConstant... keys) {
for (AmqpMessageConstant key : keys) {
dataMap.remove(key.getValue());
}
}
} | class ServiceBusMessage {
private final AmqpAnnotatedMessage amqpAnnotatedMessage;
private final ClientLogger logger = new ClientLogger(ServiceBusMessage.class);
private final byte[] binaryData;
private Context context;
/**
* Creates a {@link ServiceBusMessage} with a {@link java.nio.charset.StandardCharsets
*
* @param body The content of the Service bus message.
*
* @throws NullPointerException if {@code body} is null.
*/
public ServiceBusMessage(String body) {
this(Objects.requireNonNull(body, "'body' cannot be null.").getBytes(StandardCharsets.UTF_8));
}
/**
* Creates a {@link ServiceBusMessage} containing the {@code body}.
*
* @param body The data to set for this {@link ServiceBusMessage}.
*
* @throws NullPointerException if {@code body} is {@code null}.
*/
public ServiceBusMessage(byte[] body) {
this.binaryData = Objects.requireNonNull(body, "'body' cannot be null.");
this.context = Context.NONE;
this.amqpAnnotatedMessage = new AmqpAnnotatedMessage(new AmqpDataBody(Collections.singletonList(
new BinaryData(binaryData))));
}
/**
* Creates a {@link ServiceBusMessage} using properties from {@code receivedMessage}. This is normally used when a
* {@link ServiceBusReceivedMessage} needs to be sent to another entity.
*
* @param receivedMessage The received message to create new message from.
*
* @throws NullPointerException if {@code receivedMessage} is {@code null}.
*/
public ServiceBusMessage(ServiceBusReceivedMessage receivedMessage) {
Objects.requireNonNull(receivedMessage, "'receivedMessage' cannot be null.");
this.amqpAnnotatedMessage = new AmqpAnnotatedMessage(receivedMessage.getAmqpAnnotatedMessage());
this.context = Context.NONE;
this.binaryData = receivedMessage.getBody();
amqpAnnotatedMessage.getHeader().setDeliveryCount(null);
removeValues(amqpAnnotatedMessage.getMessageAnnotations(), LOCKED_UNTIL_KEY_ANNOTATION_NAME,
SEQUENCE_NUMBER_ANNOTATION_NAME, DEAD_LETTER_SOURCE_KEY_ANNOTATION_NAME,
ENQUEUED_SEQUENCE_NUMBER_ANNOTATION_NAME, ENQUEUED_TIME_UTC_ANNOTATION_NAME);
removeValues(amqpAnnotatedMessage.getApplicationProperties(), DEAD_LETTER_DESCRIPTION_ANNOTATION_NAME,
DEAD_LETTER_REASON_ANNOTATION_NAME);
}
/**
* Gets the {@link AmqpAnnotatedMessage}.
*
* @return the amqp message.
*/
public AmqpAnnotatedMessage getAmqpAnnotatedMessage() {
return amqpAnnotatedMessage;
}
/**
* Gets the set of free-form {@link ServiceBusMessage} properties which may be used for passing metadata associated
* with the {@link ServiceBusMessage} during Service Bus operations. A common use-case for
* {@code getApplicationProperties()} is to associate serialization hints for the {@link
* consumers who wish to deserialize the binary data.
*
* @return Application properties associated with this {@link ServiceBusMessage}.
*/
public Map<String, Object> getApplicationProperties() {
return amqpAnnotatedMessage.getApplicationProperties();
}
/**
* Gets the actual payload/data wrapped by the {@link ServiceBusMessage}.
*
* <p>
* If the means for deserializing the raw data is not apparent to consumers, a common technique is to make use of
* {@link
* consumers who wish to deserialize the binary data.
* </p>
*
* @return A byte array representing the data.
*/
public byte[] getBody() {
final AmqpBodyType type = amqpAnnotatedMessage.getBody().getBodyType();
switch (type) {
case DATA:
return Arrays.copyOf(binaryData, binaryData.length);
case SEQUENCE:
case VALUE:
throw logger.logExceptionAsError(new UnsupportedOperationException("Not supported AmqpBodyType: "
+ type.toString()));
default:
throw logger.logExceptionAsError(new IllegalArgumentException("Unknown AmqpBodyType: "
+ type.toString()));
}
}
/**
* Gets the content type of the message.
*
* @return the contentType of the {@link ServiceBusMessage}.
*/
public String getContentType() {
return amqpAnnotatedMessage.getProperties().getContentType();
}
/**
* Sets the content type of the {@link ServiceBusMessage}.
*
* @param contentType of the message.
*
* @return The updated {@link ServiceBusMessage}.
*/
public ServiceBusMessage setContentType(String contentType) {
amqpAnnotatedMessage.getProperties().setContentType(contentType);
return this;
}
/**
* Gets a correlation identifier.
* <p>
* Allows an application to specify a context for the message for the purposes of correlation, for example
* reflecting the MessageId of a message that is being replied to.
* </p>
*
* @return correlation id of this message
* @see <a href="https:
* Routing and Correlation</a>
*/
public String getCorrelationId() {
return amqpAnnotatedMessage.getProperties().getCorrelationId();
}
/**
* Sets a correlation identifier.
*
* @param correlationId correlation id of this message
*
* @return The updated {@link ServiceBusMessage}.
* @see
*/
public ServiceBusMessage setCorrelationId(String correlationId) {
amqpAnnotatedMessage.getProperties().setCorrelationId(correlationId);
return this;
}
/**
* Gets the subject for the message.
*
* @return The subject for the message.
*/
public String getSubject() {
return amqpAnnotatedMessage.getProperties().getSubject();
}
/**
* Sets the subject for the message.
*
* @param subject The subject to set.
*
* @return The updated {@link ServiceBusMessage} object.
*/
public ServiceBusMessage setSubject(String subject) {
amqpAnnotatedMessage.getProperties().setSubject(subject);
return this;
}
/**
* @return Id of the {@link ServiceBusMessage}.
*/
public String getMessageId() {
return amqpAnnotatedMessage.getProperties().getMessageId();
}
/**
* Sets the message id.
*
* @param messageId to be set.
*
* @return The updated {@link ServiceBusMessage}.
*/
public ServiceBusMessage setMessageId(String messageId) {
amqpAnnotatedMessage.getProperties().setMessageId(messageId);
return this;
}
/**
* Gets the partition key for sending a message to a partitioned entity.
* <p>
* For <a href="https:
* entities</a>, setting this value enables assigning related messages to the same internal partition, so that
* submission sequence order is correctly recorded. The partition is chosen by a hash function over this value and
* cannot be chosen directly. For session-aware entities, the {@link
* this value.
*
* @return The partition key of this message
* @see <a href="https:
* entities</a>
*/
public String getPartitionKey() {
return (String) amqpAnnotatedMessage.getMessageAnnotations().get(PARTITION_KEY_ANNOTATION_NAME.getValue());
}
/**
* Sets a partition key for sending a message to a partitioned entity
*
* @param partitionKey partition key of this message
*
* @return The updated {@link ServiceBusMessage}.
* @see
*/
public ServiceBusMessage setPartitionKey(String partitionKey) {
amqpAnnotatedMessage.getMessageAnnotations().put(PARTITION_KEY_ANNOTATION_NAME.getValue(), partitionKey);
return this;
}
/**
* Gets the address of an entity to send replies to.
* <p>
* This optional and application-defined value is a standard way to express a reply path to the receiver of the
* message. When a sender expects a reply, it sets the value to the absolute or relative path of the queue or topic
* it expects the reply to be sent to.
*
* @return ReplyTo property value of this message
* @see <a href="https:
* Routing and Correlation</a>
*/
public String getReplyTo() {
return amqpAnnotatedMessage.getProperties().getReplyTo();
}
/**
* Sets the address of an entity to send replies to.
*
* @param replyTo ReplyTo property value of this message
*
* @return The updated {@link ServiceBusMessage}.
* @see
*/
public ServiceBusMessage setReplyTo(String replyTo) {
amqpAnnotatedMessage.getProperties().setReplyTo(replyTo);
return this;
}
/**
* Gets the "to" address.
*
* @return "To" property value of this message
*/
public String getTo() {
return amqpAnnotatedMessage.getProperties().getTo();
}
/**
* Sets the "to" address.
* <p>
* This property is reserved for future use in routing scenarios and presently ignored by the broker itself.
* Applications can use this value in rule-driven
* <a href="https:
* chaining</a> scenarios to indicate the intended logical destination of the message.
*
* @param to To property value of this message
*
* @return The updated {@link ServiceBusMessage}.
*/
public ServiceBusMessage setTo(String to) {
amqpAnnotatedMessage.getProperties().setTo(to);
return this;
}
/**
* Gets the duration before this message expires.
* <p>
* This value is the relative duration after which the message expires, starting from the instant the message has
* been accepted and stored by the broker, as captured in {@link
* explicitly, the assumed value is the DefaultTimeToLive set for the respective queue or topic. A message-level
* TimeToLive value cannot be longer than the entity's DefaultTimeToLive setting and it is silently adjusted if it
* does.
*
* @return Time to live duration of this message
* @see <a href="https:
*/
public Duration getTimeToLive() {
return amqpAnnotatedMessage.getHeader().getTimeToLive();
}
/**
* Sets the duration of time before this message expires.
*
* @param timeToLive Time to Live duration of this message
*
* @return The updated {@link ServiceBusMessage}.
* @see
*/
public ServiceBusMessage setTimeToLive(Duration timeToLive) {
amqpAnnotatedMessage.getHeader().setTimeToLive(timeToLive);
return this;
}
/**
* Gets the scheduled enqueue time of this message.
* <p>
* This value is used for delayed message availability. The message is safely added to the queue, but is not
* considered active and therefore not retrievable until the scheduled enqueue time. Mind that the message may not
* be activated (enqueued) at the exact given datetime; the actual activation time depends on the queue's workload
* and its state.
* </p>
*
* @return the datetime at which the message will be enqueued in Azure Service Bus
* @see <a href="https:
* Timestamps</a>
*/
public OffsetDateTime getScheduledEnqueueTime() {
Object value = amqpAnnotatedMessage.getMessageAnnotations().get(SCHEDULED_ENQUEUE_UTC_TIME_NAME.getValue());
return value != null
? ((Date) value).toInstant().atOffset(ZoneOffset.UTC)
: null;
}
/**
* Sets the scheduled enqueue time of this message. A {@code null} will not be set. If this value needs to be unset
* it could be done by value removing from {@link AmqpAnnotatedMessage
* {@link AmqpMessageConstant
*
* @param scheduledEnqueueTime the datetime at which this message should be enqueued in Azure Service Bus.
*
* @return The updated {@link ServiceBusMessage}.
* @see
*/
/**
* Gets or sets a session identifier augmenting the {@link
* <p>
* This value augments the ReplyTo information and specifies which SessionId should be set for the reply when sent
* to the reply entity.
*
* @return ReplyToSessionId property value of this message
* @see <a href="https:
* Routing and Correlation</a>
*/
public String getReplyToSessionId() {
return amqpAnnotatedMessage.getProperties().getReplyToGroupId();
}
/**
* Gets or sets a session identifier augmenting the {@link
*
* @param replyToSessionId ReplyToSessionId property value of this message
*
* @return The updated {@link ServiceBusMessage}.
*/
public ServiceBusMessage setReplyToSessionId(String replyToSessionId) {
amqpAnnotatedMessage.getProperties().setReplyToGroupId(replyToSessionId);
return this;
}
/**
* Gets the partition key for sending a message to a entity via another partitioned transfer entity.
*
* If a message is sent via a transfer queue in the scope of a transaction, this value selects the transfer queue
* partition: This is functionally equivalent to {@link
* together and in order as they are transferred.
*
* @return partition key on the via queue.
* @see <a href="https:
* and Send Via</a>
*/
public String getViaPartitionKey() {
return (String) amqpAnnotatedMessage.getMessageAnnotations().get(VIA_PARTITION_KEY_ANNOTATION_NAME.getValue());
}
/**
* Sets a via-partition key for sending a message to a destination entity via another partitioned entity
*
* @param viaPartitionKey via-partition key of this message
*
* @return The updated {@link ServiceBusMessage}.
* @see
*/
public ServiceBusMessage setViaPartitionKey(String viaPartitionKey) {
amqpAnnotatedMessage.getMessageAnnotations().put(VIA_PARTITION_KEY_ANNOTATION_NAME.getValue(), viaPartitionKey);
return this;
}
/**
* Gets the session id of the message.
*
* @return Session Id of the {@link ServiceBusMessage}.
*/
public String getSessionId() {
return amqpAnnotatedMessage.getProperties().getGroupId();
}
/**
* Sets the session id.
*
* @param sessionId to be set.
*
* @return The updated {@link ServiceBusMessage}.
*/
public ServiceBusMessage setSessionId(String sessionId) {
amqpAnnotatedMessage.getProperties().setGroupId(sessionId);
return this;
}
/**
* A specified key-value pair of type {@link Context} to set additional information on the {@link
* ServiceBusMessage}.
*
* @return the {@link Context} object set on the {@link ServiceBusMessage}.
*/
Context getContext() {
return context;
}
/**
* Adds a new key value pair to the existing context on Message.
*
* @param key The key for this context object
* @param value The value for this context object.
*
* @return The updated {@link ServiceBusMessage}.
* @throws NullPointerException if {@code key} or {@code value} is null.
*/
public ServiceBusMessage addContext(String key, Object value) {
Objects.requireNonNull(key, "The 'key' parameter cannot be null.");
Objects.requireNonNull(value, "The 'value' parameter cannot be null.");
this.context = context.addData(key, value);
return this;
}
/*
* Gets value from given map.
*/
private void removeValues(Map<String, Object> dataMap, AmqpMessageConstant... keys) {
for (AmqpMessageConstant key : keys) {
dataMap.remove(key.getValue());
}
}
} |
yeah, this file no longer exists so updated the sample. | public static void main(final String[] args) {
FormRecognizerAsyncClient client = new FormRecognizerClientBuilder()
.credential(new AzureKeyCredential("{key}"))
.endpoint("https:
.buildAsyncClient();
PollerFlux<FormRecognizerOperationResult, List<FormPage>> recognizeContentPoller =
client.beginRecognizeContentFromUrl("https:
Mono<List<FormPage>> contentPageResults = recognizeContentPoller
.last()
.flatMap(pollResponse -> {
if (pollResponse.getStatus().isComplete()) {
return pollResponse.getFinalResult();
} else {
return Mono.error(new RuntimeException("Polling completed unsuccessfully with status:"
+ pollResponse.getStatus()));
}
});
contentPageResults.subscribe(formPages -> {
for (int i = 0; i < formPages.size(); i++) {
final FormPage formPage = formPages.get(i);
System.out.printf("---- Recognized content info for page %d ----%n", i);
System.out.printf("Has width: %f and height: %f, measured with unit: %s%n", formPage.getWidth(),
formPage.getHeight(),
formPage.getUnit());
final List<FormTable> tables = formPage.getTables();
for (int i1 = 0; i1 < tables.size(); i1++) {
final FormTable formTable = tables.get(i1);
System.out.printf("Table %d has %d rows and %d columns.%n", i1, formTable.getRowCount(),
formTable.getColumnCount());
formTable.getCells().forEach(formTableCell -> {
final StringBuilder boundingBoxStr = new StringBuilder();
if (formTableCell.getBoundingBox() != null) {
formTableCell.getBoundingBox().getPoints().forEach(point ->
boundingBoxStr.append(String.format("[%.2f, %.2f]", point.getX(), point.getY())));
}
System.out.printf("Cell has text '%s', within bounding box %s.%n", formTableCell.getText(),
boundingBoxStr);
});
System.out.println();
}
}
});
try {
TimeUnit.MINUTES.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
} | client.beginRecognizeContentFromUrl("https: | public static void main(final String[] args) {
FormRecognizerAsyncClient client = new FormRecognizerClientBuilder()
.credential(new AzureKeyCredential("{key}"))
.endpoint("https:
.buildAsyncClient();
PollerFlux<FormRecognizerOperationResult, List<FormPage>> recognizeContentPoller =
client.beginRecognizeContentFromUrl("https:
Mono<List<FormPage>> contentPageResults = recognizeContentPoller
.last()
.flatMap(pollResponse -> {
if (pollResponse.getStatus().isComplete()) {
return pollResponse.getFinalResult();
} else {
return Mono.error(new RuntimeException("Polling completed unsuccessfully with status:"
+ pollResponse.getStatus()));
}
});
contentPageResults.subscribe(formPages -> {
for (int i = 0; i < formPages.size(); i++) {
final FormPage formPage = formPages.get(i);
System.out.printf("---- Recognized content info for page %d ----%n", i);
System.out.printf("Has width: %f and height: %f, measured with unit: %s%n", formPage.getWidth(),
formPage.getHeight(),
formPage.getUnit());
final List<FormTable> tables = formPage.getTables();
for (int i1 = 0; i1 < tables.size(); i1++) {
final FormTable formTable = tables.get(i1);
System.out.printf("Table %d has %d rows and %d columns.%n", i1, formTable.getRowCount(),
formTable.getColumnCount());
formTable.getCells().forEach(formTableCell -> {
final StringBuilder boundingBoxStr = new StringBuilder();
if (formTableCell.getBoundingBox() != null) {
formTableCell.getBoundingBox().getPoints().forEach(point ->
boundingBoxStr.append(String.format("[%.2f, %.2f]", point.getX(), point.getY())));
}
System.out.printf("Cell has text '%s', within bounding box %s.%n", formTableCell.getText(),
boundingBoxStr);
});
System.out.println();
}
}
});
try {
TimeUnit.MINUTES.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
} | class RecognizeContentFromUrlAsync {
/**
* Main method to invoke this demo.
*
* @param args Unused. Arguments to the program.
*/
} | class RecognizeContentFromUrlAsync {
/**
* Main method to invoke this demo.
*
* @param args Unused. Arguments to the program.
*/
} |
``` return digitalTwinsAsyncClient.createModelsWithResponse(models, Context.NONE) .map(Response::getValue).block(); ``` | public List<ModelData> createModels(List<String> models) {
return digitalTwinsAsyncClient.createModels(models).block();
} | return digitalTwinsAsyncClient.createModels(models).block(); | public List<ModelData> createModels(List<String> models) {
return createModelsWithResponse(models, Context.NONE).getValue();
} | class to convert the relationship to.
* @param <T> The generic type to convert the relationship to.
* @param context Additional context that is passed through the Http pipeline during the service call.
* @return A {@link PagedIterable} | class to convert the relationship to.
* @param <T> The generic type to convert the relationship to.
* @param context Additional context that is passed through the Http pipeline during the service call.
* @return A {@link PagedIterable} |
nit: we've been following the pattern where each sync API calls its max arg overload, and the max arg overload calls into the async API; so this could call `createModelsWithResponse(List<String> models, Context context)` sync API with `Context.None`. | public List<ModelData> createModels(List<String> models) {
return digitalTwinsAsyncClient.createModels(models).block();
} | return digitalTwinsAsyncClient.createModels(models).block(); | public List<ModelData> createModels(List<String> models) {
return createModelsWithResponse(models, Context.NONE).getValue();
} | class to convert the relationship to.
* @param <T> The generic type to convert the relationship to.
* @param context Additional context that is passed through the Http pipeline during the service call.
* @return A {@link PagedIterable} | class to convert the relationship to.
* @param <T> The generic type to convert the relationship to.
* @param context Additional context that is passed through the Http pipeline during the service call.
* @return A {@link PagedIterable} |
👍 | public static void createAllModels() throws IOException, InterruptedException {
System.out.println("CREATING MODELS");
List<String> modelsToCreate = new ArrayList<>(FileHelper.loadAllFilesInPath(ModelsPath).values());
final CountDownLatch createModelsLatch = new CountDownLatch(1);
client.createModels(modelsToCreate)
.doOnNext(listOfModelData -> System.out.println("Count of created models: " + listOfModelData.size()))
.doOnError(IgnoreConflictError)
.doOnTerminate(createModelsLatch::countDown)
.subscribe();
createModelsLatch.await(MaxWaitTimeAsyncOperationsInSeconds, TimeUnit.SECONDS);
} | .doOnNext(listOfModelData -> System.out.println("Count of created models: " + listOfModelData.size())) | public static void createAllModels() throws IOException, InterruptedException {
System.out.println("CREATING MODELS");
List<String> modelsToCreate = new ArrayList<>(FileHelper.loadAllFilesInPath(ModelsPath).values());
final CountDownLatch createModelsLatch = new CountDownLatch(1);
client.createModels(modelsToCreate)
.doOnNext(listOfModelData -> System.out.println("Count of created models: " + listOfModelData.size()))
.doOnError(IgnoreConflictError)
.doOnTerminate(createModelsLatch::countDown)
.subscribe();
createModelsLatch.await(MaxWaitTimeAsyncOperationsInSeconds, TimeUnit.SECONDS);
} | class DigitalTwinsLifecycleAsyncSample {
private static final int MaxWaitTimeAsyncOperationsInSeconds = 10;
private static final ObjectMapper mapper = new ObjectMapper();
private static final URL DtdlDirectoryUrl = DigitalTwinsLifecycleAsyncSample.class.getClassLoader().getResource("DTDL");
private static final Path DtDlDirectoryPath;
private static final Path TwinsPath;
private static final Path ModelsPath;
private static final Path RelationshipsPath;
private static DigitalTwinsAsyncClient client;
static {
try {
assert DtdlDirectoryUrl != null;
DtDlDirectoryPath = Paths.get(DtdlDirectoryUrl.toURI());
} catch (URISyntaxException e) {
throw new RuntimeException("Unable to convert the DTDL directory URL to URI", e);
}
TwinsPath = Paths.get(DtDlDirectoryPath.toString(), "DigitalTwins");
ModelsPath = Paths.get(DtDlDirectoryPath.toString(), "Models");
RelationshipsPath = Paths.get(DtDlDirectoryPath.toString(), "Relationships");
}
public static void main(String[] args) throws IOException, InterruptedException {
SamplesArguments parsedArguments = new SamplesArguments(args);
client = new DigitalTwinsClientBuilder()
.tokenCredential(
new ClientSecretCredentialBuilder()
.tenantId(parsedArguments.getTenantId())
.clientId(parsedArguments.getClientId())
.clientSecret(parsedArguments.getClientSecret())
.build()
)
.endpoint(parsedArguments.getDigitalTwinEndpoint())
.httpLogOptions(
new HttpLogOptions()
.setLogLevel(parsedArguments.getHttpLogDetailLevel()))
.buildAsyncClient();
deleteTwins();
deleteAllModels();
createAllModels();
listAllModels();
createAllTwins();
connectTwinsTogether();
}
/**
* Delete a twin, and any relationships it might have.
* @throws IOException If an I/O error is thrown when accessing the starting file.
* @throws InterruptedException If the current thread is interrupted while waiting to acquire latch.
*/
public static void deleteTwins() throws IOException, InterruptedException {
System.out.println("DELETE DIGITAL TWINS");
Map<String, String> twins = FileHelper.loadAllFilesInPath(TwinsPath);
for (Map.Entry<String, String> twin : twins.entrySet()) {
String twinId = twin.getKey();
List<BasicRelationship> relationshipList = Collections.synchronizedList(new ArrayList<>());
Semaphore listRelationshipSemaphore = new Semaphore(0);
Semaphore deleteRelationshipsSemaphore = new Semaphore(0);
CountDownLatch deleteTwinsLatch = new CountDownLatch(1);
client.listRelationships(twinId, BasicRelationship.class)
.doOnNext(relationshipList::add)
.doOnError(IgnoreNotFoundError)
.doOnTerminate(listRelationshipSemaphore::release)
.subscribe();
client.listIncomingRelationships(twinId)
.doOnNext(e -> relationshipList.add(mapper.convertValue(e, BasicRelationship.class)))
.doOnError(IgnoreNotFoundError)
.doOnTerminate(listRelationshipSemaphore::release)
.subscribe();
if (listRelationshipSemaphore.tryAcquire(2, MaxWaitTimeAsyncOperationsInSeconds, TimeUnit.SECONDS)) {
relationshipList
.forEach(relationship -> client.deleteRelationship(relationship.getSourceId(), relationship.getId())
.doOnSuccess(aVoid -> {
if (twinId.equals(relationship.getSourceId())) {
System.out.println("Found and deleted relationship: " + relationship.getId());
} else {
System.out.println("Found and deleted incoming relationship: " + relationship.getId());
}
})
.doOnError(IgnoreNotFoundError)
.doOnTerminate(deleteRelationshipsSemaphore::release)
.subscribe());
}
if (deleteRelationshipsSemaphore.tryAcquire(relationshipList.size(), MaxWaitTimeAsyncOperationsInSeconds, TimeUnit.SECONDS)) {
client.deleteDigitalTwin(twinId)
.doOnSuccess(aVoid -> System.out.println("Deleted digital twin: " + twinId))
.doOnError(IgnoreNotFoundError)
.doOnTerminate(deleteTwinsLatch::countDown)
.subscribe();
deleteTwinsLatch.await(MaxWaitTimeAsyncOperationsInSeconds, TimeUnit.SECONDS);
}
}
}
/**
* Delete models created by FullLifecycleSample for the ADT service instance.
* @throws InterruptedException If the current thread is interrupted while waiting to acquire latch.
*/
public static void deleteAllModels() throws InterruptedException {
System.out.println("DELETING MODELS");
List<String> models = asList(RoomModelId, WifiModelId, BuildingModelId, FloorModelId, HvacModelId);
models
.forEach(modelId -> {
try {
client.deleteModel(modelId).block();
System.out.println("Deleted model: " + modelId);
} catch (ErrorResponseException ex) {
if (ex.getResponse().getStatusCode() != HttpStatus.SC_NOT_FOUND) {
System.err.println("Could not delete model " + modelId + " due to " + ex);
}
}
});
}
/**
* Loads all the models found in the Models directory into memory and uses CreateModelsAsync API to create all the models in the ADT service instance.
* @throws IOException If an I/O error is thrown when accessing the starting file.
* @throws InterruptedException If the current thread is interrupted while waiting to acquire latch.
*/
/**
* Gets all the models within the ADT service instance.
* @throws InterruptedException If the current thread is interrupted while waiting to acquire latch.
*/
public static void listAllModels() throws InterruptedException {
System.out.println("LISTING MODELS");
final CountDownLatch listModelsLatch = new CountDownLatch(1);
client.listModels()
.doOnNext(modelData -> System.out.println("Retrieved model: " + modelData.getId() + ", display name '" + modelData.getDisplayName().get("en") + "'," +
" upload time '" + modelData.getUploadTime() + "' and decommissioned '" + modelData.isDecommissioned() + "'"))
.doOnError(throwable -> System.err.println("List models error: " + throwable))
.doOnTerminate(listModelsLatch::countDown)
.subscribe();
listModelsLatch.await(MaxWaitTimeAsyncOperationsInSeconds, TimeUnit.SECONDS);
}
/**
* Creates all twins specified in the DTDL->DigitalTwins directory.
* @throws IOException If an I/O error is thrown when accessing the starting file.
* @throws InterruptedException If the current thread is interrupted while waiting to acquire latch.
*/
public static void createAllTwins() throws IOException, InterruptedException {
System.out.println("CREATE DIGITAL TWINS");
Map<String, String> twins = FileHelper.loadAllFilesInPath(TwinsPath);
final CountDownLatch createTwinsLatch = new CountDownLatch(twins.size());
twins
.forEach((twinId, twinContent) -> client.createDigitalTwin(twinId, twinContent)
.subscribe(
twin -> System.out.println("Created digital twin: " + twinId + "\n\t Body: " + twin),
throwable -> System.err.println("Could not create digital twin " + twinId + " due to " + throwable),
createTwinsLatch::countDown));
createTwinsLatch.await(MaxWaitTimeAsyncOperationsInSeconds, TimeUnit.SECONDS);
}
/**
* Creates all the relationships defined in the DTDL->Relationships directory
* @throws IOException If an I/O error is thrown when accessing the starting file.
* @throws InterruptedException If the current thread is interrupted while waiting to acquire latch.
*/
public static void connectTwinsTogether() throws IOException, InterruptedException {
System.out.println("CONNECT DIGITAL TWINS");
Map<String, String> allRelationships = FileHelper.loadAllFilesInPath(RelationshipsPath);
final CountDownLatch connectTwinsLatch = new CountDownLatch(4);
allRelationships.values().forEach(
relationshipContent -> {
try {
List<BasicRelationship> relationships = mapper.readValue(relationshipContent, new TypeReference<List<BasicRelationship>>() { });
relationships
.forEach(relationship -> {
try {
client.createRelationship(relationship.getSourceId(), relationship.getId(), mapper.writeValueAsString(relationship))
.doOnSuccess(s -> System.out.println("Linked twin " + relationship.getSourceId() + " to twin " + relationship.getTargetId() + " as " + relationship.getName()))
.doOnError(IgnoreConflictError)
.doOnTerminate(connectTwinsLatch::countDown)
.subscribe();
} catch (JsonProcessingException e) {
throw new RuntimeException("JsonProcessingException while serializing relationship string from BasicRelationship: ", e);
}
});
} catch (JsonProcessingException e) {
throw new RuntimeException("JsonProcessingException while deserializing relationship string to BasicRelationship: ", e);
}
}
);
connectTwinsLatch.await(MaxWaitTimeAsyncOperationsInSeconds, TimeUnit.SECONDS);
}
} | class DigitalTwinsLifecycleAsyncSample {
private static final int MaxWaitTimeAsyncOperationsInSeconds = 10;
private static final ObjectMapper mapper = new ObjectMapper();
private static final URL DtdlDirectoryUrl = DigitalTwinsLifecycleAsyncSample.class.getClassLoader().getResource("DTDL");
private static final Path DtDlDirectoryPath;
private static final Path TwinsPath;
private static final Path ModelsPath;
private static final Path RelationshipsPath;
private static DigitalTwinsAsyncClient client;
static {
try {
assert DtdlDirectoryUrl != null;
DtDlDirectoryPath = Paths.get(DtdlDirectoryUrl.toURI());
} catch (URISyntaxException e) {
throw new RuntimeException("Unable to convert the DTDL directory URL to URI", e);
}
TwinsPath = Paths.get(DtDlDirectoryPath.toString(), "DigitalTwins");
ModelsPath = Paths.get(DtDlDirectoryPath.toString(), "Models");
RelationshipsPath = Paths.get(DtDlDirectoryPath.toString(), "Relationships");
}
public static void main(String[] args) throws IOException, InterruptedException {
SamplesArguments parsedArguments = new SamplesArguments(args);
client = new DigitalTwinsClientBuilder()
.tokenCredential(
new ClientSecretCredentialBuilder()
.tenantId(parsedArguments.getTenantId())
.clientId(parsedArguments.getClientId())
.clientSecret(parsedArguments.getClientSecret())
.build()
)
.endpoint(parsedArguments.getDigitalTwinEndpoint())
.httpLogOptions(
new HttpLogOptions()
.setLogLevel(parsedArguments.getHttpLogDetailLevel()))
.buildAsyncClient();
deleteTwins();
deleteAllModels();
createAllModels();
listAllModels();
createAllTwins();
connectTwinsTogether();
}
/**
* Delete a twin, and any relationships it might have.
* @throws IOException If an I/O error is thrown when accessing the starting file.
* @throws InterruptedException If the current thread is interrupted while waiting to acquire latch.
*/
public static void deleteTwins() throws IOException, InterruptedException {
System.out.println("DELETE DIGITAL TWINS");
Map<String, String> twins = FileHelper.loadAllFilesInPath(TwinsPath);
for (Map.Entry<String, String> twin : twins.entrySet()) {
String twinId = twin.getKey();
List<BasicRelationship> relationshipList = Collections.synchronizedList(new ArrayList<>());
Semaphore listRelationshipSemaphore = new Semaphore(0);
Semaphore deleteRelationshipsSemaphore = new Semaphore(0);
CountDownLatch deleteTwinsLatch = new CountDownLatch(1);
client.listRelationships(twinId, BasicRelationship.class)
.doOnNext(relationshipList::add)
.doOnError(IgnoreNotFoundError)
.doOnTerminate(listRelationshipSemaphore::release)
.subscribe();
client.listIncomingRelationships(twinId)
.doOnNext(e -> relationshipList.add(mapper.convertValue(e, BasicRelationship.class)))
.doOnError(IgnoreNotFoundError)
.doOnTerminate(listRelationshipSemaphore::release)
.subscribe();
if (listRelationshipSemaphore.tryAcquire(2, MaxWaitTimeAsyncOperationsInSeconds, TimeUnit.SECONDS)) {
relationshipList
.forEach(relationship -> client.deleteRelationship(relationship.getSourceId(), relationship.getId())
.doOnSuccess(aVoid -> {
if (twinId.equals(relationship.getSourceId())) {
System.out.println("Found and deleted relationship: " + relationship.getId());
} else {
System.out.println("Found and deleted incoming relationship: " + relationship.getId());
}
})
.doOnError(IgnoreNotFoundError)
.doOnTerminate(deleteRelationshipsSemaphore::release)
.subscribe());
}
if (deleteRelationshipsSemaphore.tryAcquire(relationshipList.size(), MaxWaitTimeAsyncOperationsInSeconds, TimeUnit.SECONDS)) {
client.deleteDigitalTwin(twinId)
.doOnSuccess(aVoid -> System.out.println("Deleted digital twin: " + twinId))
.doOnError(IgnoreNotFoundError)
.doOnTerminate(deleteTwinsLatch::countDown)
.subscribe();
deleteTwinsLatch.await(MaxWaitTimeAsyncOperationsInSeconds, TimeUnit.SECONDS);
}
}
}
/**
* Delete models created by FullLifecycleSample for the ADT service instance.
* @throws InterruptedException If the current thread is interrupted while waiting to acquire latch.
*/
public static void deleteAllModels() throws InterruptedException {
System.out.println("DELETING MODELS");
List<String> models = asList(RoomModelId, WifiModelId, BuildingModelId, FloorModelId, HvacModelId);
models
.forEach(modelId -> {
try {
client.deleteModel(modelId).block();
System.out.println("Deleted model: " + modelId);
} catch (ErrorResponseException ex) {
if (ex.getResponse().getStatusCode() != HttpStatus.SC_NOT_FOUND) {
System.err.println("Could not delete model " + modelId + " due to " + ex);
}
}
});
}
/**
* Loads all the models found in the Models directory into memory and uses CreateModelsAsync API to create all the models in the ADT service instance.
* @throws IOException If an I/O error is thrown when accessing the starting file.
* @throws InterruptedException If the current thread is interrupted while waiting to acquire latch.
*/
/**
* Gets all the models within the ADT service instance.
* @throws InterruptedException If the current thread is interrupted while waiting to acquire latch.
*/
public static void listAllModels() throws InterruptedException {
System.out.println("LISTING MODELS");
final CountDownLatch listModelsLatch = new CountDownLatch(1);
client.listModels()
.doOnNext(modelData -> System.out.println("Retrieved model: " + modelData.getId() + ", display name '" + modelData.getDisplayName().get("en") + "'," +
" upload time '" + modelData.getUploadTime() + "' and decommissioned '" + modelData.isDecommissioned() + "'"))
.doOnError(throwable -> System.err.println("List models error: " + throwable))
.doOnTerminate(listModelsLatch::countDown)
.subscribe();
listModelsLatch.await(MaxWaitTimeAsyncOperationsInSeconds, TimeUnit.SECONDS);
}
/**
* Creates all twins specified in the DTDL->DigitalTwins directory.
* @throws IOException If an I/O error is thrown when accessing the starting file.
* @throws InterruptedException If the current thread is interrupted while waiting to acquire latch.
*/
public static void createAllTwins() throws IOException, InterruptedException {
System.out.println("CREATE DIGITAL TWINS");
Map<String, String> twins = FileHelper.loadAllFilesInPath(TwinsPath);
final CountDownLatch createTwinsLatch = new CountDownLatch(twins.size());
twins
.forEach((twinId, twinContent) -> client.createDigitalTwin(twinId, twinContent)
.subscribe(
twin -> System.out.println("Created digital twin: " + twinId + "\n\t Body: " + twin),
throwable -> System.err.println("Could not create digital twin " + twinId + " due to " + throwable),
createTwinsLatch::countDown));
createTwinsLatch.await(MaxWaitTimeAsyncOperationsInSeconds, TimeUnit.SECONDS);
}
/**
* Creates all the relationships defined in the DTDL->Relationships directory
* @throws IOException If an I/O error is thrown when accessing the starting file.
* @throws InterruptedException If the current thread is interrupted while waiting to acquire latch.
*/
public static void connectTwinsTogether() throws IOException, InterruptedException {
System.out.println("CONNECT DIGITAL TWINS");
Map<String, String> allRelationships = FileHelper.loadAllFilesInPath(RelationshipsPath);
final CountDownLatch connectTwinsLatch = new CountDownLatch(4);
allRelationships.values().forEach(
relationshipContent -> {
try {
List<BasicRelationship> relationships = mapper.readValue(relationshipContent, new TypeReference<List<BasicRelationship>>() { });
relationships
.forEach(relationship -> {
try {
client.createRelationship(relationship.getSourceId(), relationship.getId(), mapper.writeValueAsString(relationship))
.doOnSuccess(s -> System.out.println("Linked twin " + relationship.getSourceId() + " to twin " + relationship.getTargetId() + " as " + relationship.getName()))
.doOnError(IgnoreConflictError)
.doOnTerminate(connectTwinsLatch::countDown)
.subscribe();
} catch (JsonProcessingException e) {
throw new RuntimeException("JsonProcessingException while serializing relationship string from BasicRelationship: ", e);
}
});
} catch (JsonProcessingException e) {
throw new RuntimeException("JsonProcessingException while deserializing relationship string to BasicRelationship: ", e);
}
}
);
connectTwinsLatch.await(MaxWaitTimeAsyncOperationsInSeconds, TimeUnit.SECONDS);
}
} |
? | public List<ModelData> createModels(List<String> models) {
return digitalTwinsAsyncClient.createModels(models).block();
} | return digitalTwinsAsyncClient.createModels(models).block(); | public List<ModelData> createModels(List<String> models) {
return createModelsWithResponse(models, Context.NONE).getValue();
} | class to convert the relationship to.
* @param <T> The generic type to convert the relationship to.
* @param context Additional context that is passed through the Http pipeline during the service call.
* @return A {@link PagedIterable} | class to convert the relationship to.
* @param <T> The generic type to convert the relationship to.
* @param context Additional context that is passed through the Http pipeline during the service call.
* @return A {@link PagedIterable} |
Are we checking in with this TODO? 😮 | public static void runModelLifecycleSample() {
String componentModelId = UniqueIdHelper.getUniqueModelId(SamplesConstants.TemporaryComponentModelPrefix, client);
String sampleModelId = UniqueIdHelper.getUniqueModelId(SamplesConstants.TemporaryModelPrefix, client);
String newComponentModelPayload = SamplesConstants.TemporaryComponentModelPayload
.replace(SamplesConstants.ComponentId, componentModelId);
String newModelPayload = SamplesConstants.TemporaryModelWithComponentPayload
.replace(SamplesConstants.ModelId, sampleModelId)
.replace(SamplesConstants.ComponentId, componentModelId);
ConsoleLogger.PrintHeader("Create models");
try {
client.createModels(new ArrayList<String>(Arrays.asList(newComponentModelPayload, newModelPayload)));
ConsoleLogger.PrintSuccess("Created models " + componentModelId + " and " + sampleModelId);
}
catch (ErrorResponseException ex){
if (ex.getResponse().getStatusCode() == HttpStatus.SC_CONFLICT) {
ConsoleLogger.PrintWarning("One or more models already existed");
}
}
catch (Exception ex) {
ConsoleLogger.PrintFatal("Failed to create models due to: \n" + ex);
System.exit(0);
}
ConsoleLogger.PrintHeader("Get models");
try {
ModelData sampleModelResponse = client.getModel(sampleModelId);
ConsoleLogger.PrintSuccess("Retrieved model " + sampleModelResponse.getId());
}
catch (Exception ex){
ConsoleLogger.PrintFatal("Failed to get the model due to:\n" + ex);
System.exit(0);
}
ConsoleLogger.PrintHeader("Decommission models");
try {
client.decommissionModel(sampleModelId);
client.decommissionModel(componentModelId);
ConsoleLogger.PrintSuccess("Decommissioned "+ sampleModelId + " and " + componentModelId);
}
catch (Exception ex){
ConsoleLogger.PrintFatal("Failed to decommission models due to:\n" + ex);
System.exit(0);
}
ConsoleLogger.PrintHeader("Delete models");
try {
client.deleteModel(sampleModelId);
client.deleteModel(componentModelId);
ConsoleLogger.PrintSuccess("Deleted "+ sampleModelId + " and " + componentModelId);
}
catch (Exception ex){
ConsoleLogger.PrintFatal("Failed to deleteModel models due to:\n" + ex);
System.exit(0);
}
} | public static void runModelLifecycleSample() {
String componentModelId = UniqueIdHelper.getUniqueModelId(SamplesConstants.TemporaryComponentModelPrefix, client);
String sampleModelId = UniqueIdHelper.getUniqueModelId(SamplesConstants.TemporaryModelPrefix, client);
String newComponentModelPayload = SamplesConstants.TemporaryComponentModelPayload
.replace(SamplesConstants.ComponentId, componentModelId);
String newModelPayload = SamplesConstants.TemporaryModelWithComponentPayload
.replace(SamplesConstants.ModelId, sampleModelId)
.replace(SamplesConstants.ComponentId, componentModelId);
ConsoleLogger.PrintHeader("Create models");
try {
client.createModels(new ArrayList<String>(Arrays.asList(newComponentModelPayload, newModelPayload)));
ConsoleLogger.PrintSuccess("Created models " + componentModelId + " and " + sampleModelId);
}
catch (ErrorResponseException ex) {
if (ex.getResponse().getStatusCode() == HttpURLConnection.HTTP_CONFLICT) {
ConsoleLogger.PrintWarning("One or more models already existed");
}
}
catch (Exception ex) {
ConsoleLogger.PrintFatal("Failed to create models due to: \n" + ex);
System.exit(0);
}
ConsoleLogger.PrintHeader("Get models");
try {
ModelData sampleModelResponse = client.getModel(sampleModelId);
ConsoleLogger.PrintSuccess("Retrieved model " + sampleModelResponse.getId());
}
catch (Exception ex) {
ConsoleLogger.PrintFatal("Failed to get the model due to:\n" + ex);
System.exit(0);
}
ConsoleLogger.PrintHeader("Decommission models");
try {
client.decommissionModel(sampleModelId);
client.decommissionModel(componentModelId);
ConsoleLogger.PrintSuccess("Decommissioned "+ sampleModelId + " and " + componentModelId);
}
catch (Exception ex) {
ConsoleLogger.PrintFatal("Failed to decommission models due to:\n" + ex);
System.exit(0);
}
ConsoleLogger.PrintHeader("Delete models");
try {
client.deleteModel(sampleModelId);
client.deleteModel(componentModelId);
ConsoleLogger.PrintSuccess("Deleted "+ sampleModelId + " and " + componentModelId);
}
catch (Exception ex) {
ConsoleLogger.PrintFatal("Failed to deleteModel models due to:\n" + ex);
System.exit(0);
}
} | class ModelsLifecycleSyncSamples {
private static DigitalTwinsClient client;
public static void main(String[] args) throws IOException, InterruptedException {
SamplesArguments parsedArguments = new SamplesArguments(args);
client = new DigitalTwinsClientBuilder()
.tokenCredential(
new ClientSecretCredentialBuilder()
.tenantId(parsedArguments.getTenantId())
.clientId(parsedArguments.getClientId())
.clientSecret(parsedArguments.getClientSecret())
.build()
)
.endpoint(parsedArguments.getDigitalTwinEndpoint())
.httpLogOptions(
new HttpLogOptions()
.setLogLevel(parsedArguments.getHttpLogDetailLevel()))
.buildClient();
runModelLifecycleSample();
}
} | class ModelsLifecycleSyncSamples {
private static DigitalTwinsClient client;
public static void main(String[] args) throws IOException, InterruptedException {
SamplesArguments parsedArguments = new SamplesArguments(args);
client = new DigitalTwinsClientBuilder()
.tokenCredential(
new ClientSecretCredentialBuilder()
.tenantId(parsedArguments.getTenantId())
.clientId(parsedArguments.getClientId())
.clientSecret(parsedArguments.getClientSecret())
.build()
)
.endpoint(parsedArguments.getDigitalTwinEndpoint())
.httpLogOptions(
new HttpLogOptions()
.setLogLevel(parsedArguments.getHttpLogDetailLevel()))
.buildClient();
runModelLifecycleSample();
}
} | |
:D removed. | public static void runModelLifecycleSample() {
String componentModelId = UniqueIdHelper.getUniqueModelId(SamplesConstants.TemporaryComponentModelPrefix, client);
String sampleModelId = UniqueIdHelper.getUniqueModelId(SamplesConstants.TemporaryModelPrefix, client);
String newComponentModelPayload = SamplesConstants.TemporaryComponentModelPayload
.replace(SamplesConstants.ComponentId, componentModelId);
String newModelPayload = SamplesConstants.TemporaryModelWithComponentPayload
.replace(SamplesConstants.ModelId, sampleModelId)
.replace(SamplesConstants.ComponentId, componentModelId);
ConsoleLogger.PrintHeader("Create models");
try {
client.createModels(new ArrayList<String>(Arrays.asList(newComponentModelPayload, newModelPayload)));
ConsoleLogger.PrintSuccess("Created models " + componentModelId + " and " + sampleModelId);
}
catch (ErrorResponseException ex){
if (ex.getResponse().getStatusCode() == HttpStatus.SC_CONFLICT) {
ConsoleLogger.PrintWarning("One or more models already existed");
}
}
catch (Exception ex) {
ConsoleLogger.PrintFatal("Failed to create models due to: \n" + ex);
System.exit(0);
}
ConsoleLogger.PrintHeader("Get models");
try {
ModelData sampleModelResponse = client.getModel(sampleModelId);
ConsoleLogger.PrintSuccess("Retrieved model " + sampleModelResponse.getId());
}
catch (Exception ex){
ConsoleLogger.PrintFatal("Failed to get the model due to:\n" + ex);
System.exit(0);
}
ConsoleLogger.PrintHeader("Decommission models");
try {
client.decommissionModel(sampleModelId);
client.decommissionModel(componentModelId);
ConsoleLogger.PrintSuccess("Decommissioned "+ sampleModelId + " and " + componentModelId);
}
catch (Exception ex){
ConsoleLogger.PrintFatal("Failed to decommission models due to:\n" + ex);
System.exit(0);
}
ConsoleLogger.PrintHeader("Delete models");
try {
client.deleteModel(sampleModelId);
client.deleteModel(componentModelId);
ConsoleLogger.PrintSuccess("Deleted "+ sampleModelId + " and " + componentModelId);
}
catch (Exception ex){
ConsoleLogger.PrintFatal("Failed to deleteModel models due to:\n" + ex);
System.exit(0);
}
} | public static void runModelLifecycleSample() {
String componentModelId = UniqueIdHelper.getUniqueModelId(SamplesConstants.TemporaryComponentModelPrefix, client);
String sampleModelId = UniqueIdHelper.getUniqueModelId(SamplesConstants.TemporaryModelPrefix, client);
String newComponentModelPayload = SamplesConstants.TemporaryComponentModelPayload
.replace(SamplesConstants.ComponentId, componentModelId);
String newModelPayload = SamplesConstants.TemporaryModelWithComponentPayload
.replace(SamplesConstants.ModelId, sampleModelId)
.replace(SamplesConstants.ComponentId, componentModelId);
ConsoleLogger.PrintHeader("Create models");
try {
client.createModels(new ArrayList<String>(Arrays.asList(newComponentModelPayload, newModelPayload)));
ConsoleLogger.PrintSuccess("Created models " + componentModelId + " and " + sampleModelId);
}
catch (ErrorResponseException ex) {
if (ex.getResponse().getStatusCode() == HttpURLConnection.HTTP_CONFLICT) {
ConsoleLogger.PrintWarning("One or more models already existed");
}
}
catch (Exception ex) {
ConsoleLogger.PrintFatal("Failed to create models due to: \n" + ex);
System.exit(0);
}
ConsoleLogger.PrintHeader("Get models");
try {
ModelData sampleModelResponse = client.getModel(sampleModelId);
ConsoleLogger.PrintSuccess("Retrieved model " + sampleModelResponse.getId());
}
catch (Exception ex) {
ConsoleLogger.PrintFatal("Failed to get the model due to:\n" + ex);
System.exit(0);
}
ConsoleLogger.PrintHeader("Decommission models");
try {
client.decommissionModel(sampleModelId);
client.decommissionModel(componentModelId);
ConsoleLogger.PrintSuccess("Decommissioned "+ sampleModelId + " and " + componentModelId);
}
catch (Exception ex) {
ConsoleLogger.PrintFatal("Failed to decommission models due to:\n" + ex);
System.exit(0);
}
ConsoleLogger.PrintHeader("Delete models");
try {
client.deleteModel(sampleModelId);
client.deleteModel(componentModelId);
ConsoleLogger.PrintSuccess("Deleted "+ sampleModelId + " and " + componentModelId);
}
catch (Exception ex) {
ConsoleLogger.PrintFatal("Failed to deleteModel models due to:\n" + ex);
System.exit(0);
}
} | class ModelsLifecycleSyncSamples {
private static DigitalTwinsClient client;
public static void main(String[] args) throws IOException, InterruptedException {
SamplesArguments parsedArguments = new SamplesArguments(args);
client = new DigitalTwinsClientBuilder()
.tokenCredential(
new ClientSecretCredentialBuilder()
.tenantId(parsedArguments.getTenantId())
.clientId(parsedArguments.getClientId())
.clientSecret(parsedArguments.getClientSecret())
.build()
)
.endpoint(parsedArguments.getDigitalTwinEndpoint())
.httpLogOptions(
new HttpLogOptions()
.setLogLevel(parsedArguments.getHttpLogDetailLevel()))
.buildClient();
runModelLifecycleSample();
}
} | class ModelsLifecycleSyncSamples {
private static DigitalTwinsClient client;
public static void main(String[] args) throws IOException, InterruptedException {
SamplesArguments parsedArguments = new SamplesArguments(args);
client = new DigitalTwinsClientBuilder()
.tokenCredential(
new ClientSecretCredentialBuilder()
.tenantId(parsedArguments.getTenantId())
.clientId(parsedArguments.getClientId())
.clientSecret(parsedArguments.getClientSecret())
.build()
)
.endpoint(parsedArguments.getDigitalTwinEndpoint())
.httpLogOptions(
new HttpLogOptions()
.setLogLevel(parsedArguments.getHttpLogDetailLevel()))
.buildClient();
runModelLifecycleSample();
}
} | |
I am updating the sample to use status code from here: https://docs.oracle.com/javase/7/docs/api/java/net/HttpURLConnection.html This is what Tim used in the e2e tests, and what other sdks are using as well. | public static void runModelLifecycleSample() {
String componentModelId = UniqueIdHelper.getUniqueModelId(SamplesConstants.TemporaryComponentModelPrefix, client);
String sampleModelId = UniqueIdHelper.getUniqueModelId(SamplesConstants.TemporaryModelPrefix, client);
String newComponentModelPayload = SamplesConstants.TemporaryComponentModelPayload
.replace(SamplesConstants.ComponentId, componentModelId);
String newModelPayload = SamplesConstants.TemporaryModelWithComponentPayload
.replace(SamplesConstants.ModelId, sampleModelId)
.replace(SamplesConstants.ComponentId, componentModelId);
ConsoleLogger.PrintHeader("Create models");
try {
client.createModels(new ArrayList<String>(Arrays.asList(newComponentModelPayload, newModelPayload)));
ConsoleLogger.PrintSuccess("Created models " + componentModelId + " and " + sampleModelId);
}
catch (ErrorResponseException ex){
if (ex.getResponse().getStatusCode() == HttpStatus.SC_CONFLICT) {
ConsoleLogger.PrintWarning("One or more models already existed");
}
}
catch (Exception ex) {
ConsoleLogger.PrintFatal("Failed to create models due to: \n" + ex);
System.exit(0);
}
ConsoleLogger.PrintHeader("Get models");
try {
ModelData sampleModelResponse = client.getModel(sampleModelId);
ConsoleLogger.PrintSuccess("Retrieved model " + sampleModelResponse.getId());
}
catch (Exception ex){
ConsoleLogger.PrintFatal("Failed to get the model due to:\n" + ex);
System.exit(0);
}
ConsoleLogger.PrintHeader("Decommission models");
try {
client.decommissionModel(sampleModelId);
client.decommissionModel(componentModelId);
ConsoleLogger.PrintSuccess("Decommissioned "+ sampleModelId + " and " + componentModelId);
}
catch (Exception ex){
ConsoleLogger.PrintFatal("Failed to decommission models due to:\n" + ex);
System.exit(0);
}
ConsoleLogger.PrintHeader("Delete models");
try {
client.deleteModel(sampleModelId);
client.deleteModel(componentModelId);
ConsoleLogger.PrintSuccess("Deleted "+ sampleModelId + " and " + componentModelId);
}
catch (Exception ex){
ConsoleLogger.PrintFatal("Failed to deleteModel models due to:\n" + ex);
System.exit(0);
}
} | if (ex.getResponse().getStatusCode() == HttpStatus.SC_CONFLICT) { | public static void runModelLifecycleSample() {
String componentModelId = UniqueIdHelper.getUniqueModelId(SamplesConstants.TemporaryComponentModelPrefix, client);
String sampleModelId = UniqueIdHelper.getUniqueModelId(SamplesConstants.TemporaryModelPrefix, client);
String newComponentModelPayload = SamplesConstants.TemporaryComponentModelPayload
.replace(SamplesConstants.ComponentId, componentModelId);
String newModelPayload = SamplesConstants.TemporaryModelWithComponentPayload
.replace(SamplesConstants.ModelId, sampleModelId)
.replace(SamplesConstants.ComponentId, componentModelId);
ConsoleLogger.PrintHeader("Create models");
try {
client.createModels(new ArrayList<String>(Arrays.asList(newComponentModelPayload, newModelPayload)));
ConsoleLogger.PrintSuccess("Created models " + componentModelId + " and " + sampleModelId);
}
catch (ErrorResponseException ex) {
if (ex.getResponse().getStatusCode() == HttpURLConnection.HTTP_CONFLICT) {
ConsoleLogger.PrintWarning("One or more models already existed");
}
}
catch (Exception ex) {
ConsoleLogger.PrintFatal("Failed to create models due to: \n" + ex);
System.exit(0);
}
ConsoleLogger.PrintHeader("Get models");
try {
ModelData sampleModelResponse = client.getModel(sampleModelId);
ConsoleLogger.PrintSuccess("Retrieved model " + sampleModelResponse.getId());
}
catch (Exception ex) {
ConsoleLogger.PrintFatal("Failed to get the model due to:\n" + ex);
System.exit(0);
}
ConsoleLogger.PrintHeader("Decommission models");
try {
client.decommissionModel(sampleModelId);
client.decommissionModel(componentModelId);
ConsoleLogger.PrintSuccess("Decommissioned "+ sampleModelId + " and " + componentModelId);
}
catch (Exception ex) {
ConsoleLogger.PrintFatal("Failed to decommission models due to:\n" + ex);
System.exit(0);
}
ConsoleLogger.PrintHeader("Delete models");
try {
client.deleteModel(sampleModelId);
client.deleteModel(componentModelId);
ConsoleLogger.PrintSuccess("Deleted "+ sampleModelId + " and " + componentModelId);
}
catch (Exception ex) {
ConsoleLogger.PrintFatal("Failed to deleteModel models due to:\n" + ex);
System.exit(0);
}
} | class ModelsLifecycleSyncSamples {
private static DigitalTwinsClient client;
public static void main(String[] args) throws IOException, InterruptedException {
SamplesArguments parsedArguments = new SamplesArguments(args);
client = new DigitalTwinsClientBuilder()
.tokenCredential(
new ClientSecretCredentialBuilder()
.tenantId(parsedArguments.getTenantId())
.clientId(parsedArguments.getClientId())
.clientSecret(parsedArguments.getClientSecret())
.build()
)
.endpoint(parsedArguments.getDigitalTwinEndpoint())
.httpLogOptions(
new HttpLogOptions()
.setLogLevel(parsedArguments.getHttpLogDetailLevel()))
.buildClient();
runModelLifecycleSample();
}
} | class ModelsLifecycleSyncSamples {
private static DigitalTwinsClient client;
public static void main(String[] args) throws IOException, InterruptedException {
SamplesArguments parsedArguments = new SamplesArguments(args);
client = new DigitalTwinsClientBuilder()
.tokenCredential(
new ClientSecretCredentialBuilder()
.tenantId(parsedArguments.getTenantId())
.clientId(parsedArguments.getClientId())
.clientSecret(parsedArguments.getClientSecret())
.build()
)
.endpoint(parsedArguments.getDigitalTwinEndpoint())
.httpLogOptions(
new HttpLogOptions()
.setLogLevel(parsedArguments.getHttpLogDetailLevel()))
.buildClient();
runModelLifecycleSample();
}
} |
@chenghaoharvey Thanks for your great effort. I just have one concern that need the `ErrorMessageStrategy` be hard coded? | protected ErrorMessageStrategy getErrorMessageStrategy() {
return DEFAULT_ERROR_MESSAGE_STRATEGY;
} | return DEFAULT_ERROR_MESSAGE_STRATEGY; | protected ErrorMessageStrategy getErrorMessageStrategy() {
return DEFAULT_ERROR_MESSAGE_STRATEGY;
} | class ServiceBusMessageChannelBinder<T extends ServiceBusExtendedBindingProperties> extends
AbstractMessageChannelBinder<ExtendedConsumerProperties<ServiceBusConsumerProperties>,
ExtendedProducerProperties<ServiceBusProducerProperties>,
ServiceBusChannelProvisioner>
implements
ExtendedPropertiesBinder<MessageChannel, ServiceBusConsumerProperties, ServiceBusProducerProperties> {
protected T bindingProperties;
private static final DefaultErrorMessageStrategy DEFAULT_ERROR_MESSAGE_STRATEGY = new DefaultErrorMessageStrategy();
protected static final String EXCEPTION_MESSAGE = "exception-message";
public ServiceBusMessageChannelBinder(String[] headersToEmbed, ServiceBusChannelProvisioner provisioningProvider) {
super(headersToEmbed, provisioningProvider);
}
@Override
protected MessageHandler createProducerMessageHandler(ProducerDestination destination,
ExtendedProducerProperties<ServiceBusProducerProperties> producerProperties, MessageChannel errorChannel) {
DefaultMessageHandler handler = new DefaultMessageHandler(destination.getName(), getSendOperation());
handler.setBeanFactory(getBeanFactory());
handler.setSync(producerProperties.getExtension().isSync());
handler.setSendTimeout(producerProperties.getExtension().getSendTimeout());
handler.setSendFailureChannel(errorChannel);
if (producerProperties.isPartitioned()) {
handler.setPartitionKeyExpressionString(
"'partitionKey-' + headers['" + BinderHeaders.PARTITION_HEADER + "']");
} else {
handler.setPartitionKeyExpression(new FunctionExpression<Message<?>>(m -> m.getPayload().hashCode()));
}
return handler;
}
@Override
public ServiceBusConsumerProperties getExtendedConsumerProperties(String channelName) {
return this.bindingProperties.getExtendedConsumerProperties(channelName);
}
@Override
public ServiceBusProducerProperties getExtendedProducerProperties(String channelName) {
return this.bindingProperties.getExtendedProducerProperties(channelName);
}
@Override
public String getDefaultsPrefix() {
return this.bindingProperties.getDefaultsPrefix();
}
@Override
public Class<? extends BinderSpecificPropertiesProvider> getExtendedPropertiesEntryClass() {
return this.bindingProperties.getExtendedPropertiesEntryClass();
}
@Override
public void setBindingProperties(T bindingProperties) {
this.bindingProperties = bindingProperties;
}
protected CheckpointConfig buildCheckpointConfig(
ExtendedConsumerProperties<ServiceBusConsumerProperties> properties) {
return CheckpointConfig.builder().checkpointMode(properties.getExtension().getCheckpointMode()).build();
}
protected ServiceBusClientConfig buildClientConfig(
ExtendedConsumerProperties<ServiceBusConsumerProperties> properties) {
ServiceBusConsumerProperties consumerProperties = properties.getExtension();
return ServiceBusClientConfig.builder().setPrefetchCount(consumerProperties.getPrefetchCount())
.setConcurrency(consumerProperties.getConcurrency())
.setSessionsEnabled(consumerProperties.isSessionsEnabled()).build();
}
abstract SendOperation getSendOperation();
} | class ServiceBusMessageChannelBinder<T extends ServiceBusExtendedBindingProperties> extends
AbstractMessageChannelBinder<ExtendedConsumerProperties<ServiceBusConsumerProperties>,
ExtendedProducerProperties<ServiceBusProducerProperties>,
ServiceBusChannelProvisioner>
implements
ExtendedPropertiesBinder<MessageChannel, ServiceBusConsumerProperties, ServiceBusProducerProperties> {
protected T bindingProperties;
private static final DefaultErrorMessageStrategy DEFAULT_ERROR_MESSAGE_STRATEGY = new DefaultErrorMessageStrategy();
protected static final String EXCEPTION_MESSAGE = "exception-message";
public ServiceBusMessageChannelBinder(String[] headersToEmbed, ServiceBusChannelProvisioner provisioningProvider) {
super(headersToEmbed, provisioningProvider);
}
@Override
protected MessageHandler createProducerMessageHandler(ProducerDestination destination,
ExtendedProducerProperties<ServiceBusProducerProperties> producerProperties, MessageChannel errorChannel) {
DefaultMessageHandler handler = new DefaultMessageHandler(destination.getName(), getSendOperation());
handler.setBeanFactory(getBeanFactory());
handler.setSync(producerProperties.getExtension().isSync());
handler.setSendTimeout(producerProperties.getExtension().getSendTimeout());
handler.setSendFailureChannel(errorChannel);
if (producerProperties.isPartitioned()) {
handler.setPartitionKeyExpressionString(
"'partitionKey-' + headers['" + BinderHeaders.PARTITION_HEADER + "']");
} else {
handler.setPartitionKeyExpression(new FunctionExpression<Message<?>>(m -> m.getPayload().hashCode()));
}
return handler;
}
@Override
public ServiceBusConsumerProperties getExtendedConsumerProperties(String channelName) {
return this.bindingProperties.getExtendedConsumerProperties(channelName);
}
@Override
public ServiceBusProducerProperties getExtendedProducerProperties(String channelName) {
return this.bindingProperties.getExtendedProducerProperties(channelName);
}
@Override
public String getDefaultsPrefix() {
return this.bindingProperties.getDefaultsPrefix();
}
@Override
public Class<? extends BinderSpecificPropertiesProvider> getExtendedPropertiesEntryClass() {
return this.bindingProperties.getExtendedPropertiesEntryClass();
}
@Override
public void setBindingProperties(T bindingProperties) {
this.bindingProperties = bindingProperties;
}
protected CheckpointConfig buildCheckpointConfig(
ExtendedConsumerProperties<ServiceBusConsumerProperties> properties) {
return CheckpointConfig.builder().checkpointMode(properties.getExtension().getCheckpointMode()).build();
}
protected ServiceBusClientConfig buildClientConfig(
ExtendedConsumerProperties<ServiceBusConsumerProperties> properties) {
ServiceBusConsumerProperties consumerProperties = properties.getExtension();
return ServiceBusClientConfig.builder().setPrefetchCount(consumerProperties.getPrefetchCount())
.setConcurrency(consumerProperties.getConcurrency())
.setSessionsEnabled(consumerProperties.isSessionsEnabled()).build();
}
abstract SendOperation getSendOperation();
} |
i just refer to rabbit mq implementation. you mean that message strategy should not be hard coded and user can config it by themselves? Or i just `return new ErrorMessageStrategy()` directly? | protected ErrorMessageStrategy getErrorMessageStrategy() {
return DEFAULT_ERROR_MESSAGE_STRATEGY;
} | return DEFAULT_ERROR_MESSAGE_STRATEGY; | protected ErrorMessageStrategy getErrorMessageStrategy() {
return DEFAULT_ERROR_MESSAGE_STRATEGY;
} | class ServiceBusMessageChannelBinder<T extends ServiceBusExtendedBindingProperties> extends
AbstractMessageChannelBinder<ExtendedConsumerProperties<ServiceBusConsumerProperties>,
ExtendedProducerProperties<ServiceBusProducerProperties>,
ServiceBusChannelProvisioner>
implements
ExtendedPropertiesBinder<MessageChannel, ServiceBusConsumerProperties, ServiceBusProducerProperties> {
protected T bindingProperties;
private static final DefaultErrorMessageStrategy DEFAULT_ERROR_MESSAGE_STRATEGY = new DefaultErrorMessageStrategy();
protected static final String EXCEPTION_MESSAGE = "exception-message";
public ServiceBusMessageChannelBinder(String[] headersToEmbed, ServiceBusChannelProvisioner provisioningProvider) {
super(headersToEmbed, provisioningProvider);
}
@Override
protected MessageHandler createProducerMessageHandler(ProducerDestination destination,
ExtendedProducerProperties<ServiceBusProducerProperties> producerProperties, MessageChannel errorChannel) {
DefaultMessageHandler handler = new DefaultMessageHandler(destination.getName(), getSendOperation());
handler.setBeanFactory(getBeanFactory());
handler.setSync(producerProperties.getExtension().isSync());
handler.setSendTimeout(producerProperties.getExtension().getSendTimeout());
handler.setSendFailureChannel(errorChannel);
if (producerProperties.isPartitioned()) {
handler.setPartitionKeyExpressionString(
"'partitionKey-' + headers['" + BinderHeaders.PARTITION_HEADER + "']");
} else {
handler.setPartitionKeyExpression(new FunctionExpression<Message<?>>(m -> m.getPayload().hashCode()));
}
return handler;
}
@Override
public ServiceBusConsumerProperties getExtendedConsumerProperties(String channelName) {
return this.bindingProperties.getExtendedConsumerProperties(channelName);
}
@Override
public ServiceBusProducerProperties getExtendedProducerProperties(String channelName) {
return this.bindingProperties.getExtendedProducerProperties(channelName);
}
@Override
public String getDefaultsPrefix() {
return this.bindingProperties.getDefaultsPrefix();
}
@Override
public Class<? extends BinderSpecificPropertiesProvider> getExtendedPropertiesEntryClass() {
return this.bindingProperties.getExtendedPropertiesEntryClass();
}
@Override
public void setBindingProperties(T bindingProperties) {
this.bindingProperties = bindingProperties;
}
protected CheckpointConfig buildCheckpointConfig(
ExtendedConsumerProperties<ServiceBusConsumerProperties> properties) {
return CheckpointConfig.builder().checkpointMode(properties.getExtension().getCheckpointMode()).build();
}
protected ServiceBusClientConfig buildClientConfig(
ExtendedConsumerProperties<ServiceBusConsumerProperties> properties) {
ServiceBusConsumerProperties consumerProperties = properties.getExtension();
return ServiceBusClientConfig.builder().setPrefetchCount(consumerProperties.getPrefetchCount())
.setConcurrency(consumerProperties.getConcurrency())
.setSessionsEnabled(consumerProperties.isSessionsEnabled()).build();
}
abstract SendOperation getSendOperation();
} | class ServiceBusMessageChannelBinder<T extends ServiceBusExtendedBindingProperties> extends
AbstractMessageChannelBinder<ExtendedConsumerProperties<ServiceBusConsumerProperties>,
ExtendedProducerProperties<ServiceBusProducerProperties>,
ServiceBusChannelProvisioner>
implements
ExtendedPropertiesBinder<MessageChannel, ServiceBusConsumerProperties, ServiceBusProducerProperties> {
protected T bindingProperties;
private static final DefaultErrorMessageStrategy DEFAULT_ERROR_MESSAGE_STRATEGY = new DefaultErrorMessageStrategy();
protected static final String EXCEPTION_MESSAGE = "exception-message";
public ServiceBusMessageChannelBinder(String[] headersToEmbed, ServiceBusChannelProvisioner provisioningProvider) {
super(headersToEmbed, provisioningProvider);
}
@Override
protected MessageHandler createProducerMessageHandler(ProducerDestination destination,
ExtendedProducerProperties<ServiceBusProducerProperties> producerProperties, MessageChannel errorChannel) {
DefaultMessageHandler handler = new DefaultMessageHandler(destination.getName(), getSendOperation());
handler.setBeanFactory(getBeanFactory());
handler.setSync(producerProperties.getExtension().isSync());
handler.setSendTimeout(producerProperties.getExtension().getSendTimeout());
handler.setSendFailureChannel(errorChannel);
if (producerProperties.isPartitioned()) {
handler.setPartitionKeyExpressionString(
"'partitionKey-' + headers['" + BinderHeaders.PARTITION_HEADER + "']");
} else {
handler.setPartitionKeyExpression(new FunctionExpression<Message<?>>(m -> m.getPayload().hashCode()));
}
return handler;
}
@Override
public ServiceBusConsumerProperties getExtendedConsumerProperties(String channelName) {
return this.bindingProperties.getExtendedConsumerProperties(channelName);
}
@Override
public ServiceBusProducerProperties getExtendedProducerProperties(String channelName) {
return this.bindingProperties.getExtendedProducerProperties(channelName);
}
@Override
public String getDefaultsPrefix() {
return this.bindingProperties.getDefaultsPrefix();
}
@Override
public Class<? extends BinderSpecificPropertiesProvider> getExtendedPropertiesEntryClass() {
return this.bindingProperties.getExtendedPropertiesEntryClass();
}
@Override
public void setBindingProperties(T bindingProperties) {
this.bindingProperties = bindingProperties;
}
protected CheckpointConfig buildCheckpointConfig(
ExtendedConsumerProperties<ServiceBusConsumerProperties> properties) {
return CheckpointConfig.builder().checkpointMode(properties.getExtension().getCheckpointMode()).build();
}
protected ServiceBusClientConfig buildClientConfig(
ExtendedConsumerProperties<ServiceBusConsumerProperties> properties) {
ServiceBusConsumerProperties consumerProperties = properties.getExtension();
return ServiceBusClientConfig.builder().setPrefetchCount(consumerProperties.getPrefetchCount())
.setConcurrency(consumerProperties.getConcurrency())
.setSessionsEnabled(consumerProperties.isSessionsEnabled()).build();
}
abstract SendOperation getSendOperation();
} |
@yiliuTo may i have your input? I referred to Rabbit MQ binder and they are hard code as well. | protected ErrorMessageStrategy getErrorMessageStrategy() {
return DEFAULT_ERROR_MESSAGE_STRATEGY;
} | return DEFAULT_ERROR_MESSAGE_STRATEGY; | protected ErrorMessageStrategy getErrorMessageStrategy() {
return DEFAULT_ERROR_MESSAGE_STRATEGY;
} | class ServiceBusMessageChannelBinder<T extends ServiceBusExtendedBindingProperties> extends
AbstractMessageChannelBinder<ExtendedConsumerProperties<ServiceBusConsumerProperties>,
ExtendedProducerProperties<ServiceBusProducerProperties>,
ServiceBusChannelProvisioner>
implements
ExtendedPropertiesBinder<MessageChannel, ServiceBusConsumerProperties, ServiceBusProducerProperties> {
protected T bindingProperties;
private static final DefaultErrorMessageStrategy DEFAULT_ERROR_MESSAGE_STRATEGY = new DefaultErrorMessageStrategy();
protected static final String EXCEPTION_MESSAGE = "exception-message";
public ServiceBusMessageChannelBinder(String[] headersToEmbed, ServiceBusChannelProvisioner provisioningProvider) {
super(headersToEmbed, provisioningProvider);
}
@Override
protected MessageHandler createProducerMessageHandler(ProducerDestination destination,
ExtendedProducerProperties<ServiceBusProducerProperties> producerProperties, MessageChannel errorChannel) {
DefaultMessageHandler handler = new DefaultMessageHandler(destination.getName(), getSendOperation());
handler.setBeanFactory(getBeanFactory());
handler.setSync(producerProperties.getExtension().isSync());
handler.setSendTimeout(producerProperties.getExtension().getSendTimeout());
handler.setSendFailureChannel(errorChannel);
if (producerProperties.isPartitioned()) {
handler.setPartitionKeyExpressionString(
"'partitionKey-' + headers['" + BinderHeaders.PARTITION_HEADER + "']");
} else {
handler.setPartitionKeyExpression(new FunctionExpression<Message<?>>(m -> m.getPayload().hashCode()));
}
return handler;
}
@Override
public ServiceBusConsumerProperties getExtendedConsumerProperties(String channelName) {
return this.bindingProperties.getExtendedConsumerProperties(channelName);
}
@Override
public ServiceBusProducerProperties getExtendedProducerProperties(String channelName) {
return this.bindingProperties.getExtendedProducerProperties(channelName);
}
@Override
public String getDefaultsPrefix() {
return this.bindingProperties.getDefaultsPrefix();
}
@Override
public Class<? extends BinderSpecificPropertiesProvider> getExtendedPropertiesEntryClass() {
return this.bindingProperties.getExtendedPropertiesEntryClass();
}
@Override
public void setBindingProperties(T bindingProperties) {
this.bindingProperties = bindingProperties;
}
protected CheckpointConfig buildCheckpointConfig(
ExtendedConsumerProperties<ServiceBusConsumerProperties> properties) {
return CheckpointConfig.builder().checkpointMode(properties.getExtension().getCheckpointMode()).build();
}
protected ServiceBusClientConfig buildClientConfig(
ExtendedConsumerProperties<ServiceBusConsumerProperties> properties) {
ServiceBusConsumerProperties consumerProperties = properties.getExtension();
return ServiceBusClientConfig.builder().setPrefetchCount(consumerProperties.getPrefetchCount())
.setConcurrency(consumerProperties.getConcurrency())
.setSessionsEnabled(consumerProperties.isSessionsEnabled()).build();
}
abstract SendOperation getSendOperation();
} | class ServiceBusMessageChannelBinder<T extends ServiceBusExtendedBindingProperties> extends
AbstractMessageChannelBinder<ExtendedConsumerProperties<ServiceBusConsumerProperties>,
ExtendedProducerProperties<ServiceBusProducerProperties>,
ServiceBusChannelProvisioner>
implements
ExtendedPropertiesBinder<MessageChannel, ServiceBusConsumerProperties, ServiceBusProducerProperties> {
protected T bindingProperties;
private static final DefaultErrorMessageStrategy DEFAULT_ERROR_MESSAGE_STRATEGY = new DefaultErrorMessageStrategy();
protected static final String EXCEPTION_MESSAGE = "exception-message";
public ServiceBusMessageChannelBinder(String[] headersToEmbed, ServiceBusChannelProvisioner provisioningProvider) {
super(headersToEmbed, provisioningProvider);
}
@Override
protected MessageHandler createProducerMessageHandler(ProducerDestination destination,
ExtendedProducerProperties<ServiceBusProducerProperties> producerProperties, MessageChannel errorChannel) {
DefaultMessageHandler handler = new DefaultMessageHandler(destination.getName(), getSendOperation());
handler.setBeanFactory(getBeanFactory());
handler.setSync(producerProperties.getExtension().isSync());
handler.setSendTimeout(producerProperties.getExtension().getSendTimeout());
handler.setSendFailureChannel(errorChannel);
if (producerProperties.isPartitioned()) {
handler.setPartitionKeyExpressionString(
"'partitionKey-' + headers['" + BinderHeaders.PARTITION_HEADER + "']");
} else {
handler.setPartitionKeyExpression(new FunctionExpression<Message<?>>(m -> m.getPayload().hashCode()));
}
return handler;
}
@Override
public ServiceBusConsumerProperties getExtendedConsumerProperties(String channelName) {
return this.bindingProperties.getExtendedConsumerProperties(channelName);
}
@Override
public ServiceBusProducerProperties getExtendedProducerProperties(String channelName) {
return this.bindingProperties.getExtendedProducerProperties(channelName);
}
@Override
public String getDefaultsPrefix() {
return this.bindingProperties.getDefaultsPrefix();
}
@Override
public Class<? extends BinderSpecificPropertiesProvider> getExtendedPropertiesEntryClass() {
return this.bindingProperties.getExtendedPropertiesEntryClass();
}
@Override
public void setBindingProperties(T bindingProperties) {
this.bindingProperties = bindingProperties;
}
protected CheckpointConfig buildCheckpointConfig(
ExtendedConsumerProperties<ServiceBusConsumerProperties> properties) {
return CheckpointConfig.builder().checkpointMode(properties.getExtension().getCheckpointMode()).build();
}
protected ServiceBusClientConfig buildClientConfig(
ExtendedConsumerProperties<ServiceBusConsumerProperties> properties) {
ServiceBusConsumerProperties consumerProperties = properties.getExtension();
return ServiceBusClientConfig.builder().setPrefetchCount(consumerProperties.getPrefetchCount())
.setConcurrency(consumerProperties.getConcurrency())
.setSessionsEnabled(consumerProperties.isSessionsEnabled()).build();
}
abstract SendOperation getSendOperation();
} |
hihi,any response? | protected ErrorMessageStrategy getErrorMessageStrategy() {
return DEFAULT_ERROR_MESSAGE_STRATEGY;
} | return DEFAULT_ERROR_MESSAGE_STRATEGY; | protected ErrorMessageStrategy getErrorMessageStrategy() {
return DEFAULT_ERROR_MESSAGE_STRATEGY;
} | class ServiceBusMessageChannelBinder<T extends ServiceBusExtendedBindingProperties> extends
AbstractMessageChannelBinder<ExtendedConsumerProperties<ServiceBusConsumerProperties>,
ExtendedProducerProperties<ServiceBusProducerProperties>,
ServiceBusChannelProvisioner>
implements
ExtendedPropertiesBinder<MessageChannel, ServiceBusConsumerProperties, ServiceBusProducerProperties> {
protected T bindingProperties;
private static final DefaultErrorMessageStrategy DEFAULT_ERROR_MESSAGE_STRATEGY = new DefaultErrorMessageStrategy();
protected static final String EXCEPTION_MESSAGE = "exception-message";
public ServiceBusMessageChannelBinder(String[] headersToEmbed, ServiceBusChannelProvisioner provisioningProvider) {
super(headersToEmbed, provisioningProvider);
}
@Override
protected MessageHandler createProducerMessageHandler(ProducerDestination destination,
ExtendedProducerProperties<ServiceBusProducerProperties> producerProperties, MessageChannel errorChannel) {
DefaultMessageHandler handler = new DefaultMessageHandler(destination.getName(), getSendOperation());
handler.setBeanFactory(getBeanFactory());
handler.setSync(producerProperties.getExtension().isSync());
handler.setSendTimeout(producerProperties.getExtension().getSendTimeout());
handler.setSendFailureChannel(errorChannel);
if (producerProperties.isPartitioned()) {
handler.setPartitionKeyExpressionString(
"'partitionKey-' + headers['" + BinderHeaders.PARTITION_HEADER + "']");
} else {
handler.setPartitionKeyExpression(new FunctionExpression<Message<?>>(m -> m.getPayload().hashCode()));
}
return handler;
}
@Override
public ServiceBusConsumerProperties getExtendedConsumerProperties(String channelName) {
return this.bindingProperties.getExtendedConsumerProperties(channelName);
}
@Override
public ServiceBusProducerProperties getExtendedProducerProperties(String channelName) {
return this.bindingProperties.getExtendedProducerProperties(channelName);
}
@Override
public String getDefaultsPrefix() {
return this.bindingProperties.getDefaultsPrefix();
}
@Override
public Class<? extends BinderSpecificPropertiesProvider> getExtendedPropertiesEntryClass() {
return this.bindingProperties.getExtendedPropertiesEntryClass();
}
@Override
public void setBindingProperties(T bindingProperties) {
this.bindingProperties = bindingProperties;
}
protected CheckpointConfig buildCheckpointConfig(
ExtendedConsumerProperties<ServiceBusConsumerProperties> properties) {
return CheckpointConfig.builder().checkpointMode(properties.getExtension().getCheckpointMode()).build();
}
protected ServiceBusClientConfig buildClientConfig(
ExtendedConsumerProperties<ServiceBusConsumerProperties> properties) {
ServiceBusConsumerProperties consumerProperties = properties.getExtension();
return ServiceBusClientConfig.builder().setPrefetchCount(consumerProperties.getPrefetchCount())
.setConcurrency(consumerProperties.getConcurrency())
.setSessionsEnabled(consumerProperties.isSessionsEnabled()).build();
}
abstract SendOperation getSendOperation();
} | class ServiceBusMessageChannelBinder<T extends ServiceBusExtendedBindingProperties> extends
AbstractMessageChannelBinder<ExtendedConsumerProperties<ServiceBusConsumerProperties>,
ExtendedProducerProperties<ServiceBusProducerProperties>,
ServiceBusChannelProvisioner>
implements
ExtendedPropertiesBinder<MessageChannel, ServiceBusConsumerProperties, ServiceBusProducerProperties> {
protected T bindingProperties;
private static final DefaultErrorMessageStrategy DEFAULT_ERROR_MESSAGE_STRATEGY = new DefaultErrorMessageStrategy();
protected static final String EXCEPTION_MESSAGE = "exception-message";
public ServiceBusMessageChannelBinder(String[] headersToEmbed, ServiceBusChannelProvisioner provisioningProvider) {
super(headersToEmbed, provisioningProvider);
}
@Override
protected MessageHandler createProducerMessageHandler(ProducerDestination destination,
ExtendedProducerProperties<ServiceBusProducerProperties> producerProperties, MessageChannel errorChannel) {
DefaultMessageHandler handler = new DefaultMessageHandler(destination.getName(), getSendOperation());
handler.setBeanFactory(getBeanFactory());
handler.setSync(producerProperties.getExtension().isSync());
handler.setSendTimeout(producerProperties.getExtension().getSendTimeout());
handler.setSendFailureChannel(errorChannel);
if (producerProperties.isPartitioned()) {
handler.setPartitionKeyExpressionString(
"'partitionKey-' + headers['" + BinderHeaders.PARTITION_HEADER + "']");
} else {
handler.setPartitionKeyExpression(new FunctionExpression<Message<?>>(m -> m.getPayload().hashCode()));
}
return handler;
}
@Override
public ServiceBusConsumerProperties getExtendedConsumerProperties(String channelName) {
return this.bindingProperties.getExtendedConsumerProperties(channelName);
}
@Override
public ServiceBusProducerProperties getExtendedProducerProperties(String channelName) {
return this.bindingProperties.getExtendedProducerProperties(channelName);
}
@Override
public String getDefaultsPrefix() {
return this.bindingProperties.getDefaultsPrefix();
}
@Override
public Class<? extends BinderSpecificPropertiesProvider> getExtendedPropertiesEntryClass() {
return this.bindingProperties.getExtendedPropertiesEntryClass();
}
@Override
public void setBindingProperties(T bindingProperties) {
this.bindingProperties = bindingProperties;
}
protected CheckpointConfig buildCheckpointConfig(
ExtendedConsumerProperties<ServiceBusConsumerProperties> properties) {
return CheckpointConfig.builder().checkpointMode(properties.getExtension().getCheckpointMode()).build();
}
protected ServiceBusClientConfig buildClientConfig(
ExtendedConsumerProperties<ServiceBusConsumerProperties> properties) {
ServiceBusConsumerProperties consumerProperties = properties.getExtension();
return ServiceBusClientConfig.builder().setPrefetchCount(consumerProperties.getPrefetchCount())
.setConcurrency(consumerProperties.getConcurrency())
.setSessionsEnabled(consumerProperties.isSessionsEnabled()).build();
}
abstract SendOperation getSendOperation();
} |
I am so sorry that I have ignored this notification for so many days==. After investigating code of `ErrorMessageStrategy` from both Rabbit MQ binder and azure0-spring-integration-core project, I think it makes sense to leave it as hard coded. | protected ErrorMessageStrategy getErrorMessageStrategy() {
return DEFAULT_ERROR_MESSAGE_STRATEGY;
} | return DEFAULT_ERROR_MESSAGE_STRATEGY; | protected ErrorMessageStrategy getErrorMessageStrategy() {
return DEFAULT_ERROR_MESSAGE_STRATEGY;
} | class ServiceBusMessageChannelBinder<T extends ServiceBusExtendedBindingProperties> extends
AbstractMessageChannelBinder<ExtendedConsumerProperties<ServiceBusConsumerProperties>,
ExtendedProducerProperties<ServiceBusProducerProperties>,
ServiceBusChannelProvisioner>
implements
ExtendedPropertiesBinder<MessageChannel, ServiceBusConsumerProperties, ServiceBusProducerProperties> {
protected T bindingProperties;
private static final DefaultErrorMessageStrategy DEFAULT_ERROR_MESSAGE_STRATEGY = new DefaultErrorMessageStrategy();
protected static final String EXCEPTION_MESSAGE = "exception-message";
public ServiceBusMessageChannelBinder(String[] headersToEmbed, ServiceBusChannelProvisioner provisioningProvider) {
super(headersToEmbed, provisioningProvider);
}
@Override
protected MessageHandler createProducerMessageHandler(ProducerDestination destination,
ExtendedProducerProperties<ServiceBusProducerProperties> producerProperties, MessageChannel errorChannel) {
DefaultMessageHandler handler = new DefaultMessageHandler(destination.getName(), getSendOperation());
handler.setBeanFactory(getBeanFactory());
handler.setSync(producerProperties.getExtension().isSync());
handler.setSendTimeout(producerProperties.getExtension().getSendTimeout());
handler.setSendFailureChannel(errorChannel);
if (producerProperties.isPartitioned()) {
handler.setPartitionKeyExpressionString(
"'partitionKey-' + headers['" + BinderHeaders.PARTITION_HEADER + "']");
} else {
handler.setPartitionKeyExpression(new FunctionExpression<Message<?>>(m -> m.getPayload().hashCode()));
}
return handler;
}
@Override
public ServiceBusConsumerProperties getExtendedConsumerProperties(String channelName) {
return this.bindingProperties.getExtendedConsumerProperties(channelName);
}
@Override
public ServiceBusProducerProperties getExtendedProducerProperties(String channelName) {
return this.bindingProperties.getExtendedProducerProperties(channelName);
}
@Override
public String getDefaultsPrefix() {
return this.bindingProperties.getDefaultsPrefix();
}
@Override
public Class<? extends BinderSpecificPropertiesProvider> getExtendedPropertiesEntryClass() {
return this.bindingProperties.getExtendedPropertiesEntryClass();
}
@Override
public void setBindingProperties(T bindingProperties) {
this.bindingProperties = bindingProperties;
}
protected CheckpointConfig buildCheckpointConfig(
ExtendedConsumerProperties<ServiceBusConsumerProperties> properties) {
return CheckpointConfig.builder().checkpointMode(properties.getExtension().getCheckpointMode()).build();
}
protected ServiceBusClientConfig buildClientConfig(
ExtendedConsumerProperties<ServiceBusConsumerProperties> properties) {
ServiceBusConsumerProperties consumerProperties = properties.getExtension();
return ServiceBusClientConfig.builder().setPrefetchCount(consumerProperties.getPrefetchCount())
.setConcurrency(consumerProperties.getConcurrency())
.setSessionsEnabled(consumerProperties.isSessionsEnabled()).build();
}
abstract SendOperation getSendOperation();
} | class ServiceBusMessageChannelBinder<T extends ServiceBusExtendedBindingProperties> extends
AbstractMessageChannelBinder<ExtendedConsumerProperties<ServiceBusConsumerProperties>,
ExtendedProducerProperties<ServiceBusProducerProperties>,
ServiceBusChannelProvisioner>
implements
ExtendedPropertiesBinder<MessageChannel, ServiceBusConsumerProperties, ServiceBusProducerProperties> {
protected T bindingProperties;
private static final DefaultErrorMessageStrategy DEFAULT_ERROR_MESSAGE_STRATEGY = new DefaultErrorMessageStrategy();
protected static final String EXCEPTION_MESSAGE = "exception-message";
public ServiceBusMessageChannelBinder(String[] headersToEmbed, ServiceBusChannelProvisioner provisioningProvider) {
super(headersToEmbed, provisioningProvider);
}
@Override
protected MessageHandler createProducerMessageHandler(ProducerDestination destination,
ExtendedProducerProperties<ServiceBusProducerProperties> producerProperties, MessageChannel errorChannel) {
DefaultMessageHandler handler = new DefaultMessageHandler(destination.getName(), getSendOperation());
handler.setBeanFactory(getBeanFactory());
handler.setSync(producerProperties.getExtension().isSync());
handler.setSendTimeout(producerProperties.getExtension().getSendTimeout());
handler.setSendFailureChannel(errorChannel);
if (producerProperties.isPartitioned()) {
handler.setPartitionKeyExpressionString(
"'partitionKey-' + headers['" + BinderHeaders.PARTITION_HEADER + "']");
} else {
handler.setPartitionKeyExpression(new FunctionExpression<Message<?>>(m -> m.getPayload().hashCode()));
}
return handler;
}
@Override
public ServiceBusConsumerProperties getExtendedConsumerProperties(String channelName) {
return this.bindingProperties.getExtendedConsumerProperties(channelName);
}
@Override
public ServiceBusProducerProperties getExtendedProducerProperties(String channelName) {
return this.bindingProperties.getExtendedProducerProperties(channelName);
}
@Override
public String getDefaultsPrefix() {
return this.bindingProperties.getDefaultsPrefix();
}
@Override
public Class<? extends BinderSpecificPropertiesProvider> getExtendedPropertiesEntryClass() {
return this.bindingProperties.getExtendedPropertiesEntryClass();
}
@Override
public void setBindingProperties(T bindingProperties) {
this.bindingProperties = bindingProperties;
}
protected CheckpointConfig buildCheckpointConfig(
ExtendedConsumerProperties<ServiceBusConsumerProperties> properties) {
return CheckpointConfig.builder().checkpointMode(properties.getExtension().getCheckpointMode()).build();
}
protected ServiceBusClientConfig buildClientConfig(
ExtendedConsumerProperties<ServiceBusConsumerProperties> properties) {
ServiceBusConsumerProperties consumerProperties = properties.getExtension();
return ServiceBusClientConfig.builder().setPrefetchCount(consumerProperties.getPrefetchCount())
.setConcurrency(consumerProperties.getConcurrency())
.setSessionsEnabled(consumerProperties.isSessionsEnabled()).build();
}
abstract SendOperation getSendOperation();
} |
Why this property remains? | private void normalizeProperties() {
this.hostNameBindingsToDelete = new ArrayList<>();
this.appSettingsToAdd = new HashMap<>();
this.appSettingsToRemove = new ArrayList<>();
this.appSettingStickiness = new HashMap<>();
this.connectionStringsToAdd = new HashMap<>();
this.connectionStringsToRemove = new ArrayList<>();
this.connectionStringStickiness = new HashMap<>();
this.sourceControl = null;
this.sourceControlToDelete = false;
this.authenticationToUpdate = false;
this.diagnosticLogsToUpdate = false;
this.sslBindingsToCreate = new TreeMap<>();
this.msiHandler = null;
this.webSiteBase = new WebSiteBaseImpl(inner());
this.hostNameSslStateMap = new HashMap<>(this.webSiteBase.hostnameSslStates());
this.webAppMsiHandler.clear();
} | this.hostNameSslStateMap = new HashMap<>(this.webSiteBase.hostnameSslStates()); | private void normalizeProperties() {
this.hostNameBindingsToCreate = new TreeMap<>();
this.hostNameBindingsToDelete = new ArrayList<>();
this.appSettingsToAdd = new HashMap<>();
this.appSettingsToRemove = new ArrayList<>();
this.appSettingStickiness = new HashMap<>();
this.connectionStringsToAdd = new HashMap<>();
this.connectionStringsToRemove = new ArrayList<>();
this.connectionStringStickiness = new HashMap<>();
this.sourceControl = null;
this.sourceControlToDelete = false;
this.authenticationToUpdate = false;
this.diagnosticLogsToUpdate = false;
this.sslBindingsToCreate = new TreeMap<>();
this.msiHandler = null;
this.webSiteBase = new WebSiteBaseImpl(inner());
this.hostNameSslStateMap = new HashMap<>(this.webSiteBase.hostnameSslStates());
this.webAppMsiHandler.clear();
} | class WebAppBaseImpl<FluentT extends WebAppBase, FluentImplT extends WebAppBaseImpl<FluentT, FluentImplT>>
extends GroupableResourceImpl<FluentT, SiteInner, FluentImplT, AppServiceManager>
implements WebAppBase,
WebAppBase.Definition<FluentT>,
WebAppBase.Update<FluentT>,
WebAppBase.UpdateStages.WithWebContainer<FluentT> {
private final ClientLogger logger = new ClientLogger(getClass());
private static final Map<AzureEnvironment, String> DNS_MAP =
new HashMap<AzureEnvironment, String>() {
{
put(AzureEnvironment.AZURE, "azurewebsites.net");
put(AzureEnvironment.AZURE_CHINA, "chinacloudsites.cn");
put(AzureEnvironment.AZURE_GERMANY, "azurewebsites.de");
put(AzureEnvironment.AZURE_US_GOVERNMENT, "azurewebsites.us");
}
};
SiteConfigResourceInner siteConfig;
KuduClient kuduClient;
WebSiteBase webSiteBase;
private Map<String, HostnameSslState> hostNameSslStateMap;
private TreeMap<String, HostnameBindingImpl<FluentT, FluentImplT>> hostNameBindingsToCreate;
private List<String> hostNameBindingsToDelete;
private TreeMap<String, HostnameSslBindingImpl<FluentT, FluentImplT>> sslBindingsToCreate;
protected Map<String, String> appSettingsToAdd;
protected List<String> appSettingsToRemove;
private Map<String, Boolean> appSettingStickiness;
private Map<String, ConnStringValueTypePair> connectionStringsToAdd;
private List<String> connectionStringsToRemove;
private Map<String, Boolean> connectionStringStickiness;
private WebAppSourceControlImpl<FluentT, FluentImplT> sourceControl;
private boolean sourceControlToDelete;
private WebAppAuthenticationImpl<FluentT, FluentImplT> authentication;
private boolean authenticationToUpdate;
private WebAppDiagnosticLogsImpl<FluentT, FluentImplT> diagnosticLogs;
private boolean diagnosticLogsToUpdate;
private FunctionalTaskItem msiHandler;
private boolean isInCreateMode;
private WebAppMsiHandler<FluentT, FluentImplT> webAppMsiHandler;
WebAppBaseImpl(
String name,
SiteInner innerObject,
SiteConfigResourceInner siteConfig,
SiteLogsConfigInner logConfig,
AppServiceManager manager) {
super(name, innerObject, manager);
if (innerObject != null && innerObject.kind() != null) {
innerObject.withKind(innerObject.kind().replace(";", ","));
}
this.siteConfig = siteConfig;
if (logConfig != null) {
this.diagnosticLogs = new WebAppDiagnosticLogsImpl<>(logConfig, this);
}
webAppMsiHandler = new WebAppMsiHandler<>(manager.authorizationManager(), this);
normalizeProperties();
isInCreateMode = inner() == null || inner().id() == null;
if (!isInCreateMode) {
initializeKuduClient();
}
}
public boolean isInCreateMode() {
return isInCreateMode;
}
private void initializeKuduClient() {
if (kuduClient == null) {
kuduClient = new KuduClient(this);
}
}
@Override
public void setInner(SiteInner innerObject) {
if (innerObject.kind() != null) {
innerObject.withKind(innerObject.kind().replace(";", ","));
}
super.setInner(innerObject);
}
RoleAssignmentHelper.IdProvider idProvider() {
return new RoleAssignmentHelper.IdProvider() {
@Override
public String principalId() {
if (inner() != null && inner().identity() != null) {
return inner().identity().principalId();
} else {
return null;
}
}
@Override
public String resourceId() {
if (inner() != null) {
return inner().id();
} else {
return null;
}
}
};
}
@Override
public String state() {
return webSiteBase.state();
}
@Override
public Set<String> hostnames() {
return webSiteBase.hostnames();
}
@Override
public String repositorySiteName() {
return webSiteBase.repositorySiteName();
}
@Override
public UsageState usageState() {
return webSiteBase.usageState();
}
@Override
public boolean enabled() {
return webSiteBase.enabled();
}
@Override
public Set<String> enabledHostNames() {
return webSiteBase.enabledHostNames();
}
@Override
public SiteAvailabilityState availabilityState() {
return webSiteBase.availabilityState();
}
@Override
public Map<String, HostnameSslState> hostnameSslStates() {
return Collections.unmodifiableMap(hostNameSslStateMap);
}
@Override
public String appServicePlanId() {
return webSiteBase.appServicePlanId();
}
@Override
public OffsetDateTime lastModifiedTime() {
return webSiteBase.lastModifiedTime();
}
@Override
public Set<String> trafficManagerHostNames() {
return webSiteBase.trafficManagerHostNames();
}
@Override
public boolean scmSiteAlsoStopped() {
return webSiteBase.scmSiteAlsoStopped();
}
@Override
public String targetSwapSlot() {
return webSiteBase.targetSwapSlot();
}
@Override
public boolean clientAffinityEnabled() {
return webSiteBase.clientAffinityEnabled();
}
@Override
public boolean clientCertEnabled() {
return webSiteBase.clientCertEnabled();
}
@Override
public boolean hostnamesDisabled() {
return webSiteBase.hostnamesDisabled();
}
@Override
public Set<String> outboundIPAddresses() {
return webSiteBase.outboundIPAddresses();
}
@Override
public int containerSize() {
return webSiteBase.containerSize();
}
@Override
public CloningInfo cloningInfo() {
return webSiteBase.cloningInfo();
}
@Override
public boolean isDefaultContainer() {
return webSiteBase.isDefaultContainer();
}
@Override
public String defaultHostname() {
if (inner().defaultHostname() != null) {
return inner().defaultHostname();
} else {
AzureEnvironment environment = manager().environment();
String dns = DNS_MAP.get(environment);
String leaf = name();
if (this instanceof DeploymentSlotBaseImpl<?, ?, ?, ?, ?>) {
leaf = ((DeploymentSlotBaseImpl<?, ?, ?, ?, ?>) this).parent().name() + "-" + leaf;
}
return leaf + "." + dns;
}
}
@Override
public List<String> defaultDocuments() {
if (siteConfig == null) {
return null;
}
return Collections.unmodifiableList(siteConfig.defaultDocuments());
}
@Override
public NetFrameworkVersion netFrameworkVersion() {
if (siteConfig == null) {
return null;
}
return NetFrameworkVersion.fromString(siteConfig.netFrameworkVersion());
}
@Override
public PhpVersion phpVersion() {
if (siteConfig == null || siteConfig.phpVersion() == null) {
return PhpVersion.OFF;
}
return PhpVersion.fromString(siteConfig.phpVersion());
}
@Override
public PythonVersion pythonVersion() {
if (siteConfig == null || siteConfig.pythonVersion() == null) {
return PythonVersion.OFF;
}
return PythonVersion.fromString(siteConfig.pythonVersion());
}
@Override
public String nodeVersion() {
if (siteConfig == null) {
return null;
}
return siteConfig.nodeVersion();
}
@Override
public boolean remoteDebuggingEnabled() {
if (siteConfig == null) {
return false;
}
return Utils.toPrimitiveBoolean(siteConfig.remoteDebuggingEnabled());
}
@Override
public RemoteVisualStudioVersion remoteDebuggingVersion() {
if (siteConfig == null) {
return null;
}
return RemoteVisualStudioVersion.fromString(siteConfig.remoteDebuggingVersion());
}
@Override
public boolean webSocketsEnabled() {
if (siteConfig == null) {
return false;
}
return Utils.toPrimitiveBoolean(siteConfig.webSocketsEnabled());
}
@Override
public boolean alwaysOn() {
if (siteConfig == null) {
return false;
}
return Utils.toPrimitiveBoolean(siteConfig.alwaysOn());
}
@Override
public JavaVersion javaVersion() {
if (siteConfig == null || siteConfig.javaVersion() == null) {
return JavaVersion.OFF;
}
return JavaVersion.fromString(siteConfig.javaVersion());
}
@Override
public String javaContainer() {
if (siteConfig == null) {
return null;
}
return siteConfig.javaContainer();
}
@Override
public String javaContainerVersion() {
if (siteConfig == null) {
return null;
}
return siteConfig.javaContainerVersion();
}
@Override
public ManagedPipelineMode managedPipelineMode() {
if (siteConfig == null) {
return null;
}
return siteConfig.managedPipelineMode();
}
@Override
public PlatformArchitecture platformArchitecture() {
if (siteConfig.use32BitWorkerProcess()) {
return PlatformArchitecture.X86;
} else {
return PlatformArchitecture.X64;
}
}
@Override
public String linuxFxVersion() {
if (siteConfig == null) {
return null;
}
return siteConfig.linuxFxVersion();
}
@Override
public String autoSwapSlotName() {
if (siteConfig == null) {
return null;
}
return siteConfig.autoSwapSlotName();
}
@Override
public boolean httpsOnly() {
return webSiteBase.httpsOnly();
}
@Override
public FtpsState ftpsState() {
if (siteConfig == null) {
return null;
}
return siteConfig.ftpsState();
}
@Override
public List<VirtualApplication> virtualApplications() {
if (siteConfig == null) {
return null;
}
return siteConfig.virtualApplications();
}
@Override
public boolean http20Enabled() {
if (siteConfig == null) {
return false;
}
return Utils.toPrimitiveBoolean(siteConfig.http20Enabled());
}
@Override
public boolean localMySqlEnabled() {
if (siteConfig == null) {
return false;
}
return Utils.toPrimitiveBoolean(siteConfig.localMySqlEnabled());
}
@Override
public ScmType scmType() {
if (siteConfig == null) {
return null;
}
return siteConfig.scmType();
}
@Override
public String documentRoot() {
if (siteConfig == null) {
return null;
}
return siteConfig.documentRoot();
}
@Override
public SupportedTlsVersions minTlsVersion() {
if (siteConfig == null) {
return null;
}
return siteConfig.minTlsVersion();
}
@Override
public OperatingSystem operatingSystem() {
if (inner().kind() != null && inner().kind().toLowerCase(Locale.ROOT).contains("linux")) {
return OperatingSystem.LINUX;
} else {
return OperatingSystem.WINDOWS;
}
}
@Override
public String systemAssignedManagedServiceIdentityTenantId() {
if (inner().identity() == null) {
return null;
}
return inner().identity().tenantId();
}
@Override
public String systemAssignedManagedServiceIdentityPrincipalId() {
if (inner().identity() == null) {
return null;
}
return inner().identity().principalId();
}
@Override
public Set<String> userAssignedManagedServiceIdentityIds() {
if (inner().identity() == null) {
return null;
}
return inner().identity().userAssignedIdentities().keySet();
}
@Override
public WebAppDiagnosticLogsImpl<FluentT, FluentImplT> diagnosticLogsConfig() {
return diagnosticLogs;
}
@Override
public InputStream streamApplicationLogs() {
return pipeObservableToInputStream(streamApplicationLogsAsync());
}
@Override
public Flux<String> streamApplicationLogsAsync() {
return kuduClient.streamApplicationLogsAsync();
}
@Override
public InputStream streamHttpLogs() {
return pipeObservableToInputStream(streamHttpLogsAsync());
}
@Override
public Flux<String> streamHttpLogsAsync() {
return kuduClient.streamHttpLogsAsync();
}
@Override
public InputStream streamTraceLogs() {
return pipeObservableToInputStream(streamTraceLogsAsync());
}
@Override
public Flux<String> streamTraceLogsAsync() {
return kuduClient.streamTraceLogsAsync();
}
@Override
public InputStream streamDeploymentLogs() {
return pipeObservableToInputStream(streamDeploymentLogsAsync());
}
@Override
public Flux<String> streamDeploymentLogsAsync() {
return kuduClient.streamDeploymentLogsAsync();
}
@Override
public InputStream streamAllLogs() {
return pipeObservableToInputStream(streamAllLogsAsync());
}
@Override
public Flux<String> streamAllLogsAsync() {
return kuduClient.streamAllLogsAsync();
}
private InputStream pipeObservableToInputStream(Flux<String> observable) {
PipedInputStreamWithCallback in = new PipedInputStreamWithCallback();
final PipedOutputStream out = new PipedOutputStream();
try {
in.connect(out);
} catch (IOException e) {
throw logger.logExceptionAsError(new RuntimeException(e));
}
final Disposable subscription =
observable
.subscribeOn(Schedulers.elastic())
.subscribe(
s -> {
try {
out.write(s.getBytes(StandardCharsets.UTF_8));
out.write('\n');
out.flush();
} catch (IOException e) {
throw logger.logExceptionAsError(new RuntimeException(e));
}
});
in
.addCallback(
() -> {
subscription.dispose();
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
});
return in;
}
@Override
public Map<String, AppSetting> getAppSettings() {
return getAppSettingsAsync().block();
}
@Override
public Mono<Map<String, AppSetting>> getAppSettingsAsync() {
return Mono
.zip(
listAppSettings(),
listSlotConfigurations(),
(appSettingsInner, slotConfigs) ->
appSettingsInner
.properties()
.entrySet()
.stream()
.collect(
Collectors
.toMap(
Map.Entry::getKey,
entry ->
new AppSettingImpl(
entry.getKey(),
entry.getValue(),
slotConfigs.appSettingNames() != null
&& slotConfigs.appSettingNames().contains(entry.getKey())))));
}
@Override
public Map<String, ConnectionString> getConnectionStrings() {
return getConnectionStringsAsync().block();
}
@Override
public Mono<Map<String, ConnectionString>> getConnectionStringsAsync() {
return Mono
.zip(
listConnectionStrings(),
listSlotConfigurations(),
(connectionStringsInner, slotConfigs) ->
connectionStringsInner
.properties()
.entrySet()
.stream()
.collect(
Collectors
.toMap(
Map.Entry::getKey,
entry ->
new ConnectionStringImpl(
entry.getKey(),
entry.getValue(),
slotConfigs.connectionStringNames() != null
&& slotConfigs.connectionStringNames().contains(entry.getKey())))));
}
@Override
public WebAppAuthentication getAuthenticationConfig() {
return getAuthenticationConfigAsync().block();
}
@Override
public Mono<WebAppAuthentication> getAuthenticationConfigAsync() {
return getAuthentication()
.map(siteAuthSettingsInner -> new WebAppAuthenticationImpl<>(siteAuthSettingsInner, WebAppBaseImpl.this));
}
abstract Mono<SiteInner> createOrUpdateInner(SiteInner site);
abstract Mono<SiteInner> updateInner(SitePatchResourceInner siteUpdate);
abstract Mono<SiteInner> getInner();
abstract Mono<SiteConfigResourceInner> getConfigInner();
abstract Mono<SiteConfigResourceInner> createOrUpdateSiteConfig(SiteConfigResourceInner siteConfig);
abstract Mono<Void> deleteHostnameBinding(String hostname);
abstract Mono<StringDictionaryInner> listAppSettings();
abstract Mono<StringDictionaryInner> updateAppSettings(StringDictionaryInner inner);
abstract Mono<ConnectionStringDictionaryInner> listConnectionStrings();
abstract Mono<ConnectionStringDictionaryInner> updateConnectionStrings(ConnectionStringDictionaryInner inner);
abstract Mono<SlotConfigNamesResourceInner> listSlotConfigurations();
abstract Mono<SlotConfigNamesResourceInner> updateSlotConfigurations(SlotConfigNamesResourceInner inner);
abstract Mono<SiteSourceControlInner> createOrUpdateSourceControl(SiteSourceControlInner inner);
abstract Mono<Void> deleteSourceControl();
abstract Mono<SiteAuthSettingsInner> updateAuthentication(SiteAuthSettingsInner inner);
abstract Mono<SiteAuthSettingsInner> getAuthentication();
abstract Mono<MSDeployStatusInner> createMSDeploy(MSDeploy msDeployInner);
abstract Mono<SiteLogsConfigInner> updateDiagnosticLogsConfig(SiteLogsConfigInner siteLogsConfigInner);
@Override
public void beforeGroupCreateOrUpdate() {
if (hostNameSslStateMap.size() > 0) {
inner().withHostnameSslStates(new ArrayList<>(hostNameSslStateMap.values()));
}
IndexableTaskItem rootTaskItem =
wrapTask(
context -> {
return submitHostNameBindings()
.flatMap(fluentT -> submitSslBindings(fluentT.inner()));
});
IndexableTaskItem lastTaskItem = rootTaskItem;
lastTaskItem = sequentialTask(lastTaskItem, context -> submitSiteConfig());
lastTaskItem =
sequentialTask(
lastTaskItem,
context ->
submitMetadata()
.flatMap(ignored -> submitAppSettings().mergeWith(submitConnectionStrings()).last())
.flatMap(ignored -> submitStickiness()));
lastTaskItem =
sequentialTask(
lastTaskItem,
context -> submitSourceControlToDelete().flatMap(ignored -> submitSourceControlToCreate()));
lastTaskItem = sequentialTask(lastTaskItem, context -> submitAuthentication());
lastTaskItem = sequentialTask(lastTaskItem, context -> submitLogConfiguration());
if (msiHandler != null) {
sequentialTask(lastTaskItem, msiHandler);
}
addPostRunDependent(rootTaskItem);
}
private static IndexableTaskItem wrapTask(FunctionalTaskItem taskItem) {
return IndexableTaskItem.create(taskItem);
}
private static IndexableTaskItem sequentialTask(IndexableTaskItem taskItem1, FunctionalTaskItem taskItem2) {
IndexableTaskItem taskItem = IndexableTaskItem.create(taskItem2);
taskItem1.addPostRunDependent(taskItem);
return taskItem;
}
@Override
@SuppressWarnings("unchecked")
public Mono<FluentT> createResourceAsync() {
this.webAppMsiHandler.processCreatedExternalIdentities();
this.webAppMsiHandler.handleExternalIdentities();
return submitSite(inner())
.map(
siteInner -> {
setInner(siteInner);
return (FluentT) WebAppBaseImpl.this;
});
}
@Override
@SuppressWarnings("unchecked")
public Mono<FluentT> updateResourceAsync() {
SiteInner siteInner = this.inner();
SitePatchResourceInner siteUpdate = new SitePatchResourceInner();
siteUpdate.withHostnameSslStates(siteInner.hostnameSslStates());
siteUpdate.withKind(siteInner.kind());
siteUpdate.withEnabled(siteInner.enabled());
siteUpdate.withServerFarmId(siteInner.serverFarmId());
siteUpdate.withReserved(siteInner.reserved());
siteUpdate.withIsXenon(siteInner.isXenon());
siteUpdate.withHyperV(siteInner.hyperV());
siteUpdate.withScmSiteAlsoStopped(siteInner.scmSiteAlsoStopped());
siteUpdate.withHostingEnvironmentProfile(siteInner.hostingEnvironmentProfile());
siteUpdate.withClientAffinityEnabled(siteInner.clientAffinityEnabled());
siteUpdate.withClientCertEnabled(siteInner.clientCertEnabled());
siteUpdate.withClientCertExclusionPaths(siteInner.clientCertExclusionPaths());
siteUpdate.withHostNamesDisabled(siteInner.hostNamesDisabled());
siteUpdate.withContainerSize(siteInner.containerSize());
siteUpdate.withDailyMemoryTimeQuota(siteInner.dailyMemoryTimeQuota());
siteUpdate.withCloningInfo(siteInner.cloningInfo());
siteUpdate.withHttpsOnly(siteInner.httpsOnly());
siteUpdate.withRedundancyMode(siteInner.redundancyMode());
this.webAppMsiHandler.handleExternalIdentities(siteUpdate);
return submitSite(siteUpdate)
.map(
siteInner1 -> {
setInner(siteInner1);
webAppMsiHandler.clear();
return (FluentT) WebAppBaseImpl.this;
});
}
@Override
public Mono<Void> afterPostRunAsync(final boolean isGroupFaulted) {
if (!isGroupFaulted) {
isInCreateMode = false;
initializeKuduClient();
}
return Mono
.fromCallable(
() -> {
normalizeProperties();
return null;
});
}
Mono<SiteInner> submitSite(final SiteInner site) {
site.withSiteConfig(new SiteConfigInner());
return submitSiteWithoutSiteConfig(site);
}
Mono<SiteInner> submitSiteWithoutSiteConfig(final SiteInner site) {
return createOrUpdateInner(site)
.map(
siteInner -> {
site.withSiteConfig(null);
return siteInner;
});
}
Mono<SiteInner> submitSite(final SitePatchResourceInner siteUpdate) {
return updateInner(siteUpdate)
.map(
siteInner -> {
siteInner.withSiteConfig(null);
return siteInner;
});
}
@SuppressWarnings("unchecked")
Mono<FluentT> submitHostNameBindings() {
final List<Mono<HostnameBinding>> bindingObservables = new ArrayList<>();
for (HostnameBindingImpl<FluentT, FluentImplT> binding : hostNameBindingsToCreate.values()) {
bindingObservables.add(Utils.<HostnameBinding>rootResource(binding.createAsync().last()));
}
for (String binding : hostNameBindingsToDelete) {
bindingObservables.add(deleteHostnameBinding(binding).then(Mono.empty()));
}
if (bindingObservables.isEmpty()) {
return Mono.just((FluentT) this);
} else {
return Flux
.zip(bindingObservables, ignored -> WebAppBaseImpl.this)
.last()
.onErrorResume(
throwable -> {
if (throwable instanceof HttpResponseException
&& ((HttpResponseException) throwable).getResponse().getStatusCode() == 400) {
return submitSite(inner())
.flatMap(
ignored -> Flux.zip(bindingObservables, ignored1 -> WebAppBaseImpl.this).last());
} else {
return Mono.error(throwable);
}
})
.flatMap(WebAppBaseImpl::refreshAsync);
}
}
Mono<Indexable> submitSslBindings(final SiteInner site) {
List<Mono<AppServiceCertificate>> certs = new ArrayList<>();
for (final HostnameSslBindingImpl<FluentT, FluentImplT> binding : sslBindingsToCreate.values()) {
certs.add(binding.newCertificate());
hostNameSslStateMap.put(binding.inner().name(), binding.inner().withToUpdate(true));
}
if (certs.isEmpty()) {
return Mono.just((Indexable) this);
} else {
site.withHostnameSslStates(new ArrayList<>(hostNameSslStateMap.values()));
return Flux
.zip(certs, ignored -> site)
.last()
.flatMap(this::createOrUpdateInner)
.map(
siteInner -> {
setInner(siteInner);
return WebAppBaseImpl.this;
});
}
}
Mono<Indexable> submitSiteConfig() {
if (siteConfig == null) {
return Mono.just((Indexable) this);
}
return createOrUpdateSiteConfig(siteConfig)
.flatMap(
returnedSiteConfig -> {
siteConfig = returnedSiteConfig;
return Mono.just((Indexable) WebAppBaseImpl.this);
});
}
Mono<Indexable> submitAppSettings() {
Mono<Indexable> observable = Mono.just((Indexable) this);
if (!appSettingsToAdd.isEmpty() || !appSettingsToRemove.isEmpty()) {
observable =
listAppSettings()
.switchIfEmpty(Mono.just(new StringDictionaryInner()))
.flatMap(
stringDictionaryInner -> {
if (stringDictionaryInner.properties() == null) {
stringDictionaryInner.withProperties(new HashMap<String, String>());
}
for (String appSettingKey : appSettingsToRemove) {
stringDictionaryInner.properties().remove(appSettingKey);
}
stringDictionaryInner.properties().putAll(appSettingsToAdd);
return updateAppSettings(stringDictionaryInner);
})
.map(ignored -> WebAppBaseImpl.this);
}
return observable;
}
Mono<Indexable> submitMetadata() {
return Mono.just((Indexable) this);
}
Mono<Indexable> submitConnectionStrings() {
Mono<Indexable> observable = Mono.just((Indexable) this);
if (!connectionStringsToAdd.isEmpty() || !connectionStringsToRemove.isEmpty()) {
observable =
listConnectionStrings()
.switchIfEmpty(Mono.just(new ConnectionStringDictionaryInner()))
.flatMap(
dictionaryInner -> {
if (dictionaryInner.properties() == null) {
dictionaryInner.withProperties(new HashMap<String, ConnStringValueTypePair>());
}
for (String connectionString : connectionStringsToRemove) {
dictionaryInner.properties().remove(connectionString);
}
dictionaryInner.properties().putAll(connectionStringsToAdd);
return updateConnectionStrings(dictionaryInner);
})
.map(ignored -> WebAppBaseImpl.this);
}
return observable;
}
Mono<Indexable> submitStickiness() {
Mono<Indexable> observable = Mono.just((Indexable) this);
if (!appSettingStickiness.isEmpty() || !connectionStringStickiness.isEmpty()) {
observable =
listSlotConfigurations()
.switchIfEmpty(Mono.just(new SlotConfigNamesResourceInner()))
.flatMap(
slotConfigNamesResourceInner -> {
if (slotConfigNamesResourceInner.appSettingNames() == null) {
slotConfigNamesResourceInner.withAppSettingNames(new ArrayList<>());
}
if (slotConfigNamesResourceInner.connectionStringNames() == null) {
slotConfigNamesResourceInner.withConnectionStringNames(new ArrayList<>());
}
Set<String> stickyAppSettingKeys =
new HashSet<>(slotConfigNamesResourceInner.appSettingNames());
Set<String> stickyConnectionStringNames =
new HashSet<>(slotConfigNamesResourceInner.connectionStringNames());
for (Map.Entry<String, Boolean> stickiness : appSettingStickiness.entrySet()) {
if (stickiness.getValue()) {
stickyAppSettingKeys.add(stickiness.getKey());
} else {
stickyAppSettingKeys.remove(stickiness.getKey());
}
}
for (Map.Entry<String, Boolean> stickiness : connectionStringStickiness.entrySet()) {
if (stickiness.getValue()) {
stickyConnectionStringNames.add(stickiness.getKey());
} else {
stickyConnectionStringNames.remove(stickiness.getKey());
}
}
slotConfigNamesResourceInner.withAppSettingNames(new ArrayList<>(stickyAppSettingKeys));
slotConfigNamesResourceInner
.withConnectionStringNames(new ArrayList<>(stickyConnectionStringNames));
return updateSlotConfigurations(slotConfigNamesResourceInner);
})
.map(ignored -> WebAppBaseImpl.this);
}
return observable;
}
Mono<Indexable> submitSourceControlToCreate() {
if (sourceControl == null || sourceControlToDelete) {
return Mono.just((Indexable) this);
}
return sourceControl
.registerGithubAccessToken()
.then(createOrUpdateSourceControl(sourceControl.inner()))
.delayElement(SdkContext.getDelayDuration(Duration.ofSeconds(30)))
.map(ignored -> WebAppBaseImpl.this);
}
Mono<Indexable> submitSourceControlToDelete() {
if (!sourceControlToDelete) {
return Mono.just((Indexable) this);
}
return deleteSourceControl().map(ignored -> WebAppBaseImpl.this);
}
Mono<Indexable> submitAuthentication() {
if (!authenticationToUpdate) {
return Mono.just((Indexable) this);
}
return updateAuthentication(authentication.inner())
.map(
siteAuthSettingsInner -> {
WebAppBaseImpl.this.authentication =
new WebAppAuthenticationImpl<>(siteAuthSettingsInner, WebAppBaseImpl.this);
return WebAppBaseImpl.this;
});
}
Mono<Indexable> submitLogConfiguration() {
if (!diagnosticLogsToUpdate) {
return Mono.just((Indexable) this);
}
return updateDiagnosticLogsConfig(diagnosticLogs.inner())
.map(
siteLogsConfigInner -> {
WebAppBaseImpl.this.diagnosticLogs =
new WebAppDiagnosticLogsImpl<>(siteLogsConfigInner, WebAppBaseImpl.this);
return WebAppBaseImpl.this;
});
}
@Override
public WebDeploymentImpl<FluentT, FluentImplT> deploy() {
return new WebDeploymentImpl<>(this);
}
WebAppBaseImpl<FluentT, FluentImplT> withNewHostNameSslBinding(
final HostnameSslBindingImpl<FluentT, FluentImplT> hostNameSslBinding) {
sslBindingsToCreate.put(hostNameSslBinding.name(), hostNameSslBinding);
return this;
}
@SuppressWarnings("unchecked")
public FluentImplT withManagedHostnameBindings(AppServiceDomain domain, String... hostnames) {
for (String hostname : hostnames) {
if (hostname.equals("@") || hostname.equalsIgnoreCase(domain.name())) {
defineHostnameBinding()
.withAzureManagedDomain(domain)
.withSubDomain(hostname)
.withDnsRecordType(CustomHostnameDnsRecordType.A)
.attach();
} else {
defineHostnameBinding()
.withAzureManagedDomain(domain)
.withSubDomain(hostname)
.withDnsRecordType(CustomHostnameDnsRecordType.CNAME)
.attach();
}
}
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public HostnameBindingImpl<FluentT, FluentImplT> defineHostnameBinding() {
HostnameBindingInner inner = new HostnameBindingInner();
inner.withSiteName(name());
inner.withAzureResourceType(AzureResourceType.WEBSITE);
inner.withAzureResourceName(name());
inner.withHostnameType(HostnameType.VERIFIED);
return new HostnameBindingImpl<>(inner, (FluentImplT) this);
}
@SuppressWarnings("unchecked")
public FluentImplT withThirdPartyHostnameBinding(String domain, String... hostnames) {
for (String hostname : hostnames) {
defineHostnameBinding()
.withThirdPartyDomain(domain)
.withSubDomain(hostname)
.withDnsRecordType(CustomHostnameDnsRecordType.CNAME)
.attach();
}
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withoutHostnameBinding(String hostname) {
hostNameBindingsToDelete.add(hostname);
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withoutSslBinding(String hostname) {
if (hostNameSslStateMap.containsKey(hostname)) {
hostNameSslStateMap.get(hostname).withSslState(SslState.DISABLED).withToUpdate(true);
}
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
FluentImplT withHostNameBinding(final HostnameBindingImpl<FluentT, FluentImplT> hostNameBinding) {
this.hostNameBindingsToCreate.put(hostNameBinding.name(), hostNameBinding);
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withAppDisabledOnCreation() {
inner().withEnabled(false);
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withScmSiteAlsoStopped(boolean scmSiteAlsoStopped) {
inner().withScmSiteAlsoStopped(scmSiteAlsoStopped);
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withClientAffinityEnabled(boolean enabled) {
inner().withClientAffinityEnabled(enabled);
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withClientCertEnabled(boolean enabled) {
inner().withClientCertEnabled(enabled);
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public HostnameSslBindingImpl<FluentT, FluentImplT> defineSslBinding() {
return new HostnameSslBindingImpl<>(new HostnameSslState(), (FluentImplT) this);
}
@SuppressWarnings("unchecked")
public FluentImplT withNetFrameworkVersion(NetFrameworkVersion version) {
if (siteConfig == null) {
siteConfig = new SiteConfigResourceInner();
}
siteConfig.withNetFrameworkVersion(version.toString());
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withPhpVersion(PhpVersion version) {
if (siteConfig == null) {
siteConfig = new SiteConfigResourceInner();
}
siteConfig.withPhpVersion(version.toString());
return (FluentImplT) this;
}
public FluentImplT withoutPhp() {
return withPhpVersion(PhpVersion.fromString(""));
}
@SuppressWarnings("unchecked")
public FluentImplT withJavaVersion(JavaVersion version) {
if (siteConfig == null) {
siteConfig = new SiteConfigResourceInner();
}
siteConfig.withJavaVersion(version.toString());
return (FluentImplT) this;
}
public FluentImplT withoutJava() {
return withJavaVersion(JavaVersion.fromString("")).withWebContainer(WebContainer.fromString(""));
}
@SuppressWarnings("unchecked")
public FluentImplT withWebContainer(WebContainer webContainer) {
if (siteConfig == null) {
siteConfig = new SiteConfigResourceInner();
}
if (webContainer == null) {
siteConfig.withJavaContainer(null);
siteConfig.withJavaContainerVersion(null);
} else if (webContainer.toString().isEmpty()) {
siteConfig.withJavaContainer("");
siteConfig.withJavaContainerVersion("");
} else {
String[] containerInfo = webContainer.toString().split(" ");
siteConfig.withJavaContainer(containerInfo[0]);
siteConfig.withJavaContainerVersion(containerInfo[1]);
}
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withPythonVersion(PythonVersion version) {
if (siteConfig == null) {
siteConfig = new SiteConfigResourceInner();
}
siteConfig.withPythonVersion(version.toString());
return (FluentImplT) this;
}
public FluentImplT withoutPython() {
return withPythonVersion(PythonVersion.fromString(""));
}
@SuppressWarnings("unchecked")
public FluentImplT withPlatformArchitecture(PlatformArchitecture platform) {
if (siteConfig == null) {
siteConfig = new SiteConfigResourceInner();
}
siteConfig.withUse32BitWorkerProcess(platform.equals(PlatformArchitecture.X86));
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withWebSocketsEnabled(boolean enabled) {
if (siteConfig == null) {
siteConfig = new SiteConfigResourceInner();
}
siteConfig.withWebSocketsEnabled(enabled);
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withWebAppAlwaysOn(boolean alwaysOn) {
if (siteConfig == null) {
siteConfig = new SiteConfigResourceInner();
}
siteConfig.withAlwaysOn(alwaysOn);
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withManagedPipelineMode(ManagedPipelineMode managedPipelineMode) {
if (siteConfig == null) {
siteConfig = new SiteConfigResourceInner();
}
siteConfig.withManagedPipelineMode(managedPipelineMode);
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withAutoSwapSlotName(String slotName) {
if (siteConfig == null) {
siteConfig = new SiteConfigResourceInner();
}
siteConfig.withAutoSwapSlotName(slotName);
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withRemoteDebuggingEnabled(RemoteVisualStudioVersion remoteVisualStudioVersion) {
if (siteConfig == null) {
siteConfig = new SiteConfigResourceInner();
}
siteConfig.withRemoteDebuggingEnabled(true);
siteConfig.withRemoteDebuggingVersion(remoteVisualStudioVersion.toString());
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withRemoteDebuggingDisabled() {
if (siteConfig == null) {
siteConfig = new SiteConfigResourceInner();
}
siteConfig.withRemoteDebuggingEnabled(false);
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withDefaultDocument(String document) {
if (siteConfig == null) {
siteConfig = new SiteConfigResourceInner();
}
if (siteConfig.defaultDocuments() == null) {
siteConfig.withDefaultDocuments(new ArrayList<String>());
}
siteConfig.defaultDocuments().add(document);
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withDefaultDocuments(List<String> documents) {
if (siteConfig == null) {
siteConfig = new SiteConfigResourceInner();
}
if (siteConfig.defaultDocuments() == null) {
siteConfig.withDefaultDocuments(new ArrayList<>());
}
siteConfig.defaultDocuments().addAll(documents);
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withoutDefaultDocument(String document) {
if (siteConfig == null) {
siteConfig = new SiteConfigResourceInner();
}
if (siteConfig.defaultDocuments() != null) {
siteConfig.defaultDocuments().remove(document);
}
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withHttpsOnly(boolean httpsOnly) {
inner().withHttpsOnly(httpsOnly);
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withHttp20Enabled(boolean http20Enabled) {
if (siteConfig == null) {
siteConfig = new SiteConfigResourceInner();
}
siteConfig.withHttp20Enabled(http20Enabled);
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withFtpsState(FtpsState ftpsState) {
if (siteConfig == null) {
siteConfig = new SiteConfigResourceInner();
}
siteConfig.withFtpsState(ftpsState);
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withVirtualApplications(List<VirtualApplication> virtualApplications) {
if (siteConfig == null) {
siteConfig = new SiteConfigResourceInner();
}
siteConfig.withVirtualApplications(virtualApplications);
return (FluentImplT) this;
}
@Override
@SuppressWarnings("unchecked")
public FluentImplT withMinTlsVersion(SupportedTlsVersions minTlsVersion) {
if (siteConfig == null) {
siteConfig = new SiteConfigResourceInner();
}
siteConfig.withMinTlsVersion(minTlsVersion);
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withAppSetting(String key, String value) {
appSettingsToAdd.put(key, value);
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withAppSettings(Map<String, String> settings) {
appSettingsToAdd.putAll(settings);
return (FluentImplT) this;
}
public FluentImplT withStickyAppSetting(String key, String value) {
withAppSetting(key, value);
return withAppSettingStickiness(key, true);
}
@SuppressWarnings("unchecked")
public FluentImplT withStickyAppSettings(Map<String, String> settings) {
withAppSettings(settings);
for (String key : settings.keySet()) {
appSettingStickiness.put(key, true);
}
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withoutAppSetting(String key) {
appSettingsToRemove.add(key);
appSettingStickiness.remove(key);
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withAppSettingStickiness(String key, boolean sticky) {
appSettingStickiness.put(key, sticky);
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withConnectionString(String name, String value, ConnectionStringType type) {
connectionStringsToAdd.put(name, new ConnStringValueTypePair().withValue(value).withType(type));
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withStickyConnectionString(String name, String value, ConnectionStringType type) {
connectionStringsToAdd.put(name, new ConnStringValueTypePair().withValue(value).withType(type));
connectionStringStickiness.put(name, true);
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withoutConnectionString(String name) {
connectionStringsToRemove.add(name);
connectionStringStickiness.remove(name);
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withConnectionStringStickiness(String name, boolean stickiness) {
connectionStringStickiness.put(name, stickiness);
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
void withSourceControl(WebAppSourceControlImpl<FluentT, FluentImplT> sourceControl) {
this.sourceControl = sourceControl;
}
public WebAppSourceControlImpl<FluentT, FluentImplT> defineSourceControl() {
SiteSourceControlInner sourceControlInner = new SiteSourceControlInner();
return new WebAppSourceControlImpl<>(sourceControlInner, this);
}
@SuppressWarnings("unchecked")
public FluentImplT withLocalGitSourceControl() {
if (siteConfig == null) {
siteConfig = new SiteConfigResourceInner();
}
siteConfig.withScmType(ScmType.LOCAL_GIT);
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withoutSourceControl() {
sourceControlToDelete = true;
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
void withAuthentication(WebAppAuthenticationImpl<FluentT, FluentImplT> authentication) {
this.authentication = authentication;
authenticationToUpdate = true;
}
void withDiagnosticLogs(WebAppDiagnosticLogsImpl<FluentT, FluentImplT> diagnosticLogs) {
this.diagnosticLogs = diagnosticLogs;
diagnosticLogsToUpdate = true;
}
@Override
@SuppressWarnings("unchecked")
public Mono<FluentT> refreshAsync() {
return super
.refreshAsync()
.flatMap(
fluentT ->
getConfigInner()
.map(
returnedSiteConfig -> {
siteConfig = returnedSiteConfig;
return fluentT;
}));
}
@Override
protected Mono<SiteInner> getInnerAsync() {
return getInner();
}
@Override
public WebAppAuthenticationImpl<FluentT, FluentImplT> defineAuthentication() {
return new WebAppAuthenticationImpl<>(new SiteAuthSettingsInner().withEnabled(true), this);
}
@Override
@SuppressWarnings("unchecked")
public FluentImplT withoutAuthentication() {
this.authentication.inner().withEnabled(false);
authenticationToUpdate = true;
return (FluentImplT) this;
}
@Override
@SuppressWarnings("unchecked")
public FluentImplT withContainerLoggingEnabled(int quotaInMB, int retentionDays) {
return updateDiagnosticLogsConfiguration()
.withWebServerLogging()
.withWebServerLogsStoredOnFileSystem()
.withWebServerFileSystemQuotaInMB(quotaInMB)
.withLogRetentionDays(retentionDays)
.attach();
}
@Override
public FluentImplT withContainerLoggingEnabled() {
return withContainerLoggingEnabled(35, 0);
}
@Override
@SuppressWarnings("unchecked")
public FluentImplT withContainerLoggingDisabled() {
return updateDiagnosticLogsConfiguration().withoutWebServerLogging().attach();
}
@Override
@SuppressWarnings("unchecked")
public FluentImplT withSystemAssignedManagedServiceIdentity() {
this.webAppMsiHandler.withLocalManagedServiceIdentity();
return (FluentImplT) this;
}
@Override
@SuppressWarnings("unchecked")
public FluentImplT withoutSystemAssignedManagedServiceIdentity() {
this.webAppMsiHandler.withoutLocalManagedServiceIdentity();
return (FluentImplT) this;
}
@Override
@SuppressWarnings("unchecked")
public FluentImplT withUserAssignedManagedServiceIdentity() {
return (FluentImplT) this;
}
@Override
@SuppressWarnings("unchecked")
public FluentImplT withSystemAssignedIdentityBasedAccessTo(final String resourceId, final BuiltInRole role) {
this.webAppMsiHandler.withAccessTo(resourceId, role);
return (FluentImplT) this;
}
@Override
@SuppressWarnings("unchecked")
public FluentImplT withSystemAssignedIdentityBasedAccessToCurrentResourceGroup(final BuiltInRole role) {
this.webAppMsiHandler.withAccessToCurrentResourceGroup(role);
return (FluentImplT) this;
}
@Override
@SuppressWarnings("unchecked")
public FluentImplT withSystemAssignedIdentityBasedAccessTo(final String resourceId, final String roleDefinitionId) {
this.webAppMsiHandler.withAccessTo(resourceId, roleDefinitionId);
return (FluentImplT) this;
}
@Override
@SuppressWarnings("unchecked")
public FluentImplT withSystemAssignedIdentityBasedAccessToCurrentResourceGroup(final String roleDefinitionId) {
this.webAppMsiHandler.withAccessToCurrentResourceGroup(roleDefinitionId);
return (FluentImplT) this;
}
@Override
@SuppressWarnings("unchecked")
public FluentImplT withNewUserAssignedManagedServiceIdentity(Creatable<Identity> creatableIdentity) {
this.webAppMsiHandler.withNewExternalManagedServiceIdentity(creatableIdentity);
return (FluentImplT) this;
}
@Override
@SuppressWarnings("unchecked")
public FluentImplT withExistingUserAssignedManagedServiceIdentity(Identity identity) {
this.webAppMsiHandler.withExistingExternalManagedServiceIdentity(identity);
return (FluentImplT) this;
}
@Override
@SuppressWarnings("unchecked")
public FluentImplT withoutUserAssignedManagedServiceIdentity(String identityId) {
this.webAppMsiHandler.withoutExternalManagedServiceIdentity(identityId);
return (FluentImplT) this;
}
@Override
public WebAppDiagnosticLogsImpl<FluentT, FluentImplT> defineDiagnosticLogsConfiguration() {
if (diagnosticLogs == null) {
return new WebAppDiagnosticLogsImpl<>(new SiteLogsConfigInner(), this);
} else {
return diagnosticLogs;
}
}
@Override
public WebAppDiagnosticLogsImpl<FluentT, FluentImplT> updateDiagnosticLogsConfiguration() {
return defineDiagnosticLogsConfiguration();
}
@Override
public ManagedServiceIdentity identity() {
return webSiteBase.identity();
}
@Override
public boolean hyperV() {
return webSiteBase.hyperV();
}
@Override
public HostingEnvironmentProfile hostingEnvironmentProfile() {
return webSiteBase.hostingEnvironmentProfile();
}
@Override
public Set<String> clientCertExclusionPaths() {
return webSiteBase.clientCertExclusionPaths();
}
@Override
public Set<String> possibleOutboundIpAddresses() {
return webSiteBase.possibleOutboundIpAddresses();
}
@Override
public int dailyMemoryTimeQuota() {
return webSiteBase.dailyMemoryTimeQuota();
}
@Override
public OffsetDateTime suspendedTill() {
return webSiteBase.suspendedTill();
}
@Override
public int maxNumberOfWorkers() {
return webSiteBase.maxNumberOfWorkers();
}
@Override
public SlotSwapStatus slotSwapStatus() {
return webSiteBase.slotSwapStatus();
}
@Override
public RedundancyMode redundancyMode() {
return webSiteBase.redundancyMode();
}
@Override
public UUID inProgressOperationId() {
return webSiteBase.inProgressOperationId();
}
private static class PipedInputStreamWithCallback extends PipedInputStream {
private Runnable callback;
private void addCallback(Runnable action) {
this.callback = action;
}
@Override
public void close() throws IOException {
callback.run();
super.close();
}
}
} | class WebAppBaseImpl<FluentT extends WebAppBase, FluentImplT extends WebAppBaseImpl<FluentT, FluentImplT>>
extends GroupableResourceImpl<FluentT, SiteInner, FluentImplT, AppServiceManager>
implements WebAppBase,
WebAppBase.Definition<FluentT>,
WebAppBase.Update<FluentT>,
WebAppBase.UpdateStages.WithWebContainer<FluentT> {
private final ClientLogger logger = new ClientLogger(getClass());
private static final Map<AzureEnvironment, String> DNS_MAP =
new HashMap<AzureEnvironment, String>() {
{
put(AzureEnvironment.AZURE, "azurewebsites.net");
put(AzureEnvironment.AZURE_CHINA, "chinacloudsites.cn");
put(AzureEnvironment.AZURE_GERMANY, "azurewebsites.de");
put(AzureEnvironment.AZURE_US_GOVERNMENT, "azurewebsites.us");
}
};
SiteConfigResourceInner siteConfig;
KuduClient kuduClient;
WebSiteBase webSiteBase;
private Map<String, HostnameSslState> hostNameSslStateMap;
private TreeMap<String, HostnameBindingImpl<FluentT, FluentImplT>> hostNameBindingsToCreate;
private List<String> hostNameBindingsToDelete;
private TreeMap<String, HostnameSslBindingImpl<FluentT, FluentImplT>> sslBindingsToCreate;
protected Map<String, String> appSettingsToAdd;
protected List<String> appSettingsToRemove;
private Map<String, Boolean> appSettingStickiness;
private Map<String, ConnStringValueTypePair> connectionStringsToAdd;
private List<String> connectionStringsToRemove;
private Map<String, Boolean> connectionStringStickiness;
private WebAppSourceControlImpl<FluentT, FluentImplT> sourceControl;
private boolean sourceControlToDelete;
private WebAppAuthenticationImpl<FluentT, FluentImplT> authentication;
private boolean authenticationToUpdate;
private WebAppDiagnosticLogsImpl<FluentT, FluentImplT> diagnosticLogs;
private boolean diagnosticLogsToUpdate;
private FunctionalTaskItem msiHandler;
private boolean isInCreateMode;
private WebAppMsiHandler<FluentT, FluentImplT> webAppMsiHandler;
WebAppBaseImpl(
String name,
SiteInner innerObject,
SiteConfigResourceInner siteConfig,
SiteLogsConfigInner logConfig,
AppServiceManager manager) {
super(name, innerObject, manager);
if (innerObject != null && innerObject.kind() != null) {
innerObject.withKind(innerObject.kind().replace(";", ","));
}
this.siteConfig = siteConfig;
if (logConfig != null) {
this.diagnosticLogs = new WebAppDiagnosticLogsImpl<>(logConfig, this);
}
webAppMsiHandler = new WebAppMsiHandler<>(manager.authorizationManager(), this);
normalizeProperties();
isInCreateMode = inner() == null || inner().id() == null;
if (!isInCreateMode) {
initializeKuduClient();
}
}
public boolean isInCreateMode() {
return isInCreateMode;
}
private void initializeKuduClient() {
if (kuduClient == null) {
kuduClient = new KuduClient(this);
}
}
@Override
public void setInner(SiteInner innerObject) {
if (innerObject.kind() != null) {
innerObject.withKind(innerObject.kind().replace(";", ","));
}
super.setInner(innerObject);
}
RoleAssignmentHelper.IdProvider idProvider() {
return new RoleAssignmentHelper.IdProvider() {
@Override
public String principalId() {
if (inner() != null && inner().identity() != null) {
return inner().identity().principalId();
} else {
return null;
}
}
@Override
public String resourceId() {
if (inner() != null) {
return inner().id();
} else {
return null;
}
}
};
}
@Override
public String state() {
return webSiteBase.state();
}
@Override
public Set<String> hostnames() {
return webSiteBase.hostnames();
}
@Override
public String repositorySiteName() {
return webSiteBase.repositorySiteName();
}
@Override
public UsageState usageState() {
return webSiteBase.usageState();
}
@Override
public boolean enabled() {
return webSiteBase.enabled();
}
@Override
public Set<String> enabledHostNames() {
return webSiteBase.enabledHostNames();
}
@Override
public SiteAvailabilityState availabilityState() {
return webSiteBase.availabilityState();
}
@Override
public Map<String, HostnameSslState> hostnameSslStates() {
return Collections.unmodifiableMap(hostNameSslStateMap);
}
@Override
public String appServicePlanId() {
return webSiteBase.appServicePlanId();
}
@Override
public OffsetDateTime lastModifiedTime() {
return webSiteBase.lastModifiedTime();
}
@Override
public Set<String> trafficManagerHostNames() {
return webSiteBase.trafficManagerHostNames();
}
@Override
public boolean scmSiteAlsoStopped() {
return webSiteBase.scmSiteAlsoStopped();
}
@Override
public String targetSwapSlot() {
return webSiteBase.targetSwapSlot();
}
@Override
public boolean clientAffinityEnabled() {
return webSiteBase.clientAffinityEnabled();
}
@Override
public boolean clientCertEnabled() {
return webSiteBase.clientCertEnabled();
}
@Override
public boolean hostnamesDisabled() {
return webSiteBase.hostnamesDisabled();
}
@Override
public Set<String> outboundIPAddresses() {
return webSiteBase.outboundIPAddresses();
}
@Override
public int containerSize() {
return webSiteBase.containerSize();
}
@Override
public CloningInfo cloningInfo() {
return webSiteBase.cloningInfo();
}
@Override
public boolean isDefaultContainer() {
return webSiteBase.isDefaultContainer();
}
@Override
public String defaultHostname() {
if (inner().defaultHostname() != null) {
return inner().defaultHostname();
} else {
AzureEnvironment environment = manager().environment();
String dns = DNS_MAP.get(environment);
String leaf = name();
if (this instanceof DeploymentSlotBaseImpl<?, ?, ?, ?, ?>) {
leaf = ((DeploymentSlotBaseImpl<?, ?, ?, ?, ?>) this).parent().name() + "-" + leaf;
}
return leaf + "." + dns;
}
}
@Override
public List<String> defaultDocuments() {
if (siteConfig == null) {
return null;
}
return Collections.unmodifiableList(siteConfig.defaultDocuments());
}
@Override
public NetFrameworkVersion netFrameworkVersion() {
if (siteConfig == null) {
return null;
}
return NetFrameworkVersion.fromString(siteConfig.netFrameworkVersion());
}
@Override
public PhpVersion phpVersion() {
if (siteConfig == null || siteConfig.phpVersion() == null) {
return PhpVersion.OFF;
}
return PhpVersion.fromString(siteConfig.phpVersion());
}
@Override
public PythonVersion pythonVersion() {
if (siteConfig == null || siteConfig.pythonVersion() == null) {
return PythonVersion.OFF;
}
return PythonVersion.fromString(siteConfig.pythonVersion());
}
@Override
public String nodeVersion() {
if (siteConfig == null) {
return null;
}
return siteConfig.nodeVersion();
}
@Override
public boolean remoteDebuggingEnabled() {
if (siteConfig == null) {
return false;
}
return Utils.toPrimitiveBoolean(siteConfig.remoteDebuggingEnabled());
}
@Override
public RemoteVisualStudioVersion remoteDebuggingVersion() {
if (siteConfig == null) {
return null;
}
return RemoteVisualStudioVersion.fromString(siteConfig.remoteDebuggingVersion());
}
@Override
public boolean webSocketsEnabled() {
if (siteConfig == null) {
return false;
}
return Utils.toPrimitiveBoolean(siteConfig.webSocketsEnabled());
}
@Override
public boolean alwaysOn() {
if (siteConfig == null) {
return false;
}
return Utils.toPrimitiveBoolean(siteConfig.alwaysOn());
}
@Override
public JavaVersion javaVersion() {
if (siteConfig == null || siteConfig.javaVersion() == null) {
return JavaVersion.OFF;
}
return JavaVersion.fromString(siteConfig.javaVersion());
}
@Override
public String javaContainer() {
if (siteConfig == null) {
return null;
}
return siteConfig.javaContainer();
}
@Override
public String javaContainerVersion() {
if (siteConfig == null) {
return null;
}
return siteConfig.javaContainerVersion();
}
@Override
public ManagedPipelineMode managedPipelineMode() {
if (siteConfig == null) {
return null;
}
return siteConfig.managedPipelineMode();
}
@Override
public PlatformArchitecture platformArchitecture() {
if (siteConfig.use32BitWorkerProcess()) {
return PlatformArchitecture.X86;
} else {
return PlatformArchitecture.X64;
}
}
@Override
public String linuxFxVersion() {
if (siteConfig == null) {
return null;
}
return siteConfig.linuxFxVersion();
}
@Override
public String autoSwapSlotName() {
if (siteConfig == null) {
return null;
}
return siteConfig.autoSwapSlotName();
}
@Override
public boolean httpsOnly() {
return webSiteBase.httpsOnly();
}
@Override
public FtpsState ftpsState() {
if (siteConfig == null) {
return null;
}
return siteConfig.ftpsState();
}
@Override
public List<VirtualApplication> virtualApplications() {
if (siteConfig == null) {
return null;
}
return siteConfig.virtualApplications();
}
@Override
public boolean http20Enabled() {
if (siteConfig == null) {
return false;
}
return Utils.toPrimitiveBoolean(siteConfig.http20Enabled());
}
@Override
public boolean localMySqlEnabled() {
if (siteConfig == null) {
return false;
}
return Utils.toPrimitiveBoolean(siteConfig.localMySqlEnabled());
}
@Override
public ScmType scmType() {
if (siteConfig == null) {
return null;
}
return siteConfig.scmType();
}
@Override
public String documentRoot() {
if (siteConfig == null) {
return null;
}
return siteConfig.documentRoot();
}
@Override
public SupportedTlsVersions minTlsVersion() {
if (siteConfig == null) {
return null;
}
return siteConfig.minTlsVersion();
}
@Override
public OperatingSystem operatingSystem() {
if (inner().kind() != null && inner().kind().toLowerCase(Locale.ROOT).contains("linux")) {
return OperatingSystem.LINUX;
} else {
return OperatingSystem.WINDOWS;
}
}
@Override
public String systemAssignedManagedServiceIdentityTenantId() {
if (inner().identity() == null) {
return null;
}
return inner().identity().tenantId();
}
@Override
public String systemAssignedManagedServiceIdentityPrincipalId() {
if (inner().identity() == null) {
return null;
}
return inner().identity().principalId();
}
@Override
public Set<String> userAssignedManagedServiceIdentityIds() {
if (inner().identity() == null) {
return null;
}
return inner().identity().userAssignedIdentities().keySet();
}
@Override
public WebAppDiagnosticLogsImpl<FluentT, FluentImplT> diagnosticLogsConfig() {
return diagnosticLogs;
}
@Override
public InputStream streamApplicationLogs() {
return pipeObservableToInputStream(streamApplicationLogsAsync());
}
@Override
public Flux<String> streamApplicationLogsAsync() {
return kuduClient.streamApplicationLogsAsync();
}
@Override
public InputStream streamHttpLogs() {
return pipeObservableToInputStream(streamHttpLogsAsync());
}
@Override
public Flux<String> streamHttpLogsAsync() {
return kuduClient.streamHttpLogsAsync();
}
@Override
public InputStream streamTraceLogs() {
return pipeObservableToInputStream(streamTraceLogsAsync());
}
@Override
public Flux<String> streamTraceLogsAsync() {
return kuduClient.streamTraceLogsAsync();
}
@Override
public InputStream streamDeploymentLogs() {
return pipeObservableToInputStream(streamDeploymentLogsAsync());
}
@Override
public Flux<String> streamDeploymentLogsAsync() {
return kuduClient.streamDeploymentLogsAsync();
}
@Override
public InputStream streamAllLogs() {
return pipeObservableToInputStream(streamAllLogsAsync());
}
@Override
public Flux<String> streamAllLogsAsync() {
return kuduClient.streamAllLogsAsync();
}
private InputStream pipeObservableToInputStream(Flux<String> observable) {
PipedInputStreamWithCallback in = new PipedInputStreamWithCallback();
final PipedOutputStream out = new PipedOutputStream();
try {
in.connect(out);
} catch (IOException e) {
throw logger.logExceptionAsError(new RuntimeException(e));
}
final Disposable subscription =
observable
.subscribeOn(Schedulers.elastic())
.subscribe(
s -> {
try {
out.write(s.getBytes(StandardCharsets.UTF_8));
out.write('\n');
out.flush();
} catch (IOException e) {
throw logger.logExceptionAsError(new RuntimeException(e));
}
});
in
.addCallback(
() -> {
subscription.dispose();
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
});
return in;
}
@Override
public Map<String, AppSetting> getAppSettings() {
return getAppSettingsAsync().block();
}
@Override
public Mono<Map<String, AppSetting>> getAppSettingsAsync() {
return Mono
.zip(
listAppSettings(),
listSlotConfigurations(),
(appSettingsInner, slotConfigs) ->
appSettingsInner
.properties()
.entrySet()
.stream()
.collect(
Collectors
.toMap(
Map.Entry::getKey,
entry ->
new AppSettingImpl(
entry.getKey(),
entry.getValue(),
slotConfigs.appSettingNames() != null
&& slotConfigs.appSettingNames().contains(entry.getKey())))));
}
@Override
public Map<String, ConnectionString> getConnectionStrings() {
return getConnectionStringsAsync().block();
}
@Override
public Mono<Map<String, ConnectionString>> getConnectionStringsAsync() {
return Mono
.zip(
listConnectionStrings(),
listSlotConfigurations(),
(connectionStringsInner, slotConfigs) ->
connectionStringsInner
.properties()
.entrySet()
.stream()
.collect(
Collectors
.toMap(
Map.Entry::getKey,
entry ->
new ConnectionStringImpl(
entry.getKey(),
entry.getValue(),
slotConfigs.connectionStringNames() != null
&& slotConfigs.connectionStringNames().contains(entry.getKey())))));
}
@Override
public WebAppAuthentication getAuthenticationConfig() {
return getAuthenticationConfigAsync().block();
}
@Override
public Mono<WebAppAuthentication> getAuthenticationConfigAsync() {
return getAuthentication()
.map(siteAuthSettingsInner -> new WebAppAuthenticationImpl<>(siteAuthSettingsInner, WebAppBaseImpl.this));
}
abstract Mono<SiteInner> createOrUpdateInner(SiteInner site);
abstract Mono<SiteInner> updateInner(SitePatchResourceInner siteUpdate);
abstract Mono<SiteInner> getInner();
abstract Mono<SiteConfigResourceInner> getConfigInner();
abstract Mono<SiteConfigResourceInner> createOrUpdateSiteConfig(SiteConfigResourceInner siteConfig);
abstract Mono<Void> deleteHostnameBinding(String hostname);
abstract Mono<StringDictionaryInner> listAppSettings();
abstract Mono<StringDictionaryInner> updateAppSettings(StringDictionaryInner inner);
abstract Mono<ConnectionStringDictionaryInner> listConnectionStrings();
abstract Mono<ConnectionStringDictionaryInner> updateConnectionStrings(ConnectionStringDictionaryInner inner);
abstract Mono<SlotConfigNamesResourceInner> listSlotConfigurations();
abstract Mono<SlotConfigNamesResourceInner> updateSlotConfigurations(SlotConfigNamesResourceInner inner);
abstract Mono<SiteSourceControlInner> createOrUpdateSourceControl(SiteSourceControlInner inner);
abstract Mono<Void> deleteSourceControl();
abstract Mono<SiteAuthSettingsInner> updateAuthentication(SiteAuthSettingsInner inner);
abstract Mono<SiteAuthSettingsInner> getAuthentication();
abstract Mono<MSDeployStatusInner> createMSDeploy(MSDeploy msDeployInner);
abstract Mono<SiteLogsConfigInner> updateDiagnosticLogsConfig(SiteLogsConfigInner siteLogsConfigInner);
@Override
public void beforeGroupCreateOrUpdate() {
if (hostNameSslStateMap.size() > 0) {
inner().withHostnameSslStates(new ArrayList<>(hostNameSslStateMap.values()));
}
IndexableTaskItem rootTaskItem =
wrapTask(
context -> {
return submitHostNameBindings()
.flatMap(fluentT -> submitSslBindings(fluentT.inner()));
});
IndexableTaskItem lastTaskItem = rootTaskItem;
lastTaskItem = sequentialTask(lastTaskItem, context -> submitSiteConfig());
lastTaskItem =
sequentialTask(
lastTaskItem,
context ->
submitMetadata()
.flatMap(ignored -> submitAppSettings().mergeWith(submitConnectionStrings()).last())
.flatMap(ignored -> submitStickiness()));
lastTaskItem =
sequentialTask(
lastTaskItem,
context -> submitSourceControlToDelete().flatMap(ignored -> submitSourceControlToCreate()));
lastTaskItem = sequentialTask(lastTaskItem, context -> submitAuthentication());
lastTaskItem = sequentialTask(lastTaskItem, context -> submitLogConfiguration());
if (msiHandler != null) {
sequentialTask(lastTaskItem, msiHandler);
}
addPostRunDependent(rootTaskItem);
}
private static IndexableTaskItem wrapTask(FunctionalTaskItem taskItem) {
return IndexableTaskItem.create(taskItem);
}
private static IndexableTaskItem sequentialTask(IndexableTaskItem taskItem1, FunctionalTaskItem taskItem2) {
IndexableTaskItem taskItem = IndexableTaskItem.create(taskItem2);
taskItem1.addPostRunDependent(taskItem);
return taskItem;
}
@Override
@SuppressWarnings("unchecked")
public Mono<FluentT> createResourceAsync() {
this.webAppMsiHandler.processCreatedExternalIdentities();
this.webAppMsiHandler.handleExternalIdentities();
return submitSite(inner())
.map(
siteInner -> {
setInner(siteInner);
return (FluentT) WebAppBaseImpl.this;
});
}
@Override
@SuppressWarnings("unchecked")
public Mono<FluentT> updateResourceAsync() {
SiteInner siteInner = this.inner();
SitePatchResourceInner siteUpdate = new SitePatchResourceInner();
siteUpdate.withHostnameSslStates(siteInner.hostnameSslStates());
siteUpdate.withKind(siteInner.kind());
siteUpdate.withEnabled(siteInner.enabled());
siteUpdate.withServerFarmId(siteInner.serverFarmId());
siteUpdate.withReserved(siteInner.reserved());
siteUpdate.withIsXenon(siteInner.isXenon());
siteUpdate.withHyperV(siteInner.hyperV());
siteUpdate.withScmSiteAlsoStopped(siteInner.scmSiteAlsoStopped());
siteUpdate.withHostingEnvironmentProfile(siteInner.hostingEnvironmentProfile());
siteUpdate.withClientAffinityEnabled(siteInner.clientAffinityEnabled());
siteUpdate.withClientCertEnabled(siteInner.clientCertEnabled());
siteUpdate.withClientCertExclusionPaths(siteInner.clientCertExclusionPaths());
siteUpdate.withHostNamesDisabled(siteInner.hostNamesDisabled());
siteUpdate.withContainerSize(siteInner.containerSize());
siteUpdate.withDailyMemoryTimeQuota(siteInner.dailyMemoryTimeQuota());
siteUpdate.withCloningInfo(siteInner.cloningInfo());
siteUpdate.withHttpsOnly(siteInner.httpsOnly());
siteUpdate.withRedundancyMode(siteInner.redundancyMode());
this.webAppMsiHandler.handleExternalIdentities(siteUpdate);
return submitSite(siteUpdate)
.map(
siteInner1 -> {
setInner(siteInner1);
webAppMsiHandler.clear();
return (FluentT) WebAppBaseImpl.this;
});
}
@Override
public Mono<Void> afterPostRunAsync(final boolean isGroupFaulted) {
if (!isGroupFaulted) {
isInCreateMode = false;
initializeKuduClient();
}
return Mono
.fromCallable(
() -> {
normalizeProperties();
return null;
});
}
Mono<SiteInner> submitSite(final SiteInner site) {
site.withSiteConfig(new SiteConfigInner());
return submitSiteWithoutSiteConfig(site);
}
Mono<SiteInner> submitSiteWithoutSiteConfig(final SiteInner site) {
return createOrUpdateInner(site)
.map(
siteInner -> {
site.withSiteConfig(null);
return siteInner;
});
}
Mono<SiteInner> submitSite(final SitePatchResourceInner siteUpdate) {
return updateInner(siteUpdate)
.map(
siteInner -> {
siteInner.withSiteConfig(null);
return siteInner;
});
}
@SuppressWarnings("unchecked")
Mono<FluentT> submitHostNameBindings() {
final List<Mono<HostnameBinding>> bindingObservables = new ArrayList<>();
for (HostnameBindingImpl<FluentT, FluentImplT> binding : hostNameBindingsToCreate.values()) {
bindingObservables.add(Utils.<HostnameBinding>rootResource(binding.createAsync().last()));
}
for (String binding : hostNameBindingsToDelete) {
bindingObservables.add(deleteHostnameBinding(binding).then(Mono.empty()));
}
if (bindingObservables.isEmpty()) {
return Mono.just((FluentT) this);
} else {
return Flux
.zip(bindingObservables, ignored -> WebAppBaseImpl.this)
.last()
.onErrorResume(
throwable -> {
if (throwable instanceof HttpResponseException
&& ((HttpResponseException) throwable).getResponse().getStatusCode() == 400) {
return submitSite(inner())
.flatMap(
ignored -> Flux.zip(bindingObservables, ignored1 -> WebAppBaseImpl.this).last());
} else {
return Mono.error(throwable);
}
})
.flatMap(WebAppBaseImpl::refreshAsync);
}
}
Mono<Indexable> submitSslBindings(final SiteInner site) {
List<Mono<AppServiceCertificate>> certs = new ArrayList<>();
for (final HostnameSslBindingImpl<FluentT, FluentImplT> binding : sslBindingsToCreate.values()) {
certs.add(binding.newCertificate());
hostNameSslStateMap.put(binding.inner().name(), binding.inner().withToUpdate(true));
}
if (certs.isEmpty()) {
return Mono.just((Indexable) this);
} else {
site.withHostnameSslStates(new ArrayList<>(hostNameSslStateMap.values()));
return Flux
.zip(certs, ignored -> site)
.last()
.flatMap(this::createOrUpdateInner)
.map(
siteInner -> {
setInner(siteInner);
return WebAppBaseImpl.this;
});
}
}
Mono<Indexable> submitSiteConfig() {
if (siteConfig == null) {
return Mono.just((Indexable) this);
}
return createOrUpdateSiteConfig(siteConfig)
.flatMap(
returnedSiteConfig -> {
siteConfig = returnedSiteConfig;
return Mono.just((Indexable) WebAppBaseImpl.this);
});
}
Mono<Indexable> submitAppSettings() {
Mono<Indexable> observable = Mono.just((Indexable) this);
if (!appSettingsToAdd.isEmpty() || !appSettingsToRemove.isEmpty()) {
observable =
listAppSettings()
.switchIfEmpty(Mono.just(new StringDictionaryInner()))
.flatMap(
stringDictionaryInner -> {
if (stringDictionaryInner.properties() == null) {
stringDictionaryInner.withProperties(new HashMap<String, String>());
}
for (String appSettingKey : appSettingsToRemove) {
stringDictionaryInner.properties().remove(appSettingKey);
}
stringDictionaryInner.properties().putAll(appSettingsToAdd);
return updateAppSettings(stringDictionaryInner);
})
.map(ignored -> WebAppBaseImpl.this);
}
return observable;
}
Mono<Indexable> submitMetadata() {
return Mono.just((Indexable) this);
}
Mono<Indexable> submitConnectionStrings() {
Mono<Indexable> observable = Mono.just((Indexable) this);
if (!connectionStringsToAdd.isEmpty() || !connectionStringsToRemove.isEmpty()) {
observable =
listConnectionStrings()
.switchIfEmpty(Mono.just(new ConnectionStringDictionaryInner()))
.flatMap(
dictionaryInner -> {
if (dictionaryInner.properties() == null) {
dictionaryInner.withProperties(new HashMap<String, ConnStringValueTypePair>());
}
for (String connectionString : connectionStringsToRemove) {
dictionaryInner.properties().remove(connectionString);
}
dictionaryInner.properties().putAll(connectionStringsToAdd);
return updateConnectionStrings(dictionaryInner);
})
.map(ignored -> WebAppBaseImpl.this);
}
return observable;
}
Mono<Indexable> submitStickiness() {
Mono<Indexable> observable = Mono.just((Indexable) this);
if (!appSettingStickiness.isEmpty() || !connectionStringStickiness.isEmpty()) {
observable =
listSlotConfigurations()
.switchIfEmpty(Mono.just(new SlotConfigNamesResourceInner()))
.flatMap(
slotConfigNamesResourceInner -> {
if (slotConfigNamesResourceInner.appSettingNames() == null) {
slotConfigNamesResourceInner.withAppSettingNames(new ArrayList<>());
}
if (slotConfigNamesResourceInner.connectionStringNames() == null) {
slotConfigNamesResourceInner.withConnectionStringNames(new ArrayList<>());
}
Set<String> stickyAppSettingKeys =
new HashSet<>(slotConfigNamesResourceInner.appSettingNames());
Set<String> stickyConnectionStringNames =
new HashSet<>(slotConfigNamesResourceInner.connectionStringNames());
for (Map.Entry<String, Boolean> stickiness : appSettingStickiness.entrySet()) {
if (stickiness.getValue()) {
stickyAppSettingKeys.add(stickiness.getKey());
} else {
stickyAppSettingKeys.remove(stickiness.getKey());
}
}
for (Map.Entry<String, Boolean> stickiness : connectionStringStickiness.entrySet()) {
if (stickiness.getValue()) {
stickyConnectionStringNames.add(stickiness.getKey());
} else {
stickyConnectionStringNames.remove(stickiness.getKey());
}
}
slotConfigNamesResourceInner.withAppSettingNames(new ArrayList<>(stickyAppSettingKeys));
slotConfigNamesResourceInner
.withConnectionStringNames(new ArrayList<>(stickyConnectionStringNames));
return updateSlotConfigurations(slotConfigNamesResourceInner);
})
.map(ignored -> WebAppBaseImpl.this);
}
return observable;
}
Mono<Indexable> submitSourceControlToCreate() {
if (sourceControl == null || sourceControlToDelete) {
return Mono.just((Indexable) this);
}
return sourceControl
.registerGithubAccessToken()
.then(createOrUpdateSourceControl(sourceControl.inner()))
.delayElement(SdkContext.getDelayDuration(Duration.ofSeconds(30)))
.map(ignored -> WebAppBaseImpl.this);
}
Mono<Indexable> submitSourceControlToDelete() {
if (!sourceControlToDelete) {
return Mono.just((Indexable) this);
}
return deleteSourceControl().map(ignored -> WebAppBaseImpl.this);
}
Mono<Indexable> submitAuthentication() {
if (!authenticationToUpdate) {
return Mono.just((Indexable) this);
}
return updateAuthentication(authentication.inner())
.map(
siteAuthSettingsInner -> {
WebAppBaseImpl.this.authentication =
new WebAppAuthenticationImpl<>(siteAuthSettingsInner, WebAppBaseImpl.this);
return WebAppBaseImpl.this;
});
}
Mono<Indexable> submitLogConfiguration() {
if (!diagnosticLogsToUpdate) {
return Mono.just((Indexable) this);
}
return updateDiagnosticLogsConfig(diagnosticLogs.inner())
.map(
siteLogsConfigInner -> {
WebAppBaseImpl.this.diagnosticLogs =
new WebAppDiagnosticLogsImpl<>(siteLogsConfigInner, WebAppBaseImpl.this);
return WebAppBaseImpl.this;
});
}
@Override
public WebDeploymentImpl<FluentT, FluentImplT> deploy() {
return new WebDeploymentImpl<>(this);
}
WebAppBaseImpl<FluentT, FluentImplT> withNewHostNameSslBinding(
final HostnameSslBindingImpl<FluentT, FluentImplT> hostNameSslBinding) {
sslBindingsToCreate.put(hostNameSslBinding.name(), hostNameSslBinding);
return this;
}
@SuppressWarnings("unchecked")
public FluentImplT withManagedHostnameBindings(AppServiceDomain domain, String... hostnames) {
for (String hostname : hostnames) {
if (hostname.equals("@") || hostname.equalsIgnoreCase(domain.name())) {
defineHostnameBinding()
.withAzureManagedDomain(domain)
.withSubDomain(hostname)
.withDnsRecordType(CustomHostnameDnsRecordType.A)
.attach();
} else {
defineHostnameBinding()
.withAzureManagedDomain(domain)
.withSubDomain(hostname)
.withDnsRecordType(CustomHostnameDnsRecordType.CNAME)
.attach();
}
}
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public HostnameBindingImpl<FluentT, FluentImplT> defineHostnameBinding() {
HostnameBindingInner inner = new HostnameBindingInner();
inner.withSiteName(name());
inner.withAzureResourceType(AzureResourceType.WEBSITE);
inner.withAzureResourceName(name());
inner.withHostnameType(HostnameType.VERIFIED);
return new HostnameBindingImpl<>(inner, (FluentImplT) this);
}
@SuppressWarnings("unchecked")
public FluentImplT withThirdPartyHostnameBinding(String domain, String... hostnames) {
for (String hostname : hostnames) {
defineHostnameBinding()
.withThirdPartyDomain(domain)
.withSubDomain(hostname)
.withDnsRecordType(CustomHostnameDnsRecordType.CNAME)
.attach();
}
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withoutHostnameBinding(String hostname) {
hostNameBindingsToDelete.add(hostname);
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withoutSslBinding(String hostname) {
if (hostNameSslStateMap.containsKey(hostname)) {
hostNameSslStateMap.get(hostname).withSslState(SslState.DISABLED).withToUpdate(true);
}
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
FluentImplT withHostNameBinding(final HostnameBindingImpl<FluentT, FluentImplT> hostNameBinding) {
this.hostNameBindingsToCreate.put(hostNameBinding.name(), hostNameBinding);
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withAppDisabledOnCreation() {
inner().withEnabled(false);
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withScmSiteAlsoStopped(boolean scmSiteAlsoStopped) {
inner().withScmSiteAlsoStopped(scmSiteAlsoStopped);
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withClientAffinityEnabled(boolean enabled) {
inner().withClientAffinityEnabled(enabled);
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withClientCertEnabled(boolean enabled) {
inner().withClientCertEnabled(enabled);
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public HostnameSslBindingImpl<FluentT, FluentImplT> defineSslBinding() {
return new HostnameSslBindingImpl<>(new HostnameSslState(), (FluentImplT) this);
}
@SuppressWarnings("unchecked")
public FluentImplT withNetFrameworkVersion(NetFrameworkVersion version) {
if (siteConfig == null) {
siteConfig = new SiteConfigResourceInner();
}
siteConfig.withNetFrameworkVersion(version.toString());
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withPhpVersion(PhpVersion version) {
if (siteConfig == null) {
siteConfig = new SiteConfigResourceInner();
}
siteConfig.withPhpVersion(version.toString());
return (FluentImplT) this;
}
public FluentImplT withoutPhp() {
return withPhpVersion(PhpVersion.fromString(""));
}
@SuppressWarnings("unchecked")
public FluentImplT withJavaVersion(JavaVersion version) {
if (siteConfig == null) {
siteConfig = new SiteConfigResourceInner();
}
siteConfig.withJavaVersion(version.toString());
return (FluentImplT) this;
}
public FluentImplT withoutJava() {
return withJavaVersion(JavaVersion.fromString("")).withWebContainer(WebContainer.fromString(""));
}
@SuppressWarnings("unchecked")
public FluentImplT withWebContainer(WebContainer webContainer) {
if (siteConfig == null) {
siteConfig = new SiteConfigResourceInner();
}
if (webContainer == null) {
siteConfig.withJavaContainer(null);
siteConfig.withJavaContainerVersion(null);
} else if (webContainer.toString().isEmpty()) {
siteConfig.withJavaContainer("");
siteConfig.withJavaContainerVersion("");
} else {
String[] containerInfo = webContainer.toString().split(" ");
siteConfig.withJavaContainer(containerInfo[0]);
siteConfig.withJavaContainerVersion(containerInfo[1]);
}
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withPythonVersion(PythonVersion version) {
if (siteConfig == null) {
siteConfig = new SiteConfigResourceInner();
}
siteConfig.withPythonVersion(version.toString());
return (FluentImplT) this;
}
public FluentImplT withoutPython() {
return withPythonVersion(PythonVersion.fromString(""));
}
@SuppressWarnings("unchecked")
public FluentImplT withPlatformArchitecture(PlatformArchitecture platform) {
if (siteConfig == null) {
siteConfig = new SiteConfigResourceInner();
}
siteConfig.withUse32BitWorkerProcess(platform.equals(PlatformArchitecture.X86));
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withWebSocketsEnabled(boolean enabled) {
if (siteConfig == null) {
siteConfig = new SiteConfigResourceInner();
}
siteConfig.withWebSocketsEnabled(enabled);
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withWebAppAlwaysOn(boolean alwaysOn) {
if (siteConfig == null) {
siteConfig = new SiteConfigResourceInner();
}
siteConfig.withAlwaysOn(alwaysOn);
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withManagedPipelineMode(ManagedPipelineMode managedPipelineMode) {
if (siteConfig == null) {
siteConfig = new SiteConfigResourceInner();
}
siteConfig.withManagedPipelineMode(managedPipelineMode);
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withAutoSwapSlotName(String slotName) {
if (siteConfig == null) {
siteConfig = new SiteConfigResourceInner();
}
siteConfig.withAutoSwapSlotName(slotName);
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withRemoteDebuggingEnabled(RemoteVisualStudioVersion remoteVisualStudioVersion) {
if (siteConfig == null) {
siteConfig = new SiteConfigResourceInner();
}
siteConfig.withRemoteDebuggingEnabled(true);
siteConfig.withRemoteDebuggingVersion(remoteVisualStudioVersion.toString());
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withRemoteDebuggingDisabled() {
if (siteConfig == null) {
siteConfig = new SiteConfigResourceInner();
}
siteConfig.withRemoteDebuggingEnabled(false);
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withDefaultDocument(String document) {
if (siteConfig == null) {
siteConfig = new SiteConfigResourceInner();
}
if (siteConfig.defaultDocuments() == null) {
siteConfig.withDefaultDocuments(new ArrayList<String>());
}
siteConfig.defaultDocuments().add(document);
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withDefaultDocuments(List<String> documents) {
if (siteConfig == null) {
siteConfig = new SiteConfigResourceInner();
}
if (siteConfig.defaultDocuments() == null) {
siteConfig.withDefaultDocuments(new ArrayList<>());
}
siteConfig.defaultDocuments().addAll(documents);
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withoutDefaultDocument(String document) {
if (siteConfig == null) {
siteConfig = new SiteConfigResourceInner();
}
if (siteConfig.defaultDocuments() != null) {
siteConfig.defaultDocuments().remove(document);
}
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withHttpsOnly(boolean httpsOnly) {
inner().withHttpsOnly(httpsOnly);
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withHttp20Enabled(boolean http20Enabled) {
if (siteConfig == null) {
siteConfig = new SiteConfigResourceInner();
}
siteConfig.withHttp20Enabled(http20Enabled);
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withFtpsState(FtpsState ftpsState) {
if (siteConfig == null) {
siteConfig = new SiteConfigResourceInner();
}
siteConfig.withFtpsState(ftpsState);
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withVirtualApplications(List<VirtualApplication> virtualApplications) {
if (siteConfig == null) {
siteConfig = new SiteConfigResourceInner();
}
siteConfig.withVirtualApplications(virtualApplications);
return (FluentImplT) this;
}
@Override
@SuppressWarnings("unchecked")
public FluentImplT withMinTlsVersion(SupportedTlsVersions minTlsVersion) {
if (siteConfig == null) {
siteConfig = new SiteConfigResourceInner();
}
siteConfig.withMinTlsVersion(minTlsVersion);
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withAppSetting(String key, String value) {
appSettingsToAdd.put(key, value);
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withAppSettings(Map<String, String> settings) {
appSettingsToAdd.putAll(settings);
return (FluentImplT) this;
}
public FluentImplT withStickyAppSetting(String key, String value) {
withAppSetting(key, value);
return withAppSettingStickiness(key, true);
}
@SuppressWarnings("unchecked")
public FluentImplT withStickyAppSettings(Map<String, String> settings) {
withAppSettings(settings);
for (String key : settings.keySet()) {
appSettingStickiness.put(key, true);
}
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withoutAppSetting(String key) {
appSettingsToRemove.add(key);
appSettingStickiness.remove(key);
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withAppSettingStickiness(String key, boolean sticky) {
appSettingStickiness.put(key, sticky);
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withConnectionString(String name, String value, ConnectionStringType type) {
connectionStringsToAdd.put(name, new ConnStringValueTypePair().withValue(value).withType(type));
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withStickyConnectionString(String name, String value, ConnectionStringType type) {
connectionStringsToAdd.put(name, new ConnStringValueTypePair().withValue(value).withType(type));
connectionStringStickiness.put(name, true);
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withoutConnectionString(String name) {
connectionStringsToRemove.add(name);
connectionStringStickiness.remove(name);
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withConnectionStringStickiness(String name, boolean stickiness) {
connectionStringStickiness.put(name, stickiness);
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
void withSourceControl(WebAppSourceControlImpl<FluentT, FluentImplT> sourceControl) {
this.sourceControl = sourceControl;
}
public WebAppSourceControlImpl<FluentT, FluentImplT> defineSourceControl() {
SiteSourceControlInner sourceControlInner = new SiteSourceControlInner();
return new WebAppSourceControlImpl<>(sourceControlInner, this);
}
@SuppressWarnings("unchecked")
public FluentImplT withLocalGitSourceControl() {
if (siteConfig == null) {
siteConfig = new SiteConfigResourceInner();
}
siteConfig.withScmType(ScmType.LOCAL_GIT);
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withoutSourceControl() {
sourceControlToDelete = true;
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
void withAuthentication(WebAppAuthenticationImpl<FluentT, FluentImplT> authentication) {
this.authentication = authentication;
authenticationToUpdate = true;
}
void withDiagnosticLogs(WebAppDiagnosticLogsImpl<FluentT, FluentImplT> diagnosticLogs) {
this.diagnosticLogs = diagnosticLogs;
diagnosticLogsToUpdate = true;
}
@Override
@SuppressWarnings("unchecked")
public Mono<FluentT> refreshAsync() {
return super
.refreshAsync()
.flatMap(
fluentT ->
getConfigInner()
.map(
returnedSiteConfig -> {
siteConfig = returnedSiteConfig;
return fluentT;
}));
}
@Override
protected Mono<SiteInner> getInnerAsync() {
return getInner();
}
@Override
public WebAppAuthenticationImpl<FluentT, FluentImplT> defineAuthentication() {
return new WebAppAuthenticationImpl<>(new SiteAuthSettingsInner().withEnabled(true), this);
}
@Override
@SuppressWarnings("unchecked")
public FluentImplT withoutAuthentication() {
this.authentication.inner().withEnabled(false);
authenticationToUpdate = true;
return (FluentImplT) this;
}
@Override
@SuppressWarnings("unchecked")
public FluentImplT withContainerLoggingEnabled(int quotaInMB, int retentionDays) {
return updateDiagnosticLogsConfiguration()
.withWebServerLogging()
.withWebServerLogsStoredOnFileSystem()
.withWebServerFileSystemQuotaInMB(quotaInMB)
.withLogRetentionDays(retentionDays)
.attach();
}
@Override
public FluentImplT withContainerLoggingEnabled() {
return withContainerLoggingEnabled(35, 0);
}
@Override
@SuppressWarnings("unchecked")
public FluentImplT withContainerLoggingDisabled() {
return updateDiagnosticLogsConfiguration().withoutWebServerLogging().attach();
}
@Override
@SuppressWarnings("unchecked")
public FluentImplT withSystemAssignedManagedServiceIdentity() {
this.webAppMsiHandler.withLocalManagedServiceIdentity();
return (FluentImplT) this;
}
@Override
@SuppressWarnings("unchecked")
public FluentImplT withoutSystemAssignedManagedServiceIdentity() {
this.webAppMsiHandler.withoutLocalManagedServiceIdentity();
return (FluentImplT) this;
}
@Override
@SuppressWarnings("unchecked")
public FluentImplT withUserAssignedManagedServiceIdentity() {
return (FluentImplT) this;
}
@Override
@SuppressWarnings("unchecked")
public FluentImplT withSystemAssignedIdentityBasedAccessTo(final String resourceId, final BuiltInRole role) {
this.webAppMsiHandler.withAccessTo(resourceId, role);
return (FluentImplT) this;
}
@Override
@SuppressWarnings("unchecked")
public FluentImplT withSystemAssignedIdentityBasedAccessToCurrentResourceGroup(final BuiltInRole role) {
this.webAppMsiHandler.withAccessToCurrentResourceGroup(role);
return (FluentImplT) this;
}
@Override
@SuppressWarnings("unchecked")
public FluentImplT withSystemAssignedIdentityBasedAccessTo(final String resourceId, final String roleDefinitionId) {
this.webAppMsiHandler.withAccessTo(resourceId, roleDefinitionId);
return (FluentImplT) this;
}
@Override
@SuppressWarnings("unchecked")
public FluentImplT withSystemAssignedIdentityBasedAccessToCurrentResourceGroup(final String roleDefinitionId) {
this.webAppMsiHandler.withAccessToCurrentResourceGroup(roleDefinitionId);
return (FluentImplT) this;
}
@Override
@SuppressWarnings("unchecked")
public FluentImplT withNewUserAssignedManagedServiceIdentity(Creatable<Identity> creatableIdentity) {
this.webAppMsiHandler.withNewExternalManagedServiceIdentity(creatableIdentity);
return (FluentImplT) this;
}
@Override
@SuppressWarnings("unchecked")
public FluentImplT withExistingUserAssignedManagedServiceIdentity(Identity identity) {
this.webAppMsiHandler.withExistingExternalManagedServiceIdentity(identity);
return (FluentImplT) this;
}
@Override
@SuppressWarnings("unchecked")
public FluentImplT withoutUserAssignedManagedServiceIdentity(String identityId) {
this.webAppMsiHandler.withoutExternalManagedServiceIdentity(identityId);
return (FluentImplT) this;
}
@Override
public WebAppDiagnosticLogsImpl<FluentT, FluentImplT> defineDiagnosticLogsConfiguration() {
if (diagnosticLogs == null) {
return new WebAppDiagnosticLogsImpl<>(new SiteLogsConfigInner(), this);
} else {
return diagnosticLogs;
}
}
@Override
public WebAppDiagnosticLogsImpl<FluentT, FluentImplT> updateDiagnosticLogsConfiguration() {
return defineDiagnosticLogsConfiguration();
}
@Override
public ManagedServiceIdentity identity() {
return webSiteBase.identity();
}
@Override
public boolean hyperV() {
return webSiteBase.hyperV();
}
@Override
public HostingEnvironmentProfile hostingEnvironmentProfile() {
return webSiteBase.hostingEnvironmentProfile();
}
@Override
public Set<String> clientCertExclusionPaths() {
return webSiteBase.clientCertExclusionPaths();
}
@Override
public Set<String> possibleOutboundIpAddresses() {
return webSiteBase.possibleOutboundIpAddresses();
}
@Override
public int dailyMemoryTimeQuota() {
return webSiteBase.dailyMemoryTimeQuota();
}
@Override
public OffsetDateTime suspendedTill() {
return webSiteBase.suspendedTill();
}
@Override
public int maxNumberOfWorkers() {
return webSiteBase.maxNumberOfWorkers();
}
@Override
public SlotSwapStatus slotSwapStatus() {
return webSiteBase.slotSwapStatus();
}
@Override
public RedundancyMode redundancyMode() {
return webSiteBase.redundancyMode();
}
private static class PipedInputStreamWithCallback extends PipedInputStream {
private Runnable callback;
private void addCallback(Runnable action) {
this.callback = action;
}
@Override
public void close() throws IOException {
callback.run();
super.close();
}
}
} |
Flux.fromIterable().flatMapDelayError() | public Flux<String> deleteByIdsAsync(Collection<String> ids) {
if (ids == null || ids.isEmpty()) {
return Flux.empty();
}
Collection<Mono<String>> observables = new ArrayList<>();
for (String id : ids) {
final String resourceGroupName = ResourceUtils.groupFromResourceId(id);
final String name = ResourceUtils.nameFromResourceId(id);
Mono<String> o = ReactorMapper.map(this.inner().deleteAsync(resourceGroupName, name), id);
observables.add(o);
}
return Flux.mergeDelayError(32, observables.toArray(new Mono[0]));
} | return Flux.mergeDelayError(32, observables.toArray(new Mono[0])); | public Flux<String> deleteByIdsAsync(Collection<String> ids) {
return BatchDeletionImpl.deleteByIdsAsync(ids, this::deleteInnerAsync);
} | class WebAppsImpl
extends GroupableResourcesImpl<WebApp, WebAppImpl, SiteInner, WebAppsClient, AppServiceManager>
implements WebApps, SupportsBatchDeletion {
public WebAppsImpl(final AppServiceManager manager) {
super(manager.inner().getWebApps(), manager);
}
@Override
public Mono<WebApp> getByResourceGroupAsync(final String groupName, final String name) {
final WebAppsImpl self = this;
return this
.inner()
.getByResourceGroupAsync(groupName, name)
.flatMap(
siteInner ->
Mono
.zip(
self.inner().getConfigurationAsync(groupName, name),
self.inner().getDiagnosticLogsConfigurationAsync(groupName, name),
(SiteConfigResourceInner siteConfigResourceInner, SiteLogsConfigInner logsConfigInner) ->
wrapModel(siteInner, siteConfigResourceInner, logsConfigInner)));
}
@Override
protected Mono<SiteInner> getInnerAsync(String resourceGroupName, String name) {
return null;
}
@Override
protected Mono<Void> deleteInnerAsync(String resourceGroupName, String name) {
return null;
}
@Override
protected WebAppImpl wrapModel(String name) {
return new WebAppImpl(name, new SiteInner().withKind("app"), null, null, this.manager());
}
protected WebAppImpl wrapModel(SiteInner inner, SiteConfigResourceInner siteConfig, SiteLogsConfigInner logConfig) {
if (inner == null) {
return null;
}
return new WebAppImpl(inner.name(), inner, siteConfig, logConfig, this.manager());
}
@Override
protected WebAppImpl wrapModel(SiteInner inner) {
return wrapModel(inner, null, null);
}
@Override
protected PagedFlux<WebApp> wrapPageAsync(PagedFlux<SiteInner> innerPage) {
return PagedConverter
.flatMapPage(
innerPage,
siteInner -> {
if (siteInner.kind() == null || Arrays.asList(siteInner.kind().split(",")).contains("app")) {
return Mono
.zip(
this.inner().getConfigurationAsync(siteInner.resourceGroup(), siteInner.name()),
this
.inner()
.getDiagnosticLogsConfigurationAsync(
siteInner.resourceGroup(), siteInner.name()),
(siteConfigResourceInner, logsConfigInner) ->
this.wrapModel(siteInner, siteConfigResourceInner, logsConfigInner));
} else {
return Mono.empty();
}
});
}
@Override
public WebAppImpl define(String name) {
return wrapModel(name);
}
@Override
@SuppressWarnings({"unchecked", "rawtypes"})
@Override
public Flux<String> deleteByIdsAsync(String... ids) {
return this.deleteByIdsAsync(new ArrayList<>(Arrays.asList(ids)));
}
@Override
public void deleteByIds(Collection<String> ids) {
if (ids != null && !ids.isEmpty()) {
this.deleteByIdsAsync(ids).blockLast();
}
}
@Override
public void deleteByIds(String... ids) {
this.deleteByIds(new ArrayList<>(Arrays.asList(ids)));
}
@Override
public PagedIterable<WebAppBasic> listByResourceGroup(String resourceGroupName) {
return new PagedIterable<>(this.listByResourceGroupAsync(resourceGroupName));
}
@Override
public PagedFlux<WebAppBasic> listByResourceGroupAsync(String resourceGroupName) {
return inner().listByResourceGroupAsync(resourceGroupName)
.mapPage(inner -> new WebAppBasicImpl(inner, this.manager()));
}
@Override
public PagedIterable<WebAppBasic> list() {
return new PagedIterable<>(this.listAsync());
}
@Override
public PagedFlux<WebAppBasic> listAsync() {
return inner().listAsync()
.mapPage(inner -> new WebAppBasicImpl(inner, this.manager()));
}
} | class WebAppsImpl
extends GroupableResourcesImpl<WebApp, WebAppImpl, SiteInner, WebAppsClient, AppServiceManager>
implements WebApps, SupportsBatchDeletion {
public WebAppsImpl(final AppServiceManager manager) {
super(manager.inner().getWebApps(), manager);
}
@Override
public Mono<WebApp> getByResourceGroupAsync(final String groupName, final String name) {
final WebAppsImpl self = this;
return this
.getInnerAsync(groupName, name)
.flatMap(
siteInner ->
Mono
.zip(
self.inner().getConfigurationAsync(groupName, name),
self.inner().getDiagnosticLogsConfigurationAsync(groupName, name),
(SiteConfigResourceInner siteConfigResourceInner, SiteLogsConfigInner logsConfigInner) ->
wrapModel(siteInner, siteConfigResourceInner, logsConfigInner)));
}
@Override
protected Mono<SiteInner> getInnerAsync(String resourceGroupName, String name) {
return this.inner().getByResourceGroupAsync(resourceGroupName, name);
}
@Override
protected Mono<Void> deleteInnerAsync(String resourceGroupName, String name) {
return inner().deleteAsync(resourceGroupName, name).then();
}
@Override
protected WebAppImpl wrapModel(String name) {
return new WebAppImpl(name, new SiteInner().withKind("app"), null, null, this.manager());
}
protected WebAppImpl wrapModel(SiteInner inner, SiteConfigResourceInner siteConfig, SiteLogsConfigInner logConfig) {
if (inner == null) {
return null;
}
return new WebAppImpl(inner.name(), inner, siteConfig, logConfig, this.manager());
}
@Override
protected WebAppImpl wrapModel(SiteInner inner) {
return wrapModel(inner, null, null);
}
@Override
public WebAppImpl define(String name) {
return wrapModel(name);
}
@Override
@Override
public Flux<String> deleteByIdsAsync(String... ids) {
return this.deleteByIdsAsync(new ArrayList<>(Arrays.asList(ids)));
}
@Override
public void deleteByIds(Collection<String> ids) {
if (ids != null && !ids.isEmpty()) {
this.deleteByIdsAsync(ids).blockLast();
}
}
@Override
public void deleteByIds(String... ids) {
this.deleteByIds(new ArrayList<>(Arrays.asList(ids)));
}
@Override
public PagedIterable<WebAppBasic> listByResourceGroup(String resourceGroupName) {
return new PagedIterable<>(this.listByResourceGroupAsync(resourceGroupName));
}
@Override
public PagedFlux<WebAppBasic> listByResourceGroupAsync(String resourceGroupName) {
return inner().listByResourceGroupAsync(resourceGroupName)
.mapPage(inner -> new WebAppBasicImpl(inner, this.manager()));
}
@Override
public PagedIterable<WebAppBasic> list() {
return new PagedIterable<>(this.listAsync());
}
@Override
public PagedFlux<WebAppBasic> listAsync() {
return inner().listAsync()
.mapPage(inner -> new WebAppBasicImpl(inner, this.manager()));
}
} |
Updated. | private OffsetDateTime getExpirationTime(String sharedAccessSignature) {
String[] parts = sharedAccessSignature.split("&");
return Arrays.stream(parts)
.map(part -> part.split("="))
.filter(pair -> pair.length == 2 && pair[0].equalsIgnoreCase("se"))
.findFirst()
.map(pair -> pair[1])
.map(expirationTimeStr -> {
try {
long epochSeconds = Long.parseLong(expirationTimeStr);
return Instant.ofEpochSecond(epochSeconds).atOffset(ZoneOffset.UTC);
} catch (NumberFormatException exception) {
return OffsetDateTime.MAX;
}
})
.orElse(OffsetDateTime.MAX);
} | return OffsetDateTime.MAX; | private OffsetDateTime getExpirationTime(String sharedAccessSignature) {
String[] parts = sharedAccessSignature.split("&");
return Arrays.stream(parts)
.map(part -> part.split("="))
.filter(pair -> pair.length == 2 && pair[0].equalsIgnoreCase("se"))
.findFirst()
.map(pair -> pair[1])
.map(expirationTimeStr -> {
try {
long epochSeconds = Long.parseLong(expirationTimeStr);
return Instant.ofEpochSecond(epochSeconds).atOffset(ZoneOffset.UTC);
} catch (NumberFormatException exception) {
logger.verbose("Invalid expiration time format in the SAS token: {}. Falling back to max "
+ "expiration time.", expirationTimeStr);
return OffsetDateTime.MAX;
}
})
.orElse(OffsetDateTime.MAX);
} | class ServiceBusSharedKeyCredential implements TokenCredential {
private static final String SHARED_ACCESS_SIGNATURE_FORMAT = "SharedAccessSignature sr=%s&sig=%s&se=%s&skn=%s";
private static final String HASH_ALGORITHM = "HMACSHA256";
private final ClientLogger logger = new ClientLogger(ServiceBusSharedKeyCredential.class);
private final String policyName;
private final Mac hmac;
private final Duration tokenValidity;
private final String sharedAccessSignature;
/**
* Creates an instance that authorizes using the {@code policyName} and {@code sharedAccessKey}.
*
* @param policyName Name of the shared access key policy.
* @param sharedAccessKey Value of the shared access key.
* @throws IllegalArgumentException if {@code policyName}, {@code sharedAccessKey} is an empty string. If the
* {@code sharedAccessKey} is an invalid value for the hashing algorithm.
* @throws NullPointerException if {@code policyName} or {@code sharedAccessKey} is null.
* @throws UnsupportedOperationException If the hashing algorithm cannot be instantiated, which is used to generate
* the shared access signatures.
*/
public ServiceBusSharedKeyCredential(String policyName, String sharedAccessKey) {
this(policyName, sharedAccessKey, ServiceBusConstants.TOKEN_VALIDITY);
}
/**
* Creates an instance that authorizes using the {@code policyName} and {@code sharedAccessKey}. The authorization
* lasts for a period of {@code tokenValidity} before another token must be requested.
*
* @param policyName Name of the shared access key policy.
* @param sharedAccessKey Value of the shared access key.
* @param tokenValidity The duration for which the shared access signature is valid.
* @throws IllegalArgumentException if {@code policyName}, {@code sharedAccessKey} is an empty string. Or the
* duration of {@code tokenValidity} is zero or a negative value. If the {@code sharedAccessKey} is an invalid
* value for the hashing algorithm.
* @throws NullPointerException if {@code policyName}, {@code sharedAccessKey}, or {@code tokenValidity} is
* null.
* @throws UnsupportedOperationException If the hashing algorithm cannot be instantiated, which is used to generate
* the shared access signatures.
*/
public ServiceBusSharedKeyCredential(String policyName, String sharedAccessKey, Duration tokenValidity) {
Objects.requireNonNull(sharedAccessKey, "'sharedAccessKey' cannot be null.");
this.policyName = Objects.requireNonNull(policyName, "'sharedAccessKey' cannot be null.");
this.tokenValidity = Objects.requireNonNull(tokenValidity, "'tokenValidity' cannot be null.");
if (policyName.isEmpty()) {
throw new IllegalArgumentException("'policyName' cannot be an empty string.");
} else if (sharedAccessKey.isEmpty()) {
throw new IllegalArgumentException("'sharedAccessKey' cannot be an empty string.");
} else if (tokenValidity.isZero() || tokenValidity.isNegative()) {
throw new IllegalArgumentException("'tokenTimeToLive' has to positive and in the order-of seconds");
}
try {
hmac = Mac.getInstance(HASH_ALGORITHM);
} catch (NoSuchAlgorithmException e) {
throw logger.logExceptionAsError(new UnsupportedOperationException(
String.format("Unable to create hashing algorithm '%s'", HASH_ALGORITHM), e));
}
final byte[] sasKeyBytes = sharedAccessKey.getBytes(UTF_8);
final SecretKeySpec finalKey = new SecretKeySpec(sasKeyBytes, HASH_ALGORITHM);
try {
hmac.init(finalKey);
} catch (InvalidKeyException e) {
throw logger.logExceptionAsError(new IllegalArgumentException(
"'sharedAccessKey' is an invalid value for the hashing algorithm.", e));
}
this.sharedAccessSignature = null;
}
/**
* Creates an instance using the provided Shared Access Signature (SAS) string. The credential created using this
* constructor will not be refreshed. The expiration time is set to the time defined in "se={
* tokenValidationSeconds}`. If the SAS string does not contain this or is in invalid format, then the token
* expiration will be set to {@link OffsetDateTime
* <p><a href="https:
* programmatically.</a></p>
*
* @param sharedAccessSignature The base64 encoded shared access signature string.
* @throws NullPointerException if {@code sharedAccessSignature} is null.
*/
public ServiceBusSharedKeyCredential(String sharedAccessSignature) {
this.sharedAccessSignature = Objects.requireNonNull(sharedAccessSignature,
"'sharedAccessSignature' cannot be null");
this.policyName = null;
this.hmac = null;
this.tokenValidity = null;
}
/**
* Retrieves the token, given the audience/resources requested, for use in authorization against an Event Hubs
* namespace or a specific Event Hub instance.
*
* @param request The details of a token request
* @return A Mono that completes and returns the shared access signature.
* @throws IllegalArgumentException if {@code scopes} does not contain a single value, which is the token
* audience.
*/
@Override
public Mono<AccessToken> getToken(TokenRequestContext request) {
if (request.getScopes().size() != 1) {
throw logger.logExceptionAsError(new IllegalArgumentException(
"'scopes' should only contain a single argument that is the token audience or resource name."));
}
return Mono.fromCallable(() -> generateSharedAccessSignature(request.getScopes().get(0)));
}
private AccessToken generateSharedAccessSignature(final String resource) throws UnsupportedEncodingException {
if (CoreUtils.isNullOrEmpty(resource)) {
throw logger.logExceptionAsError(new IllegalArgumentException("resource cannot be empty"));
}
if (sharedAccessSignature != null) {
return new AccessToken(sharedAccessSignature, getExpirationTime(sharedAccessSignature));
}
final String utf8Encoding = UTF_8.name();
final OffsetDateTime expiresOn = OffsetDateTime.now(ZoneOffset.UTC).plus(tokenValidity);
final String expiresOnEpochSeconds = Long.toString(expiresOn.toEpochSecond());
final String audienceUri = URLEncoder.encode(resource, utf8Encoding);
final String secretToSign = audienceUri + "\n" + expiresOnEpochSeconds;
final byte[] signatureBytes = hmac.doFinal(secretToSign.getBytes(utf8Encoding));
final String signature = Base64.getEncoder().encodeToString(signatureBytes);
final String token = String.format(Locale.US, SHARED_ACCESS_SIGNATURE_FORMAT,
audienceUri,
URLEncoder.encode(signature, utf8Encoding),
URLEncoder.encode(expiresOnEpochSeconds, utf8Encoding),
URLEncoder.encode(policyName, utf8Encoding));
return new AccessToken(token, expiresOn);
}
} | class ServiceBusSharedKeyCredential implements TokenCredential {
private static final String SHARED_ACCESS_SIGNATURE_FORMAT = "SharedAccessSignature sr=%s&sig=%s&se=%s&skn=%s";
private static final String HASH_ALGORITHM = "HMACSHA256";
private final ClientLogger logger = new ClientLogger(ServiceBusSharedKeyCredential.class);
private final String policyName;
private final Mac hmac;
private final Duration tokenValidity;
private final String sharedAccessSignature;
/**
* Creates an instance that authorizes using the {@code policyName} and {@code sharedAccessKey}.
*
* @param policyName Name of the shared access key policy.
* @param sharedAccessKey Value of the shared access key.
* @throws IllegalArgumentException if {@code policyName}, {@code sharedAccessKey} is an empty string. If the
* {@code sharedAccessKey} is an invalid value for the hashing algorithm.
* @throws NullPointerException if {@code policyName} or {@code sharedAccessKey} is null.
* @throws UnsupportedOperationException If the hashing algorithm cannot be instantiated, which is used to generate
* the shared access signatures.
*/
public ServiceBusSharedKeyCredential(String policyName, String sharedAccessKey) {
this(policyName, sharedAccessKey, ServiceBusConstants.TOKEN_VALIDITY);
}
/**
* Creates an instance that authorizes using the {@code policyName} and {@code sharedAccessKey}. The authorization
* lasts for a period of {@code tokenValidity} before another token must be requested.
*
* @param policyName Name of the shared access key policy.
* @param sharedAccessKey Value of the shared access key.
* @param tokenValidity The duration for which the shared access signature is valid.
* @throws IllegalArgumentException if {@code policyName}, {@code sharedAccessKey} is an empty string. Or the
* duration of {@code tokenValidity} is zero or a negative value. If the {@code sharedAccessKey} is an invalid
* value for the hashing algorithm.
* @throws NullPointerException if {@code policyName}, {@code sharedAccessKey}, or {@code tokenValidity} is
* null.
* @throws UnsupportedOperationException If the hashing algorithm cannot be instantiated, which is used to generate
* the shared access signatures.
*/
public ServiceBusSharedKeyCredential(String policyName, String sharedAccessKey, Duration tokenValidity) {
Objects.requireNonNull(sharedAccessKey, "'sharedAccessKey' cannot be null.");
this.policyName = Objects.requireNonNull(policyName, "'sharedAccessKey' cannot be null.");
this.tokenValidity = Objects.requireNonNull(tokenValidity, "'tokenValidity' cannot be null.");
if (policyName.isEmpty()) {
throw new IllegalArgumentException("'policyName' cannot be an empty string.");
} else if (sharedAccessKey.isEmpty()) {
throw new IllegalArgumentException("'sharedAccessKey' cannot be an empty string.");
} else if (tokenValidity.isZero() || tokenValidity.isNegative()) {
throw new IllegalArgumentException("'tokenTimeToLive' has to positive and in the order-of seconds");
}
try {
hmac = Mac.getInstance(HASH_ALGORITHM);
} catch (NoSuchAlgorithmException e) {
throw logger.logExceptionAsError(new UnsupportedOperationException(
String.format("Unable to create hashing algorithm '%s'", HASH_ALGORITHM), e));
}
final byte[] sasKeyBytes = sharedAccessKey.getBytes(UTF_8);
final SecretKeySpec finalKey = new SecretKeySpec(sasKeyBytes, HASH_ALGORITHM);
try {
hmac.init(finalKey);
} catch (InvalidKeyException e) {
throw logger.logExceptionAsError(new IllegalArgumentException(
"'sharedAccessKey' is an invalid value for the hashing algorithm.", e));
}
this.sharedAccessSignature = null;
}
/**
* Creates an instance using the provided Shared Access Signature (SAS) string. The credential created using this
* constructor will not be refreshed. The expiration time is set to the time defined in "se={
* tokenValidationSeconds}`. If the SAS string does not contain this or is in invalid format, then the token
* expiration will be set to {@link OffsetDateTime
* <p><a href="https:
* programmatically.</a></p>
*
* @param sharedAccessSignature The base64 encoded shared access signature string.
* @throws NullPointerException if {@code sharedAccessSignature} is null.
*/
public ServiceBusSharedKeyCredential(String sharedAccessSignature) {
this.sharedAccessSignature = Objects.requireNonNull(sharedAccessSignature,
"'sharedAccessSignature' cannot be null");
this.policyName = null;
this.hmac = null;
this.tokenValidity = null;
}
/**
* Retrieves the token, given the audience/resources requested, for use in authorization against an Event Hubs
* namespace or a specific Event Hub instance.
*
* @param request The details of a token request
* @return A Mono that completes and returns the shared access signature.
* @throws IllegalArgumentException if {@code scopes} does not contain a single value, which is the token
* audience.
*/
@Override
public Mono<AccessToken> getToken(TokenRequestContext request) {
if (request.getScopes().size() != 1) {
throw logger.logExceptionAsError(new IllegalArgumentException(
"'scopes' should only contain a single argument that is the token audience or resource name."));
}
return Mono.fromCallable(() -> generateSharedAccessSignature(request.getScopes().get(0)));
}
private AccessToken generateSharedAccessSignature(final String resource) throws UnsupportedEncodingException {
if (CoreUtils.isNullOrEmpty(resource)) {
throw logger.logExceptionAsError(new IllegalArgumentException("resource cannot be empty"));
}
if (sharedAccessSignature != null) {
return new AccessToken(sharedAccessSignature, getExpirationTime(sharedAccessSignature));
}
final String utf8Encoding = UTF_8.name();
final OffsetDateTime expiresOn = OffsetDateTime.now(ZoneOffset.UTC).plus(tokenValidity);
final String expiresOnEpochSeconds = Long.toString(expiresOn.toEpochSecond());
final String audienceUri = URLEncoder.encode(resource, utf8Encoding);
final String secretToSign = audienceUri + "\n" + expiresOnEpochSeconds;
final byte[] signatureBytes = hmac.doFinal(secretToSign.getBytes(utf8Encoding));
final String signature = Base64.getEncoder().encodeToString(signatureBytes);
final String token = String.format(Locale.US, SHARED_ACCESS_SIGNATURE_FORMAT,
audienceUri,
URLEncoder.encode(signature, utf8Encoding),
URLEncoder.encode(expiresOnEpochSeconds, utf8Encoding),
URLEncoder.encode(policyName, utf8Encoding));
return new AccessToken(token, expiresOn);
}
} |
In Update flow, code changes the Map to add new items. | private void normalizeProperties() {
this.hostNameBindingsToDelete = new ArrayList<>();
this.appSettingsToAdd = new HashMap<>();
this.appSettingsToRemove = new ArrayList<>();
this.appSettingStickiness = new HashMap<>();
this.connectionStringsToAdd = new HashMap<>();
this.connectionStringsToRemove = new ArrayList<>();
this.connectionStringStickiness = new HashMap<>();
this.sourceControl = null;
this.sourceControlToDelete = false;
this.authenticationToUpdate = false;
this.diagnosticLogsToUpdate = false;
this.sslBindingsToCreate = new TreeMap<>();
this.msiHandler = null;
this.webSiteBase = new WebSiteBaseImpl(inner());
this.hostNameSslStateMap = new HashMap<>(this.webSiteBase.hostnameSslStates());
this.webAppMsiHandler.clear();
} | this.hostNameSslStateMap = new HashMap<>(this.webSiteBase.hostnameSslStates()); | private void normalizeProperties() {
this.hostNameBindingsToCreate = new TreeMap<>();
this.hostNameBindingsToDelete = new ArrayList<>();
this.appSettingsToAdd = new HashMap<>();
this.appSettingsToRemove = new ArrayList<>();
this.appSettingStickiness = new HashMap<>();
this.connectionStringsToAdd = new HashMap<>();
this.connectionStringsToRemove = new ArrayList<>();
this.connectionStringStickiness = new HashMap<>();
this.sourceControl = null;
this.sourceControlToDelete = false;
this.authenticationToUpdate = false;
this.diagnosticLogsToUpdate = false;
this.sslBindingsToCreate = new TreeMap<>();
this.msiHandler = null;
this.webSiteBase = new WebSiteBaseImpl(inner());
this.hostNameSslStateMap = new HashMap<>(this.webSiteBase.hostnameSslStates());
this.webAppMsiHandler.clear();
} | class WebAppBaseImpl<FluentT extends WebAppBase, FluentImplT extends WebAppBaseImpl<FluentT, FluentImplT>>
extends GroupableResourceImpl<FluentT, SiteInner, FluentImplT, AppServiceManager>
implements WebAppBase,
WebAppBase.Definition<FluentT>,
WebAppBase.Update<FluentT>,
WebAppBase.UpdateStages.WithWebContainer<FluentT> {
private final ClientLogger logger = new ClientLogger(getClass());
private static final Map<AzureEnvironment, String> DNS_MAP =
new HashMap<AzureEnvironment, String>() {
{
put(AzureEnvironment.AZURE, "azurewebsites.net");
put(AzureEnvironment.AZURE_CHINA, "chinacloudsites.cn");
put(AzureEnvironment.AZURE_GERMANY, "azurewebsites.de");
put(AzureEnvironment.AZURE_US_GOVERNMENT, "azurewebsites.us");
}
};
SiteConfigResourceInner siteConfig;
KuduClient kuduClient;
WebSiteBase webSiteBase;
private Map<String, HostnameSslState> hostNameSslStateMap;
private TreeMap<String, HostnameBindingImpl<FluentT, FluentImplT>> hostNameBindingsToCreate;
private List<String> hostNameBindingsToDelete;
private TreeMap<String, HostnameSslBindingImpl<FluentT, FluentImplT>> sslBindingsToCreate;
protected Map<String, String> appSettingsToAdd;
protected List<String> appSettingsToRemove;
private Map<String, Boolean> appSettingStickiness;
private Map<String, ConnStringValueTypePair> connectionStringsToAdd;
private List<String> connectionStringsToRemove;
private Map<String, Boolean> connectionStringStickiness;
private WebAppSourceControlImpl<FluentT, FluentImplT> sourceControl;
private boolean sourceControlToDelete;
private WebAppAuthenticationImpl<FluentT, FluentImplT> authentication;
private boolean authenticationToUpdate;
private WebAppDiagnosticLogsImpl<FluentT, FluentImplT> diagnosticLogs;
private boolean diagnosticLogsToUpdate;
private FunctionalTaskItem msiHandler;
private boolean isInCreateMode;
private WebAppMsiHandler<FluentT, FluentImplT> webAppMsiHandler;
WebAppBaseImpl(
String name,
SiteInner innerObject,
SiteConfigResourceInner siteConfig,
SiteLogsConfigInner logConfig,
AppServiceManager manager) {
super(name, innerObject, manager);
if (innerObject != null && innerObject.kind() != null) {
innerObject.withKind(innerObject.kind().replace(";", ","));
}
this.siteConfig = siteConfig;
if (logConfig != null) {
this.diagnosticLogs = new WebAppDiagnosticLogsImpl<>(logConfig, this);
}
webAppMsiHandler = new WebAppMsiHandler<>(manager.authorizationManager(), this);
normalizeProperties();
isInCreateMode = inner() == null || inner().id() == null;
if (!isInCreateMode) {
initializeKuduClient();
}
}
public boolean isInCreateMode() {
return isInCreateMode;
}
private void initializeKuduClient() {
if (kuduClient == null) {
kuduClient = new KuduClient(this);
}
}
@Override
public void setInner(SiteInner innerObject) {
if (innerObject.kind() != null) {
innerObject.withKind(innerObject.kind().replace(";", ","));
}
super.setInner(innerObject);
}
RoleAssignmentHelper.IdProvider idProvider() {
return new RoleAssignmentHelper.IdProvider() {
@Override
public String principalId() {
if (inner() != null && inner().identity() != null) {
return inner().identity().principalId();
} else {
return null;
}
}
@Override
public String resourceId() {
if (inner() != null) {
return inner().id();
} else {
return null;
}
}
};
}
@Override
public String state() {
return webSiteBase.state();
}
@Override
public Set<String> hostnames() {
return webSiteBase.hostnames();
}
@Override
public String repositorySiteName() {
return webSiteBase.repositorySiteName();
}
@Override
public UsageState usageState() {
return webSiteBase.usageState();
}
@Override
public boolean enabled() {
return webSiteBase.enabled();
}
@Override
public Set<String> enabledHostNames() {
return webSiteBase.enabledHostNames();
}
@Override
public SiteAvailabilityState availabilityState() {
return webSiteBase.availabilityState();
}
@Override
public Map<String, HostnameSslState> hostnameSslStates() {
return Collections.unmodifiableMap(hostNameSslStateMap);
}
@Override
public String appServicePlanId() {
return webSiteBase.appServicePlanId();
}
@Override
public OffsetDateTime lastModifiedTime() {
return webSiteBase.lastModifiedTime();
}
@Override
public Set<String> trafficManagerHostNames() {
return webSiteBase.trafficManagerHostNames();
}
@Override
public boolean scmSiteAlsoStopped() {
return webSiteBase.scmSiteAlsoStopped();
}
@Override
public String targetSwapSlot() {
return webSiteBase.targetSwapSlot();
}
@Override
public boolean clientAffinityEnabled() {
return webSiteBase.clientAffinityEnabled();
}
@Override
public boolean clientCertEnabled() {
return webSiteBase.clientCertEnabled();
}
@Override
public boolean hostnamesDisabled() {
return webSiteBase.hostnamesDisabled();
}
@Override
public Set<String> outboundIPAddresses() {
return webSiteBase.outboundIPAddresses();
}
@Override
public int containerSize() {
return webSiteBase.containerSize();
}
@Override
public CloningInfo cloningInfo() {
return webSiteBase.cloningInfo();
}
@Override
public boolean isDefaultContainer() {
return webSiteBase.isDefaultContainer();
}
@Override
public String defaultHostname() {
if (inner().defaultHostname() != null) {
return inner().defaultHostname();
} else {
AzureEnvironment environment = manager().environment();
String dns = DNS_MAP.get(environment);
String leaf = name();
if (this instanceof DeploymentSlotBaseImpl<?, ?, ?, ?, ?>) {
leaf = ((DeploymentSlotBaseImpl<?, ?, ?, ?, ?>) this).parent().name() + "-" + leaf;
}
return leaf + "." + dns;
}
}
@Override
public List<String> defaultDocuments() {
if (siteConfig == null) {
return null;
}
return Collections.unmodifiableList(siteConfig.defaultDocuments());
}
@Override
public NetFrameworkVersion netFrameworkVersion() {
if (siteConfig == null) {
return null;
}
return NetFrameworkVersion.fromString(siteConfig.netFrameworkVersion());
}
@Override
public PhpVersion phpVersion() {
if (siteConfig == null || siteConfig.phpVersion() == null) {
return PhpVersion.OFF;
}
return PhpVersion.fromString(siteConfig.phpVersion());
}
@Override
public PythonVersion pythonVersion() {
if (siteConfig == null || siteConfig.pythonVersion() == null) {
return PythonVersion.OFF;
}
return PythonVersion.fromString(siteConfig.pythonVersion());
}
@Override
public String nodeVersion() {
if (siteConfig == null) {
return null;
}
return siteConfig.nodeVersion();
}
@Override
public boolean remoteDebuggingEnabled() {
if (siteConfig == null) {
return false;
}
return Utils.toPrimitiveBoolean(siteConfig.remoteDebuggingEnabled());
}
@Override
public RemoteVisualStudioVersion remoteDebuggingVersion() {
if (siteConfig == null) {
return null;
}
return RemoteVisualStudioVersion.fromString(siteConfig.remoteDebuggingVersion());
}
@Override
public boolean webSocketsEnabled() {
if (siteConfig == null) {
return false;
}
return Utils.toPrimitiveBoolean(siteConfig.webSocketsEnabled());
}
@Override
public boolean alwaysOn() {
if (siteConfig == null) {
return false;
}
return Utils.toPrimitiveBoolean(siteConfig.alwaysOn());
}
@Override
public JavaVersion javaVersion() {
if (siteConfig == null || siteConfig.javaVersion() == null) {
return JavaVersion.OFF;
}
return JavaVersion.fromString(siteConfig.javaVersion());
}
@Override
public String javaContainer() {
if (siteConfig == null) {
return null;
}
return siteConfig.javaContainer();
}
@Override
public String javaContainerVersion() {
if (siteConfig == null) {
return null;
}
return siteConfig.javaContainerVersion();
}
@Override
public ManagedPipelineMode managedPipelineMode() {
if (siteConfig == null) {
return null;
}
return siteConfig.managedPipelineMode();
}
@Override
public PlatformArchitecture platformArchitecture() {
if (siteConfig.use32BitWorkerProcess()) {
return PlatformArchitecture.X86;
} else {
return PlatformArchitecture.X64;
}
}
@Override
public String linuxFxVersion() {
if (siteConfig == null) {
return null;
}
return siteConfig.linuxFxVersion();
}
@Override
public String autoSwapSlotName() {
if (siteConfig == null) {
return null;
}
return siteConfig.autoSwapSlotName();
}
@Override
public boolean httpsOnly() {
return webSiteBase.httpsOnly();
}
@Override
public FtpsState ftpsState() {
if (siteConfig == null) {
return null;
}
return siteConfig.ftpsState();
}
@Override
public List<VirtualApplication> virtualApplications() {
if (siteConfig == null) {
return null;
}
return siteConfig.virtualApplications();
}
@Override
public boolean http20Enabled() {
if (siteConfig == null) {
return false;
}
return Utils.toPrimitiveBoolean(siteConfig.http20Enabled());
}
@Override
public boolean localMySqlEnabled() {
if (siteConfig == null) {
return false;
}
return Utils.toPrimitiveBoolean(siteConfig.localMySqlEnabled());
}
@Override
public ScmType scmType() {
if (siteConfig == null) {
return null;
}
return siteConfig.scmType();
}
@Override
public String documentRoot() {
if (siteConfig == null) {
return null;
}
return siteConfig.documentRoot();
}
@Override
public SupportedTlsVersions minTlsVersion() {
if (siteConfig == null) {
return null;
}
return siteConfig.minTlsVersion();
}
@Override
public OperatingSystem operatingSystem() {
if (inner().kind() != null && inner().kind().toLowerCase(Locale.ROOT).contains("linux")) {
return OperatingSystem.LINUX;
} else {
return OperatingSystem.WINDOWS;
}
}
@Override
public String systemAssignedManagedServiceIdentityTenantId() {
if (inner().identity() == null) {
return null;
}
return inner().identity().tenantId();
}
@Override
public String systemAssignedManagedServiceIdentityPrincipalId() {
if (inner().identity() == null) {
return null;
}
return inner().identity().principalId();
}
@Override
public Set<String> userAssignedManagedServiceIdentityIds() {
if (inner().identity() == null) {
return null;
}
return inner().identity().userAssignedIdentities().keySet();
}
@Override
public WebAppDiagnosticLogsImpl<FluentT, FluentImplT> diagnosticLogsConfig() {
return diagnosticLogs;
}
@Override
public InputStream streamApplicationLogs() {
return pipeObservableToInputStream(streamApplicationLogsAsync());
}
@Override
public Flux<String> streamApplicationLogsAsync() {
return kuduClient.streamApplicationLogsAsync();
}
@Override
public InputStream streamHttpLogs() {
return pipeObservableToInputStream(streamHttpLogsAsync());
}
@Override
public Flux<String> streamHttpLogsAsync() {
return kuduClient.streamHttpLogsAsync();
}
@Override
public InputStream streamTraceLogs() {
return pipeObservableToInputStream(streamTraceLogsAsync());
}
@Override
public Flux<String> streamTraceLogsAsync() {
return kuduClient.streamTraceLogsAsync();
}
@Override
public InputStream streamDeploymentLogs() {
return pipeObservableToInputStream(streamDeploymentLogsAsync());
}
@Override
public Flux<String> streamDeploymentLogsAsync() {
return kuduClient.streamDeploymentLogsAsync();
}
@Override
public InputStream streamAllLogs() {
return pipeObservableToInputStream(streamAllLogsAsync());
}
@Override
public Flux<String> streamAllLogsAsync() {
return kuduClient.streamAllLogsAsync();
}
private InputStream pipeObservableToInputStream(Flux<String> observable) {
PipedInputStreamWithCallback in = new PipedInputStreamWithCallback();
final PipedOutputStream out = new PipedOutputStream();
try {
in.connect(out);
} catch (IOException e) {
throw logger.logExceptionAsError(new RuntimeException(e));
}
final Disposable subscription =
observable
.subscribeOn(Schedulers.elastic())
.subscribe(
s -> {
try {
out.write(s.getBytes(StandardCharsets.UTF_8));
out.write('\n');
out.flush();
} catch (IOException e) {
throw logger.logExceptionAsError(new RuntimeException(e));
}
});
in
.addCallback(
() -> {
subscription.dispose();
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
});
return in;
}
@Override
public Map<String, AppSetting> getAppSettings() {
return getAppSettingsAsync().block();
}
@Override
public Mono<Map<String, AppSetting>> getAppSettingsAsync() {
return Mono
.zip(
listAppSettings(),
listSlotConfigurations(),
(appSettingsInner, slotConfigs) ->
appSettingsInner
.properties()
.entrySet()
.stream()
.collect(
Collectors
.toMap(
Map.Entry::getKey,
entry ->
new AppSettingImpl(
entry.getKey(),
entry.getValue(),
slotConfigs.appSettingNames() != null
&& slotConfigs.appSettingNames().contains(entry.getKey())))));
}
@Override
public Map<String, ConnectionString> getConnectionStrings() {
return getConnectionStringsAsync().block();
}
@Override
public Mono<Map<String, ConnectionString>> getConnectionStringsAsync() {
return Mono
.zip(
listConnectionStrings(),
listSlotConfigurations(),
(connectionStringsInner, slotConfigs) ->
connectionStringsInner
.properties()
.entrySet()
.stream()
.collect(
Collectors
.toMap(
Map.Entry::getKey,
entry ->
new ConnectionStringImpl(
entry.getKey(),
entry.getValue(),
slotConfigs.connectionStringNames() != null
&& slotConfigs.connectionStringNames().contains(entry.getKey())))));
}
@Override
public WebAppAuthentication getAuthenticationConfig() {
return getAuthenticationConfigAsync().block();
}
@Override
public Mono<WebAppAuthentication> getAuthenticationConfigAsync() {
return getAuthentication()
.map(siteAuthSettingsInner -> new WebAppAuthenticationImpl<>(siteAuthSettingsInner, WebAppBaseImpl.this));
}
abstract Mono<SiteInner> createOrUpdateInner(SiteInner site);
abstract Mono<SiteInner> updateInner(SitePatchResourceInner siteUpdate);
abstract Mono<SiteInner> getInner();
abstract Mono<SiteConfigResourceInner> getConfigInner();
abstract Mono<SiteConfigResourceInner> createOrUpdateSiteConfig(SiteConfigResourceInner siteConfig);
abstract Mono<Void> deleteHostnameBinding(String hostname);
abstract Mono<StringDictionaryInner> listAppSettings();
abstract Mono<StringDictionaryInner> updateAppSettings(StringDictionaryInner inner);
abstract Mono<ConnectionStringDictionaryInner> listConnectionStrings();
abstract Mono<ConnectionStringDictionaryInner> updateConnectionStrings(ConnectionStringDictionaryInner inner);
abstract Mono<SlotConfigNamesResourceInner> listSlotConfigurations();
abstract Mono<SlotConfigNamesResourceInner> updateSlotConfigurations(SlotConfigNamesResourceInner inner);
abstract Mono<SiteSourceControlInner> createOrUpdateSourceControl(SiteSourceControlInner inner);
abstract Mono<Void> deleteSourceControl();
abstract Mono<SiteAuthSettingsInner> updateAuthentication(SiteAuthSettingsInner inner);
abstract Mono<SiteAuthSettingsInner> getAuthentication();
abstract Mono<MSDeployStatusInner> createMSDeploy(MSDeploy msDeployInner);
abstract Mono<SiteLogsConfigInner> updateDiagnosticLogsConfig(SiteLogsConfigInner siteLogsConfigInner);
@Override
public void beforeGroupCreateOrUpdate() {
if (hostNameSslStateMap.size() > 0) {
inner().withHostnameSslStates(new ArrayList<>(hostNameSslStateMap.values()));
}
IndexableTaskItem rootTaskItem =
wrapTask(
context -> {
return submitHostNameBindings()
.flatMap(fluentT -> submitSslBindings(fluentT.inner()));
});
IndexableTaskItem lastTaskItem = rootTaskItem;
lastTaskItem = sequentialTask(lastTaskItem, context -> submitSiteConfig());
lastTaskItem =
sequentialTask(
lastTaskItem,
context ->
submitMetadata()
.flatMap(ignored -> submitAppSettings().mergeWith(submitConnectionStrings()).last())
.flatMap(ignored -> submitStickiness()));
lastTaskItem =
sequentialTask(
lastTaskItem,
context -> submitSourceControlToDelete().flatMap(ignored -> submitSourceControlToCreate()));
lastTaskItem = sequentialTask(lastTaskItem, context -> submitAuthentication());
lastTaskItem = sequentialTask(lastTaskItem, context -> submitLogConfiguration());
if (msiHandler != null) {
sequentialTask(lastTaskItem, msiHandler);
}
addPostRunDependent(rootTaskItem);
}
private static IndexableTaskItem wrapTask(FunctionalTaskItem taskItem) {
return IndexableTaskItem.create(taskItem);
}
private static IndexableTaskItem sequentialTask(IndexableTaskItem taskItem1, FunctionalTaskItem taskItem2) {
IndexableTaskItem taskItem = IndexableTaskItem.create(taskItem2);
taskItem1.addPostRunDependent(taskItem);
return taskItem;
}
@Override
@SuppressWarnings("unchecked")
public Mono<FluentT> createResourceAsync() {
this.webAppMsiHandler.processCreatedExternalIdentities();
this.webAppMsiHandler.handleExternalIdentities();
return submitSite(inner())
.map(
siteInner -> {
setInner(siteInner);
return (FluentT) WebAppBaseImpl.this;
});
}
@Override
@SuppressWarnings("unchecked")
public Mono<FluentT> updateResourceAsync() {
SiteInner siteInner = this.inner();
SitePatchResourceInner siteUpdate = new SitePatchResourceInner();
siteUpdate.withHostnameSslStates(siteInner.hostnameSslStates());
siteUpdate.withKind(siteInner.kind());
siteUpdate.withEnabled(siteInner.enabled());
siteUpdate.withServerFarmId(siteInner.serverFarmId());
siteUpdate.withReserved(siteInner.reserved());
siteUpdate.withIsXenon(siteInner.isXenon());
siteUpdate.withHyperV(siteInner.hyperV());
siteUpdate.withScmSiteAlsoStopped(siteInner.scmSiteAlsoStopped());
siteUpdate.withHostingEnvironmentProfile(siteInner.hostingEnvironmentProfile());
siteUpdate.withClientAffinityEnabled(siteInner.clientAffinityEnabled());
siteUpdate.withClientCertEnabled(siteInner.clientCertEnabled());
siteUpdate.withClientCertExclusionPaths(siteInner.clientCertExclusionPaths());
siteUpdate.withHostNamesDisabled(siteInner.hostNamesDisabled());
siteUpdate.withContainerSize(siteInner.containerSize());
siteUpdate.withDailyMemoryTimeQuota(siteInner.dailyMemoryTimeQuota());
siteUpdate.withCloningInfo(siteInner.cloningInfo());
siteUpdate.withHttpsOnly(siteInner.httpsOnly());
siteUpdate.withRedundancyMode(siteInner.redundancyMode());
this.webAppMsiHandler.handleExternalIdentities(siteUpdate);
return submitSite(siteUpdate)
.map(
siteInner1 -> {
setInner(siteInner1);
webAppMsiHandler.clear();
return (FluentT) WebAppBaseImpl.this;
});
}
@Override
public Mono<Void> afterPostRunAsync(final boolean isGroupFaulted) {
if (!isGroupFaulted) {
isInCreateMode = false;
initializeKuduClient();
}
return Mono
.fromCallable(
() -> {
normalizeProperties();
return null;
});
}
Mono<SiteInner> submitSite(final SiteInner site) {
site.withSiteConfig(new SiteConfigInner());
return submitSiteWithoutSiteConfig(site);
}
Mono<SiteInner> submitSiteWithoutSiteConfig(final SiteInner site) {
return createOrUpdateInner(site)
.map(
siteInner -> {
site.withSiteConfig(null);
return siteInner;
});
}
Mono<SiteInner> submitSite(final SitePatchResourceInner siteUpdate) {
return updateInner(siteUpdate)
.map(
siteInner -> {
siteInner.withSiteConfig(null);
return siteInner;
});
}
@SuppressWarnings("unchecked")
Mono<FluentT> submitHostNameBindings() {
final List<Mono<HostnameBinding>> bindingObservables = new ArrayList<>();
for (HostnameBindingImpl<FluentT, FluentImplT> binding : hostNameBindingsToCreate.values()) {
bindingObservables.add(Utils.<HostnameBinding>rootResource(binding.createAsync().last()));
}
for (String binding : hostNameBindingsToDelete) {
bindingObservables.add(deleteHostnameBinding(binding).then(Mono.empty()));
}
if (bindingObservables.isEmpty()) {
return Mono.just((FluentT) this);
} else {
return Flux
.zip(bindingObservables, ignored -> WebAppBaseImpl.this)
.last()
.onErrorResume(
throwable -> {
if (throwable instanceof HttpResponseException
&& ((HttpResponseException) throwable).getResponse().getStatusCode() == 400) {
return submitSite(inner())
.flatMap(
ignored -> Flux.zip(bindingObservables, ignored1 -> WebAppBaseImpl.this).last());
} else {
return Mono.error(throwable);
}
})
.flatMap(WebAppBaseImpl::refreshAsync);
}
}
Mono<Indexable> submitSslBindings(final SiteInner site) {
List<Mono<AppServiceCertificate>> certs = new ArrayList<>();
for (final HostnameSslBindingImpl<FluentT, FluentImplT> binding : sslBindingsToCreate.values()) {
certs.add(binding.newCertificate());
hostNameSslStateMap.put(binding.inner().name(), binding.inner().withToUpdate(true));
}
if (certs.isEmpty()) {
return Mono.just((Indexable) this);
} else {
site.withHostnameSslStates(new ArrayList<>(hostNameSslStateMap.values()));
return Flux
.zip(certs, ignored -> site)
.last()
.flatMap(this::createOrUpdateInner)
.map(
siteInner -> {
setInner(siteInner);
return WebAppBaseImpl.this;
});
}
}
Mono<Indexable> submitSiteConfig() {
if (siteConfig == null) {
return Mono.just((Indexable) this);
}
return createOrUpdateSiteConfig(siteConfig)
.flatMap(
returnedSiteConfig -> {
siteConfig = returnedSiteConfig;
return Mono.just((Indexable) WebAppBaseImpl.this);
});
}
Mono<Indexable> submitAppSettings() {
Mono<Indexable> observable = Mono.just((Indexable) this);
if (!appSettingsToAdd.isEmpty() || !appSettingsToRemove.isEmpty()) {
observable =
listAppSettings()
.switchIfEmpty(Mono.just(new StringDictionaryInner()))
.flatMap(
stringDictionaryInner -> {
if (stringDictionaryInner.properties() == null) {
stringDictionaryInner.withProperties(new HashMap<String, String>());
}
for (String appSettingKey : appSettingsToRemove) {
stringDictionaryInner.properties().remove(appSettingKey);
}
stringDictionaryInner.properties().putAll(appSettingsToAdd);
return updateAppSettings(stringDictionaryInner);
})
.map(ignored -> WebAppBaseImpl.this);
}
return observable;
}
Mono<Indexable> submitMetadata() {
return Mono.just((Indexable) this);
}
Mono<Indexable> submitConnectionStrings() {
Mono<Indexable> observable = Mono.just((Indexable) this);
if (!connectionStringsToAdd.isEmpty() || !connectionStringsToRemove.isEmpty()) {
observable =
listConnectionStrings()
.switchIfEmpty(Mono.just(new ConnectionStringDictionaryInner()))
.flatMap(
dictionaryInner -> {
if (dictionaryInner.properties() == null) {
dictionaryInner.withProperties(new HashMap<String, ConnStringValueTypePair>());
}
for (String connectionString : connectionStringsToRemove) {
dictionaryInner.properties().remove(connectionString);
}
dictionaryInner.properties().putAll(connectionStringsToAdd);
return updateConnectionStrings(dictionaryInner);
})
.map(ignored -> WebAppBaseImpl.this);
}
return observable;
}
Mono<Indexable> submitStickiness() {
Mono<Indexable> observable = Mono.just((Indexable) this);
if (!appSettingStickiness.isEmpty() || !connectionStringStickiness.isEmpty()) {
observable =
listSlotConfigurations()
.switchIfEmpty(Mono.just(new SlotConfigNamesResourceInner()))
.flatMap(
slotConfigNamesResourceInner -> {
if (slotConfigNamesResourceInner.appSettingNames() == null) {
slotConfigNamesResourceInner.withAppSettingNames(new ArrayList<>());
}
if (slotConfigNamesResourceInner.connectionStringNames() == null) {
slotConfigNamesResourceInner.withConnectionStringNames(new ArrayList<>());
}
Set<String> stickyAppSettingKeys =
new HashSet<>(slotConfigNamesResourceInner.appSettingNames());
Set<String> stickyConnectionStringNames =
new HashSet<>(slotConfigNamesResourceInner.connectionStringNames());
for (Map.Entry<String, Boolean> stickiness : appSettingStickiness.entrySet()) {
if (stickiness.getValue()) {
stickyAppSettingKeys.add(stickiness.getKey());
} else {
stickyAppSettingKeys.remove(stickiness.getKey());
}
}
for (Map.Entry<String, Boolean> stickiness : connectionStringStickiness.entrySet()) {
if (stickiness.getValue()) {
stickyConnectionStringNames.add(stickiness.getKey());
} else {
stickyConnectionStringNames.remove(stickiness.getKey());
}
}
slotConfigNamesResourceInner.withAppSettingNames(new ArrayList<>(stickyAppSettingKeys));
slotConfigNamesResourceInner
.withConnectionStringNames(new ArrayList<>(stickyConnectionStringNames));
return updateSlotConfigurations(slotConfigNamesResourceInner);
})
.map(ignored -> WebAppBaseImpl.this);
}
return observable;
}
Mono<Indexable> submitSourceControlToCreate() {
if (sourceControl == null || sourceControlToDelete) {
return Mono.just((Indexable) this);
}
return sourceControl
.registerGithubAccessToken()
.then(createOrUpdateSourceControl(sourceControl.inner()))
.delayElement(SdkContext.getDelayDuration(Duration.ofSeconds(30)))
.map(ignored -> WebAppBaseImpl.this);
}
Mono<Indexable> submitSourceControlToDelete() {
if (!sourceControlToDelete) {
return Mono.just((Indexable) this);
}
return deleteSourceControl().map(ignored -> WebAppBaseImpl.this);
}
Mono<Indexable> submitAuthentication() {
if (!authenticationToUpdate) {
return Mono.just((Indexable) this);
}
return updateAuthentication(authentication.inner())
.map(
siteAuthSettingsInner -> {
WebAppBaseImpl.this.authentication =
new WebAppAuthenticationImpl<>(siteAuthSettingsInner, WebAppBaseImpl.this);
return WebAppBaseImpl.this;
});
}
Mono<Indexable> submitLogConfiguration() {
if (!diagnosticLogsToUpdate) {
return Mono.just((Indexable) this);
}
return updateDiagnosticLogsConfig(diagnosticLogs.inner())
.map(
siteLogsConfigInner -> {
WebAppBaseImpl.this.diagnosticLogs =
new WebAppDiagnosticLogsImpl<>(siteLogsConfigInner, WebAppBaseImpl.this);
return WebAppBaseImpl.this;
});
}
@Override
public WebDeploymentImpl<FluentT, FluentImplT> deploy() {
return new WebDeploymentImpl<>(this);
}
WebAppBaseImpl<FluentT, FluentImplT> withNewHostNameSslBinding(
final HostnameSslBindingImpl<FluentT, FluentImplT> hostNameSslBinding) {
sslBindingsToCreate.put(hostNameSslBinding.name(), hostNameSslBinding);
return this;
}
@SuppressWarnings("unchecked")
public FluentImplT withManagedHostnameBindings(AppServiceDomain domain, String... hostnames) {
for (String hostname : hostnames) {
if (hostname.equals("@") || hostname.equalsIgnoreCase(domain.name())) {
defineHostnameBinding()
.withAzureManagedDomain(domain)
.withSubDomain(hostname)
.withDnsRecordType(CustomHostnameDnsRecordType.A)
.attach();
} else {
defineHostnameBinding()
.withAzureManagedDomain(domain)
.withSubDomain(hostname)
.withDnsRecordType(CustomHostnameDnsRecordType.CNAME)
.attach();
}
}
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public HostnameBindingImpl<FluentT, FluentImplT> defineHostnameBinding() {
HostnameBindingInner inner = new HostnameBindingInner();
inner.withSiteName(name());
inner.withAzureResourceType(AzureResourceType.WEBSITE);
inner.withAzureResourceName(name());
inner.withHostnameType(HostnameType.VERIFIED);
return new HostnameBindingImpl<>(inner, (FluentImplT) this);
}
@SuppressWarnings("unchecked")
public FluentImplT withThirdPartyHostnameBinding(String domain, String... hostnames) {
for (String hostname : hostnames) {
defineHostnameBinding()
.withThirdPartyDomain(domain)
.withSubDomain(hostname)
.withDnsRecordType(CustomHostnameDnsRecordType.CNAME)
.attach();
}
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withoutHostnameBinding(String hostname) {
hostNameBindingsToDelete.add(hostname);
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withoutSslBinding(String hostname) {
if (hostNameSslStateMap.containsKey(hostname)) {
hostNameSslStateMap.get(hostname).withSslState(SslState.DISABLED).withToUpdate(true);
}
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
FluentImplT withHostNameBinding(final HostnameBindingImpl<FluentT, FluentImplT> hostNameBinding) {
this.hostNameBindingsToCreate.put(hostNameBinding.name(), hostNameBinding);
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withAppDisabledOnCreation() {
inner().withEnabled(false);
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withScmSiteAlsoStopped(boolean scmSiteAlsoStopped) {
inner().withScmSiteAlsoStopped(scmSiteAlsoStopped);
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withClientAffinityEnabled(boolean enabled) {
inner().withClientAffinityEnabled(enabled);
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withClientCertEnabled(boolean enabled) {
inner().withClientCertEnabled(enabled);
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public HostnameSslBindingImpl<FluentT, FluentImplT> defineSslBinding() {
return new HostnameSslBindingImpl<>(new HostnameSslState(), (FluentImplT) this);
}
@SuppressWarnings("unchecked")
public FluentImplT withNetFrameworkVersion(NetFrameworkVersion version) {
if (siteConfig == null) {
siteConfig = new SiteConfigResourceInner();
}
siteConfig.withNetFrameworkVersion(version.toString());
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withPhpVersion(PhpVersion version) {
if (siteConfig == null) {
siteConfig = new SiteConfigResourceInner();
}
siteConfig.withPhpVersion(version.toString());
return (FluentImplT) this;
}
public FluentImplT withoutPhp() {
return withPhpVersion(PhpVersion.fromString(""));
}
@SuppressWarnings("unchecked")
public FluentImplT withJavaVersion(JavaVersion version) {
if (siteConfig == null) {
siteConfig = new SiteConfigResourceInner();
}
siteConfig.withJavaVersion(version.toString());
return (FluentImplT) this;
}
public FluentImplT withoutJava() {
return withJavaVersion(JavaVersion.fromString("")).withWebContainer(WebContainer.fromString(""));
}
@SuppressWarnings("unchecked")
public FluentImplT withWebContainer(WebContainer webContainer) {
if (siteConfig == null) {
siteConfig = new SiteConfigResourceInner();
}
if (webContainer == null) {
siteConfig.withJavaContainer(null);
siteConfig.withJavaContainerVersion(null);
} else if (webContainer.toString().isEmpty()) {
siteConfig.withJavaContainer("");
siteConfig.withJavaContainerVersion("");
} else {
String[] containerInfo = webContainer.toString().split(" ");
siteConfig.withJavaContainer(containerInfo[0]);
siteConfig.withJavaContainerVersion(containerInfo[1]);
}
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withPythonVersion(PythonVersion version) {
if (siteConfig == null) {
siteConfig = new SiteConfigResourceInner();
}
siteConfig.withPythonVersion(version.toString());
return (FluentImplT) this;
}
public FluentImplT withoutPython() {
return withPythonVersion(PythonVersion.fromString(""));
}
@SuppressWarnings("unchecked")
public FluentImplT withPlatformArchitecture(PlatformArchitecture platform) {
if (siteConfig == null) {
siteConfig = new SiteConfigResourceInner();
}
siteConfig.withUse32BitWorkerProcess(platform.equals(PlatformArchitecture.X86));
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withWebSocketsEnabled(boolean enabled) {
if (siteConfig == null) {
siteConfig = new SiteConfigResourceInner();
}
siteConfig.withWebSocketsEnabled(enabled);
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withWebAppAlwaysOn(boolean alwaysOn) {
if (siteConfig == null) {
siteConfig = new SiteConfigResourceInner();
}
siteConfig.withAlwaysOn(alwaysOn);
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withManagedPipelineMode(ManagedPipelineMode managedPipelineMode) {
if (siteConfig == null) {
siteConfig = new SiteConfigResourceInner();
}
siteConfig.withManagedPipelineMode(managedPipelineMode);
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withAutoSwapSlotName(String slotName) {
if (siteConfig == null) {
siteConfig = new SiteConfigResourceInner();
}
siteConfig.withAutoSwapSlotName(slotName);
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withRemoteDebuggingEnabled(RemoteVisualStudioVersion remoteVisualStudioVersion) {
if (siteConfig == null) {
siteConfig = new SiteConfigResourceInner();
}
siteConfig.withRemoteDebuggingEnabled(true);
siteConfig.withRemoteDebuggingVersion(remoteVisualStudioVersion.toString());
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withRemoteDebuggingDisabled() {
if (siteConfig == null) {
siteConfig = new SiteConfigResourceInner();
}
siteConfig.withRemoteDebuggingEnabled(false);
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withDefaultDocument(String document) {
if (siteConfig == null) {
siteConfig = new SiteConfigResourceInner();
}
if (siteConfig.defaultDocuments() == null) {
siteConfig.withDefaultDocuments(new ArrayList<String>());
}
siteConfig.defaultDocuments().add(document);
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withDefaultDocuments(List<String> documents) {
if (siteConfig == null) {
siteConfig = new SiteConfigResourceInner();
}
if (siteConfig.defaultDocuments() == null) {
siteConfig.withDefaultDocuments(new ArrayList<>());
}
siteConfig.defaultDocuments().addAll(documents);
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withoutDefaultDocument(String document) {
if (siteConfig == null) {
siteConfig = new SiteConfigResourceInner();
}
if (siteConfig.defaultDocuments() != null) {
siteConfig.defaultDocuments().remove(document);
}
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withHttpsOnly(boolean httpsOnly) {
inner().withHttpsOnly(httpsOnly);
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withHttp20Enabled(boolean http20Enabled) {
if (siteConfig == null) {
siteConfig = new SiteConfigResourceInner();
}
siteConfig.withHttp20Enabled(http20Enabled);
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withFtpsState(FtpsState ftpsState) {
if (siteConfig == null) {
siteConfig = new SiteConfigResourceInner();
}
siteConfig.withFtpsState(ftpsState);
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withVirtualApplications(List<VirtualApplication> virtualApplications) {
if (siteConfig == null) {
siteConfig = new SiteConfigResourceInner();
}
siteConfig.withVirtualApplications(virtualApplications);
return (FluentImplT) this;
}
@Override
@SuppressWarnings("unchecked")
public FluentImplT withMinTlsVersion(SupportedTlsVersions minTlsVersion) {
if (siteConfig == null) {
siteConfig = new SiteConfigResourceInner();
}
siteConfig.withMinTlsVersion(minTlsVersion);
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withAppSetting(String key, String value) {
appSettingsToAdd.put(key, value);
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withAppSettings(Map<String, String> settings) {
appSettingsToAdd.putAll(settings);
return (FluentImplT) this;
}
public FluentImplT withStickyAppSetting(String key, String value) {
withAppSetting(key, value);
return withAppSettingStickiness(key, true);
}
@SuppressWarnings("unchecked")
public FluentImplT withStickyAppSettings(Map<String, String> settings) {
withAppSettings(settings);
for (String key : settings.keySet()) {
appSettingStickiness.put(key, true);
}
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withoutAppSetting(String key) {
appSettingsToRemove.add(key);
appSettingStickiness.remove(key);
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withAppSettingStickiness(String key, boolean sticky) {
appSettingStickiness.put(key, sticky);
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withConnectionString(String name, String value, ConnectionStringType type) {
connectionStringsToAdd.put(name, new ConnStringValueTypePair().withValue(value).withType(type));
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withStickyConnectionString(String name, String value, ConnectionStringType type) {
connectionStringsToAdd.put(name, new ConnStringValueTypePair().withValue(value).withType(type));
connectionStringStickiness.put(name, true);
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withoutConnectionString(String name) {
connectionStringsToRemove.add(name);
connectionStringStickiness.remove(name);
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withConnectionStringStickiness(String name, boolean stickiness) {
connectionStringStickiness.put(name, stickiness);
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
void withSourceControl(WebAppSourceControlImpl<FluentT, FluentImplT> sourceControl) {
this.sourceControl = sourceControl;
}
public WebAppSourceControlImpl<FluentT, FluentImplT> defineSourceControl() {
SiteSourceControlInner sourceControlInner = new SiteSourceControlInner();
return new WebAppSourceControlImpl<>(sourceControlInner, this);
}
@SuppressWarnings("unchecked")
public FluentImplT withLocalGitSourceControl() {
if (siteConfig == null) {
siteConfig = new SiteConfigResourceInner();
}
siteConfig.withScmType(ScmType.LOCAL_GIT);
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withoutSourceControl() {
sourceControlToDelete = true;
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
void withAuthentication(WebAppAuthenticationImpl<FluentT, FluentImplT> authentication) {
this.authentication = authentication;
authenticationToUpdate = true;
}
void withDiagnosticLogs(WebAppDiagnosticLogsImpl<FluentT, FluentImplT> diagnosticLogs) {
this.diagnosticLogs = diagnosticLogs;
diagnosticLogsToUpdate = true;
}
@Override
@SuppressWarnings("unchecked")
public Mono<FluentT> refreshAsync() {
return super
.refreshAsync()
.flatMap(
fluentT ->
getConfigInner()
.map(
returnedSiteConfig -> {
siteConfig = returnedSiteConfig;
return fluentT;
}));
}
@Override
protected Mono<SiteInner> getInnerAsync() {
return getInner();
}
@Override
public WebAppAuthenticationImpl<FluentT, FluentImplT> defineAuthentication() {
return new WebAppAuthenticationImpl<>(new SiteAuthSettingsInner().withEnabled(true), this);
}
@Override
@SuppressWarnings("unchecked")
public FluentImplT withoutAuthentication() {
this.authentication.inner().withEnabled(false);
authenticationToUpdate = true;
return (FluentImplT) this;
}
@Override
@SuppressWarnings("unchecked")
public FluentImplT withContainerLoggingEnabled(int quotaInMB, int retentionDays) {
return updateDiagnosticLogsConfiguration()
.withWebServerLogging()
.withWebServerLogsStoredOnFileSystem()
.withWebServerFileSystemQuotaInMB(quotaInMB)
.withLogRetentionDays(retentionDays)
.attach();
}
@Override
public FluentImplT withContainerLoggingEnabled() {
return withContainerLoggingEnabled(35, 0);
}
@Override
@SuppressWarnings("unchecked")
public FluentImplT withContainerLoggingDisabled() {
return updateDiagnosticLogsConfiguration().withoutWebServerLogging().attach();
}
@Override
@SuppressWarnings("unchecked")
public FluentImplT withSystemAssignedManagedServiceIdentity() {
this.webAppMsiHandler.withLocalManagedServiceIdentity();
return (FluentImplT) this;
}
@Override
@SuppressWarnings("unchecked")
public FluentImplT withoutSystemAssignedManagedServiceIdentity() {
this.webAppMsiHandler.withoutLocalManagedServiceIdentity();
return (FluentImplT) this;
}
@Override
@SuppressWarnings("unchecked")
public FluentImplT withUserAssignedManagedServiceIdentity() {
return (FluentImplT) this;
}
@Override
@SuppressWarnings("unchecked")
public FluentImplT withSystemAssignedIdentityBasedAccessTo(final String resourceId, final BuiltInRole role) {
this.webAppMsiHandler.withAccessTo(resourceId, role);
return (FluentImplT) this;
}
@Override
@SuppressWarnings("unchecked")
public FluentImplT withSystemAssignedIdentityBasedAccessToCurrentResourceGroup(final BuiltInRole role) {
this.webAppMsiHandler.withAccessToCurrentResourceGroup(role);
return (FluentImplT) this;
}
@Override
@SuppressWarnings("unchecked")
public FluentImplT withSystemAssignedIdentityBasedAccessTo(final String resourceId, final String roleDefinitionId) {
this.webAppMsiHandler.withAccessTo(resourceId, roleDefinitionId);
return (FluentImplT) this;
}
@Override
@SuppressWarnings("unchecked")
public FluentImplT withSystemAssignedIdentityBasedAccessToCurrentResourceGroup(final String roleDefinitionId) {
this.webAppMsiHandler.withAccessToCurrentResourceGroup(roleDefinitionId);
return (FluentImplT) this;
}
@Override
@SuppressWarnings("unchecked")
public FluentImplT withNewUserAssignedManagedServiceIdentity(Creatable<Identity> creatableIdentity) {
this.webAppMsiHandler.withNewExternalManagedServiceIdentity(creatableIdentity);
return (FluentImplT) this;
}
@Override
@SuppressWarnings("unchecked")
public FluentImplT withExistingUserAssignedManagedServiceIdentity(Identity identity) {
this.webAppMsiHandler.withExistingExternalManagedServiceIdentity(identity);
return (FluentImplT) this;
}
@Override
@SuppressWarnings("unchecked")
public FluentImplT withoutUserAssignedManagedServiceIdentity(String identityId) {
this.webAppMsiHandler.withoutExternalManagedServiceIdentity(identityId);
return (FluentImplT) this;
}
@Override
public WebAppDiagnosticLogsImpl<FluentT, FluentImplT> defineDiagnosticLogsConfiguration() {
if (diagnosticLogs == null) {
return new WebAppDiagnosticLogsImpl<>(new SiteLogsConfigInner(), this);
} else {
return diagnosticLogs;
}
}
@Override
public WebAppDiagnosticLogsImpl<FluentT, FluentImplT> updateDiagnosticLogsConfiguration() {
return defineDiagnosticLogsConfiguration();
}
@Override
public ManagedServiceIdentity identity() {
return webSiteBase.identity();
}
@Override
public boolean hyperV() {
return webSiteBase.hyperV();
}
@Override
public HostingEnvironmentProfile hostingEnvironmentProfile() {
return webSiteBase.hostingEnvironmentProfile();
}
@Override
public Set<String> clientCertExclusionPaths() {
return webSiteBase.clientCertExclusionPaths();
}
@Override
public Set<String> possibleOutboundIpAddresses() {
return webSiteBase.possibleOutboundIpAddresses();
}
@Override
public int dailyMemoryTimeQuota() {
return webSiteBase.dailyMemoryTimeQuota();
}
@Override
public OffsetDateTime suspendedTill() {
return webSiteBase.suspendedTill();
}
@Override
public int maxNumberOfWorkers() {
return webSiteBase.maxNumberOfWorkers();
}
@Override
public SlotSwapStatus slotSwapStatus() {
return webSiteBase.slotSwapStatus();
}
@Override
public RedundancyMode redundancyMode() {
return webSiteBase.redundancyMode();
}
@Override
public UUID inProgressOperationId() {
return webSiteBase.inProgressOperationId();
}
private static class PipedInputStreamWithCallback extends PipedInputStream {
private Runnable callback;
private void addCallback(Runnable action) {
this.callback = action;
}
@Override
public void close() throws IOException {
callback.run();
super.close();
}
}
} | class WebAppBaseImpl<FluentT extends WebAppBase, FluentImplT extends WebAppBaseImpl<FluentT, FluentImplT>>
extends GroupableResourceImpl<FluentT, SiteInner, FluentImplT, AppServiceManager>
implements WebAppBase,
WebAppBase.Definition<FluentT>,
WebAppBase.Update<FluentT>,
WebAppBase.UpdateStages.WithWebContainer<FluentT> {
private final ClientLogger logger = new ClientLogger(getClass());
private static final Map<AzureEnvironment, String> DNS_MAP =
new HashMap<AzureEnvironment, String>() {
{
put(AzureEnvironment.AZURE, "azurewebsites.net");
put(AzureEnvironment.AZURE_CHINA, "chinacloudsites.cn");
put(AzureEnvironment.AZURE_GERMANY, "azurewebsites.de");
put(AzureEnvironment.AZURE_US_GOVERNMENT, "azurewebsites.us");
}
};
SiteConfigResourceInner siteConfig;
KuduClient kuduClient;
WebSiteBase webSiteBase;
private Map<String, HostnameSslState> hostNameSslStateMap;
private TreeMap<String, HostnameBindingImpl<FluentT, FluentImplT>> hostNameBindingsToCreate;
private List<String> hostNameBindingsToDelete;
private TreeMap<String, HostnameSslBindingImpl<FluentT, FluentImplT>> sslBindingsToCreate;
protected Map<String, String> appSettingsToAdd;
protected List<String> appSettingsToRemove;
private Map<String, Boolean> appSettingStickiness;
private Map<String, ConnStringValueTypePair> connectionStringsToAdd;
private List<String> connectionStringsToRemove;
private Map<String, Boolean> connectionStringStickiness;
private WebAppSourceControlImpl<FluentT, FluentImplT> sourceControl;
private boolean sourceControlToDelete;
private WebAppAuthenticationImpl<FluentT, FluentImplT> authentication;
private boolean authenticationToUpdate;
private WebAppDiagnosticLogsImpl<FluentT, FluentImplT> diagnosticLogs;
private boolean diagnosticLogsToUpdate;
private FunctionalTaskItem msiHandler;
private boolean isInCreateMode;
private WebAppMsiHandler<FluentT, FluentImplT> webAppMsiHandler;
WebAppBaseImpl(
String name,
SiteInner innerObject,
SiteConfigResourceInner siteConfig,
SiteLogsConfigInner logConfig,
AppServiceManager manager) {
super(name, innerObject, manager);
if (innerObject != null && innerObject.kind() != null) {
innerObject.withKind(innerObject.kind().replace(";", ","));
}
this.siteConfig = siteConfig;
if (logConfig != null) {
this.diagnosticLogs = new WebAppDiagnosticLogsImpl<>(logConfig, this);
}
webAppMsiHandler = new WebAppMsiHandler<>(manager.authorizationManager(), this);
normalizeProperties();
isInCreateMode = inner() == null || inner().id() == null;
if (!isInCreateMode) {
initializeKuduClient();
}
}
public boolean isInCreateMode() {
return isInCreateMode;
}
private void initializeKuduClient() {
if (kuduClient == null) {
kuduClient = new KuduClient(this);
}
}
@Override
public void setInner(SiteInner innerObject) {
if (innerObject.kind() != null) {
innerObject.withKind(innerObject.kind().replace(";", ","));
}
super.setInner(innerObject);
}
RoleAssignmentHelper.IdProvider idProvider() {
return new RoleAssignmentHelper.IdProvider() {
@Override
public String principalId() {
if (inner() != null && inner().identity() != null) {
return inner().identity().principalId();
} else {
return null;
}
}
@Override
public String resourceId() {
if (inner() != null) {
return inner().id();
} else {
return null;
}
}
};
}
@Override
public String state() {
return webSiteBase.state();
}
@Override
public Set<String> hostnames() {
return webSiteBase.hostnames();
}
@Override
public String repositorySiteName() {
return webSiteBase.repositorySiteName();
}
@Override
public UsageState usageState() {
return webSiteBase.usageState();
}
@Override
public boolean enabled() {
return webSiteBase.enabled();
}
@Override
public Set<String> enabledHostNames() {
return webSiteBase.enabledHostNames();
}
@Override
public SiteAvailabilityState availabilityState() {
return webSiteBase.availabilityState();
}
@Override
public Map<String, HostnameSslState> hostnameSslStates() {
return Collections.unmodifiableMap(hostNameSslStateMap);
}
@Override
public String appServicePlanId() {
return webSiteBase.appServicePlanId();
}
@Override
public OffsetDateTime lastModifiedTime() {
return webSiteBase.lastModifiedTime();
}
@Override
public Set<String> trafficManagerHostNames() {
return webSiteBase.trafficManagerHostNames();
}
@Override
public boolean scmSiteAlsoStopped() {
return webSiteBase.scmSiteAlsoStopped();
}
@Override
public String targetSwapSlot() {
return webSiteBase.targetSwapSlot();
}
@Override
public boolean clientAffinityEnabled() {
return webSiteBase.clientAffinityEnabled();
}
@Override
public boolean clientCertEnabled() {
return webSiteBase.clientCertEnabled();
}
@Override
public boolean hostnamesDisabled() {
return webSiteBase.hostnamesDisabled();
}
@Override
public Set<String> outboundIPAddresses() {
return webSiteBase.outboundIPAddresses();
}
@Override
public int containerSize() {
return webSiteBase.containerSize();
}
@Override
public CloningInfo cloningInfo() {
return webSiteBase.cloningInfo();
}
@Override
public boolean isDefaultContainer() {
return webSiteBase.isDefaultContainer();
}
@Override
public String defaultHostname() {
if (inner().defaultHostname() != null) {
return inner().defaultHostname();
} else {
AzureEnvironment environment = manager().environment();
String dns = DNS_MAP.get(environment);
String leaf = name();
if (this instanceof DeploymentSlotBaseImpl<?, ?, ?, ?, ?>) {
leaf = ((DeploymentSlotBaseImpl<?, ?, ?, ?, ?>) this).parent().name() + "-" + leaf;
}
return leaf + "." + dns;
}
}
@Override
public List<String> defaultDocuments() {
if (siteConfig == null) {
return null;
}
return Collections.unmodifiableList(siteConfig.defaultDocuments());
}
@Override
public NetFrameworkVersion netFrameworkVersion() {
if (siteConfig == null) {
return null;
}
return NetFrameworkVersion.fromString(siteConfig.netFrameworkVersion());
}
@Override
public PhpVersion phpVersion() {
if (siteConfig == null || siteConfig.phpVersion() == null) {
return PhpVersion.OFF;
}
return PhpVersion.fromString(siteConfig.phpVersion());
}
@Override
public PythonVersion pythonVersion() {
if (siteConfig == null || siteConfig.pythonVersion() == null) {
return PythonVersion.OFF;
}
return PythonVersion.fromString(siteConfig.pythonVersion());
}
@Override
public String nodeVersion() {
if (siteConfig == null) {
return null;
}
return siteConfig.nodeVersion();
}
@Override
public boolean remoteDebuggingEnabled() {
if (siteConfig == null) {
return false;
}
return Utils.toPrimitiveBoolean(siteConfig.remoteDebuggingEnabled());
}
@Override
public RemoteVisualStudioVersion remoteDebuggingVersion() {
if (siteConfig == null) {
return null;
}
return RemoteVisualStudioVersion.fromString(siteConfig.remoteDebuggingVersion());
}
@Override
public boolean webSocketsEnabled() {
if (siteConfig == null) {
return false;
}
return Utils.toPrimitiveBoolean(siteConfig.webSocketsEnabled());
}
@Override
public boolean alwaysOn() {
if (siteConfig == null) {
return false;
}
return Utils.toPrimitiveBoolean(siteConfig.alwaysOn());
}
@Override
public JavaVersion javaVersion() {
if (siteConfig == null || siteConfig.javaVersion() == null) {
return JavaVersion.OFF;
}
return JavaVersion.fromString(siteConfig.javaVersion());
}
@Override
public String javaContainer() {
if (siteConfig == null) {
return null;
}
return siteConfig.javaContainer();
}
@Override
public String javaContainerVersion() {
if (siteConfig == null) {
return null;
}
return siteConfig.javaContainerVersion();
}
@Override
public ManagedPipelineMode managedPipelineMode() {
if (siteConfig == null) {
return null;
}
return siteConfig.managedPipelineMode();
}
@Override
public PlatformArchitecture platformArchitecture() {
if (siteConfig.use32BitWorkerProcess()) {
return PlatformArchitecture.X86;
} else {
return PlatformArchitecture.X64;
}
}
@Override
public String linuxFxVersion() {
if (siteConfig == null) {
return null;
}
return siteConfig.linuxFxVersion();
}
@Override
public String autoSwapSlotName() {
if (siteConfig == null) {
return null;
}
return siteConfig.autoSwapSlotName();
}
@Override
public boolean httpsOnly() {
return webSiteBase.httpsOnly();
}
@Override
public FtpsState ftpsState() {
if (siteConfig == null) {
return null;
}
return siteConfig.ftpsState();
}
@Override
public List<VirtualApplication> virtualApplications() {
if (siteConfig == null) {
return null;
}
return siteConfig.virtualApplications();
}
@Override
public boolean http20Enabled() {
if (siteConfig == null) {
return false;
}
return Utils.toPrimitiveBoolean(siteConfig.http20Enabled());
}
@Override
public boolean localMySqlEnabled() {
if (siteConfig == null) {
return false;
}
return Utils.toPrimitiveBoolean(siteConfig.localMySqlEnabled());
}
@Override
public ScmType scmType() {
if (siteConfig == null) {
return null;
}
return siteConfig.scmType();
}
@Override
public String documentRoot() {
if (siteConfig == null) {
return null;
}
return siteConfig.documentRoot();
}
@Override
public SupportedTlsVersions minTlsVersion() {
if (siteConfig == null) {
return null;
}
return siteConfig.minTlsVersion();
}
@Override
public OperatingSystem operatingSystem() {
if (inner().kind() != null && inner().kind().toLowerCase(Locale.ROOT).contains("linux")) {
return OperatingSystem.LINUX;
} else {
return OperatingSystem.WINDOWS;
}
}
@Override
public String systemAssignedManagedServiceIdentityTenantId() {
if (inner().identity() == null) {
return null;
}
return inner().identity().tenantId();
}
@Override
public String systemAssignedManagedServiceIdentityPrincipalId() {
if (inner().identity() == null) {
return null;
}
return inner().identity().principalId();
}
@Override
public Set<String> userAssignedManagedServiceIdentityIds() {
if (inner().identity() == null) {
return null;
}
return inner().identity().userAssignedIdentities().keySet();
}
@Override
public WebAppDiagnosticLogsImpl<FluentT, FluentImplT> diagnosticLogsConfig() {
return diagnosticLogs;
}
@Override
public InputStream streamApplicationLogs() {
return pipeObservableToInputStream(streamApplicationLogsAsync());
}
@Override
public Flux<String> streamApplicationLogsAsync() {
return kuduClient.streamApplicationLogsAsync();
}
@Override
public InputStream streamHttpLogs() {
return pipeObservableToInputStream(streamHttpLogsAsync());
}
@Override
public Flux<String> streamHttpLogsAsync() {
return kuduClient.streamHttpLogsAsync();
}
@Override
public InputStream streamTraceLogs() {
return pipeObservableToInputStream(streamTraceLogsAsync());
}
@Override
public Flux<String> streamTraceLogsAsync() {
return kuduClient.streamTraceLogsAsync();
}
@Override
public InputStream streamDeploymentLogs() {
return pipeObservableToInputStream(streamDeploymentLogsAsync());
}
@Override
public Flux<String> streamDeploymentLogsAsync() {
return kuduClient.streamDeploymentLogsAsync();
}
@Override
public InputStream streamAllLogs() {
return pipeObservableToInputStream(streamAllLogsAsync());
}
@Override
public Flux<String> streamAllLogsAsync() {
return kuduClient.streamAllLogsAsync();
}
private InputStream pipeObservableToInputStream(Flux<String> observable) {
PipedInputStreamWithCallback in = new PipedInputStreamWithCallback();
final PipedOutputStream out = new PipedOutputStream();
try {
in.connect(out);
} catch (IOException e) {
throw logger.logExceptionAsError(new RuntimeException(e));
}
final Disposable subscription =
observable
.subscribeOn(Schedulers.elastic())
.subscribe(
s -> {
try {
out.write(s.getBytes(StandardCharsets.UTF_8));
out.write('\n');
out.flush();
} catch (IOException e) {
throw logger.logExceptionAsError(new RuntimeException(e));
}
});
in
.addCallback(
() -> {
subscription.dispose();
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
});
return in;
}
@Override
public Map<String, AppSetting> getAppSettings() {
return getAppSettingsAsync().block();
}
@Override
public Mono<Map<String, AppSetting>> getAppSettingsAsync() {
return Mono
.zip(
listAppSettings(),
listSlotConfigurations(),
(appSettingsInner, slotConfigs) ->
appSettingsInner
.properties()
.entrySet()
.stream()
.collect(
Collectors
.toMap(
Map.Entry::getKey,
entry ->
new AppSettingImpl(
entry.getKey(),
entry.getValue(),
slotConfigs.appSettingNames() != null
&& slotConfigs.appSettingNames().contains(entry.getKey())))));
}
@Override
public Map<String, ConnectionString> getConnectionStrings() {
return getConnectionStringsAsync().block();
}
@Override
public Mono<Map<String, ConnectionString>> getConnectionStringsAsync() {
return Mono
.zip(
listConnectionStrings(),
listSlotConfigurations(),
(connectionStringsInner, slotConfigs) ->
connectionStringsInner
.properties()
.entrySet()
.stream()
.collect(
Collectors
.toMap(
Map.Entry::getKey,
entry ->
new ConnectionStringImpl(
entry.getKey(),
entry.getValue(),
slotConfigs.connectionStringNames() != null
&& slotConfigs.connectionStringNames().contains(entry.getKey())))));
}
@Override
public WebAppAuthentication getAuthenticationConfig() {
return getAuthenticationConfigAsync().block();
}
@Override
public Mono<WebAppAuthentication> getAuthenticationConfigAsync() {
return getAuthentication()
.map(siteAuthSettingsInner -> new WebAppAuthenticationImpl<>(siteAuthSettingsInner, WebAppBaseImpl.this));
}
abstract Mono<SiteInner> createOrUpdateInner(SiteInner site);
abstract Mono<SiteInner> updateInner(SitePatchResourceInner siteUpdate);
abstract Mono<SiteInner> getInner();
abstract Mono<SiteConfigResourceInner> getConfigInner();
abstract Mono<SiteConfigResourceInner> createOrUpdateSiteConfig(SiteConfigResourceInner siteConfig);
abstract Mono<Void> deleteHostnameBinding(String hostname);
abstract Mono<StringDictionaryInner> listAppSettings();
abstract Mono<StringDictionaryInner> updateAppSettings(StringDictionaryInner inner);
abstract Mono<ConnectionStringDictionaryInner> listConnectionStrings();
abstract Mono<ConnectionStringDictionaryInner> updateConnectionStrings(ConnectionStringDictionaryInner inner);
abstract Mono<SlotConfigNamesResourceInner> listSlotConfigurations();
abstract Mono<SlotConfigNamesResourceInner> updateSlotConfigurations(SlotConfigNamesResourceInner inner);
abstract Mono<SiteSourceControlInner> createOrUpdateSourceControl(SiteSourceControlInner inner);
abstract Mono<Void> deleteSourceControl();
abstract Mono<SiteAuthSettingsInner> updateAuthentication(SiteAuthSettingsInner inner);
abstract Mono<SiteAuthSettingsInner> getAuthentication();
abstract Mono<MSDeployStatusInner> createMSDeploy(MSDeploy msDeployInner);
abstract Mono<SiteLogsConfigInner> updateDiagnosticLogsConfig(SiteLogsConfigInner siteLogsConfigInner);
@Override
public void beforeGroupCreateOrUpdate() {
if (hostNameSslStateMap.size() > 0) {
inner().withHostnameSslStates(new ArrayList<>(hostNameSslStateMap.values()));
}
IndexableTaskItem rootTaskItem =
wrapTask(
context -> {
return submitHostNameBindings()
.flatMap(fluentT -> submitSslBindings(fluentT.inner()));
});
IndexableTaskItem lastTaskItem = rootTaskItem;
lastTaskItem = sequentialTask(lastTaskItem, context -> submitSiteConfig());
lastTaskItem =
sequentialTask(
lastTaskItem,
context ->
submitMetadata()
.flatMap(ignored -> submitAppSettings().mergeWith(submitConnectionStrings()).last())
.flatMap(ignored -> submitStickiness()));
lastTaskItem =
sequentialTask(
lastTaskItem,
context -> submitSourceControlToDelete().flatMap(ignored -> submitSourceControlToCreate()));
lastTaskItem = sequentialTask(lastTaskItem, context -> submitAuthentication());
lastTaskItem = sequentialTask(lastTaskItem, context -> submitLogConfiguration());
if (msiHandler != null) {
sequentialTask(lastTaskItem, msiHandler);
}
addPostRunDependent(rootTaskItem);
}
private static IndexableTaskItem wrapTask(FunctionalTaskItem taskItem) {
return IndexableTaskItem.create(taskItem);
}
private static IndexableTaskItem sequentialTask(IndexableTaskItem taskItem1, FunctionalTaskItem taskItem2) {
IndexableTaskItem taskItem = IndexableTaskItem.create(taskItem2);
taskItem1.addPostRunDependent(taskItem);
return taskItem;
}
@Override
@SuppressWarnings("unchecked")
public Mono<FluentT> createResourceAsync() {
this.webAppMsiHandler.processCreatedExternalIdentities();
this.webAppMsiHandler.handleExternalIdentities();
return submitSite(inner())
.map(
siteInner -> {
setInner(siteInner);
return (FluentT) WebAppBaseImpl.this;
});
}
@Override
@SuppressWarnings("unchecked")
public Mono<FluentT> updateResourceAsync() {
SiteInner siteInner = this.inner();
SitePatchResourceInner siteUpdate = new SitePatchResourceInner();
siteUpdate.withHostnameSslStates(siteInner.hostnameSslStates());
siteUpdate.withKind(siteInner.kind());
siteUpdate.withEnabled(siteInner.enabled());
siteUpdate.withServerFarmId(siteInner.serverFarmId());
siteUpdate.withReserved(siteInner.reserved());
siteUpdate.withIsXenon(siteInner.isXenon());
siteUpdate.withHyperV(siteInner.hyperV());
siteUpdate.withScmSiteAlsoStopped(siteInner.scmSiteAlsoStopped());
siteUpdate.withHostingEnvironmentProfile(siteInner.hostingEnvironmentProfile());
siteUpdate.withClientAffinityEnabled(siteInner.clientAffinityEnabled());
siteUpdate.withClientCertEnabled(siteInner.clientCertEnabled());
siteUpdate.withClientCertExclusionPaths(siteInner.clientCertExclusionPaths());
siteUpdate.withHostNamesDisabled(siteInner.hostNamesDisabled());
siteUpdate.withContainerSize(siteInner.containerSize());
siteUpdate.withDailyMemoryTimeQuota(siteInner.dailyMemoryTimeQuota());
siteUpdate.withCloningInfo(siteInner.cloningInfo());
siteUpdate.withHttpsOnly(siteInner.httpsOnly());
siteUpdate.withRedundancyMode(siteInner.redundancyMode());
this.webAppMsiHandler.handleExternalIdentities(siteUpdate);
return submitSite(siteUpdate)
.map(
siteInner1 -> {
setInner(siteInner1);
webAppMsiHandler.clear();
return (FluentT) WebAppBaseImpl.this;
});
}
@Override
public Mono<Void> afterPostRunAsync(final boolean isGroupFaulted) {
if (!isGroupFaulted) {
isInCreateMode = false;
initializeKuduClient();
}
return Mono
.fromCallable(
() -> {
normalizeProperties();
return null;
});
}
Mono<SiteInner> submitSite(final SiteInner site) {
site.withSiteConfig(new SiteConfigInner());
return submitSiteWithoutSiteConfig(site);
}
Mono<SiteInner> submitSiteWithoutSiteConfig(final SiteInner site) {
return createOrUpdateInner(site)
.map(
siteInner -> {
site.withSiteConfig(null);
return siteInner;
});
}
Mono<SiteInner> submitSite(final SitePatchResourceInner siteUpdate) {
return updateInner(siteUpdate)
.map(
siteInner -> {
siteInner.withSiteConfig(null);
return siteInner;
});
}
@SuppressWarnings("unchecked")
Mono<FluentT> submitHostNameBindings() {
final List<Mono<HostnameBinding>> bindingObservables = new ArrayList<>();
for (HostnameBindingImpl<FluentT, FluentImplT> binding : hostNameBindingsToCreate.values()) {
bindingObservables.add(Utils.<HostnameBinding>rootResource(binding.createAsync().last()));
}
for (String binding : hostNameBindingsToDelete) {
bindingObservables.add(deleteHostnameBinding(binding).then(Mono.empty()));
}
if (bindingObservables.isEmpty()) {
return Mono.just((FluentT) this);
} else {
return Flux
.zip(bindingObservables, ignored -> WebAppBaseImpl.this)
.last()
.onErrorResume(
throwable -> {
if (throwable instanceof HttpResponseException
&& ((HttpResponseException) throwable).getResponse().getStatusCode() == 400) {
return submitSite(inner())
.flatMap(
ignored -> Flux.zip(bindingObservables, ignored1 -> WebAppBaseImpl.this).last());
} else {
return Mono.error(throwable);
}
})
.flatMap(WebAppBaseImpl::refreshAsync);
}
}
Mono<Indexable> submitSslBindings(final SiteInner site) {
List<Mono<AppServiceCertificate>> certs = new ArrayList<>();
for (final HostnameSslBindingImpl<FluentT, FluentImplT> binding : sslBindingsToCreate.values()) {
certs.add(binding.newCertificate());
hostNameSslStateMap.put(binding.inner().name(), binding.inner().withToUpdate(true));
}
if (certs.isEmpty()) {
return Mono.just((Indexable) this);
} else {
site.withHostnameSslStates(new ArrayList<>(hostNameSslStateMap.values()));
return Flux
.zip(certs, ignored -> site)
.last()
.flatMap(this::createOrUpdateInner)
.map(
siteInner -> {
setInner(siteInner);
return WebAppBaseImpl.this;
});
}
}
Mono<Indexable> submitSiteConfig() {
if (siteConfig == null) {
return Mono.just((Indexable) this);
}
return createOrUpdateSiteConfig(siteConfig)
.flatMap(
returnedSiteConfig -> {
siteConfig = returnedSiteConfig;
return Mono.just((Indexable) WebAppBaseImpl.this);
});
}
Mono<Indexable> submitAppSettings() {
Mono<Indexable> observable = Mono.just((Indexable) this);
if (!appSettingsToAdd.isEmpty() || !appSettingsToRemove.isEmpty()) {
observable =
listAppSettings()
.switchIfEmpty(Mono.just(new StringDictionaryInner()))
.flatMap(
stringDictionaryInner -> {
if (stringDictionaryInner.properties() == null) {
stringDictionaryInner.withProperties(new HashMap<String, String>());
}
for (String appSettingKey : appSettingsToRemove) {
stringDictionaryInner.properties().remove(appSettingKey);
}
stringDictionaryInner.properties().putAll(appSettingsToAdd);
return updateAppSettings(stringDictionaryInner);
})
.map(ignored -> WebAppBaseImpl.this);
}
return observable;
}
Mono<Indexable> submitMetadata() {
return Mono.just((Indexable) this);
}
Mono<Indexable> submitConnectionStrings() {
Mono<Indexable> observable = Mono.just((Indexable) this);
if (!connectionStringsToAdd.isEmpty() || !connectionStringsToRemove.isEmpty()) {
observable =
listConnectionStrings()
.switchIfEmpty(Mono.just(new ConnectionStringDictionaryInner()))
.flatMap(
dictionaryInner -> {
if (dictionaryInner.properties() == null) {
dictionaryInner.withProperties(new HashMap<String, ConnStringValueTypePair>());
}
for (String connectionString : connectionStringsToRemove) {
dictionaryInner.properties().remove(connectionString);
}
dictionaryInner.properties().putAll(connectionStringsToAdd);
return updateConnectionStrings(dictionaryInner);
})
.map(ignored -> WebAppBaseImpl.this);
}
return observable;
}
Mono<Indexable> submitStickiness() {
Mono<Indexable> observable = Mono.just((Indexable) this);
if (!appSettingStickiness.isEmpty() || !connectionStringStickiness.isEmpty()) {
observable =
listSlotConfigurations()
.switchIfEmpty(Mono.just(new SlotConfigNamesResourceInner()))
.flatMap(
slotConfigNamesResourceInner -> {
if (slotConfigNamesResourceInner.appSettingNames() == null) {
slotConfigNamesResourceInner.withAppSettingNames(new ArrayList<>());
}
if (slotConfigNamesResourceInner.connectionStringNames() == null) {
slotConfigNamesResourceInner.withConnectionStringNames(new ArrayList<>());
}
Set<String> stickyAppSettingKeys =
new HashSet<>(slotConfigNamesResourceInner.appSettingNames());
Set<String> stickyConnectionStringNames =
new HashSet<>(slotConfigNamesResourceInner.connectionStringNames());
for (Map.Entry<String, Boolean> stickiness : appSettingStickiness.entrySet()) {
if (stickiness.getValue()) {
stickyAppSettingKeys.add(stickiness.getKey());
} else {
stickyAppSettingKeys.remove(stickiness.getKey());
}
}
for (Map.Entry<String, Boolean> stickiness : connectionStringStickiness.entrySet()) {
if (stickiness.getValue()) {
stickyConnectionStringNames.add(stickiness.getKey());
} else {
stickyConnectionStringNames.remove(stickiness.getKey());
}
}
slotConfigNamesResourceInner.withAppSettingNames(new ArrayList<>(stickyAppSettingKeys));
slotConfigNamesResourceInner
.withConnectionStringNames(new ArrayList<>(stickyConnectionStringNames));
return updateSlotConfigurations(slotConfigNamesResourceInner);
})
.map(ignored -> WebAppBaseImpl.this);
}
return observable;
}
Mono<Indexable> submitSourceControlToCreate() {
if (sourceControl == null || sourceControlToDelete) {
return Mono.just((Indexable) this);
}
return sourceControl
.registerGithubAccessToken()
.then(createOrUpdateSourceControl(sourceControl.inner()))
.delayElement(SdkContext.getDelayDuration(Duration.ofSeconds(30)))
.map(ignored -> WebAppBaseImpl.this);
}
Mono<Indexable> submitSourceControlToDelete() {
if (!sourceControlToDelete) {
return Mono.just((Indexable) this);
}
return deleteSourceControl().map(ignored -> WebAppBaseImpl.this);
}
Mono<Indexable> submitAuthentication() {
if (!authenticationToUpdate) {
return Mono.just((Indexable) this);
}
return updateAuthentication(authentication.inner())
.map(
siteAuthSettingsInner -> {
WebAppBaseImpl.this.authentication =
new WebAppAuthenticationImpl<>(siteAuthSettingsInner, WebAppBaseImpl.this);
return WebAppBaseImpl.this;
});
}
Mono<Indexable> submitLogConfiguration() {
if (!diagnosticLogsToUpdate) {
return Mono.just((Indexable) this);
}
return updateDiagnosticLogsConfig(diagnosticLogs.inner())
.map(
siteLogsConfigInner -> {
WebAppBaseImpl.this.diagnosticLogs =
new WebAppDiagnosticLogsImpl<>(siteLogsConfigInner, WebAppBaseImpl.this);
return WebAppBaseImpl.this;
});
}
@Override
public WebDeploymentImpl<FluentT, FluentImplT> deploy() {
return new WebDeploymentImpl<>(this);
}
WebAppBaseImpl<FluentT, FluentImplT> withNewHostNameSslBinding(
final HostnameSslBindingImpl<FluentT, FluentImplT> hostNameSslBinding) {
sslBindingsToCreate.put(hostNameSslBinding.name(), hostNameSslBinding);
return this;
}
@SuppressWarnings("unchecked")
public FluentImplT withManagedHostnameBindings(AppServiceDomain domain, String... hostnames) {
for (String hostname : hostnames) {
if (hostname.equals("@") || hostname.equalsIgnoreCase(domain.name())) {
defineHostnameBinding()
.withAzureManagedDomain(domain)
.withSubDomain(hostname)
.withDnsRecordType(CustomHostnameDnsRecordType.A)
.attach();
} else {
defineHostnameBinding()
.withAzureManagedDomain(domain)
.withSubDomain(hostname)
.withDnsRecordType(CustomHostnameDnsRecordType.CNAME)
.attach();
}
}
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public HostnameBindingImpl<FluentT, FluentImplT> defineHostnameBinding() {
HostnameBindingInner inner = new HostnameBindingInner();
inner.withSiteName(name());
inner.withAzureResourceType(AzureResourceType.WEBSITE);
inner.withAzureResourceName(name());
inner.withHostnameType(HostnameType.VERIFIED);
return new HostnameBindingImpl<>(inner, (FluentImplT) this);
}
@SuppressWarnings("unchecked")
public FluentImplT withThirdPartyHostnameBinding(String domain, String... hostnames) {
for (String hostname : hostnames) {
defineHostnameBinding()
.withThirdPartyDomain(domain)
.withSubDomain(hostname)
.withDnsRecordType(CustomHostnameDnsRecordType.CNAME)
.attach();
}
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withoutHostnameBinding(String hostname) {
hostNameBindingsToDelete.add(hostname);
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withoutSslBinding(String hostname) {
if (hostNameSslStateMap.containsKey(hostname)) {
hostNameSslStateMap.get(hostname).withSslState(SslState.DISABLED).withToUpdate(true);
}
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
FluentImplT withHostNameBinding(final HostnameBindingImpl<FluentT, FluentImplT> hostNameBinding) {
this.hostNameBindingsToCreate.put(hostNameBinding.name(), hostNameBinding);
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withAppDisabledOnCreation() {
inner().withEnabled(false);
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withScmSiteAlsoStopped(boolean scmSiteAlsoStopped) {
inner().withScmSiteAlsoStopped(scmSiteAlsoStopped);
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withClientAffinityEnabled(boolean enabled) {
inner().withClientAffinityEnabled(enabled);
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withClientCertEnabled(boolean enabled) {
inner().withClientCertEnabled(enabled);
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public HostnameSslBindingImpl<FluentT, FluentImplT> defineSslBinding() {
return new HostnameSslBindingImpl<>(new HostnameSslState(), (FluentImplT) this);
}
@SuppressWarnings("unchecked")
public FluentImplT withNetFrameworkVersion(NetFrameworkVersion version) {
if (siteConfig == null) {
siteConfig = new SiteConfigResourceInner();
}
siteConfig.withNetFrameworkVersion(version.toString());
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withPhpVersion(PhpVersion version) {
if (siteConfig == null) {
siteConfig = new SiteConfigResourceInner();
}
siteConfig.withPhpVersion(version.toString());
return (FluentImplT) this;
}
public FluentImplT withoutPhp() {
return withPhpVersion(PhpVersion.fromString(""));
}
@SuppressWarnings("unchecked")
public FluentImplT withJavaVersion(JavaVersion version) {
if (siteConfig == null) {
siteConfig = new SiteConfigResourceInner();
}
siteConfig.withJavaVersion(version.toString());
return (FluentImplT) this;
}
public FluentImplT withoutJava() {
return withJavaVersion(JavaVersion.fromString("")).withWebContainer(WebContainer.fromString(""));
}
@SuppressWarnings("unchecked")
public FluentImplT withWebContainer(WebContainer webContainer) {
if (siteConfig == null) {
siteConfig = new SiteConfigResourceInner();
}
if (webContainer == null) {
siteConfig.withJavaContainer(null);
siteConfig.withJavaContainerVersion(null);
} else if (webContainer.toString().isEmpty()) {
siteConfig.withJavaContainer("");
siteConfig.withJavaContainerVersion("");
} else {
String[] containerInfo = webContainer.toString().split(" ");
siteConfig.withJavaContainer(containerInfo[0]);
siteConfig.withJavaContainerVersion(containerInfo[1]);
}
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withPythonVersion(PythonVersion version) {
if (siteConfig == null) {
siteConfig = new SiteConfigResourceInner();
}
siteConfig.withPythonVersion(version.toString());
return (FluentImplT) this;
}
public FluentImplT withoutPython() {
return withPythonVersion(PythonVersion.fromString(""));
}
@SuppressWarnings("unchecked")
public FluentImplT withPlatformArchitecture(PlatformArchitecture platform) {
if (siteConfig == null) {
siteConfig = new SiteConfigResourceInner();
}
siteConfig.withUse32BitWorkerProcess(platform.equals(PlatformArchitecture.X86));
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withWebSocketsEnabled(boolean enabled) {
if (siteConfig == null) {
siteConfig = new SiteConfigResourceInner();
}
siteConfig.withWebSocketsEnabled(enabled);
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withWebAppAlwaysOn(boolean alwaysOn) {
if (siteConfig == null) {
siteConfig = new SiteConfigResourceInner();
}
siteConfig.withAlwaysOn(alwaysOn);
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withManagedPipelineMode(ManagedPipelineMode managedPipelineMode) {
if (siteConfig == null) {
siteConfig = new SiteConfigResourceInner();
}
siteConfig.withManagedPipelineMode(managedPipelineMode);
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withAutoSwapSlotName(String slotName) {
if (siteConfig == null) {
siteConfig = new SiteConfigResourceInner();
}
siteConfig.withAutoSwapSlotName(slotName);
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withRemoteDebuggingEnabled(RemoteVisualStudioVersion remoteVisualStudioVersion) {
if (siteConfig == null) {
siteConfig = new SiteConfigResourceInner();
}
siteConfig.withRemoteDebuggingEnabled(true);
siteConfig.withRemoteDebuggingVersion(remoteVisualStudioVersion.toString());
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withRemoteDebuggingDisabled() {
if (siteConfig == null) {
siteConfig = new SiteConfigResourceInner();
}
siteConfig.withRemoteDebuggingEnabled(false);
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withDefaultDocument(String document) {
if (siteConfig == null) {
siteConfig = new SiteConfigResourceInner();
}
if (siteConfig.defaultDocuments() == null) {
siteConfig.withDefaultDocuments(new ArrayList<String>());
}
siteConfig.defaultDocuments().add(document);
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withDefaultDocuments(List<String> documents) {
if (siteConfig == null) {
siteConfig = new SiteConfigResourceInner();
}
if (siteConfig.defaultDocuments() == null) {
siteConfig.withDefaultDocuments(new ArrayList<>());
}
siteConfig.defaultDocuments().addAll(documents);
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withoutDefaultDocument(String document) {
if (siteConfig == null) {
siteConfig = new SiteConfigResourceInner();
}
if (siteConfig.defaultDocuments() != null) {
siteConfig.defaultDocuments().remove(document);
}
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withHttpsOnly(boolean httpsOnly) {
inner().withHttpsOnly(httpsOnly);
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withHttp20Enabled(boolean http20Enabled) {
if (siteConfig == null) {
siteConfig = new SiteConfigResourceInner();
}
siteConfig.withHttp20Enabled(http20Enabled);
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withFtpsState(FtpsState ftpsState) {
if (siteConfig == null) {
siteConfig = new SiteConfigResourceInner();
}
siteConfig.withFtpsState(ftpsState);
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withVirtualApplications(List<VirtualApplication> virtualApplications) {
if (siteConfig == null) {
siteConfig = new SiteConfigResourceInner();
}
siteConfig.withVirtualApplications(virtualApplications);
return (FluentImplT) this;
}
@Override
@SuppressWarnings("unchecked")
public FluentImplT withMinTlsVersion(SupportedTlsVersions minTlsVersion) {
if (siteConfig == null) {
siteConfig = new SiteConfigResourceInner();
}
siteConfig.withMinTlsVersion(minTlsVersion);
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withAppSetting(String key, String value) {
appSettingsToAdd.put(key, value);
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withAppSettings(Map<String, String> settings) {
appSettingsToAdd.putAll(settings);
return (FluentImplT) this;
}
public FluentImplT withStickyAppSetting(String key, String value) {
withAppSetting(key, value);
return withAppSettingStickiness(key, true);
}
@SuppressWarnings("unchecked")
public FluentImplT withStickyAppSettings(Map<String, String> settings) {
withAppSettings(settings);
for (String key : settings.keySet()) {
appSettingStickiness.put(key, true);
}
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withoutAppSetting(String key) {
appSettingsToRemove.add(key);
appSettingStickiness.remove(key);
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withAppSettingStickiness(String key, boolean sticky) {
appSettingStickiness.put(key, sticky);
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withConnectionString(String name, String value, ConnectionStringType type) {
connectionStringsToAdd.put(name, new ConnStringValueTypePair().withValue(value).withType(type));
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withStickyConnectionString(String name, String value, ConnectionStringType type) {
connectionStringsToAdd.put(name, new ConnStringValueTypePair().withValue(value).withType(type));
connectionStringStickiness.put(name, true);
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withoutConnectionString(String name) {
connectionStringsToRemove.add(name);
connectionStringStickiness.remove(name);
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withConnectionStringStickiness(String name, boolean stickiness) {
connectionStringStickiness.put(name, stickiness);
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
void withSourceControl(WebAppSourceControlImpl<FluentT, FluentImplT> sourceControl) {
this.sourceControl = sourceControl;
}
public WebAppSourceControlImpl<FluentT, FluentImplT> defineSourceControl() {
SiteSourceControlInner sourceControlInner = new SiteSourceControlInner();
return new WebAppSourceControlImpl<>(sourceControlInner, this);
}
@SuppressWarnings("unchecked")
public FluentImplT withLocalGitSourceControl() {
if (siteConfig == null) {
siteConfig = new SiteConfigResourceInner();
}
siteConfig.withScmType(ScmType.LOCAL_GIT);
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withoutSourceControl() {
sourceControlToDelete = true;
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
void withAuthentication(WebAppAuthenticationImpl<FluentT, FluentImplT> authentication) {
this.authentication = authentication;
authenticationToUpdate = true;
}
void withDiagnosticLogs(WebAppDiagnosticLogsImpl<FluentT, FluentImplT> diagnosticLogs) {
this.diagnosticLogs = diagnosticLogs;
diagnosticLogsToUpdate = true;
}
@Override
@SuppressWarnings("unchecked")
public Mono<FluentT> refreshAsync() {
return super
.refreshAsync()
.flatMap(
fluentT ->
getConfigInner()
.map(
returnedSiteConfig -> {
siteConfig = returnedSiteConfig;
return fluentT;
}));
}
@Override
protected Mono<SiteInner> getInnerAsync() {
return getInner();
}
@Override
public WebAppAuthenticationImpl<FluentT, FluentImplT> defineAuthentication() {
return new WebAppAuthenticationImpl<>(new SiteAuthSettingsInner().withEnabled(true), this);
}
@Override
@SuppressWarnings("unchecked")
public FluentImplT withoutAuthentication() {
this.authentication.inner().withEnabled(false);
authenticationToUpdate = true;
return (FluentImplT) this;
}
@Override
@SuppressWarnings("unchecked")
public FluentImplT withContainerLoggingEnabled(int quotaInMB, int retentionDays) {
return updateDiagnosticLogsConfiguration()
.withWebServerLogging()
.withWebServerLogsStoredOnFileSystem()
.withWebServerFileSystemQuotaInMB(quotaInMB)
.withLogRetentionDays(retentionDays)
.attach();
}
@Override
public FluentImplT withContainerLoggingEnabled() {
return withContainerLoggingEnabled(35, 0);
}
@Override
@SuppressWarnings("unchecked")
public FluentImplT withContainerLoggingDisabled() {
return updateDiagnosticLogsConfiguration().withoutWebServerLogging().attach();
}
@Override
@SuppressWarnings("unchecked")
public FluentImplT withSystemAssignedManagedServiceIdentity() {
this.webAppMsiHandler.withLocalManagedServiceIdentity();
return (FluentImplT) this;
}
@Override
@SuppressWarnings("unchecked")
public FluentImplT withoutSystemAssignedManagedServiceIdentity() {
this.webAppMsiHandler.withoutLocalManagedServiceIdentity();
return (FluentImplT) this;
}
@Override
@SuppressWarnings("unchecked")
public FluentImplT withUserAssignedManagedServiceIdentity() {
return (FluentImplT) this;
}
@Override
@SuppressWarnings("unchecked")
public FluentImplT withSystemAssignedIdentityBasedAccessTo(final String resourceId, final BuiltInRole role) {
this.webAppMsiHandler.withAccessTo(resourceId, role);
return (FluentImplT) this;
}
@Override
@SuppressWarnings("unchecked")
public FluentImplT withSystemAssignedIdentityBasedAccessToCurrentResourceGroup(final BuiltInRole role) {
this.webAppMsiHandler.withAccessToCurrentResourceGroup(role);
return (FluentImplT) this;
}
@Override
@SuppressWarnings("unchecked")
public FluentImplT withSystemAssignedIdentityBasedAccessTo(final String resourceId, final String roleDefinitionId) {
this.webAppMsiHandler.withAccessTo(resourceId, roleDefinitionId);
return (FluentImplT) this;
}
@Override
@SuppressWarnings("unchecked")
public FluentImplT withSystemAssignedIdentityBasedAccessToCurrentResourceGroup(final String roleDefinitionId) {
this.webAppMsiHandler.withAccessToCurrentResourceGroup(roleDefinitionId);
return (FluentImplT) this;
}
@Override
@SuppressWarnings("unchecked")
public FluentImplT withNewUserAssignedManagedServiceIdentity(Creatable<Identity> creatableIdentity) {
this.webAppMsiHandler.withNewExternalManagedServiceIdentity(creatableIdentity);
return (FluentImplT) this;
}
@Override
@SuppressWarnings("unchecked")
public FluentImplT withExistingUserAssignedManagedServiceIdentity(Identity identity) {
this.webAppMsiHandler.withExistingExternalManagedServiceIdentity(identity);
return (FluentImplT) this;
}
@Override
@SuppressWarnings("unchecked")
public FluentImplT withoutUserAssignedManagedServiceIdentity(String identityId) {
this.webAppMsiHandler.withoutExternalManagedServiceIdentity(identityId);
return (FluentImplT) this;
}
@Override
public WebAppDiagnosticLogsImpl<FluentT, FluentImplT> defineDiagnosticLogsConfiguration() {
if (diagnosticLogs == null) {
return new WebAppDiagnosticLogsImpl<>(new SiteLogsConfigInner(), this);
} else {
return diagnosticLogs;
}
}
@Override
public WebAppDiagnosticLogsImpl<FluentT, FluentImplT> updateDiagnosticLogsConfiguration() {
return defineDiagnosticLogsConfiguration();
}
@Override
public ManagedServiceIdentity identity() {
return webSiteBase.identity();
}
@Override
public boolean hyperV() {
return webSiteBase.hyperV();
}
@Override
public HostingEnvironmentProfile hostingEnvironmentProfile() {
return webSiteBase.hostingEnvironmentProfile();
}
@Override
public Set<String> clientCertExclusionPaths() {
return webSiteBase.clientCertExclusionPaths();
}
@Override
public Set<String> possibleOutboundIpAddresses() {
return webSiteBase.possibleOutboundIpAddresses();
}
@Override
public int dailyMemoryTimeQuota() {
return webSiteBase.dailyMemoryTimeQuota();
}
@Override
public OffsetDateTime suspendedTill() {
return webSiteBase.suspendedTill();
}
@Override
public int maxNumberOfWorkers() {
return webSiteBase.maxNumberOfWorkers();
}
@Override
public SlotSwapStatus slotSwapStatus() {
return webSiteBase.slotSwapStatus();
}
@Override
public RedundancyMode redundancyMode() {
return webSiteBase.redundancyMode();
}
private static class PipedInputStreamWithCallback extends PipedInputStream {
private Runnable callback;
private void addCallback(Runnable action) {
this.callback = action;
}
@Override
public void close() throws IOException {
callback.run();
super.close();
}
}
} |
Then should we just use it to save the update items? | private void normalizeProperties() {
this.hostNameBindingsToDelete = new ArrayList<>();
this.appSettingsToAdd = new HashMap<>();
this.appSettingsToRemove = new ArrayList<>();
this.appSettingStickiness = new HashMap<>();
this.connectionStringsToAdd = new HashMap<>();
this.connectionStringsToRemove = new ArrayList<>();
this.connectionStringStickiness = new HashMap<>();
this.sourceControl = null;
this.sourceControlToDelete = false;
this.authenticationToUpdate = false;
this.diagnosticLogsToUpdate = false;
this.sslBindingsToCreate = new TreeMap<>();
this.msiHandler = null;
this.webSiteBase = new WebSiteBaseImpl(inner());
this.hostNameSslStateMap = new HashMap<>(this.webSiteBase.hostnameSslStates());
this.webAppMsiHandler.clear();
} | this.hostNameSslStateMap = new HashMap<>(this.webSiteBase.hostnameSslStates()); | private void normalizeProperties() {
this.hostNameBindingsToCreate = new TreeMap<>();
this.hostNameBindingsToDelete = new ArrayList<>();
this.appSettingsToAdd = new HashMap<>();
this.appSettingsToRemove = new ArrayList<>();
this.appSettingStickiness = new HashMap<>();
this.connectionStringsToAdd = new HashMap<>();
this.connectionStringsToRemove = new ArrayList<>();
this.connectionStringStickiness = new HashMap<>();
this.sourceControl = null;
this.sourceControlToDelete = false;
this.authenticationToUpdate = false;
this.diagnosticLogsToUpdate = false;
this.sslBindingsToCreate = new TreeMap<>();
this.msiHandler = null;
this.webSiteBase = new WebSiteBaseImpl(inner());
this.hostNameSslStateMap = new HashMap<>(this.webSiteBase.hostnameSslStates());
this.webAppMsiHandler.clear();
} | class WebAppBaseImpl<FluentT extends WebAppBase, FluentImplT extends WebAppBaseImpl<FluentT, FluentImplT>>
extends GroupableResourceImpl<FluentT, SiteInner, FluentImplT, AppServiceManager>
implements WebAppBase,
WebAppBase.Definition<FluentT>,
WebAppBase.Update<FluentT>,
WebAppBase.UpdateStages.WithWebContainer<FluentT> {
private final ClientLogger logger = new ClientLogger(getClass());
private static final Map<AzureEnvironment, String> DNS_MAP =
new HashMap<AzureEnvironment, String>() {
{
put(AzureEnvironment.AZURE, "azurewebsites.net");
put(AzureEnvironment.AZURE_CHINA, "chinacloudsites.cn");
put(AzureEnvironment.AZURE_GERMANY, "azurewebsites.de");
put(AzureEnvironment.AZURE_US_GOVERNMENT, "azurewebsites.us");
}
};
SiteConfigResourceInner siteConfig;
KuduClient kuduClient;
WebSiteBase webSiteBase;
private Map<String, HostnameSslState> hostNameSslStateMap;
private TreeMap<String, HostnameBindingImpl<FluentT, FluentImplT>> hostNameBindingsToCreate;
private List<String> hostNameBindingsToDelete;
private TreeMap<String, HostnameSslBindingImpl<FluentT, FluentImplT>> sslBindingsToCreate;
protected Map<String, String> appSettingsToAdd;
protected List<String> appSettingsToRemove;
private Map<String, Boolean> appSettingStickiness;
private Map<String, ConnStringValueTypePair> connectionStringsToAdd;
private List<String> connectionStringsToRemove;
private Map<String, Boolean> connectionStringStickiness;
private WebAppSourceControlImpl<FluentT, FluentImplT> sourceControl;
private boolean sourceControlToDelete;
private WebAppAuthenticationImpl<FluentT, FluentImplT> authentication;
private boolean authenticationToUpdate;
private WebAppDiagnosticLogsImpl<FluentT, FluentImplT> diagnosticLogs;
private boolean diagnosticLogsToUpdate;
private FunctionalTaskItem msiHandler;
private boolean isInCreateMode;
private WebAppMsiHandler<FluentT, FluentImplT> webAppMsiHandler;
WebAppBaseImpl(
String name,
SiteInner innerObject,
SiteConfigResourceInner siteConfig,
SiteLogsConfigInner logConfig,
AppServiceManager manager) {
super(name, innerObject, manager);
if (innerObject != null && innerObject.kind() != null) {
innerObject.withKind(innerObject.kind().replace(";", ","));
}
this.siteConfig = siteConfig;
if (logConfig != null) {
this.diagnosticLogs = new WebAppDiagnosticLogsImpl<>(logConfig, this);
}
webAppMsiHandler = new WebAppMsiHandler<>(manager.authorizationManager(), this);
normalizeProperties();
isInCreateMode = inner() == null || inner().id() == null;
if (!isInCreateMode) {
initializeKuduClient();
}
}
public boolean isInCreateMode() {
return isInCreateMode;
}
private void initializeKuduClient() {
if (kuduClient == null) {
kuduClient = new KuduClient(this);
}
}
@Override
public void setInner(SiteInner innerObject) {
if (innerObject.kind() != null) {
innerObject.withKind(innerObject.kind().replace(";", ","));
}
super.setInner(innerObject);
}
RoleAssignmentHelper.IdProvider idProvider() {
return new RoleAssignmentHelper.IdProvider() {
@Override
public String principalId() {
if (inner() != null && inner().identity() != null) {
return inner().identity().principalId();
} else {
return null;
}
}
@Override
public String resourceId() {
if (inner() != null) {
return inner().id();
} else {
return null;
}
}
};
}
@Override
public String state() {
return webSiteBase.state();
}
@Override
public Set<String> hostnames() {
return webSiteBase.hostnames();
}
@Override
public String repositorySiteName() {
return webSiteBase.repositorySiteName();
}
@Override
public UsageState usageState() {
return webSiteBase.usageState();
}
@Override
public boolean enabled() {
return webSiteBase.enabled();
}
@Override
public Set<String> enabledHostNames() {
return webSiteBase.enabledHostNames();
}
@Override
public SiteAvailabilityState availabilityState() {
return webSiteBase.availabilityState();
}
@Override
public Map<String, HostnameSslState> hostnameSslStates() {
return Collections.unmodifiableMap(hostNameSslStateMap);
}
@Override
public String appServicePlanId() {
return webSiteBase.appServicePlanId();
}
@Override
public OffsetDateTime lastModifiedTime() {
return webSiteBase.lastModifiedTime();
}
@Override
public Set<String> trafficManagerHostNames() {
return webSiteBase.trafficManagerHostNames();
}
@Override
public boolean scmSiteAlsoStopped() {
return webSiteBase.scmSiteAlsoStopped();
}
@Override
public String targetSwapSlot() {
return webSiteBase.targetSwapSlot();
}
@Override
public boolean clientAffinityEnabled() {
return webSiteBase.clientAffinityEnabled();
}
@Override
public boolean clientCertEnabled() {
return webSiteBase.clientCertEnabled();
}
@Override
public boolean hostnamesDisabled() {
return webSiteBase.hostnamesDisabled();
}
@Override
public Set<String> outboundIPAddresses() {
return webSiteBase.outboundIPAddresses();
}
@Override
public int containerSize() {
return webSiteBase.containerSize();
}
@Override
public CloningInfo cloningInfo() {
return webSiteBase.cloningInfo();
}
@Override
public boolean isDefaultContainer() {
return webSiteBase.isDefaultContainer();
}
@Override
public String defaultHostname() {
if (inner().defaultHostname() != null) {
return inner().defaultHostname();
} else {
AzureEnvironment environment = manager().environment();
String dns = DNS_MAP.get(environment);
String leaf = name();
if (this instanceof DeploymentSlotBaseImpl<?, ?, ?, ?, ?>) {
leaf = ((DeploymentSlotBaseImpl<?, ?, ?, ?, ?>) this).parent().name() + "-" + leaf;
}
return leaf + "." + dns;
}
}
@Override
public List<String> defaultDocuments() {
if (siteConfig == null) {
return null;
}
return Collections.unmodifiableList(siteConfig.defaultDocuments());
}
@Override
public NetFrameworkVersion netFrameworkVersion() {
if (siteConfig == null) {
return null;
}
return NetFrameworkVersion.fromString(siteConfig.netFrameworkVersion());
}
@Override
public PhpVersion phpVersion() {
if (siteConfig == null || siteConfig.phpVersion() == null) {
return PhpVersion.OFF;
}
return PhpVersion.fromString(siteConfig.phpVersion());
}
@Override
public PythonVersion pythonVersion() {
if (siteConfig == null || siteConfig.pythonVersion() == null) {
return PythonVersion.OFF;
}
return PythonVersion.fromString(siteConfig.pythonVersion());
}
@Override
public String nodeVersion() {
if (siteConfig == null) {
return null;
}
return siteConfig.nodeVersion();
}
@Override
public boolean remoteDebuggingEnabled() {
if (siteConfig == null) {
return false;
}
return Utils.toPrimitiveBoolean(siteConfig.remoteDebuggingEnabled());
}
@Override
public RemoteVisualStudioVersion remoteDebuggingVersion() {
if (siteConfig == null) {
return null;
}
return RemoteVisualStudioVersion.fromString(siteConfig.remoteDebuggingVersion());
}
@Override
public boolean webSocketsEnabled() {
if (siteConfig == null) {
return false;
}
return Utils.toPrimitiveBoolean(siteConfig.webSocketsEnabled());
}
@Override
public boolean alwaysOn() {
if (siteConfig == null) {
return false;
}
return Utils.toPrimitiveBoolean(siteConfig.alwaysOn());
}
@Override
public JavaVersion javaVersion() {
if (siteConfig == null || siteConfig.javaVersion() == null) {
return JavaVersion.OFF;
}
return JavaVersion.fromString(siteConfig.javaVersion());
}
@Override
public String javaContainer() {
if (siteConfig == null) {
return null;
}
return siteConfig.javaContainer();
}
@Override
public String javaContainerVersion() {
if (siteConfig == null) {
return null;
}
return siteConfig.javaContainerVersion();
}
@Override
public ManagedPipelineMode managedPipelineMode() {
if (siteConfig == null) {
return null;
}
return siteConfig.managedPipelineMode();
}
@Override
public PlatformArchitecture platformArchitecture() {
if (siteConfig.use32BitWorkerProcess()) {
return PlatformArchitecture.X86;
} else {
return PlatformArchitecture.X64;
}
}
@Override
public String linuxFxVersion() {
if (siteConfig == null) {
return null;
}
return siteConfig.linuxFxVersion();
}
@Override
public String autoSwapSlotName() {
if (siteConfig == null) {
return null;
}
return siteConfig.autoSwapSlotName();
}
@Override
public boolean httpsOnly() {
return webSiteBase.httpsOnly();
}
@Override
public FtpsState ftpsState() {
if (siteConfig == null) {
return null;
}
return siteConfig.ftpsState();
}
@Override
public List<VirtualApplication> virtualApplications() {
if (siteConfig == null) {
return null;
}
return siteConfig.virtualApplications();
}
@Override
public boolean http20Enabled() {
if (siteConfig == null) {
return false;
}
return Utils.toPrimitiveBoolean(siteConfig.http20Enabled());
}
@Override
public boolean localMySqlEnabled() {
if (siteConfig == null) {
return false;
}
return Utils.toPrimitiveBoolean(siteConfig.localMySqlEnabled());
}
@Override
public ScmType scmType() {
if (siteConfig == null) {
return null;
}
return siteConfig.scmType();
}
@Override
public String documentRoot() {
if (siteConfig == null) {
return null;
}
return siteConfig.documentRoot();
}
@Override
public SupportedTlsVersions minTlsVersion() {
if (siteConfig == null) {
return null;
}
return siteConfig.minTlsVersion();
}
@Override
public OperatingSystem operatingSystem() {
if (inner().kind() != null && inner().kind().toLowerCase(Locale.ROOT).contains("linux")) {
return OperatingSystem.LINUX;
} else {
return OperatingSystem.WINDOWS;
}
}
@Override
public String systemAssignedManagedServiceIdentityTenantId() {
if (inner().identity() == null) {
return null;
}
return inner().identity().tenantId();
}
@Override
public String systemAssignedManagedServiceIdentityPrincipalId() {
if (inner().identity() == null) {
return null;
}
return inner().identity().principalId();
}
@Override
public Set<String> userAssignedManagedServiceIdentityIds() {
if (inner().identity() == null) {
return null;
}
return inner().identity().userAssignedIdentities().keySet();
}
@Override
public WebAppDiagnosticLogsImpl<FluentT, FluentImplT> diagnosticLogsConfig() {
return diagnosticLogs;
}
@Override
public InputStream streamApplicationLogs() {
return pipeObservableToInputStream(streamApplicationLogsAsync());
}
@Override
public Flux<String> streamApplicationLogsAsync() {
return kuduClient.streamApplicationLogsAsync();
}
@Override
public InputStream streamHttpLogs() {
return pipeObservableToInputStream(streamHttpLogsAsync());
}
@Override
public Flux<String> streamHttpLogsAsync() {
return kuduClient.streamHttpLogsAsync();
}
@Override
public InputStream streamTraceLogs() {
return pipeObservableToInputStream(streamTraceLogsAsync());
}
@Override
public Flux<String> streamTraceLogsAsync() {
return kuduClient.streamTraceLogsAsync();
}
@Override
public InputStream streamDeploymentLogs() {
return pipeObservableToInputStream(streamDeploymentLogsAsync());
}
@Override
public Flux<String> streamDeploymentLogsAsync() {
return kuduClient.streamDeploymentLogsAsync();
}
@Override
public InputStream streamAllLogs() {
return pipeObservableToInputStream(streamAllLogsAsync());
}
@Override
public Flux<String> streamAllLogsAsync() {
return kuduClient.streamAllLogsAsync();
}
private InputStream pipeObservableToInputStream(Flux<String> observable) {
PipedInputStreamWithCallback in = new PipedInputStreamWithCallback();
final PipedOutputStream out = new PipedOutputStream();
try {
in.connect(out);
} catch (IOException e) {
throw logger.logExceptionAsError(new RuntimeException(e));
}
final Disposable subscription =
observable
.subscribeOn(Schedulers.elastic())
.subscribe(
s -> {
try {
out.write(s.getBytes(StandardCharsets.UTF_8));
out.write('\n');
out.flush();
} catch (IOException e) {
throw logger.logExceptionAsError(new RuntimeException(e));
}
});
in
.addCallback(
() -> {
subscription.dispose();
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
});
return in;
}
@Override
public Map<String, AppSetting> getAppSettings() {
return getAppSettingsAsync().block();
}
@Override
public Mono<Map<String, AppSetting>> getAppSettingsAsync() {
return Mono
.zip(
listAppSettings(),
listSlotConfigurations(),
(appSettingsInner, slotConfigs) ->
appSettingsInner
.properties()
.entrySet()
.stream()
.collect(
Collectors
.toMap(
Map.Entry::getKey,
entry ->
new AppSettingImpl(
entry.getKey(),
entry.getValue(),
slotConfigs.appSettingNames() != null
&& slotConfigs.appSettingNames().contains(entry.getKey())))));
}
@Override
public Map<String, ConnectionString> getConnectionStrings() {
return getConnectionStringsAsync().block();
}
@Override
public Mono<Map<String, ConnectionString>> getConnectionStringsAsync() {
return Mono
.zip(
listConnectionStrings(),
listSlotConfigurations(),
(connectionStringsInner, slotConfigs) ->
connectionStringsInner
.properties()
.entrySet()
.stream()
.collect(
Collectors
.toMap(
Map.Entry::getKey,
entry ->
new ConnectionStringImpl(
entry.getKey(),
entry.getValue(),
slotConfigs.connectionStringNames() != null
&& slotConfigs.connectionStringNames().contains(entry.getKey())))));
}
@Override
public WebAppAuthentication getAuthenticationConfig() {
return getAuthenticationConfigAsync().block();
}
@Override
public Mono<WebAppAuthentication> getAuthenticationConfigAsync() {
return getAuthentication()
.map(siteAuthSettingsInner -> new WebAppAuthenticationImpl<>(siteAuthSettingsInner, WebAppBaseImpl.this));
}
abstract Mono<SiteInner> createOrUpdateInner(SiteInner site);
abstract Mono<SiteInner> updateInner(SitePatchResourceInner siteUpdate);
abstract Mono<SiteInner> getInner();
abstract Mono<SiteConfigResourceInner> getConfigInner();
abstract Mono<SiteConfigResourceInner> createOrUpdateSiteConfig(SiteConfigResourceInner siteConfig);
abstract Mono<Void> deleteHostnameBinding(String hostname);
abstract Mono<StringDictionaryInner> listAppSettings();
abstract Mono<StringDictionaryInner> updateAppSettings(StringDictionaryInner inner);
abstract Mono<ConnectionStringDictionaryInner> listConnectionStrings();
abstract Mono<ConnectionStringDictionaryInner> updateConnectionStrings(ConnectionStringDictionaryInner inner);
abstract Mono<SlotConfigNamesResourceInner> listSlotConfigurations();
abstract Mono<SlotConfigNamesResourceInner> updateSlotConfigurations(SlotConfigNamesResourceInner inner);
abstract Mono<SiteSourceControlInner> createOrUpdateSourceControl(SiteSourceControlInner inner);
abstract Mono<Void> deleteSourceControl();
abstract Mono<SiteAuthSettingsInner> updateAuthentication(SiteAuthSettingsInner inner);
abstract Mono<SiteAuthSettingsInner> getAuthentication();
abstract Mono<MSDeployStatusInner> createMSDeploy(MSDeploy msDeployInner);
abstract Mono<SiteLogsConfigInner> updateDiagnosticLogsConfig(SiteLogsConfigInner siteLogsConfigInner);
@Override
public void beforeGroupCreateOrUpdate() {
if (hostNameSslStateMap.size() > 0) {
inner().withHostnameSslStates(new ArrayList<>(hostNameSslStateMap.values()));
}
IndexableTaskItem rootTaskItem =
wrapTask(
context -> {
return submitHostNameBindings()
.flatMap(fluentT -> submitSslBindings(fluentT.inner()));
});
IndexableTaskItem lastTaskItem = rootTaskItem;
lastTaskItem = sequentialTask(lastTaskItem, context -> submitSiteConfig());
lastTaskItem =
sequentialTask(
lastTaskItem,
context ->
submitMetadata()
.flatMap(ignored -> submitAppSettings().mergeWith(submitConnectionStrings()).last())
.flatMap(ignored -> submitStickiness()));
lastTaskItem =
sequentialTask(
lastTaskItem,
context -> submitSourceControlToDelete().flatMap(ignored -> submitSourceControlToCreate()));
lastTaskItem = sequentialTask(lastTaskItem, context -> submitAuthentication());
lastTaskItem = sequentialTask(lastTaskItem, context -> submitLogConfiguration());
if (msiHandler != null) {
sequentialTask(lastTaskItem, msiHandler);
}
addPostRunDependent(rootTaskItem);
}
private static IndexableTaskItem wrapTask(FunctionalTaskItem taskItem) {
return IndexableTaskItem.create(taskItem);
}
private static IndexableTaskItem sequentialTask(IndexableTaskItem taskItem1, FunctionalTaskItem taskItem2) {
IndexableTaskItem taskItem = IndexableTaskItem.create(taskItem2);
taskItem1.addPostRunDependent(taskItem);
return taskItem;
}
@Override
@SuppressWarnings("unchecked")
public Mono<FluentT> createResourceAsync() {
this.webAppMsiHandler.processCreatedExternalIdentities();
this.webAppMsiHandler.handleExternalIdentities();
return submitSite(inner())
.map(
siteInner -> {
setInner(siteInner);
return (FluentT) WebAppBaseImpl.this;
});
}
@Override
@SuppressWarnings("unchecked")
public Mono<FluentT> updateResourceAsync() {
SiteInner siteInner = this.inner();
SitePatchResourceInner siteUpdate = new SitePatchResourceInner();
siteUpdate.withHostnameSslStates(siteInner.hostnameSslStates());
siteUpdate.withKind(siteInner.kind());
siteUpdate.withEnabled(siteInner.enabled());
siteUpdate.withServerFarmId(siteInner.serverFarmId());
siteUpdate.withReserved(siteInner.reserved());
siteUpdate.withIsXenon(siteInner.isXenon());
siteUpdate.withHyperV(siteInner.hyperV());
siteUpdate.withScmSiteAlsoStopped(siteInner.scmSiteAlsoStopped());
siteUpdate.withHostingEnvironmentProfile(siteInner.hostingEnvironmentProfile());
siteUpdate.withClientAffinityEnabled(siteInner.clientAffinityEnabled());
siteUpdate.withClientCertEnabled(siteInner.clientCertEnabled());
siteUpdate.withClientCertExclusionPaths(siteInner.clientCertExclusionPaths());
siteUpdate.withHostNamesDisabled(siteInner.hostNamesDisabled());
siteUpdate.withContainerSize(siteInner.containerSize());
siteUpdate.withDailyMemoryTimeQuota(siteInner.dailyMemoryTimeQuota());
siteUpdate.withCloningInfo(siteInner.cloningInfo());
siteUpdate.withHttpsOnly(siteInner.httpsOnly());
siteUpdate.withRedundancyMode(siteInner.redundancyMode());
this.webAppMsiHandler.handleExternalIdentities(siteUpdate);
return submitSite(siteUpdate)
.map(
siteInner1 -> {
setInner(siteInner1);
webAppMsiHandler.clear();
return (FluentT) WebAppBaseImpl.this;
});
}
@Override
public Mono<Void> afterPostRunAsync(final boolean isGroupFaulted) {
if (!isGroupFaulted) {
isInCreateMode = false;
initializeKuduClient();
}
return Mono
.fromCallable(
() -> {
normalizeProperties();
return null;
});
}
Mono<SiteInner> submitSite(final SiteInner site) {
site.withSiteConfig(new SiteConfigInner());
return submitSiteWithoutSiteConfig(site);
}
Mono<SiteInner> submitSiteWithoutSiteConfig(final SiteInner site) {
return createOrUpdateInner(site)
.map(
siteInner -> {
site.withSiteConfig(null);
return siteInner;
});
}
Mono<SiteInner> submitSite(final SitePatchResourceInner siteUpdate) {
return updateInner(siteUpdate)
.map(
siteInner -> {
siteInner.withSiteConfig(null);
return siteInner;
});
}
@SuppressWarnings("unchecked")
Mono<FluentT> submitHostNameBindings() {
final List<Mono<HostnameBinding>> bindingObservables = new ArrayList<>();
for (HostnameBindingImpl<FluentT, FluentImplT> binding : hostNameBindingsToCreate.values()) {
bindingObservables.add(Utils.<HostnameBinding>rootResource(binding.createAsync().last()));
}
for (String binding : hostNameBindingsToDelete) {
bindingObservables.add(deleteHostnameBinding(binding).then(Mono.empty()));
}
if (bindingObservables.isEmpty()) {
return Mono.just((FluentT) this);
} else {
return Flux
.zip(bindingObservables, ignored -> WebAppBaseImpl.this)
.last()
.onErrorResume(
throwable -> {
if (throwable instanceof HttpResponseException
&& ((HttpResponseException) throwable).getResponse().getStatusCode() == 400) {
return submitSite(inner())
.flatMap(
ignored -> Flux.zip(bindingObservables, ignored1 -> WebAppBaseImpl.this).last());
} else {
return Mono.error(throwable);
}
})
.flatMap(WebAppBaseImpl::refreshAsync);
}
}
Mono<Indexable> submitSslBindings(final SiteInner site) {
List<Mono<AppServiceCertificate>> certs = new ArrayList<>();
for (final HostnameSslBindingImpl<FluentT, FluentImplT> binding : sslBindingsToCreate.values()) {
certs.add(binding.newCertificate());
hostNameSslStateMap.put(binding.inner().name(), binding.inner().withToUpdate(true));
}
if (certs.isEmpty()) {
return Mono.just((Indexable) this);
} else {
site.withHostnameSslStates(new ArrayList<>(hostNameSslStateMap.values()));
return Flux
.zip(certs, ignored -> site)
.last()
.flatMap(this::createOrUpdateInner)
.map(
siteInner -> {
setInner(siteInner);
return WebAppBaseImpl.this;
});
}
}
Mono<Indexable> submitSiteConfig() {
if (siteConfig == null) {
return Mono.just((Indexable) this);
}
return createOrUpdateSiteConfig(siteConfig)
.flatMap(
returnedSiteConfig -> {
siteConfig = returnedSiteConfig;
return Mono.just((Indexable) WebAppBaseImpl.this);
});
}
Mono<Indexable> submitAppSettings() {
Mono<Indexable> observable = Mono.just((Indexable) this);
if (!appSettingsToAdd.isEmpty() || !appSettingsToRemove.isEmpty()) {
observable =
listAppSettings()
.switchIfEmpty(Mono.just(new StringDictionaryInner()))
.flatMap(
stringDictionaryInner -> {
if (stringDictionaryInner.properties() == null) {
stringDictionaryInner.withProperties(new HashMap<String, String>());
}
for (String appSettingKey : appSettingsToRemove) {
stringDictionaryInner.properties().remove(appSettingKey);
}
stringDictionaryInner.properties().putAll(appSettingsToAdd);
return updateAppSettings(stringDictionaryInner);
})
.map(ignored -> WebAppBaseImpl.this);
}
return observable;
}
Mono<Indexable> submitMetadata() {
return Mono.just((Indexable) this);
}
Mono<Indexable> submitConnectionStrings() {
Mono<Indexable> observable = Mono.just((Indexable) this);
if (!connectionStringsToAdd.isEmpty() || !connectionStringsToRemove.isEmpty()) {
observable =
listConnectionStrings()
.switchIfEmpty(Mono.just(new ConnectionStringDictionaryInner()))
.flatMap(
dictionaryInner -> {
if (dictionaryInner.properties() == null) {
dictionaryInner.withProperties(new HashMap<String, ConnStringValueTypePair>());
}
for (String connectionString : connectionStringsToRemove) {
dictionaryInner.properties().remove(connectionString);
}
dictionaryInner.properties().putAll(connectionStringsToAdd);
return updateConnectionStrings(dictionaryInner);
})
.map(ignored -> WebAppBaseImpl.this);
}
return observable;
}
Mono<Indexable> submitStickiness() {
Mono<Indexable> observable = Mono.just((Indexable) this);
if (!appSettingStickiness.isEmpty() || !connectionStringStickiness.isEmpty()) {
observable =
listSlotConfigurations()
.switchIfEmpty(Mono.just(new SlotConfigNamesResourceInner()))
.flatMap(
slotConfigNamesResourceInner -> {
if (slotConfigNamesResourceInner.appSettingNames() == null) {
slotConfigNamesResourceInner.withAppSettingNames(new ArrayList<>());
}
if (slotConfigNamesResourceInner.connectionStringNames() == null) {
slotConfigNamesResourceInner.withConnectionStringNames(new ArrayList<>());
}
Set<String> stickyAppSettingKeys =
new HashSet<>(slotConfigNamesResourceInner.appSettingNames());
Set<String> stickyConnectionStringNames =
new HashSet<>(slotConfigNamesResourceInner.connectionStringNames());
for (Map.Entry<String, Boolean> stickiness : appSettingStickiness.entrySet()) {
if (stickiness.getValue()) {
stickyAppSettingKeys.add(stickiness.getKey());
} else {
stickyAppSettingKeys.remove(stickiness.getKey());
}
}
for (Map.Entry<String, Boolean> stickiness : connectionStringStickiness.entrySet()) {
if (stickiness.getValue()) {
stickyConnectionStringNames.add(stickiness.getKey());
} else {
stickyConnectionStringNames.remove(stickiness.getKey());
}
}
slotConfigNamesResourceInner.withAppSettingNames(new ArrayList<>(stickyAppSettingKeys));
slotConfigNamesResourceInner
.withConnectionStringNames(new ArrayList<>(stickyConnectionStringNames));
return updateSlotConfigurations(slotConfigNamesResourceInner);
})
.map(ignored -> WebAppBaseImpl.this);
}
return observable;
}
Mono<Indexable> submitSourceControlToCreate() {
if (sourceControl == null || sourceControlToDelete) {
return Mono.just((Indexable) this);
}
return sourceControl
.registerGithubAccessToken()
.then(createOrUpdateSourceControl(sourceControl.inner()))
.delayElement(SdkContext.getDelayDuration(Duration.ofSeconds(30)))
.map(ignored -> WebAppBaseImpl.this);
}
Mono<Indexable> submitSourceControlToDelete() {
if (!sourceControlToDelete) {
return Mono.just((Indexable) this);
}
return deleteSourceControl().map(ignored -> WebAppBaseImpl.this);
}
Mono<Indexable> submitAuthentication() {
if (!authenticationToUpdate) {
return Mono.just((Indexable) this);
}
return updateAuthentication(authentication.inner())
.map(
siteAuthSettingsInner -> {
WebAppBaseImpl.this.authentication =
new WebAppAuthenticationImpl<>(siteAuthSettingsInner, WebAppBaseImpl.this);
return WebAppBaseImpl.this;
});
}
Mono<Indexable> submitLogConfiguration() {
if (!diagnosticLogsToUpdate) {
return Mono.just((Indexable) this);
}
return updateDiagnosticLogsConfig(diagnosticLogs.inner())
.map(
siteLogsConfigInner -> {
WebAppBaseImpl.this.diagnosticLogs =
new WebAppDiagnosticLogsImpl<>(siteLogsConfigInner, WebAppBaseImpl.this);
return WebAppBaseImpl.this;
});
}
@Override
public WebDeploymentImpl<FluentT, FluentImplT> deploy() {
return new WebDeploymentImpl<>(this);
}
WebAppBaseImpl<FluentT, FluentImplT> withNewHostNameSslBinding(
final HostnameSslBindingImpl<FluentT, FluentImplT> hostNameSslBinding) {
sslBindingsToCreate.put(hostNameSslBinding.name(), hostNameSslBinding);
return this;
}
@SuppressWarnings("unchecked")
public FluentImplT withManagedHostnameBindings(AppServiceDomain domain, String... hostnames) {
for (String hostname : hostnames) {
if (hostname.equals("@") || hostname.equalsIgnoreCase(domain.name())) {
defineHostnameBinding()
.withAzureManagedDomain(domain)
.withSubDomain(hostname)
.withDnsRecordType(CustomHostnameDnsRecordType.A)
.attach();
} else {
defineHostnameBinding()
.withAzureManagedDomain(domain)
.withSubDomain(hostname)
.withDnsRecordType(CustomHostnameDnsRecordType.CNAME)
.attach();
}
}
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public HostnameBindingImpl<FluentT, FluentImplT> defineHostnameBinding() {
HostnameBindingInner inner = new HostnameBindingInner();
inner.withSiteName(name());
inner.withAzureResourceType(AzureResourceType.WEBSITE);
inner.withAzureResourceName(name());
inner.withHostnameType(HostnameType.VERIFIED);
return new HostnameBindingImpl<>(inner, (FluentImplT) this);
}
@SuppressWarnings("unchecked")
public FluentImplT withThirdPartyHostnameBinding(String domain, String... hostnames) {
for (String hostname : hostnames) {
defineHostnameBinding()
.withThirdPartyDomain(domain)
.withSubDomain(hostname)
.withDnsRecordType(CustomHostnameDnsRecordType.CNAME)
.attach();
}
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withoutHostnameBinding(String hostname) {
hostNameBindingsToDelete.add(hostname);
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withoutSslBinding(String hostname) {
if (hostNameSslStateMap.containsKey(hostname)) {
hostNameSslStateMap.get(hostname).withSslState(SslState.DISABLED).withToUpdate(true);
}
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
FluentImplT withHostNameBinding(final HostnameBindingImpl<FluentT, FluentImplT> hostNameBinding) {
this.hostNameBindingsToCreate.put(hostNameBinding.name(), hostNameBinding);
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withAppDisabledOnCreation() {
inner().withEnabled(false);
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withScmSiteAlsoStopped(boolean scmSiteAlsoStopped) {
inner().withScmSiteAlsoStopped(scmSiteAlsoStopped);
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withClientAffinityEnabled(boolean enabled) {
inner().withClientAffinityEnabled(enabled);
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withClientCertEnabled(boolean enabled) {
inner().withClientCertEnabled(enabled);
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public HostnameSslBindingImpl<FluentT, FluentImplT> defineSslBinding() {
return new HostnameSslBindingImpl<>(new HostnameSslState(), (FluentImplT) this);
}
@SuppressWarnings("unchecked")
public FluentImplT withNetFrameworkVersion(NetFrameworkVersion version) {
if (siteConfig == null) {
siteConfig = new SiteConfigResourceInner();
}
siteConfig.withNetFrameworkVersion(version.toString());
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withPhpVersion(PhpVersion version) {
if (siteConfig == null) {
siteConfig = new SiteConfigResourceInner();
}
siteConfig.withPhpVersion(version.toString());
return (FluentImplT) this;
}
public FluentImplT withoutPhp() {
return withPhpVersion(PhpVersion.fromString(""));
}
@SuppressWarnings("unchecked")
public FluentImplT withJavaVersion(JavaVersion version) {
if (siteConfig == null) {
siteConfig = new SiteConfigResourceInner();
}
siteConfig.withJavaVersion(version.toString());
return (FluentImplT) this;
}
public FluentImplT withoutJava() {
return withJavaVersion(JavaVersion.fromString("")).withWebContainer(WebContainer.fromString(""));
}
@SuppressWarnings("unchecked")
public FluentImplT withWebContainer(WebContainer webContainer) {
if (siteConfig == null) {
siteConfig = new SiteConfigResourceInner();
}
if (webContainer == null) {
siteConfig.withJavaContainer(null);
siteConfig.withJavaContainerVersion(null);
} else if (webContainer.toString().isEmpty()) {
siteConfig.withJavaContainer("");
siteConfig.withJavaContainerVersion("");
} else {
String[] containerInfo = webContainer.toString().split(" ");
siteConfig.withJavaContainer(containerInfo[0]);
siteConfig.withJavaContainerVersion(containerInfo[1]);
}
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withPythonVersion(PythonVersion version) {
if (siteConfig == null) {
siteConfig = new SiteConfigResourceInner();
}
siteConfig.withPythonVersion(version.toString());
return (FluentImplT) this;
}
public FluentImplT withoutPython() {
return withPythonVersion(PythonVersion.fromString(""));
}
@SuppressWarnings("unchecked")
public FluentImplT withPlatformArchitecture(PlatformArchitecture platform) {
if (siteConfig == null) {
siteConfig = new SiteConfigResourceInner();
}
siteConfig.withUse32BitWorkerProcess(platform.equals(PlatformArchitecture.X86));
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withWebSocketsEnabled(boolean enabled) {
if (siteConfig == null) {
siteConfig = new SiteConfigResourceInner();
}
siteConfig.withWebSocketsEnabled(enabled);
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withWebAppAlwaysOn(boolean alwaysOn) {
if (siteConfig == null) {
siteConfig = new SiteConfigResourceInner();
}
siteConfig.withAlwaysOn(alwaysOn);
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withManagedPipelineMode(ManagedPipelineMode managedPipelineMode) {
if (siteConfig == null) {
siteConfig = new SiteConfigResourceInner();
}
siteConfig.withManagedPipelineMode(managedPipelineMode);
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withAutoSwapSlotName(String slotName) {
if (siteConfig == null) {
siteConfig = new SiteConfigResourceInner();
}
siteConfig.withAutoSwapSlotName(slotName);
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withRemoteDebuggingEnabled(RemoteVisualStudioVersion remoteVisualStudioVersion) {
if (siteConfig == null) {
siteConfig = new SiteConfigResourceInner();
}
siteConfig.withRemoteDebuggingEnabled(true);
siteConfig.withRemoteDebuggingVersion(remoteVisualStudioVersion.toString());
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withRemoteDebuggingDisabled() {
if (siteConfig == null) {
siteConfig = new SiteConfigResourceInner();
}
siteConfig.withRemoteDebuggingEnabled(false);
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withDefaultDocument(String document) {
if (siteConfig == null) {
siteConfig = new SiteConfigResourceInner();
}
if (siteConfig.defaultDocuments() == null) {
siteConfig.withDefaultDocuments(new ArrayList<String>());
}
siteConfig.defaultDocuments().add(document);
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withDefaultDocuments(List<String> documents) {
if (siteConfig == null) {
siteConfig = new SiteConfigResourceInner();
}
if (siteConfig.defaultDocuments() == null) {
siteConfig.withDefaultDocuments(new ArrayList<>());
}
siteConfig.defaultDocuments().addAll(documents);
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withoutDefaultDocument(String document) {
if (siteConfig == null) {
siteConfig = new SiteConfigResourceInner();
}
if (siteConfig.defaultDocuments() != null) {
siteConfig.defaultDocuments().remove(document);
}
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withHttpsOnly(boolean httpsOnly) {
inner().withHttpsOnly(httpsOnly);
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withHttp20Enabled(boolean http20Enabled) {
if (siteConfig == null) {
siteConfig = new SiteConfigResourceInner();
}
siteConfig.withHttp20Enabled(http20Enabled);
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withFtpsState(FtpsState ftpsState) {
if (siteConfig == null) {
siteConfig = new SiteConfigResourceInner();
}
siteConfig.withFtpsState(ftpsState);
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withVirtualApplications(List<VirtualApplication> virtualApplications) {
if (siteConfig == null) {
siteConfig = new SiteConfigResourceInner();
}
siteConfig.withVirtualApplications(virtualApplications);
return (FluentImplT) this;
}
@Override
@SuppressWarnings("unchecked")
public FluentImplT withMinTlsVersion(SupportedTlsVersions minTlsVersion) {
if (siteConfig == null) {
siteConfig = new SiteConfigResourceInner();
}
siteConfig.withMinTlsVersion(minTlsVersion);
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withAppSetting(String key, String value) {
appSettingsToAdd.put(key, value);
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withAppSettings(Map<String, String> settings) {
appSettingsToAdd.putAll(settings);
return (FluentImplT) this;
}
public FluentImplT withStickyAppSetting(String key, String value) {
withAppSetting(key, value);
return withAppSettingStickiness(key, true);
}
@SuppressWarnings("unchecked")
public FluentImplT withStickyAppSettings(Map<String, String> settings) {
withAppSettings(settings);
for (String key : settings.keySet()) {
appSettingStickiness.put(key, true);
}
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withoutAppSetting(String key) {
appSettingsToRemove.add(key);
appSettingStickiness.remove(key);
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withAppSettingStickiness(String key, boolean sticky) {
appSettingStickiness.put(key, sticky);
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withConnectionString(String name, String value, ConnectionStringType type) {
connectionStringsToAdd.put(name, new ConnStringValueTypePair().withValue(value).withType(type));
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withStickyConnectionString(String name, String value, ConnectionStringType type) {
connectionStringsToAdd.put(name, new ConnStringValueTypePair().withValue(value).withType(type));
connectionStringStickiness.put(name, true);
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withoutConnectionString(String name) {
connectionStringsToRemove.add(name);
connectionStringStickiness.remove(name);
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withConnectionStringStickiness(String name, boolean stickiness) {
connectionStringStickiness.put(name, stickiness);
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
void withSourceControl(WebAppSourceControlImpl<FluentT, FluentImplT> sourceControl) {
this.sourceControl = sourceControl;
}
public WebAppSourceControlImpl<FluentT, FluentImplT> defineSourceControl() {
SiteSourceControlInner sourceControlInner = new SiteSourceControlInner();
return new WebAppSourceControlImpl<>(sourceControlInner, this);
}
@SuppressWarnings("unchecked")
public FluentImplT withLocalGitSourceControl() {
if (siteConfig == null) {
siteConfig = new SiteConfigResourceInner();
}
siteConfig.withScmType(ScmType.LOCAL_GIT);
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withoutSourceControl() {
sourceControlToDelete = true;
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
void withAuthentication(WebAppAuthenticationImpl<FluentT, FluentImplT> authentication) {
this.authentication = authentication;
authenticationToUpdate = true;
}
void withDiagnosticLogs(WebAppDiagnosticLogsImpl<FluentT, FluentImplT> diagnosticLogs) {
this.diagnosticLogs = diagnosticLogs;
diagnosticLogsToUpdate = true;
}
@Override
@SuppressWarnings("unchecked")
public Mono<FluentT> refreshAsync() {
return super
.refreshAsync()
.flatMap(
fluentT ->
getConfigInner()
.map(
returnedSiteConfig -> {
siteConfig = returnedSiteConfig;
return fluentT;
}));
}
@Override
protected Mono<SiteInner> getInnerAsync() {
return getInner();
}
@Override
public WebAppAuthenticationImpl<FluentT, FluentImplT> defineAuthentication() {
return new WebAppAuthenticationImpl<>(new SiteAuthSettingsInner().withEnabled(true), this);
}
@Override
@SuppressWarnings("unchecked")
public FluentImplT withoutAuthentication() {
this.authentication.inner().withEnabled(false);
authenticationToUpdate = true;
return (FluentImplT) this;
}
@Override
@SuppressWarnings("unchecked")
public FluentImplT withContainerLoggingEnabled(int quotaInMB, int retentionDays) {
return updateDiagnosticLogsConfiguration()
.withWebServerLogging()
.withWebServerLogsStoredOnFileSystem()
.withWebServerFileSystemQuotaInMB(quotaInMB)
.withLogRetentionDays(retentionDays)
.attach();
}
@Override
public FluentImplT withContainerLoggingEnabled() {
return withContainerLoggingEnabled(35, 0);
}
@Override
@SuppressWarnings("unchecked")
public FluentImplT withContainerLoggingDisabled() {
return updateDiagnosticLogsConfiguration().withoutWebServerLogging().attach();
}
@Override
@SuppressWarnings("unchecked")
public FluentImplT withSystemAssignedManagedServiceIdentity() {
this.webAppMsiHandler.withLocalManagedServiceIdentity();
return (FluentImplT) this;
}
@Override
@SuppressWarnings("unchecked")
public FluentImplT withoutSystemAssignedManagedServiceIdentity() {
this.webAppMsiHandler.withoutLocalManagedServiceIdentity();
return (FluentImplT) this;
}
@Override
@SuppressWarnings("unchecked")
public FluentImplT withUserAssignedManagedServiceIdentity() {
return (FluentImplT) this;
}
@Override
@SuppressWarnings("unchecked")
public FluentImplT withSystemAssignedIdentityBasedAccessTo(final String resourceId, final BuiltInRole role) {
this.webAppMsiHandler.withAccessTo(resourceId, role);
return (FluentImplT) this;
}
@Override
@SuppressWarnings("unchecked")
public FluentImplT withSystemAssignedIdentityBasedAccessToCurrentResourceGroup(final BuiltInRole role) {
this.webAppMsiHandler.withAccessToCurrentResourceGroup(role);
return (FluentImplT) this;
}
@Override
@SuppressWarnings("unchecked")
public FluentImplT withSystemAssignedIdentityBasedAccessTo(final String resourceId, final String roleDefinitionId) {
this.webAppMsiHandler.withAccessTo(resourceId, roleDefinitionId);
return (FluentImplT) this;
}
@Override
@SuppressWarnings("unchecked")
public FluentImplT withSystemAssignedIdentityBasedAccessToCurrentResourceGroup(final String roleDefinitionId) {
this.webAppMsiHandler.withAccessToCurrentResourceGroup(roleDefinitionId);
return (FluentImplT) this;
}
@Override
@SuppressWarnings("unchecked")
public FluentImplT withNewUserAssignedManagedServiceIdentity(Creatable<Identity> creatableIdentity) {
this.webAppMsiHandler.withNewExternalManagedServiceIdentity(creatableIdentity);
return (FluentImplT) this;
}
@Override
@SuppressWarnings("unchecked")
public FluentImplT withExistingUserAssignedManagedServiceIdentity(Identity identity) {
this.webAppMsiHandler.withExistingExternalManagedServiceIdentity(identity);
return (FluentImplT) this;
}
@Override
@SuppressWarnings("unchecked")
public FluentImplT withoutUserAssignedManagedServiceIdentity(String identityId) {
this.webAppMsiHandler.withoutExternalManagedServiceIdentity(identityId);
return (FluentImplT) this;
}
@Override
public WebAppDiagnosticLogsImpl<FluentT, FluentImplT> defineDiagnosticLogsConfiguration() {
if (diagnosticLogs == null) {
return new WebAppDiagnosticLogsImpl<>(new SiteLogsConfigInner(), this);
} else {
return diagnosticLogs;
}
}
@Override
public WebAppDiagnosticLogsImpl<FluentT, FluentImplT> updateDiagnosticLogsConfiguration() {
return defineDiagnosticLogsConfiguration();
}
@Override
public ManagedServiceIdentity identity() {
return webSiteBase.identity();
}
@Override
public boolean hyperV() {
return webSiteBase.hyperV();
}
@Override
public HostingEnvironmentProfile hostingEnvironmentProfile() {
return webSiteBase.hostingEnvironmentProfile();
}
@Override
public Set<String> clientCertExclusionPaths() {
return webSiteBase.clientCertExclusionPaths();
}
@Override
public Set<String> possibleOutboundIpAddresses() {
return webSiteBase.possibleOutboundIpAddresses();
}
@Override
public int dailyMemoryTimeQuota() {
return webSiteBase.dailyMemoryTimeQuota();
}
@Override
public OffsetDateTime suspendedTill() {
return webSiteBase.suspendedTill();
}
@Override
public int maxNumberOfWorkers() {
return webSiteBase.maxNumberOfWorkers();
}
@Override
public SlotSwapStatus slotSwapStatus() {
return webSiteBase.slotSwapStatus();
}
@Override
public RedundancyMode redundancyMode() {
return webSiteBase.redundancyMode();
}
@Override
public UUID inProgressOperationId() {
return webSiteBase.inProgressOperationId();
}
private static class PipedInputStreamWithCallback extends PipedInputStream {
private Runnable callback;
private void addCallback(Runnable action) {
this.callback = action;
}
@Override
public void close() throws IOException {
callback.run();
super.close();
}
}
} | class WebAppBaseImpl<FluentT extends WebAppBase, FluentImplT extends WebAppBaseImpl<FluentT, FluentImplT>>
extends GroupableResourceImpl<FluentT, SiteInner, FluentImplT, AppServiceManager>
implements WebAppBase,
WebAppBase.Definition<FluentT>,
WebAppBase.Update<FluentT>,
WebAppBase.UpdateStages.WithWebContainer<FluentT> {
private final ClientLogger logger = new ClientLogger(getClass());
private static final Map<AzureEnvironment, String> DNS_MAP =
new HashMap<AzureEnvironment, String>() {
{
put(AzureEnvironment.AZURE, "azurewebsites.net");
put(AzureEnvironment.AZURE_CHINA, "chinacloudsites.cn");
put(AzureEnvironment.AZURE_GERMANY, "azurewebsites.de");
put(AzureEnvironment.AZURE_US_GOVERNMENT, "azurewebsites.us");
}
};
SiteConfigResourceInner siteConfig;
KuduClient kuduClient;
WebSiteBase webSiteBase;
private Map<String, HostnameSslState> hostNameSslStateMap;
private TreeMap<String, HostnameBindingImpl<FluentT, FluentImplT>> hostNameBindingsToCreate;
private List<String> hostNameBindingsToDelete;
private TreeMap<String, HostnameSslBindingImpl<FluentT, FluentImplT>> sslBindingsToCreate;
protected Map<String, String> appSettingsToAdd;
protected List<String> appSettingsToRemove;
private Map<String, Boolean> appSettingStickiness;
private Map<String, ConnStringValueTypePair> connectionStringsToAdd;
private List<String> connectionStringsToRemove;
private Map<String, Boolean> connectionStringStickiness;
private WebAppSourceControlImpl<FluentT, FluentImplT> sourceControl;
private boolean sourceControlToDelete;
private WebAppAuthenticationImpl<FluentT, FluentImplT> authentication;
private boolean authenticationToUpdate;
private WebAppDiagnosticLogsImpl<FluentT, FluentImplT> diagnosticLogs;
private boolean diagnosticLogsToUpdate;
private FunctionalTaskItem msiHandler;
private boolean isInCreateMode;
private WebAppMsiHandler<FluentT, FluentImplT> webAppMsiHandler;
WebAppBaseImpl(
String name,
SiteInner innerObject,
SiteConfigResourceInner siteConfig,
SiteLogsConfigInner logConfig,
AppServiceManager manager) {
super(name, innerObject, manager);
if (innerObject != null && innerObject.kind() != null) {
innerObject.withKind(innerObject.kind().replace(";", ","));
}
this.siteConfig = siteConfig;
if (logConfig != null) {
this.diagnosticLogs = new WebAppDiagnosticLogsImpl<>(logConfig, this);
}
webAppMsiHandler = new WebAppMsiHandler<>(manager.authorizationManager(), this);
normalizeProperties();
isInCreateMode = inner() == null || inner().id() == null;
if (!isInCreateMode) {
initializeKuduClient();
}
}
public boolean isInCreateMode() {
return isInCreateMode;
}
private void initializeKuduClient() {
if (kuduClient == null) {
kuduClient = new KuduClient(this);
}
}
@Override
public void setInner(SiteInner innerObject) {
if (innerObject.kind() != null) {
innerObject.withKind(innerObject.kind().replace(";", ","));
}
super.setInner(innerObject);
}
RoleAssignmentHelper.IdProvider idProvider() {
return new RoleAssignmentHelper.IdProvider() {
@Override
public String principalId() {
if (inner() != null && inner().identity() != null) {
return inner().identity().principalId();
} else {
return null;
}
}
@Override
public String resourceId() {
if (inner() != null) {
return inner().id();
} else {
return null;
}
}
};
}
@Override
public String state() {
return webSiteBase.state();
}
@Override
public Set<String> hostnames() {
return webSiteBase.hostnames();
}
@Override
public String repositorySiteName() {
return webSiteBase.repositorySiteName();
}
@Override
public UsageState usageState() {
return webSiteBase.usageState();
}
@Override
public boolean enabled() {
return webSiteBase.enabled();
}
@Override
public Set<String> enabledHostNames() {
return webSiteBase.enabledHostNames();
}
@Override
public SiteAvailabilityState availabilityState() {
return webSiteBase.availabilityState();
}
@Override
public Map<String, HostnameSslState> hostnameSslStates() {
return Collections.unmodifiableMap(hostNameSslStateMap);
}
@Override
public String appServicePlanId() {
return webSiteBase.appServicePlanId();
}
@Override
public OffsetDateTime lastModifiedTime() {
return webSiteBase.lastModifiedTime();
}
@Override
public Set<String> trafficManagerHostNames() {
return webSiteBase.trafficManagerHostNames();
}
@Override
public boolean scmSiteAlsoStopped() {
return webSiteBase.scmSiteAlsoStopped();
}
@Override
public String targetSwapSlot() {
return webSiteBase.targetSwapSlot();
}
@Override
public boolean clientAffinityEnabled() {
return webSiteBase.clientAffinityEnabled();
}
@Override
public boolean clientCertEnabled() {
return webSiteBase.clientCertEnabled();
}
@Override
public boolean hostnamesDisabled() {
return webSiteBase.hostnamesDisabled();
}
@Override
public Set<String> outboundIPAddresses() {
return webSiteBase.outboundIPAddresses();
}
@Override
public int containerSize() {
return webSiteBase.containerSize();
}
@Override
public CloningInfo cloningInfo() {
return webSiteBase.cloningInfo();
}
@Override
public boolean isDefaultContainer() {
return webSiteBase.isDefaultContainer();
}
@Override
public String defaultHostname() {
if (inner().defaultHostname() != null) {
return inner().defaultHostname();
} else {
AzureEnvironment environment = manager().environment();
String dns = DNS_MAP.get(environment);
String leaf = name();
if (this instanceof DeploymentSlotBaseImpl<?, ?, ?, ?, ?>) {
leaf = ((DeploymentSlotBaseImpl<?, ?, ?, ?, ?>) this).parent().name() + "-" + leaf;
}
return leaf + "." + dns;
}
}
@Override
public List<String> defaultDocuments() {
if (siteConfig == null) {
return null;
}
return Collections.unmodifiableList(siteConfig.defaultDocuments());
}
@Override
public NetFrameworkVersion netFrameworkVersion() {
if (siteConfig == null) {
return null;
}
return NetFrameworkVersion.fromString(siteConfig.netFrameworkVersion());
}
@Override
public PhpVersion phpVersion() {
if (siteConfig == null || siteConfig.phpVersion() == null) {
return PhpVersion.OFF;
}
return PhpVersion.fromString(siteConfig.phpVersion());
}
@Override
public PythonVersion pythonVersion() {
if (siteConfig == null || siteConfig.pythonVersion() == null) {
return PythonVersion.OFF;
}
return PythonVersion.fromString(siteConfig.pythonVersion());
}
@Override
public String nodeVersion() {
if (siteConfig == null) {
return null;
}
return siteConfig.nodeVersion();
}
@Override
public boolean remoteDebuggingEnabled() {
if (siteConfig == null) {
return false;
}
return Utils.toPrimitiveBoolean(siteConfig.remoteDebuggingEnabled());
}
@Override
public RemoteVisualStudioVersion remoteDebuggingVersion() {
if (siteConfig == null) {
return null;
}
return RemoteVisualStudioVersion.fromString(siteConfig.remoteDebuggingVersion());
}
@Override
public boolean webSocketsEnabled() {
if (siteConfig == null) {
return false;
}
return Utils.toPrimitiveBoolean(siteConfig.webSocketsEnabled());
}
@Override
public boolean alwaysOn() {
if (siteConfig == null) {
return false;
}
return Utils.toPrimitiveBoolean(siteConfig.alwaysOn());
}
@Override
public JavaVersion javaVersion() {
if (siteConfig == null || siteConfig.javaVersion() == null) {
return JavaVersion.OFF;
}
return JavaVersion.fromString(siteConfig.javaVersion());
}
@Override
public String javaContainer() {
if (siteConfig == null) {
return null;
}
return siteConfig.javaContainer();
}
@Override
public String javaContainerVersion() {
if (siteConfig == null) {
return null;
}
return siteConfig.javaContainerVersion();
}
@Override
public ManagedPipelineMode managedPipelineMode() {
if (siteConfig == null) {
return null;
}
return siteConfig.managedPipelineMode();
}
@Override
public PlatformArchitecture platformArchitecture() {
if (siteConfig.use32BitWorkerProcess()) {
return PlatformArchitecture.X86;
} else {
return PlatformArchitecture.X64;
}
}
@Override
public String linuxFxVersion() {
if (siteConfig == null) {
return null;
}
return siteConfig.linuxFxVersion();
}
@Override
public String autoSwapSlotName() {
if (siteConfig == null) {
return null;
}
return siteConfig.autoSwapSlotName();
}
@Override
public boolean httpsOnly() {
return webSiteBase.httpsOnly();
}
@Override
public FtpsState ftpsState() {
if (siteConfig == null) {
return null;
}
return siteConfig.ftpsState();
}
@Override
public List<VirtualApplication> virtualApplications() {
if (siteConfig == null) {
return null;
}
return siteConfig.virtualApplications();
}
@Override
public boolean http20Enabled() {
if (siteConfig == null) {
return false;
}
return Utils.toPrimitiveBoolean(siteConfig.http20Enabled());
}
@Override
public boolean localMySqlEnabled() {
if (siteConfig == null) {
return false;
}
return Utils.toPrimitiveBoolean(siteConfig.localMySqlEnabled());
}
@Override
public ScmType scmType() {
if (siteConfig == null) {
return null;
}
return siteConfig.scmType();
}
@Override
public String documentRoot() {
if (siteConfig == null) {
return null;
}
return siteConfig.documentRoot();
}
@Override
public SupportedTlsVersions minTlsVersion() {
if (siteConfig == null) {
return null;
}
return siteConfig.minTlsVersion();
}
@Override
public OperatingSystem operatingSystem() {
if (inner().kind() != null && inner().kind().toLowerCase(Locale.ROOT).contains("linux")) {
return OperatingSystem.LINUX;
} else {
return OperatingSystem.WINDOWS;
}
}
@Override
public String systemAssignedManagedServiceIdentityTenantId() {
if (inner().identity() == null) {
return null;
}
return inner().identity().tenantId();
}
@Override
public String systemAssignedManagedServiceIdentityPrincipalId() {
if (inner().identity() == null) {
return null;
}
return inner().identity().principalId();
}
@Override
public Set<String> userAssignedManagedServiceIdentityIds() {
if (inner().identity() == null) {
return null;
}
return inner().identity().userAssignedIdentities().keySet();
}
@Override
public WebAppDiagnosticLogsImpl<FluentT, FluentImplT> diagnosticLogsConfig() {
return diagnosticLogs;
}
@Override
public InputStream streamApplicationLogs() {
return pipeObservableToInputStream(streamApplicationLogsAsync());
}
@Override
public Flux<String> streamApplicationLogsAsync() {
return kuduClient.streamApplicationLogsAsync();
}
@Override
public InputStream streamHttpLogs() {
return pipeObservableToInputStream(streamHttpLogsAsync());
}
@Override
public Flux<String> streamHttpLogsAsync() {
return kuduClient.streamHttpLogsAsync();
}
@Override
public InputStream streamTraceLogs() {
return pipeObservableToInputStream(streamTraceLogsAsync());
}
@Override
public Flux<String> streamTraceLogsAsync() {
return kuduClient.streamTraceLogsAsync();
}
@Override
public InputStream streamDeploymentLogs() {
return pipeObservableToInputStream(streamDeploymentLogsAsync());
}
@Override
public Flux<String> streamDeploymentLogsAsync() {
return kuduClient.streamDeploymentLogsAsync();
}
@Override
public InputStream streamAllLogs() {
return pipeObservableToInputStream(streamAllLogsAsync());
}
@Override
public Flux<String> streamAllLogsAsync() {
return kuduClient.streamAllLogsAsync();
}
private InputStream pipeObservableToInputStream(Flux<String> observable) {
PipedInputStreamWithCallback in = new PipedInputStreamWithCallback();
final PipedOutputStream out = new PipedOutputStream();
try {
in.connect(out);
} catch (IOException e) {
throw logger.logExceptionAsError(new RuntimeException(e));
}
final Disposable subscription =
observable
.subscribeOn(Schedulers.elastic())
.subscribe(
s -> {
try {
out.write(s.getBytes(StandardCharsets.UTF_8));
out.write('\n');
out.flush();
} catch (IOException e) {
throw logger.logExceptionAsError(new RuntimeException(e));
}
});
in
.addCallback(
() -> {
subscription.dispose();
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
});
return in;
}
@Override
public Map<String, AppSetting> getAppSettings() {
return getAppSettingsAsync().block();
}
@Override
public Mono<Map<String, AppSetting>> getAppSettingsAsync() {
return Mono
.zip(
listAppSettings(),
listSlotConfigurations(),
(appSettingsInner, slotConfigs) ->
appSettingsInner
.properties()
.entrySet()
.stream()
.collect(
Collectors
.toMap(
Map.Entry::getKey,
entry ->
new AppSettingImpl(
entry.getKey(),
entry.getValue(),
slotConfigs.appSettingNames() != null
&& slotConfigs.appSettingNames().contains(entry.getKey())))));
}
@Override
public Map<String, ConnectionString> getConnectionStrings() {
return getConnectionStringsAsync().block();
}
@Override
public Mono<Map<String, ConnectionString>> getConnectionStringsAsync() {
return Mono
.zip(
listConnectionStrings(),
listSlotConfigurations(),
(connectionStringsInner, slotConfigs) ->
connectionStringsInner
.properties()
.entrySet()
.stream()
.collect(
Collectors
.toMap(
Map.Entry::getKey,
entry ->
new ConnectionStringImpl(
entry.getKey(),
entry.getValue(),
slotConfigs.connectionStringNames() != null
&& slotConfigs.connectionStringNames().contains(entry.getKey())))));
}
@Override
public WebAppAuthentication getAuthenticationConfig() {
return getAuthenticationConfigAsync().block();
}
@Override
public Mono<WebAppAuthentication> getAuthenticationConfigAsync() {
return getAuthentication()
.map(siteAuthSettingsInner -> new WebAppAuthenticationImpl<>(siteAuthSettingsInner, WebAppBaseImpl.this));
}
abstract Mono<SiteInner> createOrUpdateInner(SiteInner site);
abstract Mono<SiteInner> updateInner(SitePatchResourceInner siteUpdate);
abstract Mono<SiteInner> getInner();
abstract Mono<SiteConfigResourceInner> getConfigInner();
abstract Mono<SiteConfigResourceInner> createOrUpdateSiteConfig(SiteConfigResourceInner siteConfig);
abstract Mono<Void> deleteHostnameBinding(String hostname);
abstract Mono<StringDictionaryInner> listAppSettings();
abstract Mono<StringDictionaryInner> updateAppSettings(StringDictionaryInner inner);
abstract Mono<ConnectionStringDictionaryInner> listConnectionStrings();
abstract Mono<ConnectionStringDictionaryInner> updateConnectionStrings(ConnectionStringDictionaryInner inner);
abstract Mono<SlotConfigNamesResourceInner> listSlotConfigurations();
abstract Mono<SlotConfigNamesResourceInner> updateSlotConfigurations(SlotConfigNamesResourceInner inner);
abstract Mono<SiteSourceControlInner> createOrUpdateSourceControl(SiteSourceControlInner inner);
abstract Mono<Void> deleteSourceControl();
abstract Mono<SiteAuthSettingsInner> updateAuthentication(SiteAuthSettingsInner inner);
abstract Mono<SiteAuthSettingsInner> getAuthentication();
abstract Mono<MSDeployStatusInner> createMSDeploy(MSDeploy msDeployInner);
abstract Mono<SiteLogsConfigInner> updateDiagnosticLogsConfig(SiteLogsConfigInner siteLogsConfigInner);
@Override
public void beforeGroupCreateOrUpdate() {
if (hostNameSslStateMap.size() > 0) {
inner().withHostnameSslStates(new ArrayList<>(hostNameSslStateMap.values()));
}
IndexableTaskItem rootTaskItem =
wrapTask(
context -> {
return submitHostNameBindings()
.flatMap(fluentT -> submitSslBindings(fluentT.inner()));
});
IndexableTaskItem lastTaskItem = rootTaskItem;
lastTaskItem = sequentialTask(lastTaskItem, context -> submitSiteConfig());
lastTaskItem =
sequentialTask(
lastTaskItem,
context ->
submitMetadata()
.flatMap(ignored -> submitAppSettings().mergeWith(submitConnectionStrings()).last())
.flatMap(ignored -> submitStickiness()));
lastTaskItem =
sequentialTask(
lastTaskItem,
context -> submitSourceControlToDelete().flatMap(ignored -> submitSourceControlToCreate()));
lastTaskItem = sequentialTask(lastTaskItem, context -> submitAuthentication());
lastTaskItem = sequentialTask(lastTaskItem, context -> submitLogConfiguration());
if (msiHandler != null) {
sequentialTask(lastTaskItem, msiHandler);
}
addPostRunDependent(rootTaskItem);
}
private static IndexableTaskItem wrapTask(FunctionalTaskItem taskItem) {
return IndexableTaskItem.create(taskItem);
}
private static IndexableTaskItem sequentialTask(IndexableTaskItem taskItem1, FunctionalTaskItem taskItem2) {
IndexableTaskItem taskItem = IndexableTaskItem.create(taskItem2);
taskItem1.addPostRunDependent(taskItem);
return taskItem;
}
@Override
@SuppressWarnings("unchecked")
public Mono<FluentT> createResourceAsync() {
this.webAppMsiHandler.processCreatedExternalIdentities();
this.webAppMsiHandler.handleExternalIdentities();
return submitSite(inner())
.map(
siteInner -> {
setInner(siteInner);
return (FluentT) WebAppBaseImpl.this;
});
}
@Override
@SuppressWarnings("unchecked")
public Mono<FluentT> updateResourceAsync() {
SiteInner siteInner = this.inner();
SitePatchResourceInner siteUpdate = new SitePatchResourceInner();
siteUpdate.withHostnameSslStates(siteInner.hostnameSslStates());
siteUpdate.withKind(siteInner.kind());
siteUpdate.withEnabled(siteInner.enabled());
siteUpdate.withServerFarmId(siteInner.serverFarmId());
siteUpdate.withReserved(siteInner.reserved());
siteUpdate.withIsXenon(siteInner.isXenon());
siteUpdate.withHyperV(siteInner.hyperV());
siteUpdate.withScmSiteAlsoStopped(siteInner.scmSiteAlsoStopped());
siteUpdate.withHostingEnvironmentProfile(siteInner.hostingEnvironmentProfile());
siteUpdate.withClientAffinityEnabled(siteInner.clientAffinityEnabled());
siteUpdate.withClientCertEnabled(siteInner.clientCertEnabled());
siteUpdate.withClientCertExclusionPaths(siteInner.clientCertExclusionPaths());
siteUpdate.withHostNamesDisabled(siteInner.hostNamesDisabled());
siteUpdate.withContainerSize(siteInner.containerSize());
siteUpdate.withDailyMemoryTimeQuota(siteInner.dailyMemoryTimeQuota());
siteUpdate.withCloningInfo(siteInner.cloningInfo());
siteUpdate.withHttpsOnly(siteInner.httpsOnly());
siteUpdate.withRedundancyMode(siteInner.redundancyMode());
this.webAppMsiHandler.handleExternalIdentities(siteUpdate);
return submitSite(siteUpdate)
.map(
siteInner1 -> {
setInner(siteInner1);
webAppMsiHandler.clear();
return (FluentT) WebAppBaseImpl.this;
});
}
@Override
public Mono<Void> afterPostRunAsync(final boolean isGroupFaulted) {
if (!isGroupFaulted) {
isInCreateMode = false;
initializeKuduClient();
}
return Mono
.fromCallable(
() -> {
normalizeProperties();
return null;
});
}
Mono<SiteInner> submitSite(final SiteInner site) {
site.withSiteConfig(new SiteConfigInner());
return submitSiteWithoutSiteConfig(site);
}
Mono<SiteInner> submitSiteWithoutSiteConfig(final SiteInner site) {
return createOrUpdateInner(site)
.map(
siteInner -> {
site.withSiteConfig(null);
return siteInner;
});
}
Mono<SiteInner> submitSite(final SitePatchResourceInner siteUpdate) {
return updateInner(siteUpdate)
.map(
siteInner -> {
siteInner.withSiteConfig(null);
return siteInner;
});
}
@SuppressWarnings("unchecked")
Mono<FluentT> submitHostNameBindings() {
final List<Mono<HostnameBinding>> bindingObservables = new ArrayList<>();
for (HostnameBindingImpl<FluentT, FluentImplT> binding : hostNameBindingsToCreate.values()) {
bindingObservables.add(Utils.<HostnameBinding>rootResource(binding.createAsync().last()));
}
for (String binding : hostNameBindingsToDelete) {
bindingObservables.add(deleteHostnameBinding(binding).then(Mono.empty()));
}
if (bindingObservables.isEmpty()) {
return Mono.just((FluentT) this);
} else {
return Flux
.zip(bindingObservables, ignored -> WebAppBaseImpl.this)
.last()
.onErrorResume(
throwable -> {
if (throwable instanceof HttpResponseException
&& ((HttpResponseException) throwable).getResponse().getStatusCode() == 400) {
return submitSite(inner())
.flatMap(
ignored -> Flux.zip(bindingObservables, ignored1 -> WebAppBaseImpl.this).last());
} else {
return Mono.error(throwable);
}
})
.flatMap(WebAppBaseImpl::refreshAsync);
}
}
Mono<Indexable> submitSslBindings(final SiteInner site) {
List<Mono<AppServiceCertificate>> certs = new ArrayList<>();
for (final HostnameSslBindingImpl<FluentT, FluentImplT> binding : sslBindingsToCreate.values()) {
certs.add(binding.newCertificate());
hostNameSslStateMap.put(binding.inner().name(), binding.inner().withToUpdate(true));
}
if (certs.isEmpty()) {
return Mono.just((Indexable) this);
} else {
site.withHostnameSslStates(new ArrayList<>(hostNameSslStateMap.values()));
return Flux
.zip(certs, ignored -> site)
.last()
.flatMap(this::createOrUpdateInner)
.map(
siteInner -> {
setInner(siteInner);
return WebAppBaseImpl.this;
});
}
}
Mono<Indexable> submitSiteConfig() {
if (siteConfig == null) {
return Mono.just((Indexable) this);
}
return createOrUpdateSiteConfig(siteConfig)
.flatMap(
returnedSiteConfig -> {
siteConfig = returnedSiteConfig;
return Mono.just((Indexable) WebAppBaseImpl.this);
});
}
Mono<Indexable> submitAppSettings() {
Mono<Indexable> observable = Mono.just((Indexable) this);
if (!appSettingsToAdd.isEmpty() || !appSettingsToRemove.isEmpty()) {
observable =
listAppSettings()
.switchIfEmpty(Mono.just(new StringDictionaryInner()))
.flatMap(
stringDictionaryInner -> {
if (stringDictionaryInner.properties() == null) {
stringDictionaryInner.withProperties(new HashMap<String, String>());
}
for (String appSettingKey : appSettingsToRemove) {
stringDictionaryInner.properties().remove(appSettingKey);
}
stringDictionaryInner.properties().putAll(appSettingsToAdd);
return updateAppSettings(stringDictionaryInner);
})
.map(ignored -> WebAppBaseImpl.this);
}
return observable;
}
Mono<Indexable> submitMetadata() {
return Mono.just((Indexable) this);
}
Mono<Indexable> submitConnectionStrings() {
Mono<Indexable> observable = Mono.just((Indexable) this);
if (!connectionStringsToAdd.isEmpty() || !connectionStringsToRemove.isEmpty()) {
observable =
listConnectionStrings()
.switchIfEmpty(Mono.just(new ConnectionStringDictionaryInner()))
.flatMap(
dictionaryInner -> {
if (dictionaryInner.properties() == null) {
dictionaryInner.withProperties(new HashMap<String, ConnStringValueTypePair>());
}
for (String connectionString : connectionStringsToRemove) {
dictionaryInner.properties().remove(connectionString);
}
dictionaryInner.properties().putAll(connectionStringsToAdd);
return updateConnectionStrings(dictionaryInner);
})
.map(ignored -> WebAppBaseImpl.this);
}
return observable;
}
Mono<Indexable> submitStickiness() {
Mono<Indexable> observable = Mono.just((Indexable) this);
if (!appSettingStickiness.isEmpty() || !connectionStringStickiness.isEmpty()) {
observable =
listSlotConfigurations()
.switchIfEmpty(Mono.just(new SlotConfigNamesResourceInner()))
.flatMap(
slotConfigNamesResourceInner -> {
if (slotConfigNamesResourceInner.appSettingNames() == null) {
slotConfigNamesResourceInner.withAppSettingNames(new ArrayList<>());
}
if (slotConfigNamesResourceInner.connectionStringNames() == null) {
slotConfigNamesResourceInner.withConnectionStringNames(new ArrayList<>());
}
Set<String> stickyAppSettingKeys =
new HashSet<>(slotConfigNamesResourceInner.appSettingNames());
Set<String> stickyConnectionStringNames =
new HashSet<>(slotConfigNamesResourceInner.connectionStringNames());
for (Map.Entry<String, Boolean> stickiness : appSettingStickiness.entrySet()) {
if (stickiness.getValue()) {
stickyAppSettingKeys.add(stickiness.getKey());
} else {
stickyAppSettingKeys.remove(stickiness.getKey());
}
}
for (Map.Entry<String, Boolean> stickiness : connectionStringStickiness.entrySet()) {
if (stickiness.getValue()) {
stickyConnectionStringNames.add(stickiness.getKey());
} else {
stickyConnectionStringNames.remove(stickiness.getKey());
}
}
slotConfigNamesResourceInner.withAppSettingNames(new ArrayList<>(stickyAppSettingKeys));
slotConfigNamesResourceInner
.withConnectionStringNames(new ArrayList<>(stickyConnectionStringNames));
return updateSlotConfigurations(slotConfigNamesResourceInner);
})
.map(ignored -> WebAppBaseImpl.this);
}
return observable;
}
Mono<Indexable> submitSourceControlToCreate() {
if (sourceControl == null || sourceControlToDelete) {
return Mono.just((Indexable) this);
}
return sourceControl
.registerGithubAccessToken()
.then(createOrUpdateSourceControl(sourceControl.inner()))
.delayElement(SdkContext.getDelayDuration(Duration.ofSeconds(30)))
.map(ignored -> WebAppBaseImpl.this);
}
Mono<Indexable> submitSourceControlToDelete() {
if (!sourceControlToDelete) {
return Mono.just((Indexable) this);
}
return deleteSourceControl().map(ignored -> WebAppBaseImpl.this);
}
Mono<Indexable> submitAuthentication() {
if (!authenticationToUpdate) {
return Mono.just((Indexable) this);
}
return updateAuthentication(authentication.inner())
.map(
siteAuthSettingsInner -> {
WebAppBaseImpl.this.authentication =
new WebAppAuthenticationImpl<>(siteAuthSettingsInner, WebAppBaseImpl.this);
return WebAppBaseImpl.this;
});
}
Mono<Indexable> submitLogConfiguration() {
if (!diagnosticLogsToUpdate) {
return Mono.just((Indexable) this);
}
return updateDiagnosticLogsConfig(diagnosticLogs.inner())
.map(
siteLogsConfigInner -> {
WebAppBaseImpl.this.diagnosticLogs =
new WebAppDiagnosticLogsImpl<>(siteLogsConfigInner, WebAppBaseImpl.this);
return WebAppBaseImpl.this;
});
}
@Override
public WebDeploymentImpl<FluentT, FluentImplT> deploy() {
return new WebDeploymentImpl<>(this);
}
WebAppBaseImpl<FluentT, FluentImplT> withNewHostNameSslBinding(
final HostnameSslBindingImpl<FluentT, FluentImplT> hostNameSslBinding) {
sslBindingsToCreate.put(hostNameSslBinding.name(), hostNameSslBinding);
return this;
}
@SuppressWarnings("unchecked")
public FluentImplT withManagedHostnameBindings(AppServiceDomain domain, String... hostnames) {
for (String hostname : hostnames) {
if (hostname.equals("@") || hostname.equalsIgnoreCase(domain.name())) {
defineHostnameBinding()
.withAzureManagedDomain(domain)
.withSubDomain(hostname)
.withDnsRecordType(CustomHostnameDnsRecordType.A)
.attach();
} else {
defineHostnameBinding()
.withAzureManagedDomain(domain)
.withSubDomain(hostname)
.withDnsRecordType(CustomHostnameDnsRecordType.CNAME)
.attach();
}
}
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public HostnameBindingImpl<FluentT, FluentImplT> defineHostnameBinding() {
HostnameBindingInner inner = new HostnameBindingInner();
inner.withSiteName(name());
inner.withAzureResourceType(AzureResourceType.WEBSITE);
inner.withAzureResourceName(name());
inner.withHostnameType(HostnameType.VERIFIED);
return new HostnameBindingImpl<>(inner, (FluentImplT) this);
}
@SuppressWarnings("unchecked")
public FluentImplT withThirdPartyHostnameBinding(String domain, String... hostnames) {
for (String hostname : hostnames) {
defineHostnameBinding()
.withThirdPartyDomain(domain)
.withSubDomain(hostname)
.withDnsRecordType(CustomHostnameDnsRecordType.CNAME)
.attach();
}
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withoutHostnameBinding(String hostname) {
hostNameBindingsToDelete.add(hostname);
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withoutSslBinding(String hostname) {
if (hostNameSslStateMap.containsKey(hostname)) {
hostNameSslStateMap.get(hostname).withSslState(SslState.DISABLED).withToUpdate(true);
}
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
FluentImplT withHostNameBinding(final HostnameBindingImpl<FluentT, FluentImplT> hostNameBinding) {
this.hostNameBindingsToCreate.put(hostNameBinding.name(), hostNameBinding);
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withAppDisabledOnCreation() {
inner().withEnabled(false);
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withScmSiteAlsoStopped(boolean scmSiteAlsoStopped) {
inner().withScmSiteAlsoStopped(scmSiteAlsoStopped);
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withClientAffinityEnabled(boolean enabled) {
inner().withClientAffinityEnabled(enabled);
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withClientCertEnabled(boolean enabled) {
inner().withClientCertEnabled(enabled);
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public HostnameSslBindingImpl<FluentT, FluentImplT> defineSslBinding() {
return new HostnameSslBindingImpl<>(new HostnameSslState(), (FluentImplT) this);
}
@SuppressWarnings("unchecked")
public FluentImplT withNetFrameworkVersion(NetFrameworkVersion version) {
if (siteConfig == null) {
siteConfig = new SiteConfigResourceInner();
}
siteConfig.withNetFrameworkVersion(version.toString());
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withPhpVersion(PhpVersion version) {
if (siteConfig == null) {
siteConfig = new SiteConfigResourceInner();
}
siteConfig.withPhpVersion(version.toString());
return (FluentImplT) this;
}
public FluentImplT withoutPhp() {
return withPhpVersion(PhpVersion.fromString(""));
}
@SuppressWarnings("unchecked")
public FluentImplT withJavaVersion(JavaVersion version) {
if (siteConfig == null) {
siteConfig = new SiteConfigResourceInner();
}
siteConfig.withJavaVersion(version.toString());
return (FluentImplT) this;
}
public FluentImplT withoutJava() {
return withJavaVersion(JavaVersion.fromString("")).withWebContainer(WebContainer.fromString(""));
}
@SuppressWarnings("unchecked")
public FluentImplT withWebContainer(WebContainer webContainer) {
if (siteConfig == null) {
siteConfig = new SiteConfigResourceInner();
}
if (webContainer == null) {
siteConfig.withJavaContainer(null);
siteConfig.withJavaContainerVersion(null);
} else if (webContainer.toString().isEmpty()) {
siteConfig.withJavaContainer("");
siteConfig.withJavaContainerVersion("");
} else {
String[] containerInfo = webContainer.toString().split(" ");
siteConfig.withJavaContainer(containerInfo[0]);
siteConfig.withJavaContainerVersion(containerInfo[1]);
}
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withPythonVersion(PythonVersion version) {
if (siteConfig == null) {
siteConfig = new SiteConfigResourceInner();
}
siteConfig.withPythonVersion(version.toString());
return (FluentImplT) this;
}
public FluentImplT withoutPython() {
return withPythonVersion(PythonVersion.fromString(""));
}
@SuppressWarnings("unchecked")
public FluentImplT withPlatformArchitecture(PlatformArchitecture platform) {
if (siteConfig == null) {
siteConfig = new SiteConfigResourceInner();
}
siteConfig.withUse32BitWorkerProcess(platform.equals(PlatformArchitecture.X86));
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withWebSocketsEnabled(boolean enabled) {
if (siteConfig == null) {
siteConfig = new SiteConfigResourceInner();
}
siteConfig.withWebSocketsEnabled(enabled);
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withWebAppAlwaysOn(boolean alwaysOn) {
if (siteConfig == null) {
siteConfig = new SiteConfigResourceInner();
}
siteConfig.withAlwaysOn(alwaysOn);
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withManagedPipelineMode(ManagedPipelineMode managedPipelineMode) {
if (siteConfig == null) {
siteConfig = new SiteConfigResourceInner();
}
siteConfig.withManagedPipelineMode(managedPipelineMode);
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withAutoSwapSlotName(String slotName) {
if (siteConfig == null) {
siteConfig = new SiteConfigResourceInner();
}
siteConfig.withAutoSwapSlotName(slotName);
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withRemoteDebuggingEnabled(RemoteVisualStudioVersion remoteVisualStudioVersion) {
if (siteConfig == null) {
siteConfig = new SiteConfigResourceInner();
}
siteConfig.withRemoteDebuggingEnabled(true);
siteConfig.withRemoteDebuggingVersion(remoteVisualStudioVersion.toString());
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withRemoteDebuggingDisabled() {
if (siteConfig == null) {
siteConfig = new SiteConfigResourceInner();
}
siteConfig.withRemoteDebuggingEnabled(false);
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withDefaultDocument(String document) {
if (siteConfig == null) {
siteConfig = new SiteConfigResourceInner();
}
if (siteConfig.defaultDocuments() == null) {
siteConfig.withDefaultDocuments(new ArrayList<String>());
}
siteConfig.defaultDocuments().add(document);
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withDefaultDocuments(List<String> documents) {
if (siteConfig == null) {
siteConfig = new SiteConfigResourceInner();
}
if (siteConfig.defaultDocuments() == null) {
siteConfig.withDefaultDocuments(new ArrayList<>());
}
siteConfig.defaultDocuments().addAll(documents);
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withoutDefaultDocument(String document) {
if (siteConfig == null) {
siteConfig = new SiteConfigResourceInner();
}
if (siteConfig.defaultDocuments() != null) {
siteConfig.defaultDocuments().remove(document);
}
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withHttpsOnly(boolean httpsOnly) {
inner().withHttpsOnly(httpsOnly);
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withHttp20Enabled(boolean http20Enabled) {
if (siteConfig == null) {
siteConfig = new SiteConfigResourceInner();
}
siteConfig.withHttp20Enabled(http20Enabled);
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withFtpsState(FtpsState ftpsState) {
if (siteConfig == null) {
siteConfig = new SiteConfigResourceInner();
}
siteConfig.withFtpsState(ftpsState);
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withVirtualApplications(List<VirtualApplication> virtualApplications) {
if (siteConfig == null) {
siteConfig = new SiteConfigResourceInner();
}
siteConfig.withVirtualApplications(virtualApplications);
return (FluentImplT) this;
}
@Override
@SuppressWarnings("unchecked")
public FluentImplT withMinTlsVersion(SupportedTlsVersions minTlsVersion) {
if (siteConfig == null) {
siteConfig = new SiteConfigResourceInner();
}
siteConfig.withMinTlsVersion(minTlsVersion);
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withAppSetting(String key, String value) {
appSettingsToAdd.put(key, value);
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withAppSettings(Map<String, String> settings) {
appSettingsToAdd.putAll(settings);
return (FluentImplT) this;
}
public FluentImplT withStickyAppSetting(String key, String value) {
withAppSetting(key, value);
return withAppSettingStickiness(key, true);
}
@SuppressWarnings("unchecked")
public FluentImplT withStickyAppSettings(Map<String, String> settings) {
withAppSettings(settings);
for (String key : settings.keySet()) {
appSettingStickiness.put(key, true);
}
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withoutAppSetting(String key) {
appSettingsToRemove.add(key);
appSettingStickiness.remove(key);
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withAppSettingStickiness(String key, boolean sticky) {
appSettingStickiness.put(key, sticky);
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withConnectionString(String name, String value, ConnectionStringType type) {
connectionStringsToAdd.put(name, new ConnStringValueTypePair().withValue(value).withType(type));
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withStickyConnectionString(String name, String value, ConnectionStringType type) {
connectionStringsToAdd.put(name, new ConnStringValueTypePair().withValue(value).withType(type));
connectionStringStickiness.put(name, true);
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withoutConnectionString(String name) {
connectionStringsToRemove.add(name);
connectionStringStickiness.remove(name);
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withConnectionStringStickiness(String name, boolean stickiness) {
connectionStringStickiness.put(name, stickiness);
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
void withSourceControl(WebAppSourceControlImpl<FluentT, FluentImplT> sourceControl) {
this.sourceControl = sourceControl;
}
public WebAppSourceControlImpl<FluentT, FluentImplT> defineSourceControl() {
SiteSourceControlInner sourceControlInner = new SiteSourceControlInner();
return new WebAppSourceControlImpl<>(sourceControlInner, this);
}
@SuppressWarnings("unchecked")
public FluentImplT withLocalGitSourceControl() {
if (siteConfig == null) {
siteConfig = new SiteConfigResourceInner();
}
siteConfig.withScmType(ScmType.LOCAL_GIT);
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withoutSourceControl() {
sourceControlToDelete = true;
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
void withAuthentication(WebAppAuthenticationImpl<FluentT, FluentImplT> authentication) {
this.authentication = authentication;
authenticationToUpdate = true;
}
void withDiagnosticLogs(WebAppDiagnosticLogsImpl<FluentT, FluentImplT> diagnosticLogs) {
this.diagnosticLogs = diagnosticLogs;
diagnosticLogsToUpdate = true;
}
@Override
@SuppressWarnings("unchecked")
public Mono<FluentT> refreshAsync() {
return super
.refreshAsync()
.flatMap(
fluentT ->
getConfigInner()
.map(
returnedSiteConfig -> {
siteConfig = returnedSiteConfig;
return fluentT;
}));
}
@Override
protected Mono<SiteInner> getInnerAsync() {
return getInner();
}
@Override
public WebAppAuthenticationImpl<FluentT, FluentImplT> defineAuthentication() {
return new WebAppAuthenticationImpl<>(new SiteAuthSettingsInner().withEnabled(true), this);
}
@Override
@SuppressWarnings("unchecked")
public FluentImplT withoutAuthentication() {
this.authentication.inner().withEnabled(false);
authenticationToUpdate = true;
return (FluentImplT) this;
}
@Override
@SuppressWarnings("unchecked")
public FluentImplT withContainerLoggingEnabled(int quotaInMB, int retentionDays) {
return updateDiagnosticLogsConfiguration()
.withWebServerLogging()
.withWebServerLogsStoredOnFileSystem()
.withWebServerFileSystemQuotaInMB(quotaInMB)
.withLogRetentionDays(retentionDays)
.attach();
}
@Override
public FluentImplT withContainerLoggingEnabled() {
return withContainerLoggingEnabled(35, 0);
}
@Override
@SuppressWarnings("unchecked")
public FluentImplT withContainerLoggingDisabled() {
return updateDiagnosticLogsConfiguration().withoutWebServerLogging().attach();
}
@Override
@SuppressWarnings("unchecked")
public FluentImplT withSystemAssignedManagedServiceIdentity() {
this.webAppMsiHandler.withLocalManagedServiceIdentity();
return (FluentImplT) this;
}
@Override
@SuppressWarnings("unchecked")
public FluentImplT withoutSystemAssignedManagedServiceIdentity() {
this.webAppMsiHandler.withoutLocalManagedServiceIdentity();
return (FluentImplT) this;
}
@Override
@SuppressWarnings("unchecked")
public FluentImplT withUserAssignedManagedServiceIdentity() {
return (FluentImplT) this;
}
@Override
@SuppressWarnings("unchecked")
public FluentImplT withSystemAssignedIdentityBasedAccessTo(final String resourceId, final BuiltInRole role) {
this.webAppMsiHandler.withAccessTo(resourceId, role);
return (FluentImplT) this;
}
@Override
@SuppressWarnings("unchecked")
public FluentImplT withSystemAssignedIdentityBasedAccessToCurrentResourceGroup(final BuiltInRole role) {
this.webAppMsiHandler.withAccessToCurrentResourceGroup(role);
return (FluentImplT) this;
}
@Override
@SuppressWarnings("unchecked")
public FluentImplT withSystemAssignedIdentityBasedAccessTo(final String resourceId, final String roleDefinitionId) {
this.webAppMsiHandler.withAccessTo(resourceId, roleDefinitionId);
return (FluentImplT) this;
}
@Override
@SuppressWarnings("unchecked")
public FluentImplT withSystemAssignedIdentityBasedAccessToCurrentResourceGroup(final String roleDefinitionId) {
this.webAppMsiHandler.withAccessToCurrentResourceGroup(roleDefinitionId);
return (FluentImplT) this;
}
@Override
@SuppressWarnings("unchecked")
public FluentImplT withNewUserAssignedManagedServiceIdentity(Creatable<Identity> creatableIdentity) {
this.webAppMsiHandler.withNewExternalManagedServiceIdentity(creatableIdentity);
return (FluentImplT) this;
}
@Override
@SuppressWarnings("unchecked")
public FluentImplT withExistingUserAssignedManagedServiceIdentity(Identity identity) {
this.webAppMsiHandler.withExistingExternalManagedServiceIdentity(identity);
return (FluentImplT) this;
}
@Override
@SuppressWarnings("unchecked")
public FluentImplT withoutUserAssignedManagedServiceIdentity(String identityId) {
this.webAppMsiHandler.withoutExternalManagedServiceIdentity(identityId);
return (FluentImplT) this;
}
@Override
public WebAppDiagnosticLogsImpl<FluentT, FluentImplT> defineDiagnosticLogsConfiguration() {
if (diagnosticLogs == null) {
return new WebAppDiagnosticLogsImpl<>(new SiteLogsConfigInner(), this);
} else {
return diagnosticLogs;
}
}
@Override
public WebAppDiagnosticLogsImpl<FluentT, FluentImplT> updateDiagnosticLogsConfiguration() {
return defineDiagnosticLogsConfiguration();
}
@Override
public ManagedServiceIdentity identity() {
return webSiteBase.identity();
}
@Override
public boolean hyperV() {
return webSiteBase.hyperV();
}
@Override
public HostingEnvironmentProfile hostingEnvironmentProfile() {
return webSiteBase.hostingEnvironmentProfile();
}
@Override
public Set<String> clientCertExclusionPaths() {
return webSiteBase.clientCertExclusionPaths();
}
@Override
public Set<String> possibleOutboundIpAddresses() {
return webSiteBase.possibleOutboundIpAddresses();
}
@Override
public int dailyMemoryTimeQuota() {
return webSiteBase.dailyMemoryTimeQuota();
}
@Override
public OffsetDateTime suspendedTill() {
return webSiteBase.suspendedTill();
}
@Override
public int maxNumberOfWorkers() {
return webSiteBase.maxNumberOfWorkers();
}
@Override
public SlotSwapStatus slotSwapStatus() {
return webSiteBase.slotSwapStatus();
}
@Override
public RedundancyMode redundancyMode() {
return webSiteBase.redundancyMode();
}
private static class PipedInputStreamWithCallback extends PipedInputStream {
private Runnable callback;
private void addCallback(Runnable action) {
this.callback = action;
}
@Override
public void close() throws IOException {
callback.run();
super.close();
}
}
} |
Yes. Hence I keep it there. I.e., WebSiteBase init the variable (instead of previous code in this method), then logic remains same as before. | private void normalizeProperties() {
this.hostNameBindingsToDelete = new ArrayList<>();
this.appSettingsToAdd = new HashMap<>();
this.appSettingsToRemove = new ArrayList<>();
this.appSettingStickiness = new HashMap<>();
this.connectionStringsToAdd = new HashMap<>();
this.connectionStringsToRemove = new ArrayList<>();
this.connectionStringStickiness = new HashMap<>();
this.sourceControl = null;
this.sourceControlToDelete = false;
this.authenticationToUpdate = false;
this.diagnosticLogsToUpdate = false;
this.sslBindingsToCreate = new TreeMap<>();
this.msiHandler = null;
this.webSiteBase = new WebSiteBaseImpl(inner());
this.hostNameSslStateMap = new HashMap<>(this.webSiteBase.hostnameSslStates());
this.webAppMsiHandler.clear();
} | this.hostNameSslStateMap = new HashMap<>(this.webSiteBase.hostnameSslStates()); | private void normalizeProperties() {
this.hostNameBindingsToCreate = new TreeMap<>();
this.hostNameBindingsToDelete = new ArrayList<>();
this.appSettingsToAdd = new HashMap<>();
this.appSettingsToRemove = new ArrayList<>();
this.appSettingStickiness = new HashMap<>();
this.connectionStringsToAdd = new HashMap<>();
this.connectionStringsToRemove = new ArrayList<>();
this.connectionStringStickiness = new HashMap<>();
this.sourceControl = null;
this.sourceControlToDelete = false;
this.authenticationToUpdate = false;
this.diagnosticLogsToUpdate = false;
this.sslBindingsToCreate = new TreeMap<>();
this.msiHandler = null;
this.webSiteBase = new WebSiteBaseImpl(inner());
this.hostNameSslStateMap = new HashMap<>(this.webSiteBase.hostnameSslStates());
this.webAppMsiHandler.clear();
} | class WebAppBaseImpl<FluentT extends WebAppBase, FluentImplT extends WebAppBaseImpl<FluentT, FluentImplT>>
extends GroupableResourceImpl<FluentT, SiteInner, FluentImplT, AppServiceManager>
implements WebAppBase,
WebAppBase.Definition<FluentT>,
WebAppBase.Update<FluentT>,
WebAppBase.UpdateStages.WithWebContainer<FluentT> {
private final ClientLogger logger = new ClientLogger(getClass());
private static final Map<AzureEnvironment, String> DNS_MAP =
new HashMap<AzureEnvironment, String>() {
{
put(AzureEnvironment.AZURE, "azurewebsites.net");
put(AzureEnvironment.AZURE_CHINA, "chinacloudsites.cn");
put(AzureEnvironment.AZURE_GERMANY, "azurewebsites.de");
put(AzureEnvironment.AZURE_US_GOVERNMENT, "azurewebsites.us");
}
};
SiteConfigResourceInner siteConfig;
KuduClient kuduClient;
WebSiteBase webSiteBase;
private Map<String, HostnameSslState> hostNameSslStateMap;
private TreeMap<String, HostnameBindingImpl<FluentT, FluentImplT>> hostNameBindingsToCreate;
private List<String> hostNameBindingsToDelete;
private TreeMap<String, HostnameSslBindingImpl<FluentT, FluentImplT>> sslBindingsToCreate;
protected Map<String, String> appSettingsToAdd;
protected List<String> appSettingsToRemove;
private Map<String, Boolean> appSettingStickiness;
private Map<String, ConnStringValueTypePair> connectionStringsToAdd;
private List<String> connectionStringsToRemove;
private Map<String, Boolean> connectionStringStickiness;
private WebAppSourceControlImpl<FluentT, FluentImplT> sourceControl;
private boolean sourceControlToDelete;
private WebAppAuthenticationImpl<FluentT, FluentImplT> authentication;
private boolean authenticationToUpdate;
private WebAppDiagnosticLogsImpl<FluentT, FluentImplT> diagnosticLogs;
private boolean diagnosticLogsToUpdate;
private FunctionalTaskItem msiHandler;
private boolean isInCreateMode;
private WebAppMsiHandler<FluentT, FluentImplT> webAppMsiHandler;
WebAppBaseImpl(
String name,
SiteInner innerObject,
SiteConfigResourceInner siteConfig,
SiteLogsConfigInner logConfig,
AppServiceManager manager) {
super(name, innerObject, manager);
if (innerObject != null && innerObject.kind() != null) {
innerObject.withKind(innerObject.kind().replace(";", ","));
}
this.siteConfig = siteConfig;
if (logConfig != null) {
this.diagnosticLogs = new WebAppDiagnosticLogsImpl<>(logConfig, this);
}
webAppMsiHandler = new WebAppMsiHandler<>(manager.authorizationManager(), this);
normalizeProperties();
isInCreateMode = inner() == null || inner().id() == null;
if (!isInCreateMode) {
initializeKuduClient();
}
}
public boolean isInCreateMode() {
return isInCreateMode;
}
private void initializeKuduClient() {
if (kuduClient == null) {
kuduClient = new KuduClient(this);
}
}
@Override
public void setInner(SiteInner innerObject) {
if (innerObject.kind() != null) {
innerObject.withKind(innerObject.kind().replace(";", ","));
}
super.setInner(innerObject);
}
RoleAssignmentHelper.IdProvider idProvider() {
return new RoleAssignmentHelper.IdProvider() {
@Override
public String principalId() {
if (inner() != null && inner().identity() != null) {
return inner().identity().principalId();
} else {
return null;
}
}
@Override
public String resourceId() {
if (inner() != null) {
return inner().id();
} else {
return null;
}
}
};
}
@Override
public String state() {
return webSiteBase.state();
}
@Override
public Set<String> hostnames() {
return webSiteBase.hostnames();
}
@Override
public String repositorySiteName() {
return webSiteBase.repositorySiteName();
}
@Override
public UsageState usageState() {
return webSiteBase.usageState();
}
@Override
public boolean enabled() {
return webSiteBase.enabled();
}
@Override
public Set<String> enabledHostNames() {
return webSiteBase.enabledHostNames();
}
@Override
public SiteAvailabilityState availabilityState() {
return webSiteBase.availabilityState();
}
@Override
public Map<String, HostnameSslState> hostnameSslStates() {
return Collections.unmodifiableMap(hostNameSslStateMap);
}
@Override
public String appServicePlanId() {
return webSiteBase.appServicePlanId();
}
@Override
public OffsetDateTime lastModifiedTime() {
return webSiteBase.lastModifiedTime();
}
@Override
public Set<String> trafficManagerHostNames() {
return webSiteBase.trafficManagerHostNames();
}
@Override
public boolean scmSiteAlsoStopped() {
return webSiteBase.scmSiteAlsoStopped();
}
@Override
public String targetSwapSlot() {
return webSiteBase.targetSwapSlot();
}
@Override
public boolean clientAffinityEnabled() {
return webSiteBase.clientAffinityEnabled();
}
@Override
public boolean clientCertEnabled() {
return webSiteBase.clientCertEnabled();
}
@Override
public boolean hostnamesDisabled() {
return webSiteBase.hostnamesDisabled();
}
@Override
public Set<String> outboundIPAddresses() {
return webSiteBase.outboundIPAddresses();
}
@Override
public int containerSize() {
return webSiteBase.containerSize();
}
@Override
public CloningInfo cloningInfo() {
return webSiteBase.cloningInfo();
}
@Override
public boolean isDefaultContainer() {
return webSiteBase.isDefaultContainer();
}
@Override
public String defaultHostname() {
if (inner().defaultHostname() != null) {
return inner().defaultHostname();
} else {
AzureEnvironment environment = manager().environment();
String dns = DNS_MAP.get(environment);
String leaf = name();
if (this instanceof DeploymentSlotBaseImpl<?, ?, ?, ?, ?>) {
leaf = ((DeploymentSlotBaseImpl<?, ?, ?, ?, ?>) this).parent().name() + "-" + leaf;
}
return leaf + "." + dns;
}
}
@Override
public List<String> defaultDocuments() {
if (siteConfig == null) {
return null;
}
return Collections.unmodifiableList(siteConfig.defaultDocuments());
}
@Override
public NetFrameworkVersion netFrameworkVersion() {
if (siteConfig == null) {
return null;
}
return NetFrameworkVersion.fromString(siteConfig.netFrameworkVersion());
}
@Override
public PhpVersion phpVersion() {
if (siteConfig == null || siteConfig.phpVersion() == null) {
return PhpVersion.OFF;
}
return PhpVersion.fromString(siteConfig.phpVersion());
}
@Override
public PythonVersion pythonVersion() {
if (siteConfig == null || siteConfig.pythonVersion() == null) {
return PythonVersion.OFF;
}
return PythonVersion.fromString(siteConfig.pythonVersion());
}
@Override
public String nodeVersion() {
if (siteConfig == null) {
return null;
}
return siteConfig.nodeVersion();
}
@Override
public boolean remoteDebuggingEnabled() {
if (siteConfig == null) {
return false;
}
return Utils.toPrimitiveBoolean(siteConfig.remoteDebuggingEnabled());
}
@Override
public RemoteVisualStudioVersion remoteDebuggingVersion() {
if (siteConfig == null) {
return null;
}
return RemoteVisualStudioVersion.fromString(siteConfig.remoteDebuggingVersion());
}
@Override
public boolean webSocketsEnabled() {
if (siteConfig == null) {
return false;
}
return Utils.toPrimitiveBoolean(siteConfig.webSocketsEnabled());
}
@Override
public boolean alwaysOn() {
if (siteConfig == null) {
return false;
}
return Utils.toPrimitiveBoolean(siteConfig.alwaysOn());
}
@Override
public JavaVersion javaVersion() {
if (siteConfig == null || siteConfig.javaVersion() == null) {
return JavaVersion.OFF;
}
return JavaVersion.fromString(siteConfig.javaVersion());
}
@Override
public String javaContainer() {
if (siteConfig == null) {
return null;
}
return siteConfig.javaContainer();
}
@Override
public String javaContainerVersion() {
if (siteConfig == null) {
return null;
}
return siteConfig.javaContainerVersion();
}
@Override
public ManagedPipelineMode managedPipelineMode() {
if (siteConfig == null) {
return null;
}
return siteConfig.managedPipelineMode();
}
@Override
public PlatformArchitecture platformArchitecture() {
if (siteConfig.use32BitWorkerProcess()) {
return PlatformArchitecture.X86;
} else {
return PlatformArchitecture.X64;
}
}
@Override
public String linuxFxVersion() {
if (siteConfig == null) {
return null;
}
return siteConfig.linuxFxVersion();
}
@Override
public String autoSwapSlotName() {
if (siteConfig == null) {
return null;
}
return siteConfig.autoSwapSlotName();
}
@Override
public boolean httpsOnly() {
return webSiteBase.httpsOnly();
}
@Override
public FtpsState ftpsState() {
if (siteConfig == null) {
return null;
}
return siteConfig.ftpsState();
}
@Override
public List<VirtualApplication> virtualApplications() {
if (siteConfig == null) {
return null;
}
return siteConfig.virtualApplications();
}
@Override
public boolean http20Enabled() {
if (siteConfig == null) {
return false;
}
return Utils.toPrimitiveBoolean(siteConfig.http20Enabled());
}
@Override
public boolean localMySqlEnabled() {
if (siteConfig == null) {
return false;
}
return Utils.toPrimitiveBoolean(siteConfig.localMySqlEnabled());
}
@Override
public ScmType scmType() {
if (siteConfig == null) {
return null;
}
return siteConfig.scmType();
}
@Override
public String documentRoot() {
if (siteConfig == null) {
return null;
}
return siteConfig.documentRoot();
}
@Override
public SupportedTlsVersions minTlsVersion() {
if (siteConfig == null) {
return null;
}
return siteConfig.minTlsVersion();
}
@Override
public OperatingSystem operatingSystem() {
if (inner().kind() != null && inner().kind().toLowerCase(Locale.ROOT).contains("linux")) {
return OperatingSystem.LINUX;
} else {
return OperatingSystem.WINDOWS;
}
}
@Override
public String systemAssignedManagedServiceIdentityTenantId() {
if (inner().identity() == null) {
return null;
}
return inner().identity().tenantId();
}
@Override
public String systemAssignedManagedServiceIdentityPrincipalId() {
if (inner().identity() == null) {
return null;
}
return inner().identity().principalId();
}
@Override
public Set<String> userAssignedManagedServiceIdentityIds() {
if (inner().identity() == null) {
return null;
}
return inner().identity().userAssignedIdentities().keySet();
}
@Override
public WebAppDiagnosticLogsImpl<FluentT, FluentImplT> diagnosticLogsConfig() {
return diagnosticLogs;
}
@Override
public InputStream streamApplicationLogs() {
return pipeObservableToInputStream(streamApplicationLogsAsync());
}
@Override
public Flux<String> streamApplicationLogsAsync() {
return kuduClient.streamApplicationLogsAsync();
}
@Override
public InputStream streamHttpLogs() {
return pipeObservableToInputStream(streamHttpLogsAsync());
}
@Override
public Flux<String> streamHttpLogsAsync() {
return kuduClient.streamHttpLogsAsync();
}
@Override
public InputStream streamTraceLogs() {
return pipeObservableToInputStream(streamTraceLogsAsync());
}
@Override
public Flux<String> streamTraceLogsAsync() {
return kuduClient.streamTraceLogsAsync();
}
@Override
public InputStream streamDeploymentLogs() {
return pipeObservableToInputStream(streamDeploymentLogsAsync());
}
@Override
public Flux<String> streamDeploymentLogsAsync() {
return kuduClient.streamDeploymentLogsAsync();
}
@Override
public InputStream streamAllLogs() {
return pipeObservableToInputStream(streamAllLogsAsync());
}
@Override
public Flux<String> streamAllLogsAsync() {
return kuduClient.streamAllLogsAsync();
}
private InputStream pipeObservableToInputStream(Flux<String> observable) {
PipedInputStreamWithCallback in = new PipedInputStreamWithCallback();
final PipedOutputStream out = new PipedOutputStream();
try {
in.connect(out);
} catch (IOException e) {
throw logger.logExceptionAsError(new RuntimeException(e));
}
final Disposable subscription =
observable
.subscribeOn(Schedulers.elastic())
.subscribe(
s -> {
try {
out.write(s.getBytes(StandardCharsets.UTF_8));
out.write('\n');
out.flush();
} catch (IOException e) {
throw logger.logExceptionAsError(new RuntimeException(e));
}
});
in
.addCallback(
() -> {
subscription.dispose();
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
});
return in;
}
@Override
public Map<String, AppSetting> getAppSettings() {
return getAppSettingsAsync().block();
}
@Override
public Mono<Map<String, AppSetting>> getAppSettingsAsync() {
return Mono
.zip(
listAppSettings(),
listSlotConfigurations(),
(appSettingsInner, slotConfigs) ->
appSettingsInner
.properties()
.entrySet()
.stream()
.collect(
Collectors
.toMap(
Map.Entry::getKey,
entry ->
new AppSettingImpl(
entry.getKey(),
entry.getValue(),
slotConfigs.appSettingNames() != null
&& slotConfigs.appSettingNames().contains(entry.getKey())))));
}
@Override
public Map<String, ConnectionString> getConnectionStrings() {
return getConnectionStringsAsync().block();
}
@Override
public Mono<Map<String, ConnectionString>> getConnectionStringsAsync() {
return Mono
.zip(
listConnectionStrings(),
listSlotConfigurations(),
(connectionStringsInner, slotConfigs) ->
connectionStringsInner
.properties()
.entrySet()
.stream()
.collect(
Collectors
.toMap(
Map.Entry::getKey,
entry ->
new ConnectionStringImpl(
entry.getKey(),
entry.getValue(),
slotConfigs.connectionStringNames() != null
&& slotConfigs.connectionStringNames().contains(entry.getKey())))));
}
@Override
public WebAppAuthentication getAuthenticationConfig() {
return getAuthenticationConfigAsync().block();
}
@Override
public Mono<WebAppAuthentication> getAuthenticationConfigAsync() {
return getAuthentication()
.map(siteAuthSettingsInner -> new WebAppAuthenticationImpl<>(siteAuthSettingsInner, WebAppBaseImpl.this));
}
abstract Mono<SiteInner> createOrUpdateInner(SiteInner site);
abstract Mono<SiteInner> updateInner(SitePatchResourceInner siteUpdate);
abstract Mono<SiteInner> getInner();
abstract Mono<SiteConfigResourceInner> getConfigInner();
abstract Mono<SiteConfigResourceInner> createOrUpdateSiteConfig(SiteConfigResourceInner siteConfig);
abstract Mono<Void> deleteHostnameBinding(String hostname);
abstract Mono<StringDictionaryInner> listAppSettings();
abstract Mono<StringDictionaryInner> updateAppSettings(StringDictionaryInner inner);
abstract Mono<ConnectionStringDictionaryInner> listConnectionStrings();
abstract Mono<ConnectionStringDictionaryInner> updateConnectionStrings(ConnectionStringDictionaryInner inner);
abstract Mono<SlotConfigNamesResourceInner> listSlotConfigurations();
abstract Mono<SlotConfigNamesResourceInner> updateSlotConfigurations(SlotConfigNamesResourceInner inner);
abstract Mono<SiteSourceControlInner> createOrUpdateSourceControl(SiteSourceControlInner inner);
abstract Mono<Void> deleteSourceControl();
abstract Mono<SiteAuthSettingsInner> updateAuthentication(SiteAuthSettingsInner inner);
abstract Mono<SiteAuthSettingsInner> getAuthentication();
abstract Mono<MSDeployStatusInner> createMSDeploy(MSDeploy msDeployInner);
abstract Mono<SiteLogsConfigInner> updateDiagnosticLogsConfig(SiteLogsConfigInner siteLogsConfigInner);
@Override
public void beforeGroupCreateOrUpdate() {
if (hostNameSslStateMap.size() > 0) {
inner().withHostnameSslStates(new ArrayList<>(hostNameSslStateMap.values()));
}
IndexableTaskItem rootTaskItem =
wrapTask(
context -> {
return submitHostNameBindings()
.flatMap(fluentT -> submitSslBindings(fluentT.inner()));
});
IndexableTaskItem lastTaskItem = rootTaskItem;
lastTaskItem = sequentialTask(lastTaskItem, context -> submitSiteConfig());
lastTaskItem =
sequentialTask(
lastTaskItem,
context ->
submitMetadata()
.flatMap(ignored -> submitAppSettings().mergeWith(submitConnectionStrings()).last())
.flatMap(ignored -> submitStickiness()));
lastTaskItem =
sequentialTask(
lastTaskItem,
context -> submitSourceControlToDelete().flatMap(ignored -> submitSourceControlToCreate()));
lastTaskItem = sequentialTask(lastTaskItem, context -> submitAuthentication());
lastTaskItem = sequentialTask(lastTaskItem, context -> submitLogConfiguration());
if (msiHandler != null) {
sequentialTask(lastTaskItem, msiHandler);
}
addPostRunDependent(rootTaskItem);
}
private static IndexableTaskItem wrapTask(FunctionalTaskItem taskItem) {
return IndexableTaskItem.create(taskItem);
}
private static IndexableTaskItem sequentialTask(IndexableTaskItem taskItem1, FunctionalTaskItem taskItem2) {
IndexableTaskItem taskItem = IndexableTaskItem.create(taskItem2);
taskItem1.addPostRunDependent(taskItem);
return taskItem;
}
@Override
@SuppressWarnings("unchecked")
public Mono<FluentT> createResourceAsync() {
this.webAppMsiHandler.processCreatedExternalIdentities();
this.webAppMsiHandler.handleExternalIdentities();
return submitSite(inner())
.map(
siteInner -> {
setInner(siteInner);
return (FluentT) WebAppBaseImpl.this;
});
}
@Override
@SuppressWarnings("unchecked")
public Mono<FluentT> updateResourceAsync() {
SiteInner siteInner = this.inner();
SitePatchResourceInner siteUpdate = new SitePatchResourceInner();
siteUpdate.withHostnameSslStates(siteInner.hostnameSslStates());
siteUpdate.withKind(siteInner.kind());
siteUpdate.withEnabled(siteInner.enabled());
siteUpdate.withServerFarmId(siteInner.serverFarmId());
siteUpdate.withReserved(siteInner.reserved());
siteUpdate.withIsXenon(siteInner.isXenon());
siteUpdate.withHyperV(siteInner.hyperV());
siteUpdate.withScmSiteAlsoStopped(siteInner.scmSiteAlsoStopped());
siteUpdate.withHostingEnvironmentProfile(siteInner.hostingEnvironmentProfile());
siteUpdate.withClientAffinityEnabled(siteInner.clientAffinityEnabled());
siteUpdate.withClientCertEnabled(siteInner.clientCertEnabled());
siteUpdate.withClientCertExclusionPaths(siteInner.clientCertExclusionPaths());
siteUpdate.withHostNamesDisabled(siteInner.hostNamesDisabled());
siteUpdate.withContainerSize(siteInner.containerSize());
siteUpdate.withDailyMemoryTimeQuota(siteInner.dailyMemoryTimeQuota());
siteUpdate.withCloningInfo(siteInner.cloningInfo());
siteUpdate.withHttpsOnly(siteInner.httpsOnly());
siteUpdate.withRedundancyMode(siteInner.redundancyMode());
this.webAppMsiHandler.handleExternalIdentities(siteUpdate);
return submitSite(siteUpdate)
.map(
siteInner1 -> {
setInner(siteInner1);
webAppMsiHandler.clear();
return (FluentT) WebAppBaseImpl.this;
});
}
@Override
public Mono<Void> afterPostRunAsync(final boolean isGroupFaulted) {
if (!isGroupFaulted) {
isInCreateMode = false;
initializeKuduClient();
}
return Mono
.fromCallable(
() -> {
normalizeProperties();
return null;
});
}
Mono<SiteInner> submitSite(final SiteInner site) {
site.withSiteConfig(new SiteConfigInner());
return submitSiteWithoutSiteConfig(site);
}
Mono<SiteInner> submitSiteWithoutSiteConfig(final SiteInner site) {
return createOrUpdateInner(site)
.map(
siteInner -> {
site.withSiteConfig(null);
return siteInner;
});
}
Mono<SiteInner> submitSite(final SitePatchResourceInner siteUpdate) {
return updateInner(siteUpdate)
.map(
siteInner -> {
siteInner.withSiteConfig(null);
return siteInner;
});
}
@SuppressWarnings("unchecked")
Mono<FluentT> submitHostNameBindings() {
final List<Mono<HostnameBinding>> bindingObservables = new ArrayList<>();
for (HostnameBindingImpl<FluentT, FluentImplT> binding : hostNameBindingsToCreate.values()) {
bindingObservables.add(Utils.<HostnameBinding>rootResource(binding.createAsync().last()));
}
for (String binding : hostNameBindingsToDelete) {
bindingObservables.add(deleteHostnameBinding(binding).then(Mono.empty()));
}
if (bindingObservables.isEmpty()) {
return Mono.just((FluentT) this);
} else {
return Flux
.zip(bindingObservables, ignored -> WebAppBaseImpl.this)
.last()
.onErrorResume(
throwable -> {
if (throwable instanceof HttpResponseException
&& ((HttpResponseException) throwable).getResponse().getStatusCode() == 400) {
return submitSite(inner())
.flatMap(
ignored -> Flux.zip(bindingObservables, ignored1 -> WebAppBaseImpl.this).last());
} else {
return Mono.error(throwable);
}
})
.flatMap(WebAppBaseImpl::refreshAsync);
}
}
Mono<Indexable> submitSslBindings(final SiteInner site) {
List<Mono<AppServiceCertificate>> certs = new ArrayList<>();
for (final HostnameSslBindingImpl<FluentT, FluentImplT> binding : sslBindingsToCreate.values()) {
certs.add(binding.newCertificate());
hostNameSslStateMap.put(binding.inner().name(), binding.inner().withToUpdate(true));
}
if (certs.isEmpty()) {
return Mono.just((Indexable) this);
} else {
site.withHostnameSslStates(new ArrayList<>(hostNameSslStateMap.values()));
return Flux
.zip(certs, ignored -> site)
.last()
.flatMap(this::createOrUpdateInner)
.map(
siteInner -> {
setInner(siteInner);
return WebAppBaseImpl.this;
});
}
}
Mono<Indexable> submitSiteConfig() {
if (siteConfig == null) {
return Mono.just((Indexable) this);
}
return createOrUpdateSiteConfig(siteConfig)
.flatMap(
returnedSiteConfig -> {
siteConfig = returnedSiteConfig;
return Mono.just((Indexable) WebAppBaseImpl.this);
});
}
Mono<Indexable> submitAppSettings() {
Mono<Indexable> observable = Mono.just((Indexable) this);
if (!appSettingsToAdd.isEmpty() || !appSettingsToRemove.isEmpty()) {
observable =
listAppSettings()
.switchIfEmpty(Mono.just(new StringDictionaryInner()))
.flatMap(
stringDictionaryInner -> {
if (stringDictionaryInner.properties() == null) {
stringDictionaryInner.withProperties(new HashMap<String, String>());
}
for (String appSettingKey : appSettingsToRemove) {
stringDictionaryInner.properties().remove(appSettingKey);
}
stringDictionaryInner.properties().putAll(appSettingsToAdd);
return updateAppSettings(stringDictionaryInner);
})
.map(ignored -> WebAppBaseImpl.this);
}
return observable;
}
Mono<Indexable> submitMetadata() {
return Mono.just((Indexable) this);
}
Mono<Indexable> submitConnectionStrings() {
Mono<Indexable> observable = Mono.just((Indexable) this);
if (!connectionStringsToAdd.isEmpty() || !connectionStringsToRemove.isEmpty()) {
observable =
listConnectionStrings()
.switchIfEmpty(Mono.just(new ConnectionStringDictionaryInner()))
.flatMap(
dictionaryInner -> {
if (dictionaryInner.properties() == null) {
dictionaryInner.withProperties(new HashMap<String, ConnStringValueTypePair>());
}
for (String connectionString : connectionStringsToRemove) {
dictionaryInner.properties().remove(connectionString);
}
dictionaryInner.properties().putAll(connectionStringsToAdd);
return updateConnectionStrings(dictionaryInner);
})
.map(ignored -> WebAppBaseImpl.this);
}
return observable;
}
Mono<Indexable> submitStickiness() {
Mono<Indexable> observable = Mono.just((Indexable) this);
if (!appSettingStickiness.isEmpty() || !connectionStringStickiness.isEmpty()) {
observable =
listSlotConfigurations()
.switchIfEmpty(Mono.just(new SlotConfigNamesResourceInner()))
.flatMap(
slotConfigNamesResourceInner -> {
if (slotConfigNamesResourceInner.appSettingNames() == null) {
slotConfigNamesResourceInner.withAppSettingNames(new ArrayList<>());
}
if (slotConfigNamesResourceInner.connectionStringNames() == null) {
slotConfigNamesResourceInner.withConnectionStringNames(new ArrayList<>());
}
Set<String> stickyAppSettingKeys =
new HashSet<>(slotConfigNamesResourceInner.appSettingNames());
Set<String> stickyConnectionStringNames =
new HashSet<>(slotConfigNamesResourceInner.connectionStringNames());
for (Map.Entry<String, Boolean> stickiness : appSettingStickiness.entrySet()) {
if (stickiness.getValue()) {
stickyAppSettingKeys.add(stickiness.getKey());
} else {
stickyAppSettingKeys.remove(stickiness.getKey());
}
}
for (Map.Entry<String, Boolean> stickiness : connectionStringStickiness.entrySet()) {
if (stickiness.getValue()) {
stickyConnectionStringNames.add(stickiness.getKey());
} else {
stickyConnectionStringNames.remove(stickiness.getKey());
}
}
slotConfigNamesResourceInner.withAppSettingNames(new ArrayList<>(stickyAppSettingKeys));
slotConfigNamesResourceInner
.withConnectionStringNames(new ArrayList<>(stickyConnectionStringNames));
return updateSlotConfigurations(slotConfigNamesResourceInner);
})
.map(ignored -> WebAppBaseImpl.this);
}
return observable;
}
Mono<Indexable> submitSourceControlToCreate() {
if (sourceControl == null || sourceControlToDelete) {
return Mono.just((Indexable) this);
}
return sourceControl
.registerGithubAccessToken()
.then(createOrUpdateSourceControl(sourceControl.inner()))
.delayElement(SdkContext.getDelayDuration(Duration.ofSeconds(30)))
.map(ignored -> WebAppBaseImpl.this);
}
Mono<Indexable> submitSourceControlToDelete() {
if (!sourceControlToDelete) {
return Mono.just((Indexable) this);
}
return deleteSourceControl().map(ignored -> WebAppBaseImpl.this);
}
Mono<Indexable> submitAuthentication() {
if (!authenticationToUpdate) {
return Mono.just((Indexable) this);
}
return updateAuthentication(authentication.inner())
.map(
siteAuthSettingsInner -> {
WebAppBaseImpl.this.authentication =
new WebAppAuthenticationImpl<>(siteAuthSettingsInner, WebAppBaseImpl.this);
return WebAppBaseImpl.this;
});
}
Mono<Indexable> submitLogConfiguration() {
if (!diagnosticLogsToUpdate) {
return Mono.just((Indexable) this);
}
return updateDiagnosticLogsConfig(diagnosticLogs.inner())
.map(
siteLogsConfigInner -> {
WebAppBaseImpl.this.diagnosticLogs =
new WebAppDiagnosticLogsImpl<>(siteLogsConfigInner, WebAppBaseImpl.this);
return WebAppBaseImpl.this;
});
}
@Override
public WebDeploymentImpl<FluentT, FluentImplT> deploy() {
return new WebDeploymentImpl<>(this);
}
WebAppBaseImpl<FluentT, FluentImplT> withNewHostNameSslBinding(
final HostnameSslBindingImpl<FluentT, FluentImplT> hostNameSslBinding) {
sslBindingsToCreate.put(hostNameSslBinding.name(), hostNameSslBinding);
return this;
}
@SuppressWarnings("unchecked")
public FluentImplT withManagedHostnameBindings(AppServiceDomain domain, String... hostnames) {
for (String hostname : hostnames) {
if (hostname.equals("@") || hostname.equalsIgnoreCase(domain.name())) {
defineHostnameBinding()
.withAzureManagedDomain(domain)
.withSubDomain(hostname)
.withDnsRecordType(CustomHostnameDnsRecordType.A)
.attach();
} else {
defineHostnameBinding()
.withAzureManagedDomain(domain)
.withSubDomain(hostname)
.withDnsRecordType(CustomHostnameDnsRecordType.CNAME)
.attach();
}
}
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public HostnameBindingImpl<FluentT, FluentImplT> defineHostnameBinding() {
HostnameBindingInner inner = new HostnameBindingInner();
inner.withSiteName(name());
inner.withAzureResourceType(AzureResourceType.WEBSITE);
inner.withAzureResourceName(name());
inner.withHostnameType(HostnameType.VERIFIED);
return new HostnameBindingImpl<>(inner, (FluentImplT) this);
}
@SuppressWarnings("unchecked")
public FluentImplT withThirdPartyHostnameBinding(String domain, String... hostnames) {
for (String hostname : hostnames) {
defineHostnameBinding()
.withThirdPartyDomain(domain)
.withSubDomain(hostname)
.withDnsRecordType(CustomHostnameDnsRecordType.CNAME)
.attach();
}
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withoutHostnameBinding(String hostname) {
hostNameBindingsToDelete.add(hostname);
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withoutSslBinding(String hostname) {
if (hostNameSslStateMap.containsKey(hostname)) {
hostNameSslStateMap.get(hostname).withSslState(SslState.DISABLED).withToUpdate(true);
}
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
FluentImplT withHostNameBinding(final HostnameBindingImpl<FluentT, FluentImplT> hostNameBinding) {
this.hostNameBindingsToCreate.put(hostNameBinding.name(), hostNameBinding);
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withAppDisabledOnCreation() {
inner().withEnabled(false);
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withScmSiteAlsoStopped(boolean scmSiteAlsoStopped) {
inner().withScmSiteAlsoStopped(scmSiteAlsoStopped);
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withClientAffinityEnabled(boolean enabled) {
inner().withClientAffinityEnabled(enabled);
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withClientCertEnabled(boolean enabled) {
inner().withClientCertEnabled(enabled);
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public HostnameSslBindingImpl<FluentT, FluentImplT> defineSslBinding() {
return new HostnameSslBindingImpl<>(new HostnameSslState(), (FluentImplT) this);
}
@SuppressWarnings("unchecked")
public FluentImplT withNetFrameworkVersion(NetFrameworkVersion version) {
if (siteConfig == null) {
siteConfig = new SiteConfigResourceInner();
}
siteConfig.withNetFrameworkVersion(version.toString());
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withPhpVersion(PhpVersion version) {
if (siteConfig == null) {
siteConfig = new SiteConfigResourceInner();
}
siteConfig.withPhpVersion(version.toString());
return (FluentImplT) this;
}
public FluentImplT withoutPhp() {
return withPhpVersion(PhpVersion.fromString(""));
}
@SuppressWarnings("unchecked")
public FluentImplT withJavaVersion(JavaVersion version) {
if (siteConfig == null) {
siteConfig = new SiteConfigResourceInner();
}
siteConfig.withJavaVersion(version.toString());
return (FluentImplT) this;
}
public FluentImplT withoutJava() {
return withJavaVersion(JavaVersion.fromString("")).withWebContainer(WebContainer.fromString(""));
}
@SuppressWarnings("unchecked")
public FluentImplT withWebContainer(WebContainer webContainer) {
if (siteConfig == null) {
siteConfig = new SiteConfigResourceInner();
}
if (webContainer == null) {
siteConfig.withJavaContainer(null);
siteConfig.withJavaContainerVersion(null);
} else if (webContainer.toString().isEmpty()) {
siteConfig.withJavaContainer("");
siteConfig.withJavaContainerVersion("");
} else {
String[] containerInfo = webContainer.toString().split(" ");
siteConfig.withJavaContainer(containerInfo[0]);
siteConfig.withJavaContainerVersion(containerInfo[1]);
}
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withPythonVersion(PythonVersion version) {
if (siteConfig == null) {
siteConfig = new SiteConfigResourceInner();
}
siteConfig.withPythonVersion(version.toString());
return (FluentImplT) this;
}
public FluentImplT withoutPython() {
return withPythonVersion(PythonVersion.fromString(""));
}
@SuppressWarnings("unchecked")
public FluentImplT withPlatformArchitecture(PlatformArchitecture platform) {
if (siteConfig == null) {
siteConfig = new SiteConfigResourceInner();
}
siteConfig.withUse32BitWorkerProcess(platform.equals(PlatformArchitecture.X86));
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withWebSocketsEnabled(boolean enabled) {
if (siteConfig == null) {
siteConfig = new SiteConfigResourceInner();
}
siteConfig.withWebSocketsEnabled(enabled);
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withWebAppAlwaysOn(boolean alwaysOn) {
if (siteConfig == null) {
siteConfig = new SiteConfigResourceInner();
}
siteConfig.withAlwaysOn(alwaysOn);
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withManagedPipelineMode(ManagedPipelineMode managedPipelineMode) {
if (siteConfig == null) {
siteConfig = new SiteConfigResourceInner();
}
siteConfig.withManagedPipelineMode(managedPipelineMode);
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withAutoSwapSlotName(String slotName) {
if (siteConfig == null) {
siteConfig = new SiteConfigResourceInner();
}
siteConfig.withAutoSwapSlotName(slotName);
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withRemoteDebuggingEnabled(RemoteVisualStudioVersion remoteVisualStudioVersion) {
if (siteConfig == null) {
siteConfig = new SiteConfigResourceInner();
}
siteConfig.withRemoteDebuggingEnabled(true);
siteConfig.withRemoteDebuggingVersion(remoteVisualStudioVersion.toString());
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withRemoteDebuggingDisabled() {
if (siteConfig == null) {
siteConfig = new SiteConfigResourceInner();
}
siteConfig.withRemoteDebuggingEnabled(false);
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withDefaultDocument(String document) {
if (siteConfig == null) {
siteConfig = new SiteConfigResourceInner();
}
if (siteConfig.defaultDocuments() == null) {
siteConfig.withDefaultDocuments(new ArrayList<String>());
}
siteConfig.defaultDocuments().add(document);
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withDefaultDocuments(List<String> documents) {
if (siteConfig == null) {
siteConfig = new SiteConfigResourceInner();
}
if (siteConfig.defaultDocuments() == null) {
siteConfig.withDefaultDocuments(new ArrayList<>());
}
siteConfig.defaultDocuments().addAll(documents);
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withoutDefaultDocument(String document) {
if (siteConfig == null) {
siteConfig = new SiteConfigResourceInner();
}
if (siteConfig.defaultDocuments() != null) {
siteConfig.defaultDocuments().remove(document);
}
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withHttpsOnly(boolean httpsOnly) {
inner().withHttpsOnly(httpsOnly);
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withHttp20Enabled(boolean http20Enabled) {
if (siteConfig == null) {
siteConfig = new SiteConfigResourceInner();
}
siteConfig.withHttp20Enabled(http20Enabled);
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withFtpsState(FtpsState ftpsState) {
if (siteConfig == null) {
siteConfig = new SiteConfigResourceInner();
}
siteConfig.withFtpsState(ftpsState);
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withVirtualApplications(List<VirtualApplication> virtualApplications) {
if (siteConfig == null) {
siteConfig = new SiteConfigResourceInner();
}
siteConfig.withVirtualApplications(virtualApplications);
return (FluentImplT) this;
}
@Override
@SuppressWarnings("unchecked")
public FluentImplT withMinTlsVersion(SupportedTlsVersions minTlsVersion) {
if (siteConfig == null) {
siteConfig = new SiteConfigResourceInner();
}
siteConfig.withMinTlsVersion(minTlsVersion);
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withAppSetting(String key, String value) {
appSettingsToAdd.put(key, value);
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withAppSettings(Map<String, String> settings) {
appSettingsToAdd.putAll(settings);
return (FluentImplT) this;
}
public FluentImplT withStickyAppSetting(String key, String value) {
withAppSetting(key, value);
return withAppSettingStickiness(key, true);
}
@SuppressWarnings("unchecked")
public FluentImplT withStickyAppSettings(Map<String, String> settings) {
withAppSettings(settings);
for (String key : settings.keySet()) {
appSettingStickiness.put(key, true);
}
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withoutAppSetting(String key) {
appSettingsToRemove.add(key);
appSettingStickiness.remove(key);
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withAppSettingStickiness(String key, boolean sticky) {
appSettingStickiness.put(key, sticky);
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withConnectionString(String name, String value, ConnectionStringType type) {
connectionStringsToAdd.put(name, new ConnStringValueTypePair().withValue(value).withType(type));
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withStickyConnectionString(String name, String value, ConnectionStringType type) {
connectionStringsToAdd.put(name, new ConnStringValueTypePair().withValue(value).withType(type));
connectionStringStickiness.put(name, true);
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withoutConnectionString(String name) {
connectionStringsToRemove.add(name);
connectionStringStickiness.remove(name);
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withConnectionStringStickiness(String name, boolean stickiness) {
connectionStringStickiness.put(name, stickiness);
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
void withSourceControl(WebAppSourceControlImpl<FluentT, FluentImplT> sourceControl) {
this.sourceControl = sourceControl;
}
public WebAppSourceControlImpl<FluentT, FluentImplT> defineSourceControl() {
SiteSourceControlInner sourceControlInner = new SiteSourceControlInner();
return new WebAppSourceControlImpl<>(sourceControlInner, this);
}
@SuppressWarnings("unchecked")
public FluentImplT withLocalGitSourceControl() {
if (siteConfig == null) {
siteConfig = new SiteConfigResourceInner();
}
siteConfig.withScmType(ScmType.LOCAL_GIT);
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withoutSourceControl() {
sourceControlToDelete = true;
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
void withAuthentication(WebAppAuthenticationImpl<FluentT, FluentImplT> authentication) {
this.authentication = authentication;
authenticationToUpdate = true;
}
void withDiagnosticLogs(WebAppDiagnosticLogsImpl<FluentT, FluentImplT> diagnosticLogs) {
this.diagnosticLogs = diagnosticLogs;
diagnosticLogsToUpdate = true;
}
@Override
@SuppressWarnings("unchecked")
public Mono<FluentT> refreshAsync() {
return super
.refreshAsync()
.flatMap(
fluentT ->
getConfigInner()
.map(
returnedSiteConfig -> {
siteConfig = returnedSiteConfig;
return fluentT;
}));
}
@Override
protected Mono<SiteInner> getInnerAsync() {
return getInner();
}
@Override
public WebAppAuthenticationImpl<FluentT, FluentImplT> defineAuthentication() {
return new WebAppAuthenticationImpl<>(new SiteAuthSettingsInner().withEnabled(true), this);
}
@Override
@SuppressWarnings("unchecked")
public FluentImplT withoutAuthentication() {
this.authentication.inner().withEnabled(false);
authenticationToUpdate = true;
return (FluentImplT) this;
}
@Override
@SuppressWarnings("unchecked")
public FluentImplT withContainerLoggingEnabled(int quotaInMB, int retentionDays) {
return updateDiagnosticLogsConfiguration()
.withWebServerLogging()
.withWebServerLogsStoredOnFileSystem()
.withWebServerFileSystemQuotaInMB(quotaInMB)
.withLogRetentionDays(retentionDays)
.attach();
}
@Override
public FluentImplT withContainerLoggingEnabled() {
return withContainerLoggingEnabled(35, 0);
}
@Override
@SuppressWarnings("unchecked")
public FluentImplT withContainerLoggingDisabled() {
return updateDiagnosticLogsConfiguration().withoutWebServerLogging().attach();
}
@Override
@SuppressWarnings("unchecked")
public FluentImplT withSystemAssignedManagedServiceIdentity() {
this.webAppMsiHandler.withLocalManagedServiceIdentity();
return (FluentImplT) this;
}
@Override
@SuppressWarnings("unchecked")
public FluentImplT withoutSystemAssignedManagedServiceIdentity() {
this.webAppMsiHandler.withoutLocalManagedServiceIdentity();
return (FluentImplT) this;
}
@Override
@SuppressWarnings("unchecked")
public FluentImplT withUserAssignedManagedServiceIdentity() {
return (FluentImplT) this;
}
@Override
@SuppressWarnings("unchecked")
public FluentImplT withSystemAssignedIdentityBasedAccessTo(final String resourceId, final BuiltInRole role) {
this.webAppMsiHandler.withAccessTo(resourceId, role);
return (FluentImplT) this;
}
@Override
@SuppressWarnings("unchecked")
public FluentImplT withSystemAssignedIdentityBasedAccessToCurrentResourceGroup(final BuiltInRole role) {
this.webAppMsiHandler.withAccessToCurrentResourceGroup(role);
return (FluentImplT) this;
}
@Override
@SuppressWarnings("unchecked")
public FluentImplT withSystemAssignedIdentityBasedAccessTo(final String resourceId, final String roleDefinitionId) {
this.webAppMsiHandler.withAccessTo(resourceId, roleDefinitionId);
return (FluentImplT) this;
}
@Override
@SuppressWarnings("unchecked")
public FluentImplT withSystemAssignedIdentityBasedAccessToCurrentResourceGroup(final String roleDefinitionId) {
this.webAppMsiHandler.withAccessToCurrentResourceGroup(roleDefinitionId);
return (FluentImplT) this;
}
@Override
@SuppressWarnings("unchecked")
public FluentImplT withNewUserAssignedManagedServiceIdentity(Creatable<Identity> creatableIdentity) {
this.webAppMsiHandler.withNewExternalManagedServiceIdentity(creatableIdentity);
return (FluentImplT) this;
}
@Override
@SuppressWarnings("unchecked")
public FluentImplT withExistingUserAssignedManagedServiceIdentity(Identity identity) {
this.webAppMsiHandler.withExistingExternalManagedServiceIdentity(identity);
return (FluentImplT) this;
}
@Override
@SuppressWarnings("unchecked")
public FluentImplT withoutUserAssignedManagedServiceIdentity(String identityId) {
this.webAppMsiHandler.withoutExternalManagedServiceIdentity(identityId);
return (FluentImplT) this;
}
@Override
public WebAppDiagnosticLogsImpl<FluentT, FluentImplT> defineDiagnosticLogsConfiguration() {
if (diagnosticLogs == null) {
return new WebAppDiagnosticLogsImpl<>(new SiteLogsConfigInner(), this);
} else {
return diagnosticLogs;
}
}
@Override
public WebAppDiagnosticLogsImpl<FluentT, FluentImplT> updateDiagnosticLogsConfiguration() {
return defineDiagnosticLogsConfiguration();
}
@Override
public ManagedServiceIdentity identity() {
return webSiteBase.identity();
}
@Override
public boolean hyperV() {
return webSiteBase.hyperV();
}
@Override
public HostingEnvironmentProfile hostingEnvironmentProfile() {
return webSiteBase.hostingEnvironmentProfile();
}
@Override
public Set<String> clientCertExclusionPaths() {
return webSiteBase.clientCertExclusionPaths();
}
@Override
public Set<String> possibleOutboundIpAddresses() {
return webSiteBase.possibleOutboundIpAddresses();
}
@Override
public int dailyMemoryTimeQuota() {
return webSiteBase.dailyMemoryTimeQuota();
}
@Override
public OffsetDateTime suspendedTill() {
return webSiteBase.suspendedTill();
}
@Override
public int maxNumberOfWorkers() {
return webSiteBase.maxNumberOfWorkers();
}
@Override
public SlotSwapStatus slotSwapStatus() {
return webSiteBase.slotSwapStatus();
}
@Override
public RedundancyMode redundancyMode() {
return webSiteBase.redundancyMode();
}
@Override
public UUID inProgressOperationId() {
return webSiteBase.inProgressOperationId();
}
private static class PipedInputStreamWithCallback extends PipedInputStream {
private Runnable callback;
private void addCallback(Runnable action) {
this.callback = action;
}
@Override
public void close() throws IOException {
callback.run();
super.close();
}
}
} | class WebAppBaseImpl<FluentT extends WebAppBase, FluentImplT extends WebAppBaseImpl<FluentT, FluentImplT>>
extends GroupableResourceImpl<FluentT, SiteInner, FluentImplT, AppServiceManager>
implements WebAppBase,
WebAppBase.Definition<FluentT>,
WebAppBase.Update<FluentT>,
WebAppBase.UpdateStages.WithWebContainer<FluentT> {
private final ClientLogger logger = new ClientLogger(getClass());
private static final Map<AzureEnvironment, String> DNS_MAP =
new HashMap<AzureEnvironment, String>() {
{
put(AzureEnvironment.AZURE, "azurewebsites.net");
put(AzureEnvironment.AZURE_CHINA, "chinacloudsites.cn");
put(AzureEnvironment.AZURE_GERMANY, "azurewebsites.de");
put(AzureEnvironment.AZURE_US_GOVERNMENT, "azurewebsites.us");
}
};
SiteConfigResourceInner siteConfig;
KuduClient kuduClient;
WebSiteBase webSiteBase;
private Map<String, HostnameSslState> hostNameSslStateMap;
private TreeMap<String, HostnameBindingImpl<FluentT, FluentImplT>> hostNameBindingsToCreate;
private List<String> hostNameBindingsToDelete;
private TreeMap<String, HostnameSslBindingImpl<FluentT, FluentImplT>> sslBindingsToCreate;
protected Map<String, String> appSettingsToAdd;
protected List<String> appSettingsToRemove;
private Map<String, Boolean> appSettingStickiness;
private Map<String, ConnStringValueTypePair> connectionStringsToAdd;
private List<String> connectionStringsToRemove;
private Map<String, Boolean> connectionStringStickiness;
private WebAppSourceControlImpl<FluentT, FluentImplT> sourceControl;
private boolean sourceControlToDelete;
private WebAppAuthenticationImpl<FluentT, FluentImplT> authentication;
private boolean authenticationToUpdate;
private WebAppDiagnosticLogsImpl<FluentT, FluentImplT> diagnosticLogs;
private boolean diagnosticLogsToUpdate;
private FunctionalTaskItem msiHandler;
private boolean isInCreateMode;
private WebAppMsiHandler<FluentT, FluentImplT> webAppMsiHandler;
WebAppBaseImpl(
String name,
SiteInner innerObject,
SiteConfigResourceInner siteConfig,
SiteLogsConfigInner logConfig,
AppServiceManager manager) {
super(name, innerObject, manager);
if (innerObject != null && innerObject.kind() != null) {
innerObject.withKind(innerObject.kind().replace(";", ","));
}
this.siteConfig = siteConfig;
if (logConfig != null) {
this.diagnosticLogs = new WebAppDiagnosticLogsImpl<>(logConfig, this);
}
webAppMsiHandler = new WebAppMsiHandler<>(manager.authorizationManager(), this);
normalizeProperties();
isInCreateMode = inner() == null || inner().id() == null;
if (!isInCreateMode) {
initializeKuduClient();
}
}
public boolean isInCreateMode() {
return isInCreateMode;
}
private void initializeKuduClient() {
if (kuduClient == null) {
kuduClient = new KuduClient(this);
}
}
@Override
public void setInner(SiteInner innerObject) {
if (innerObject.kind() != null) {
innerObject.withKind(innerObject.kind().replace(";", ","));
}
super.setInner(innerObject);
}
RoleAssignmentHelper.IdProvider idProvider() {
return new RoleAssignmentHelper.IdProvider() {
@Override
public String principalId() {
if (inner() != null && inner().identity() != null) {
return inner().identity().principalId();
} else {
return null;
}
}
@Override
public String resourceId() {
if (inner() != null) {
return inner().id();
} else {
return null;
}
}
};
}
@Override
public String state() {
return webSiteBase.state();
}
@Override
public Set<String> hostnames() {
return webSiteBase.hostnames();
}
@Override
public String repositorySiteName() {
return webSiteBase.repositorySiteName();
}
@Override
public UsageState usageState() {
return webSiteBase.usageState();
}
@Override
public boolean enabled() {
return webSiteBase.enabled();
}
@Override
public Set<String> enabledHostNames() {
return webSiteBase.enabledHostNames();
}
@Override
public SiteAvailabilityState availabilityState() {
return webSiteBase.availabilityState();
}
@Override
public Map<String, HostnameSslState> hostnameSslStates() {
return Collections.unmodifiableMap(hostNameSslStateMap);
}
@Override
public String appServicePlanId() {
return webSiteBase.appServicePlanId();
}
@Override
public OffsetDateTime lastModifiedTime() {
return webSiteBase.lastModifiedTime();
}
@Override
public Set<String> trafficManagerHostNames() {
return webSiteBase.trafficManagerHostNames();
}
@Override
public boolean scmSiteAlsoStopped() {
return webSiteBase.scmSiteAlsoStopped();
}
@Override
public String targetSwapSlot() {
return webSiteBase.targetSwapSlot();
}
@Override
public boolean clientAffinityEnabled() {
return webSiteBase.clientAffinityEnabled();
}
@Override
public boolean clientCertEnabled() {
return webSiteBase.clientCertEnabled();
}
@Override
public boolean hostnamesDisabled() {
return webSiteBase.hostnamesDisabled();
}
@Override
public Set<String> outboundIPAddresses() {
return webSiteBase.outboundIPAddresses();
}
@Override
public int containerSize() {
return webSiteBase.containerSize();
}
@Override
public CloningInfo cloningInfo() {
return webSiteBase.cloningInfo();
}
@Override
public boolean isDefaultContainer() {
return webSiteBase.isDefaultContainer();
}
@Override
public String defaultHostname() {
if (inner().defaultHostname() != null) {
return inner().defaultHostname();
} else {
AzureEnvironment environment = manager().environment();
String dns = DNS_MAP.get(environment);
String leaf = name();
if (this instanceof DeploymentSlotBaseImpl<?, ?, ?, ?, ?>) {
leaf = ((DeploymentSlotBaseImpl<?, ?, ?, ?, ?>) this).parent().name() + "-" + leaf;
}
return leaf + "." + dns;
}
}
@Override
public List<String> defaultDocuments() {
if (siteConfig == null) {
return null;
}
return Collections.unmodifiableList(siteConfig.defaultDocuments());
}
@Override
public NetFrameworkVersion netFrameworkVersion() {
if (siteConfig == null) {
return null;
}
return NetFrameworkVersion.fromString(siteConfig.netFrameworkVersion());
}
@Override
public PhpVersion phpVersion() {
if (siteConfig == null || siteConfig.phpVersion() == null) {
return PhpVersion.OFF;
}
return PhpVersion.fromString(siteConfig.phpVersion());
}
@Override
public PythonVersion pythonVersion() {
if (siteConfig == null || siteConfig.pythonVersion() == null) {
return PythonVersion.OFF;
}
return PythonVersion.fromString(siteConfig.pythonVersion());
}
@Override
public String nodeVersion() {
if (siteConfig == null) {
return null;
}
return siteConfig.nodeVersion();
}
@Override
public boolean remoteDebuggingEnabled() {
if (siteConfig == null) {
return false;
}
return Utils.toPrimitiveBoolean(siteConfig.remoteDebuggingEnabled());
}
@Override
public RemoteVisualStudioVersion remoteDebuggingVersion() {
if (siteConfig == null) {
return null;
}
return RemoteVisualStudioVersion.fromString(siteConfig.remoteDebuggingVersion());
}
@Override
public boolean webSocketsEnabled() {
if (siteConfig == null) {
return false;
}
return Utils.toPrimitiveBoolean(siteConfig.webSocketsEnabled());
}
@Override
public boolean alwaysOn() {
if (siteConfig == null) {
return false;
}
return Utils.toPrimitiveBoolean(siteConfig.alwaysOn());
}
@Override
public JavaVersion javaVersion() {
if (siteConfig == null || siteConfig.javaVersion() == null) {
return JavaVersion.OFF;
}
return JavaVersion.fromString(siteConfig.javaVersion());
}
@Override
public String javaContainer() {
if (siteConfig == null) {
return null;
}
return siteConfig.javaContainer();
}
@Override
public String javaContainerVersion() {
if (siteConfig == null) {
return null;
}
return siteConfig.javaContainerVersion();
}
@Override
public ManagedPipelineMode managedPipelineMode() {
if (siteConfig == null) {
return null;
}
return siteConfig.managedPipelineMode();
}
@Override
public PlatformArchitecture platformArchitecture() {
if (siteConfig.use32BitWorkerProcess()) {
return PlatformArchitecture.X86;
} else {
return PlatformArchitecture.X64;
}
}
@Override
public String linuxFxVersion() {
if (siteConfig == null) {
return null;
}
return siteConfig.linuxFxVersion();
}
@Override
public String autoSwapSlotName() {
if (siteConfig == null) {
return null;
}
return siteConfig.autoSwapSlotName();
}
@Override
public boolean httpsOnly() {
return webSiteBase.httpsOnly();
}
@Override
public FtpsState ftpsState() {
if (siteConfig == null) {
return null;
}
return siteConfig.ftpsState();
}
@Override
public List<VirtualApplication> virtualApplications() {
if (siteConfig == null) {
return null;
}
return siteConfig.virtualApplications();
}
@Override
public boolean http20Enabled() {
if (siteConfig == null) {
return false;
}
return Utils.toPrimitiveBoolean(siteConfig.http20Enabled());
}
@Override
public boolean localMySqlEnabled() {
if (siteConfig == null) {
return false;
}
return Utils.toPrimitiveBoolean(siteConfig.localMySqlEnabled());
}
@Override
public ScmType scmType() {
if (siteConfig == null) {
return null;
}
return siteConfig.scmType();
}
@Override
public String documentRoot() {
if (siteConfig == null) {
return null;
}
return siteConfig.documentRoot();
}
@Override
public SupportedTlsVersions minTlsVersion() {
if (siteConfig == null) {
return null;
}
return siteConfig.minTlsVersion();
}
@Override
public OperatingSystem operatingSystem() {
if (inner().kind() != null && inner().kind().toLowerCase(Locale.ROOT).contains("linux")) {
return OperatingSystem.LINUX;
} else {
return OperatingSystem.WINDOWS;
}
}
@Override
public String systemAssignedManagedServiceIdentityTenantId() {
if (inner().identity() == null) {
return null;
}
return inner().identity().tenantId();
}
@Override
public String systemAssignedManagedServiceIdentityPrincipalId() {
if (inner().identity() == null) {
return null;
}
return inner().identity().principalId();
}
@Override
public Set<String> userAssignedManagedServiceIdentityIds() {
if (inner().identity() == null) {
return null;
}
return inner().identity().userAssignedIdentities().keySet();
}
@Override
public WebAppDiagnosticLogsImpl<FluentT, FluentImplT> diagnosticLogsConfig() {
return diagnosticLogs;
}
@Override
public InputStream streamApplicationLogs() {
return pipeObservableToInputStream(streamApplicationLogsAsync());
}
@Override
public Flux<String> streamApplicationLogsAsync() {
return kuduClient.streamApplicationLogsAsync();
}
@Override
public InputStream streamHttpLogs() {
return pipeObservableToInputStream(streamHttpLogsAsync());
}
@Override
public Flux<String> streamHttpLogsAsync() {
return kuduClient.streamHttpLogsAsync();
}
@Override
public InputStream streamTraceLogs() {
return pipeObservableToInputStream(streamTraceLogsAsync());
}
@Override
public Flux<String> streamTraceLogsAsync() {
return kuduClient.streamTraceLogsAsync();
}
@Override
public InputStream streamDeploymentLogs() {
return pipeObservableToInputStream(streamDeploymentLogsAsync());
}
@Override
public Flux<String> streamDeploymentLogsAsync() {
return kuduClient.streamDeploymentLogsAsync();
}
@Override
public InputStream streamAllLogs() {
return pipeObservableToInputStream(streamAllLogsAsync());
}
@Override
public Flux<String> streamAllLogsAsync() {
return kuduClient.streamAllLogsAsync();
}
private InputStream pipeObservableToInputStream(Flux<String> observable) {
PipedInputStreamWithCallback in = new PipedInputStreamWithCallback();
final PipedOutputStream out = new PipedOutputStream();
try {
in.connect(out);
} catch (IOException e) {
throw logger.logExceptionAsError(new RuntimeException(e));
}
final Disposable subscription =
observable
.subscribeOn(Schedulers.elastic())
.subscribe(
s -> {
try {
out.write(s.getBytes(StandardCharsets.UTF_8));
out.write('\n');
out.flush();
} catch (IOException e) {
throw logger.logExceptionAsError(new RuntimeException(e));
}
});
in
.addCallback(
() -> {
subscription.dispose();
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
});
return in;
}
@Override
public Map<String, AppSetting> getAppSettings() {
return getAppSettingsAsync().block();
}
@Override
public Mono<Map<String, AppSetting>> getAppSettingsAsync() {
return Mono
.zip(
listAppSettings(),
listSlotConfigurations(),
(appSettingsInner, slotConfigs) ->
appSettingsInner
.properties()
.entrySet()
.stream()
.collect(
Collectors
.toMap(
Map.Entry::getKey,
entry ->
new AppSettingImpl(
entry.getKey(),
entry.getValue(),
slotConfigs.appSettingNames() != null
&& slotConfigs.appSettingNames().contains(entry.getKey())))));
}
@Override
public Map<String, ConnectionString> getConnectionStrings() {
return getConnectionStringsAsync().block();
}
@Override
public Mono<Map<String, ConnectionString>> getConnectionStringsAsync() {
return Mono
.zip(
listConnectionStrings(),
listSlotConfigurations(),
(connectionStringsInner, slotConfigs) ->
connectionStringsInner
.properties()
.entrySet()
.stream()
.collect(
Collectors
.toMap(
Map.Entry::getKey,
entry ->
new ConnectionStringImpl(
entry.getKey(),
entry.getValue(),
slotConfigs.connectionStringNames() != null
&& slotConfigs.connectionStringNames().contains(entry.getKey())))));
}
@Override
public WebAppAuthentication getAuthenticationConfig() {
return getAuthenticationConfigAsync().block();
}
@Override
public Mono<WebAppAuthentication> getAuthenticationConfigAsync() {
return getAuthentication()
.map(siteAuthSettingsInner -> new WebAppAuthenticationImpl<>(siteAuthSettingsInner, WebAppBaseImpl.this));
}
abstract Mono<SiteInner> createOrUpdateInner(SiteInner site);
abstract Mono<SiteInner> updateInner(SitePatchResourceInner siteUpdate);
abstract Mono<SiteInner> getInner();
abstract Mono<SiteConfigResourceInner> getConfigInner();
abstract Mono<SiteConfigResourceInner> createOrUpdateSiteConfig(SiteConfigResourceInner siteConfig);
abstract Mono<Void> deleteHostnameBinding(String hostname);
abstract Mono<StringDictionaryInner> listAppSettings();
abstract Mono<StringDictionaryInner> updateAppSettings(StringDictionaryInner inner);
abstract Mono<ConnectionStringDictionaryInner> listConnectionStrings();
abstract Mono<ConnectionStringDictionaryInner> updateConnectionStrings(ConnectionStringDictionaryInner inner);
abstract Mono<SlotConfigNamesResourceInner> listSlotConfigurations();
abstract Mono<SlotConfigNamesResourceInner> updateSlotConfigurations(SlotConfigNamesResourceInner inner);
abstract Mono<SiteSourceControlInner> createOrUpdateSourceControl(SiteSourceControlInner inner);
abstract Mono<Void> deleteSourceControl();
abstract Mono<SiteAuthSettingsInner> updateAuthentication(SiteAuthSettingsInner inner);
abstract Mono<SiteAuthSettingsInner> getAuthentication();
abstract Mono<MSDeployStatusInner> createMSDeploy(MSDeploy msDeployInner);
abstract Mono<SiteLogsConfigInner> updateDiagnosticLogsConfig(SiteLogsConfigInner siteLogsConfigInner);
@Override
public void beforeGroupCreateOrUpdate() {
if (hostNameSslStateMap.size() > 0) {
inner().withHostnameSslStates(new ArrayList<>(hostNameSslStateMap.values()));
}
IndexableTaskItem rootTaskItem =
wrapTask(
context -> {
return submitHostNameBindings()
.flatMap(fluentT -> submitSslBindings(fluentT.inner()));
});
IndexableTaskItem lastTaskItem = rootTaskItem;
lastTaskItem = sequentialTask(lastTaskItem, context -> submitSiteConfig());
lastTaskItem =
sequentialTask(
lastTaskItem,
context ->
submitMetadata()
.flatMap(ignored -> submitAppSettings().mergeWith(submitConnectionStrings()).last())
.flatMap(ignored -> submitStickiness()));
lastTaskItem =
sequentialTask(
lastTaskItem,
context -> submitSourceControlToDelete().flatMap(ignored -> submitSourceControlToCreate()));
lastTaskItem = sequentialTask(lastTaskItem, context -> submitAuthentication());
lastTaskItem = sequentialTask(lastTaskItem, context -> submitLogConfiguration());
if (msiHandler != null) {
sequentialTask(lastTaskItem, msiHandler);
}
addPostRunDependent(rootTaskItem);
}
private static IndexableTaskItem wrapTask(FunctionalTaskItem taskItem) {
return IndexableTaskItem.create(taskItem);
}
private static IndexableTaskItem sequentialTask(IndexableTaskItem taskItem1, FunctionalTaskItem taskItem2) {
IndexableTaskItem taskItem = IndexableTaskItem.create(taskItem2);
taskItem1.addPostRunDependent(taskItem);
return taskItem;
}
@Override
@SuppressWarnings("unchecked")
public Mono<FluentT> createResourceAsync() {
this.webAppMsiHandler.processCreatedExternalIdentities();
this.webAppMsiHandler.handleExternalIdentities();
return submitSite(inner())
.map(
siteInner -> {
setInner(siteInner);
return (FluentT) WebAppBaseImpl.this;
});
}
@Override
@SuppressWarnings("unchecked")
public Mono<FluentT> updateResourceAsync() {
SiteInner siteInner = this.inner();
SitePatchResourceInner siteUpdate = new SitePatchResourceInner();
siteUpdate.withHostnameSslStates(siteInner.hostnameSslStates());
siteUpdate.withKind(siteInner.kind());
siteUpdate.withEnabled(siteInner.enabled());
siteUpdate.withServerFarmId(siteInner.serverFarmId());
siteUpdate.withReserved(siteInner.reserved());
siteUpdate.withIsXenon(siteInner.isXenon());
siteUpdate.withHyperV(siteInner.hyperV());
siteUpdate.withScmSiteAlsoStopped(siteInner.scmSiteAlsoStopped());
siteUpdate.withHostingEnvironmentProfile(siteInner.hostingEnvironmentProfile());
siteUpdate.withClientAffinityEnabled(siteInner.clientAffinityEnabled());
siteUpdate.withClientCertEnabled(siteInner.clientCertEnabled());
siteUpdate.withClientCertExclusionPaths(siteInner.clientCertExclusionPaths());
siteUpdate.withHostNamesDisabled(siteInner.hostNamesDisabled());
siteUpdate.withContainerSize(siteInner.containerSize());
siteUpdate.withDailyMemoryTimeQuota(siteInner.dailyMemoryTimeQuota());
siteUpdate.withCloningInfo(siteInner.cloningInfo());
siteUpdate.withHttpsOnly(siteInner.httpsOnly());
siteUpdate.withRedundancyMode(siteInner.redundancyMode());
this.webAppMsiHandler.handleExternalIdentities(siteUpdate);
return submitSite(siteUpdate)
.map(
siteInner1 -> {
setInner(siteInner1);
webAppMsiHandler.clear();
return (FluentT) WebAppBaseImpl.this;
});
}
@Override
public Mono<Void> afterPostRunAsync(final boolean isGroupFaulted) {
if (!isGroupFaulted) {
isInCreateMode = false;
initializeKuduClient();
}
return Mono
.fromCallable(
() -> {
normalizeProperties();
return null;
});
}
Mono<SiteInner> submitSite(final SiteInner site) {
site.withSiteConfig(new SiteConfigInner());
return submitSiteWithoutSiteConfig(site);
}
Mono<SiteInner> submitSiteWithoutSiteConfig(final SiteInner site) {
return createOrUpdateInner(site)
.map(
siteInner -> {
site.withSiteConfig(null);
return siteInner;
});
}
Mono<SiteInner> submitSite(final SitePatchResourceInner siteUpdate) {
return updateInner(siteUpdate)
.map(
siteInner -> {
siteInner.withSiteConfig(null);
return siteInner;
});
}
@SuppressWarnings("unchecked")
Mono<FluentT> submitHostNameBindings() {
final List<Mono<HostnameBinding>> bindingObservables = new ArrayList<>();
for (HostnameBindingImpl<FluentT, FluentImplT> binding : hostNameBindingsToCreate.values()) {
bindingObservables.add(Utils.<HostnameBinding>rootResource(binding.createAsync().last()));
}
for (String binding : hostNameBindingsToDelete) {
bindingObservables.add(deleteHostnameBinding(binding).then(Mono.empty()));
}
if (bindingObservables.isEmpty()) {
return Mono.just((FluentT) this);
} else {
return Flux
.zip(bindingObservables, ignored -> WebAppBaseImpl.this)
.last()
.onErrorResume(
throwable -> {
if (throwable instanceof HttpResponseException
&& ((HttpResponseException) throwable).getResponse().getStatusCode() == 400) {
return submitSite(inner())
.flatMap(
ignored -> Flux.zip(bindingObservables, ignored1 -> WebAppBaseImpl.this).last());
} else {
return Mono.error(throwable);
}
})
.flatMap(WebAppBaseImpl::refreshAsync);
}
}
Mono<Indexable> submitSslBindings(final SiteInner site) {
List<Mono<AppServiceCertificate>> certs = new ArrayList<>();
for (final HostnameSslBindingImpl<FluentT, FluentImplT> binding : sslBindingsToCreate.values()) {
certs.add(binding.newCertificate());
hostNameSslStateMap.put(binding.inner().name(), binding.inner().withToUpdate(true));
}
if (certs.isEmpty()) {
return Mono.just((Indexable) this);
} else {
site.withHostnameSslStates(new ArrayList<>(hostNameSslStateMap.values()));
return Flux
.zip(certs, ignored -> site)
.last()
.flatMap(this::createOrUpdateInner)
.map(
siteInner -> {
setInner(siteInner);
return WebAppBaseImpl.this;
});
}
}
Mono<Indexable> submitSiteConfig() {
if (siteConfig == null) {
return Mono.just((Indexable) this);
}
return createOrUpdateSiteConfig(siteConfig)
.flatMap(
returnedSiteConfig -> {
siteConfig = returnedSiteConfig;
return Mono.just((Indexable) WebAppBaseImpl.this);
});
}
Mono<Indexable> submitAppSettings() {
Mono<Indexable> observable = Mono.just((Indexable) this);
if (!appSettingsToAdd.isEmpty() || !appSettingsToRemove.isEmpty()) {
observable =
listAppSettings()
.switchIfEmpty(Mono.just(new StringDictionaryInner()))
.flatMap(
stringDictionaryInner -> {
if (stringDictionaryInner.properties() == null) {
stringDictionaryInner.withProperties(new HashMap<String, String>());
}
for (String appSettingKey : appSettingsToRemove) {
stringDictionaryInner.properties().remove(appSettingKey);
}
stringDictionaryInner.properties().putAll(appSettingsToAdd);
return updateAppSettings(stringDictionaryInner);
})
.map(ignored -> WebAppBaseImpl.this);
}
return observable;
}
Mono<Indexable> submitMetadata() {
return Mono.just((Indexable) this);
}
Mono<Indexable> submitConnectionStrings() {
Mono<Indexable> observable = Mono.just((Indexable) this);
if (!connectionStringsToAdd.isEmpty() || !connectionStringsToRemove.isEmpty()) {
observable =
listConnectionStrings()
.switchIfEmpty(Mono.just(new ConnectionStringDictionaryInner()))
.flatMap(
dictionaryInner -> {
if (dictionaryInner.properties() == null) {
dictionaryInner.withProperties(new HashMap<String, ConnStringValueTypePair>());
}
for (String connectionString : connectionStringsToRemove) {
dictionaryInner.properties().remove(connectionString);
}
dictionaryInner.properties().putAll(connectionStringsToAdd);
return updateConnectionStrings(dictionaryInner);
})
.map(ignored -> WebAppBaseImpl.this);
}
return observable;
}
Mono<Indexable> submitStickiness() {
Mono<Indexable> observable = Mono.just((Indexable) this);
if (!appSettingStickiness.isEmpty() || !connectionStringStickiness.isEmpty()) {
observable =
listSlotConfigurations()
.switchIfEmpty(Mono.just(new SlotConfigNamesResourceInner()))
.flatMap(
slotConfigNamesResourceInner -> {
if (slotConfigNamesResourceInner.appSettingNames() == null) {
slotConfigNamesResourceInner.withAppSettingNames(new ArrayList<>());
}
if (slotConfigNamesResourceInner.connectionStringNames() == null) {
slotConfigNamesResourceInner.withConnectionStringNames(new ArrayList<>());
}
Set<String> stickyAppSettingKeys =
new HashSet<>(slotConfigNamesResourceInner.appSettingNames());
Set<String> stickyConnectionStringNames =
new HashSet<>(slotConfigNamesResourceInner.connectionStringNames());
for (Map.Entry<String, Boolean> stickiness : appSettingStickiness.entrySet()) {
if (stickiness.getValue()) {
stickyAppSettingKeys.add(stickiness.getKey());
} else {
stickyAppSettingKeys.remove(stickiness.getKey());
}
}
for (Map.Entry<String, Boolean> stickiness : connectionStringStickiness.entrySet()) {
if (stickiness.getValue()) {
stickyConnectionStringNames.add(stickiness.getKey());
} else {
stickyConnectionStringNames.remove(stickiness.getKey());
}
}
slotConfigNamesResourceInner.withAppSettingNames(new ArrayList<>(stickyAppSettingKeys));
slotConfigNamesResourceInner
.withConnectionStringNames(new ArrayList<>(stickyConnectionStringNames));
return updateSlotConfigurations(slotConfigNamesResourceInner);
})
.map(ignored -> WebAppBaseImpl.this);
}
return observable;
}
Mono<Indexable> submitSourceControlToCreate() {
if (sourceControl == null || sourceControlToDelete) {
return Mono.just((Indexable) this);
}
return sourceControl
.registerGithubAccessToken()
.then(createOrUpdateSourceControl(sourceControl.inner()))
.delayElement(SdkContext.getDelayDuration(Duration.ofSeconds(30)))
.map(ignored -> WebAppBaseImpl.this);
}
Mono<Indexable> submitSourceControlToDelete() {
if (!sourceControlToDelete) {
return Mono.just((Indexable) this);
}
return deleteSourceControl().map(ignored -> WebAppBaseImpl.this);
}
Mono<Indexable> submitAuthentication() {
if (!authenticationToUpdate) {
return Mono.just((Indexable) this);
}
return updateAuthentication(authentication.inner())
.map(
siteAuthSettingsInner -> {
WebAppBaseImpl.this.authentication =
new WebAppAuthenticationImpl<>(siteAuthSettingsInner, WebAppBaseImpl.this);
return WebAppBaseImpl.this;
});
}
Mono<Indexable> submitLogConfiguration() {
if (!diagnosticLogsToUpdate) {
return Mono.just((Indexable) this);
}
return updateDiagnosticLogsConfig(diagnosticLogs.inner())
.map(
siteLogsConfigInner -> {
WebAppBaseImpl.this.diagnosticLogs =
new WebAppDiagnosticLogsImpl<>(siteLogsConfigInner, WebAppBaseImpl.this);
return WebAppBaseImpl.this;
});
}
@Override
public WebDeploymentImpl<FluentT, FluentImplT> deploy() {
return new WebDeploymentImpl<>(this);
}
WebAppBaseImpl<FluentT, FluentImplT> withNewHostNameSslBinding(
final HostnameSslBindingImpl<FluentT, FluentImplT> hostNameSslBinding) {
sslBindingsToCreate.put(hostNameSslBinding.name(), hostNameSslBinding);
return this;
}
@SuppressWarnings("unchecked")
public FluentImplT withManagedHostnameBindings(AppServiceDomain domain, String... hostnames) {
for (String hostname : hostnames) {
if (hostname.equals("@") || hostname.equalsIgnoreCase(domain.name())) {
defineHostnameBinding()
.withAzureManagedDomain(domain)
.withSubDomain(hostname)
.withDnsRecordType(CustomHostnameDnsRecordType.A)
.attach();
} else {
defineHostnameBinding()
.withAzureManagedDomain(domain)
.withSubDomain(hostname)
.withDnsRecordType(CustomHostnameDnsRecordType.CNAME)
.attach();
}
}
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public HostnameBindingImpl<FluentT, FluentImplT> defineHostnameBinding() {
HostnameBindingInner inner = new HostnameBindingInner();
inner.withSiteName(name());
inner.withAzureResourceType(AzureResourceType.WEBSITE);
inner.withAzureResourceName(name());
inner.withHostnameType(HostnameType.VERIFIED);
return new HostnameBindingImpl<>(inner, (FluentImplT) this);
}
@SuppressWarnings("unchecked")
public FluentImplT withThirdPartyHostnameBinding(String domain, String... hostnames) {
for (String hostname : hostnames) {
defineHostnameBinding()
.withThirdPartyDomain(domain)
.withSubDomain(hostname)
.withDnsRecordType(CustomHostnameDnsRecordType.CNAME)
.attach();
}
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withoutHostnameBinding(String hostname) {
hostNameBindingsToDelete.add(hostname);
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withoutSslBinding(String hostname) {
if (hostNameSslStateMap.containsKey(hostname)) {
hostNameSslStateMap.get(hostname).withSslState(SslState.DISABLED).withToUpdate(true);
}
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
FluentImplT withHostNameBinding(final HostnameBindingImpl<FluentT, FluentImplT> hostNameBinding) {
this.hostNameBindingsToCreate.put(hostNameBinding.name(), hostNameBinding);
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withAppDisabledOnCreation() {
inner().withEnabled(false);
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withScmSiteAlsoStopped(boolean scmSiteAlsoStopped) {
inner().withScmSiteAlsoStopped(scmSiteAlsoStopped);
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withClientAffinityEnabled(boolean enabled) {
inner().withClientAffinityEnabled(enabled);
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withClientCertEnabled(boolean enabled) {
inner().withClientCertEnabled(enabled);
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public HostnameSslBindingImpl<FluentT, FluentImplT> defineSslBinding() {
return new HostnameSslBindingImpl<>(new HostnameSslState(), (FluentImplT) this);
}
@SuppressWarnings("unchecked")
public FluentImplT withNetFrameworkVersion(NetFrameworkVersion version) {
if (siteConfig == null) {
siteConfig = new SiteConfigResourceInner();
}
siteConfig.withNetFrameworkVersion(version.toString());
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withPhpVersion(PhpVersion version) {
if (siteConfig == null) {
siteConfig = new SiteConfigResourceInner();
}
siteConfig.withPhpVersion(version.toString());
return (FluentImplT) this;
}
public FluentImplT withoutPhp() {
return withPhpVersion(PhpVersion.fromString(""));
}
@SuppressWarnings("unchecked")
public FluentImplT withJavaVersion(JavaVersion version) {
if (siteConfig == null) {
siteConfig = new SiteConfigResourceInner();
}
siteConfig.withJavaVersion(version.toString());
return (FluentImplT) this;
}
public FluentImplT withoutJava() {
return withJavaVersion(JavaVersion.fromString("")).withWebContainer(WebContainer.fromString(""));
}
@SuppressWarnings("unchecked")
public FluentImplT withWebContainer(WebContainer webContainer) {
if (siteConfig == null) {
siteConfig = new SiteConfigResourceInner();
}
if (webContainer == null) {
siteConfig.withJavaContainer(null);
siteConfig.withJavaContainerVersion(null);
} else if (webContainer.toString().isEmpty()) {
siteConfig.withJavaContainer("");
siteConfig.withJavaContainerVersion("");
} else {
String[] containerInfo = webContainer.toString().split(" ");
siteConfig.withJavaContainer(containerInfo[0]);
siteConfig.withJavaContainerVersion(containerInfo[1]);
}
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withPythonVersion(PythonVersion version) {
if (siteConfig == null) {
siteConfig = new SiteConfigResourceInner();
}
siteConfig.withPythonVersion(version.toString());
return (FluentImplT) this;
}
public FluentImplT withoutPython() {
return withPythonVersion(PythonVersion.fromString(""));
}
@SuppressWarnings("unchecked")
public FluentImplT withPlatformArchitecture(PlatformArchitecture platform) {
if (siteConfig == null) {
siteConfig = new SiteConfigResourceInner();
}
siteConfig.withUse32BitWorkerProcess(platform.equals(PlatformArchitecture.X86));
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withWebSocketsEnabled(boolean enabled) {
if (siteConfig == null) {
siteConfig = new SiteConfigResourceInner();
}
siteConfig.withWebSocketsEnabled(enabled);
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withWebAppAlwaysOn(boolean alwaysOn) {
if (siteConfig == null) {
siteConfig = new SiteConfigResourceInner();
}
siteConfig.withAlwaysOn(alwaysOn);
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withManagedPipelineMode(ManagedPipelineMode managedPipelineMode) {
if (siteConfig == null) {
siteConfig = new SiteConfigResourceInner();
}
siteConfig.withManagedPipelineMode(managedPipelineMode);
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withAutoSwapSlotName(String slotName) {
if (siteConfig == null) {
siteConfig = new SiteConfigResourceInner();
}
siteConfig.withAutoSwapSlotName(slotName);
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withRemoteDebuggingEnabled(RemoteVisualStudioVersion remoteVisualStudioVersion) {
if (siteConfig == null) {
siteConfig = new SiteConfigResourceInner();
}
siteConfig.withRemoteDebuggingEnabled(true);
siteConfig.withRemoteDebuggingVersion(remoteVisualStudioVersion.toString());
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withRemoteDebuggingDisabled() {
if (siteConfig == null) {
siteConfig = new SiteConfigResourceInner();
}
siteConfig.withRemoteDebuggingEnabled(false);
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withDefaultDocument(String document) {
if (siteConfig == null) {
siteConfig = new SiteConfigResourceInner();
}
if (siteConfig.defaultDocuments() == null) {
siteConfig.withDefaultDocuments(new ArrayList<String>());
}
siteConfig.defaultDocuments().add(document);
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withDefaultDocuments(List<String> documents) {
if (siteConfig == null) {
siteConfig = new SiteConfigResourceInner();
}
if (siteConfig.defaultDocuments() == null) {
siteConfig.withDefaultDocuments(new ArrayList<>());
}
siteConfig.defaultDocuments().addAll(documents);
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withoutDefaultDocument(String document) {
if (siteConfig == null) {
siteConfig = new SiteConfigResourceInner();
}
if (siteConfig.defaultDocuments() != null) {
siteConfig.defaultDocuments().remove(document);
}
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withHttpsOnly(boolean httpsOnly) {
inner().withHttpsOnly(httpsOnly);
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withHttp20Enabled(boolean http20Enabled) {
if (siteConfig == null) {
siteConfig = new SiteConfigResourceInner();
}
siteConfig.withHttp20Enabled(http20Enabled);
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withFtpsState(FtpsState ftpsState) {
if (siteConfig == null) {
siteConfig = new SiteConfigResourceInner();
}
siteConfig.withFtpsState(ftpsState);
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withVirtualApplications(List<VirtualApplication> virtualApplications) {
if (siteConfig == null) {
siteConfig = new SiteConfigResourceInner();
}
siteConfig.withVirtualApplications(virtualApplications);
return (FluentImplT) this;
}
@Override
@SuppressWarnings("unchecked")
public FluentImplT withMinTlsVersion(SupportedTlsVersions minTlsVersion) {
if (siteConfig == null) {
siteConfig = new SiteConfigResourceInner();
}
siteConfig.withMinTlsVersion(minTlsVersion);
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withAppSetting(String key, String value) {
appSettingsToAdd.put(key, value);
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withAppSettings(Map<String, String> settings) {
appSettingsToAdd.putAll(settings);
return (FluentImplT) this;
}
public FluentImplT withStickyAppSetting(String key, String value) {
withAppSetting(key, value);
return withAppSettingStickiness(key, true);
}
@SuppressWarnings("unchecked")
public FluentImplT withStickyAppSettings(Map<String, String> settings) {
withAppSettings(settings);
for (String key : settings.keySet()) {
appSettingStickiness.put(key, true);
}
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withoutAppSetting(String key) {
appSettingsToRemove.add(key);
appSettingStickiness.remove(key);
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withAppSettingStickiness(String key, boolean sticky) {
appSettingStickiness.put(key, sticky);
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withConnectionString(String name, String value, ConnectionStringType type) {
connectionStringsToAdd.put(name, new ConnStringValueTypePair().withValue(value).withType(type));
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withStickyConnectionString(String name, String value, ConnectionStringType type) {
connectionStringsToAdd.put(name, new ConnStringValueTypePair().withValue(value).withType(type));
connectionStringStickiness.put(name, true);
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withoutConnectionString(String name) {
connectionStringsToRemove.add(name);
connectionStringStickiness.remove(name);
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withConnectionStringStickiness(String name, boolean stickiness) {
connectionStringStickiness.put(name, stickiness);
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
void withSourceControl(WebAppSourceControlImpl<FluentT, FluentImplT> sourceControl) {
this.sourceControl = sourceControl;
}
public WebAppSourceControlImpl<FluentT, FluentImplT> defineSourceControl() {
SiteSourceControlInner sourceControlInner = new SiteSourceControlInner();
return new WebAppSourceControlImpl<>(sourceControlInner, this);
}
@SuppressWarnings("unchecked")
public FluentImplT withLocalGitSourceControl() {
if (siteConfig == null) {
siteConfig = new SiteConfigResourceInner();
}
siteConfig.withScmType(ScmType.LOCAL_GIT);
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
public FluentImplT withoutSourceControl() {
sourceControlToDelete = true;
return (FluentImplT) this;
}
@SuppressWarnings("unchecked")
void withAuthentication(WebAppAuthenticationImpl<FluentT, FluentImplT> authentication) {
this.authentication = authentication;
authenticationToUpdate = true;
}
void withDiagnosticLogs(WebAppDiagnosticLogsImpl<FluentT, FluentImplT> diagnosticLogs) {
this.diagnosticLogs = diagnosticLogs;
diagnosticLogsToUpdate = true;
}
@Override
@SuppressWarnings("unchecked")
public Mono<FluentT> refreshAsync() {
return super
.refreshAsync()
.flatMap(
fluentT ->
getConfigInner()
.map(
returnedSiteConfig -> {
siteConfig = returnedSiteConfig;
return fluentT;
}));
}
@Override
protected Mono<SiteInner> getInnerAsync() {
return getInner();
}
@Override
public WebAppAuthenticationImpl<FluentT, FluentImplT> defineAuthentication() {
return new WebAppAuthenticationImpl<>(new SiteAuthSettingsInner().withEnabled(true), this);
}
@Override
@SuppressWarnings("unchecked")
public FluentImplT withoutAuthentication() {
this.authentication.inner().withEnabled(false);
authenticationToUpdate = true;
return (FluentImplT) this;
}
@Override
@SuppressWarnings("unchecked")
public FluentImplT withContainerLoggingEnabled(int quotaInMB, int retentionDays) {
return updateDiagnosticLogsConfiguration()
.withWebServerLogging()
.withWebServerLogsStoredOnFileSystem()
.withWebServerFileSystemQuotaInMB(quotaInMB)
.withLogRetentionDays(retentionDays)
.attach();
}
@Override
public FluentImplT withContainerLoggingEnabled() {
return withContainerLoggingEnabled(35, 0);
}
@Override
@SuppressWarnings("unchecked")
public FluentImplT withContainerLoggingDisabled() {
return updateDiagnosticLogsConfiguration().withoutWebServerLogging().attach();
}
@Override
@SuppressWarnings("unchecked")
public FluentImplT withSystemAssignedManagedServiceIdentity() {
this.webAppMsiHandler.withLocalManagedServiceIdentity();
return (FluentImplT) this;
}
@Override
@SuppressWarnings("unchecked")
public FluentImplT withoutSystemAssignedManagedServiceIdentity() {
this.webAppMsiHandler.withoutLocalManagedServiceIdentity();
return (FluentImplT) this;
}
@Override
@SuppressWarnings("unchecked")
public FluentImplT withUserAssignedManagedServiceIdentity() {
return (FluentImplT) this;
}
@Override
@SuppressWarnings("unchecked")
public FluentImplT withSystemAssignedIdentityBasedAccessTo(final String resourceId, final BuiltInRole role) {
this.webAppMsiHandler.withAccessTo(resourceId, role);
return (FluentImplT) this;
}
@Override
@SuppressWarnings("unchecked")
public FluentImplT withSystemAssignedIdentityBasedAccessToCurrentResourceGroup(final BuiltInRole role) {
this.webAppMsiHandler.withAccessToCurrentResourceGroup(role);
return (FluentImplT) this;
}
@Override
@SuppressWarnings("unchecked")
public FluentImplT withSystemAssignedIdentityBasedAccessTo(final String resourceId, final String roleDefinitionId) {
this.webAppMsiHandler.withAccessTo(resourceId, roleDefinitionId);
return (FluentImplT) this;
}
@Override
@SuppressWarnings("unchecked")
public FluentImplT withSystemAssignedIdentityBasedAccessToCurrentResourceGroup(final String roleDefinitionId) {
this.webAppMsiHandler.withAccessToCurrentResourceGroup(roleDefinitionId);
return (FluentImplT) this;
}
@Override
@SuppressWarnings("unchecked")
public FluentImplT withNewUserAssignedManagedServiceIdentity(Creatable<Identity> creatableIdentity) {
this.webAppMsiHandler.withNewExternalManagedServiceIdentity(creatableIdentity);
return (FluentImplT) this;
}
@Override
@SuppressWarnings("unchecked")
public FluentImplT withExistingUserAssignedManagedServiceIdentity(Identity identity) {
this.webAppMsiHandler.withExistingExternalManagedServiceIdentity(identity);
return (FluentImplT) this;
}
@Override
@SuppressWarnings("unchecked")
public FluentImplT withoutUserAssignedManagedServiceIdentity(String identityId) {
this.webAppMsiHandler.withoutExternalManagedServiceIdentity(identityId);
return (FluentImplT) this;
}
@Override
public WebAppDiagnosticLogsImpl<FluentT, FluentImplT> defineDiagnosticLogsConfiguration() {
if (diagnosticLogs == null) {
return new WebAppDiagnosticLogsImpl<>(new SiteLogsConfigInner(), this);
} else {
return diagnosticLogs;
}
}
@Override
public WebAppDiagnosticLogsImpl<FluentT, FluentImplT> updateDiagnosticLogsConfiguration() {
return defineDiagnosticLogsConfiguration();
}
@Override
public ManagedServiceIdentity identity() {
return webSiteBase.identity();
}
@Override
public boolean hyperV() {
return webSiteBase.hyperV();
}
@Override
public HostingEnvironmentProfile hostingEnvironmentProfile() {
return webSiteBase.hostingEnvironmentProfile();
}
@Override
public Set<String> clientCertExclusionPaths() {
return webSiteBase.clientCertExclusionPaths();
}
@Override
public Set<String> possibleOutboundIpAddresses() {
return webSiteBase.possibleOutboundIpAddresses();
}
@Override
public int dailyMemoryTimeQuota() {
return webSiteBase.dailyMemoryTimeQuota();
}
@Override
public OffsetDateTime suspendedTill() {
return webSiteBase.suspendedTill();
}
@Override
public int maxNumberOfWorkers() {
return webSiteBase.maxNumberOfWorkers();
}
@Override
public SlotSwapStatus slotSwapStatus() {
return webSiteBase.slotSwapStatus();
}
@Override
public RedundancyMode redundancyMode() {
return webSiteBase.redundancyMode();
}
private static class PipedInputStreamWithCallback extends PipedInputStream {
private Runnable callback;
private void addCallback(Runnable action) {
this.callback = action;
}
@Override
public void close() throws IOException {
callback.run();
super.close();
}
}
} |
Done | public Flux<String> deleteByIdsAsync(Collection<String> ids) {
if (ids == null || ids.isEmpty()) {
return Flux.empty();
}
Collection<Mono<String>> observables = new ArrayList<>();
for (String id : ids) {
final String resourceGroupName = ResourceUtils.groupFromResourceId(id);
final String name = ResourceUtils.nameFromResourceId(id);
Mono<String> o = ReactorMapper.map(this.inner().deleteAsync(resourceGroupName, name), id);
observables.add(o);
}
return Flux.mergeDelayError(32, observables.toArray(new Mono[0]));
} | return Flux.mergeDelayError(32, observables.toArray(new Mono[0])); | public Flux<String> deleteByIdsAsync(Collection<String> ids) {
return BatchDeletionImpl.deleteByIdsAsync(ids, this::deleteInnerAsync);
} | class WebAppsImpl
extends GroupableResourcesImpl<WebApp, WebAppImpl, SiteInner, WebAppsClient, AppServiceManager>
implements WebApps, SupportsBatchDeletion {
public WebAppsImpl(final AppServiceManager manager) {
super(manager.inner().getWebApps(), manager);
}
@Override
public Mono<WebApp> getByResourceGroupAsync(final String groupName, final String name) {
final WebAppsImpl self = this;
return this
.inner()
.getByResourceGroupAsync(groupName, name)
.flatMap(
siteInner ->
Mono
.zip(
self.inner().getConfigurationAsync(groupName, name),
self.inner().getDiagnosticLogsConfigurationAsync(groupName, name),
(SiteConfigResourceInner siteConfigResourceInner, SiteLogsConfigInner logsConfigInner) ->
wrapModel(siteInner, siteConfigResourceInner, logsConfigInner)));
}
@Override
protected Mono<SiteInner> getInnerAsync(String resourceGroupName, String name) {
return null;
}
@Override
protected Mono<Void> deleteInnerAsync(String resourceGroupName, String name) {
return null;
}
@Override
protected WebAppImpl wrapModel(String name) {
return new WebAppImpl(name, new SiteInner().withKind("app"), null, null, this.manager());
}
protected WebAppImpl wrapModel(SiteInner inner, SiteConfigResourceInner siteConfig, SiteLogsConfigInner logConfig) {
if (inner == null) {
return null;
}
return new WebAppImpl(inner.name(), inner, siteConfig, logConfig, this.manager());
}
@Override
protected WebAppImpl wrapModel(SiteInner inner) {
return wrapModel(inner, null, null);
}
@Override
protected PagedFlux<WebApp> wrapPageAsync(PagedFlux<SiteInner> innerPage) {
return PagedConverter
.flatMapPage(
innerPage,
siteInner -> {
if (siteInner.kind() == null || Arrays.asList(siteInner.kind().split(",")).contains("app")) {
return Mono
.zip(
this.inner().getConfigurationAsync(siteInner.resourceGroup(), siteInner.name()),
this
.inner()
.getDiagnosticLogsConfigurationAsync(
siteInner.resourceGroup(), siteInner.name()),
(siteConfigResourceInner, logsConfigInner) ->
this.wrapModel(siteInner, siteConfigResourceInner, logsConfigInner));
} else {
return Mono.empty();
}
});
}
@Override
public WebAppImpl define(String name) {
return wrapModel(name);
}
@Override
@SuppressWarnings({"unchecked", "rawtypes"})
@Override
public Flux<String> deleteByIdsAsync(String... ids) {
return this.deleteByIdsAsync(new ArrayList<>(Arrays.asList(ids)));
}
@Override
public void deleteByIds(Collection<String> ids) {
if (ids != null && !ids.isEmpty()) {
this.deleteByIdsAsync(ids).blockLast();
}
}
@Override
public void deleteByIds(String... ids) {
this.deleteByIds(new ArrayList<>(Arrays.asList(ids)));
}
@Override
public PagedIterable<WebAppBasic> listByResourceGroup(String resourceGroupName) {
return new PagedIterable<>(this.listByResourceGroupAsync(resourceGroupName));
}
@Override
public PagedFlux<WebAppBasic> listByResourceGroupAsync(String resourceGroupName) {
return inner().listByResourceGroupAsync(resourceGroupName)
.mapPage(inner -> new WebAppBasicImpl(inner, this.manager()));
}
@Override
public PagedIterable<WebAppBasic> list() {
return new PagedIterable<>(this.listAsync());
}
@Override
public PagedFlux<WebAppBasic> listAsync() {
return inner().listAsync()
.mapPage(inner -> new WebAppBasicImpl(inner, this.manager()));
}
} | class WebAppsImpl
extends GroupableResourcesImpl<WebApp, WebAppImpl, SiteInner, WebAppsClient, AppServiceManager>
implements WebApps, SupportsBatchDeletion {
public WebAppsImpl(final AppServiceManager manager) {
super(manager.inner().getWebApps(), manager);
}
@Override
public Mono<WebApp> getByResourceGroupAsync(final String groupName, final String name) {
final WebAppsImpl self = this;
return this
.getInnerAsync(groupName, name)
.flatMap(
siteInner ->
Mono
.zip(
self.inner().getConfigurationAsync(groupName, name),
self.inner().getDiagnosticLogsConfigurationAsync(groupName, name),
(SiteConfigResourceInner siteConfigResourceInner, SiteLogsConfigInner logsConfigInner) ->
wrapModel(siteInner, siteConfigResourceInner, logsConfigInner)));
}
@Override
protected Mono<SiteInner> getInnerAsync(String resourceGroupName, String name) {
return this.inner().getByResourceGroupAsync(resourceGroupName, name);
}
@Override
protected Mono<Void> deleteInnerAsync(String resourceGroupName, String name) {
return inner().deleteAsync(resourceGroupName, name).then();
}
@Override
protected WebAppImpl wrapModel(String name) {
return new WebAppImpl(name, new SiteInner().withKind("app"), null, null, this.manager());
}
protected WebAppImpl wrapModel(SiteInner inner, SiteConfigResourceInner siteConfig, SiteLogsConfigInner logConfig) {
if (inner == null) {
return null;
}
return new WebAppImpl(inner.name(), inner, siteConfig, logConfig, this.manager());
}
@Override
protected WebAppImpl wrapModel(SiteInner inner) {
return wrapModel(inner, null, null);
}
@Override
public WebAppImpl define(String name) {
return wrapModel(name);
}
@Override
@Override
public Flux<String> deleteByIdsAsync(String... ids) {
return this.deleteByIdsAsync(new ArrayList<>(Arrays.asList(ids)));
}
@Override
public void deleteByIds(Collection<String> ids) {
if (ids != null && !ids.isEmpty()) {
this.deleteByIdsAsync(ids).blockLast();
}
}
@Override
public void deleteByIds(String... ids) {
this.deleteByIds(new ArrayList<>(Arrays.asList(ids)));
}
@Override
public PagedIterable<WebAppBasic> listByResourceGroup(String resourceGroupName) {
return new PagedIterable<>(this.listByResourceGroupAsync(resourceGroupName));
}
@Override
public PagedFlux<WebAppBasic> listByResourceGroupAsync(String resourceGroupName) {
return inner().listByResourceGroupAsync(resourceGroupName)
.mapPage(inner -> new WebAppBasicImpl(inner, this.manager()));
}
@Override
public PagedIterable<WebAppBasic> list() {
return new PagedIterable<>(this.listAsync());
}
@Override
public PagedFlux<WebAppBasic> listAsync() {
return inner().listAsync()
.mapPage(inner -> new WebAppBasicImpl(inner, this.manager()));
}
} |
If no order needed, use `Flux.mergeDelayError` | public Mono<CdnEndpoint> updateResourceAsync() {
final CdnEndpointImpl self = this;
EndpointUpdateParameters endpointUpdateParameters = new EndpointUpdateParameters();
endpointUpdateParameters.withIsHttpAllowed(this.inner().isHttpAllowed())
.withIsHttpsAllowed(this.inner().isHttpsAllowed())
.withOriginPath(this.inner().originPath())
.withOriginHostHeader(this.inner().originHostHeader())
.withIsCompressionEnabled(this.inner().isCompressionEnabled())
.withContentTypesToCompress(this.inner().contentTypesToCompress())
.withGeoFilters(this.inner().geoFilters())
.withOptimizationType(this.inner().optimizationType())
.withQueryStringCachingBehavior(this.inner().queryStringCachingBehavior())
.withTags(this.inner().tags());
DeepCreatedOrigin originInner = this.inner().origins().get(0);
OriginUpdateParameters originUpdateParameters = new OriginUpdateParameters()
.withHostname(originInner.hostname())
.withHttpPort(originInner.httpPort())
.withHttpsPort(originInner.httpsPort());
Mono<OriginInner> originUpdateTask = this.parent().manager().inner().getOrigins().updateAsync(
this.parent().resourceGroupName(),
this.parent().name(),
this.name(),
originInner.name(),
originUpdateParameters);
Mono<EndpointInner> endpointUpdateTask = this.parent().manager().inner().getEndpoints().updateAsync(
this.parent().resourceGroupName(),
this.parent().name(),
this.name(),
endpointUpdateParameters);
Flux<CustomDomainInner> customDomainCreateTask = Flux.fromIterable(this.customDomainList)
.flatMapDelayError(itemToCreate -> this.parent().manager().inner().getCustomDomains().createAsync(
this.parent().resourceGroupName(),
this.parent().name(),
this.name(),
self.parent().manager().sdkContext().randomResourceName("CustomDomain", 50),
itemToCreate.hostname()
), 32, 32);
Flux<CustomDomainInner> customDomainDeleteTask = Flux.fromIterable(this.deletedCustomDomainList)
.flatMapDelayError(itemToDelete -> this.parent().manager().inner().getCustomDomains().deleteAsync(
this.parent().resourceGroupName(),
this.parent().name(),
this.name(),
itemToDelete.name()
), 32, 32);
Flux<CustomDomainInner> customDomainTask = Flux.concat(customDomainCreateTask, customDomainDeleteTask);
return customDomainTask.then(originUpdateTask).then(endpointUpdateTask)
.map(inner -> {
self.setInner(inner);
self.customDomainList.clear();
self.deletedCustomDomainList.clear();
return self;
});
} | Flux<CustomDomainInner> customDomainTask = Flux.concat(customDomainCreateTask, customDomainDeleteTask); | public Mono<CdnEndpoint> updateResourceAsync() {
final CdnEndpointImpl self = this;
EndpointUpdateParameters endpointUpdateParameters = new EndpointUpdateParameters();
endpointUpdateParameters.withIsHttpAllowed(this.inner().isHttpAllowed())
.withIsHttpsAllowed(this.inner().isHttpsAllowed())
.withOriginPath(this.inner().originPath())
.withOriginHostHeader(this.inner().originHostHeader())
.withIsCompressionEnabled(this.inner().isCompressionEnabled())
.withContentTypesToCompress(this.inner().contentTypesToCompress())
.withGeoFilters(this.inner().geoFilters())
.withOptimizationType(this.inner().optimizationType())
.withQueryStringCachingBehavior(this.inner().queryStringCachingBehavior())
.withTags(this.inner().tags());
DeepCreatedOrigin originInner = this.inner().origins().get(0);
OriginUpdateParameters originUpdateParameters = new OriginUpdateParameters()
.withHostname(originInner.hostname())
.withHttpPort(originInner.httpPort())
.withHttpsPort(originInner.httpsPort());
Mono<EndpointInner> originUpdateTask = this.parent().manager().inner().getOrigins().updateAsync(
this.parent().resourceGroupName(),
this.parent().name(),
this.name(),
originInner.name(),
originUpdateParameters)
.then(Mono.empty());
Mono<EndpointInner> endpointUpdateTask = this.parent().manager().inner().getEndpoints().updateAsync(
this.parent().resourceGroupName(),
this.parent().name(),
this.name(),
endpointUpdateParameters);
Flux<CustomDomainInner> customDomainCreateTask = Flux.fromIterable(this.customDomainList)
.flatMapDelayError(itemToCreate -> this.parent().manager().inner().getCustomDomains().createAsync(
this.parent().resourceGroupName(),
this.parent().name(),
this.name(),
self.parent().manager().sdkContext().randomResourceName("CustomDomain", 50),
itemToCreate.hostname()
), 32, 32);
Flux<CustomDomainInner> customDomainDeleteTask = Flux.fromIterable(this.deletedCustomDomainList)
.flatMapDelayError(itemToDelete -> this.parent().manager().inner().getCustomDomains().deleteAsync(
this.parent().resourceGroupName(),
this.parent().name(),
this.name(),
itemToDelete.name()
), 32, 32);
Mono<EndpointInner> customDomainTask = Flux.concat(customDomainCreateTask, customDomainDeleteTask)
.then(Mono.empty());
return Flux.mergeDelayError(32, customDomainTask, originUpdateTask, endpointUpdateTask)
.last()
.map(inner -> {
self.setInner(inner);
self.customDomainList.clear();
self.deletedCustomDomainList.clear();
return self;
});
} | class CdnEndpointImpl
extends ExternalChildResourceImpl<
CdnEndpoint,
EndpointInner,
CdnProfileImpl,
CdnProfile>
implements CdnEndpoint,
CdnEndpoint.DefinitionStages.Blank.StandardEndpoint<CdnProfile.DefinitionStages.WithStandardCreate>,
CdnEndpoint.DefinitionStages.Blank.PremiumEndpoint<CdnProfile.DefinitionStages.WithPremiumVerizonCreate>,
CdnEndpoint.DefinitionStages.WithStandardAttach<CdnProfile.DefinitionStages.WithStandardCreate>,
CdnEndpoint.DefinitionStages.WithPremiumAttach<CdnProfile.DefinitionStages.WithPremiumVerizonCreate>,
CdnEndpoint.UpdateDefinitionStages.Blank.StandardEndpoint<CdnProfile.Update>,
CdnEndpoint.UpdateDefinitionStages.Blank.PremiumEndpoint<CdnProfile.Update>,
CdnEndpoint.UpdateDefinitionStages.WithStandardAttach<CdnProfile.Update>,
CdnEndpoint.UpdateDefinitionStages.WithPremiumAttach<CdnProfile.Update>,
CdnEndpoint.UpdateStandardEndpoint,
CdnEndpoint.UpdatePremiumEndpoint {
private List<CustomDomainInner> customDomainList;
private List<CustomDomainInner> deletedCustomDomainList;
CdnEndpointImpl(String name, CdnProfileImpl parent, EndpointInner inner) {
super(name, parent, inner);
this.customDomainList = new ArrayList<>();
this.deletedCustomDomainList = new ArrayList<>();
}
@Override
public String id() {
return this.inner().id();
}
@Override
public Mono<CdnEndpoint> createResourceAsync() {
final CdnEndpointImpl self = this;
return this.parent().manager().inner().getEndpoints().createAsync(this.parent().resourceGroupName(),
this.parent().name(),
this.name(),
this.inner())
.flatMap(inner -> {
self.setInner(inner);
return Flux.fromIterable(self.customDomainList)
.flatMapDelayError(customDomainInner -> self.parent().manager().inner()
.getCustomDomains().createAsync(
self.parent().resourceGroupName(),
self.parent().name(),
self.name(),
self.parent().manager().sdkContext().randomResourceName("CustomDomain", 50),
customDomainInner.hostname()), 32, 32)
.then(self.parent().manager().inner()
.getCustomDomains().listByEndpointAsync(
self.parent().resourceGroupName(),
self.parent().name(),
self.name())
.collectList()
.map(customDomainInners -> {
self.customDomainList.addAll(customDomainInners);
return self;
}));
});
}
@Override
@Override
public Mono<Void> deleteResourceAsync() {
return this.parent().manager().inner().getEndpoints().deleteAsync(this.parent().resourceGroupName(),
this.parent().name(),
this.name());
}
@Override
public Mono<CdnEndpoint> refreshAsync() {
final CdnEndpointImpl self = this;
return super.refreshAsync()
.flatMap(cdnEndpoint -> {
self.customDomainList.clear();
self.deletedCustomDomainList.clear();
return self.parent().manager().inner().getCustomDomains().listByEndpointAsync(
self.parent().resourceGroupName(),
self.parent().name(),
self.name()
)
.collectList()
.map(customDomainInners -> {
self.customDomainList.addAll(customDomainInners);
return self;
});
});
}
@Override
protected Mono<EndpointInner> getInnerAsync() {
return this.parent().manager().inner().getEndpoints().getAsync(this.parent().resourceGroupName(),
this.parent().name(),
this.name());
}
@Override
public PagedIterable<ResourceUsage> listResourceUsage() {
return this.parent().manager().inner().getEndpoints().listResourceUsage(
this.parent().resourceGroupName(),
this.parent().name(),
this.name())
.mapPage(ResourceUsage::new);
}
@Override
public CdnProfileImpl attach() {
return this.parent();
}
@Override
public String originHostHeader() {
return this.inner().originHostHeader();
}
@Override
public String originPath() {
return this.inner().originPath();
}
@Override
public Set<String> contentTypesToCompress() {
List<String> contentTypes = this.inner().contentTypesToCompress();
Set<String> set = new HashSet<>();
if (contentTypes != null) {
set.addAll(contentTypes);
}
return Collections.unmodifiableSet(set);
}
@Override
public boolean isCompressionEnabled() {
return this.inner().isCompressionEnabled();
}
@Override
public boolean isHttpAllowed() {
return this.inner().isHttpAllowed();
}
@Override
public boolean isHttpsAllowed() {
return this.inner().isHttpsAllowed();
}
@Override
public QueryStringCachingBehavior queryStringCachingBehavior() {
return this.inner().queryStringCachingBehavior();
}
@Override
public String optimizationType() {
if (this.inner().optimizationType() == null) {
return null;
}
return this.inner().optimizationType().toString();
}
@Override
public List<GeoFilter> geoFilters() {
return this.inner().geoFilters();
}
@Override
public String hostname() {
return this.inner().hostname();
}
@Override
public EndpointResourceState resourceState() {
return this.inner().resourceState();
}
@Override
public String provisioningState() {
return this.inner().provisioningState();
}
@Override
public String originHostName() {
if (this.inner().origins() != null && !this.inner().origins().isEmpty()) {
return this.inner().origins().get(0).hostname();
}
return null;
}
@Override
public int httpPort() {
if (this.inner().origins() != null && !this.inner().origins().isEmpty()) {
Integer httpPort = this.inner().origins().get(0).httpPort();
return (httpPort != null) ? httpPort : 0;
}
return 0;
}
@Override
public int httpsPort() {
if (this.inner().origins() != null && !this.inner().origins().isEmpty()) {
Integer httpsPort = this.inner().origins().get(0).httpsPort();
return (httpsPort != null) ? httpsPort : 0;
}
return 0;
}
@Override
public Set<String> customDomains() {
Set<String> set = new HashSet<>();
for (CustomDomainInner customDomainInner : this.parent().manager().inner().getCustomDomains()
.listByEndpoint(this.parent().resourceGroupName(), this.parent().name(), this.name())) {
set.add(customDomainInner.hostname());
}
return Collections.unmodifiableSet(set);
}
@Override
public void start() {
this.parent().startEndpoint(this.name());
}
@Override
public Mono<Void> startAsync() {
return this.parent().startEndpointAsync(this.name());
}
@Override
public void stop() {
this.stopAsync().block();
}
@Override
public Mono<Void> stopAsync() {
return this.parent().stopEndpointAsync(this.name());
}
@Override
public void purgeContent(Set<String> contentPaths) {
if (contentPaths != null) {
this.purgeContentAsync(contentPaths).block();
}
}
@Override
public Mono<Void> purgeContentAsync(Set<String> contentPaths) {
return this.parent().purgeEndpointContentAsync(this.name(), contentPaths);
}
@Override
public void loadContent(Set<String> contentPaths) {
this.loadContentAsync(contentPaths).block();
}
@Override
public Mono<Void> loadContentAsync(Set<String> contentPaths) {
return this.parent().loadEndpointContentAsync(this.name(), contentPaths);
}
@Override
public CustomDomainValidationResult validateCustomDomain(String hostName) {
return this.validateCustomDomainAsync(hostName).block();
}
@Override
public Mono<CustomDomainValidationResult> validateCustomDomainAsync(String hostName) {
return this.parent().validateEndpointCustomDomainAsync(this.name(), hostName);
}
@Override
public CdnEndpointImpl withOrigin(String originName, String hostname) {
this.inner().origins().add(
new DeepCreatedOrigin()
.withName(originName)
.withHostname(hostname));
return this;
}
@Override
public CdnEndpointImpl withOrigin(String hostname) {
return this.withOrigin("origin", hostname);
}
@Override
public CdnEndpointImpl withPremiumOrigin(String originName, String hostname) {
return this.withOrigin(originName, hostname);
}
@Override
public CdnEndpointImpl withPremiumOrigin(String hostname) {
return this.withOrigin(hostname);
}
@Override
public CdnEndpointImpl withOriginPath(String originPath) {
this.inner().withOriginPath(originPath);
return this;
}
@Override
public CdnEndpointImpl withHttpAllowed(boolean httpAllowed) {
this.inner().withIsHttpAllowed(httpAllowed);
return this;
}
@Override
public CdnEndpointImpl withHttpsAllowed(boolean httpsAllowed) {
this.inner().withIsHttpsAllowed(httpsAllowed);
return this;
}
@Override
public CdnEndpointImpl withHttpPort(int httpPort) {
if (this.inner().origins() != null && !this.inner().origins().isEmpty()) {
this.inner().origins().get(0).withHttpPort(httpPort);
}
return this;
}
@Override
public CdnEndpointImpl withHttpsPort(int httpsPort) {
if (this.inner().origins() != null && !this.inner().origins().isEmpty()) {
this.inner().origins().get(0).withHttpsPort(httpsPort);
}
return this;
}
@Override
public CdnEndpointImpl withHostHeader(String hostHeader) {
this.inner().withOriginHostHeader(hostHeader);
return this;
}
@Override
public CdnEndpointImpl withContentTypesToCompress(Set<String> contentTypesToCompress) {
List<String> list = null;
if (contentTypesToCompress != null) {
list = new ArrayList<>(contentTypesToCompress);
}
this.inner().withContentTypesToCompress(list);
return this;
}
@Override
public CdnEndpointImpl withoutContentTypesToCompress() {
if (this.inner().contentTypesToCompress() != null) {
this.inner().contentTypesToCompress().clear();
}
return this;
}
@Override
public CdnEndpointImpl withContentTypeToCompress(String contentTypeToCompress) {
if (this.inner().contentTypesToCompress() == null) {
this.inner().withContentTypesToCompress(new ArrayList<>());
}
this.inner().contentTypesToCompress().add(contentTypeToCompress);
return this;
}
@Override
public CdnEndpointImpl withoutContentTypeToCompress(String contentTypeToCompress) {
if (this.inner().contentTypesToCompress() != null) {
this.inner().contentTypesToCompress().remove(contentTypeToCompress);
}
return this;
}
@Override
public CdnEndpointImpl withCompressionEnabled(boolean compressionEnabled) {
this.inner().withIsCompressionEnabled(compressionEnabled);
return this;
}
@Override
public CdnEndpointImpl withQueryStringCachingBehavior(QueryStringCachingBehavior cachingBehavior) {
this.inner().withQueryStringCachingBehavior(cachingBehavior);
return this;
}
@Override
public CdnEndpointImpl withGeoFilters(Collection<GeoFilter> geoFilters) {
List<GeoFilter> list = null;
if (geoFilters != null) {
list = new ArrayList<>(geoFilters);
}
this.inner().withGeoFilters(list);
return this;
}
@Override
public CdnEndpointImpl withoutGeoFilters() {
if (this.inner().geoFilters() != null) {
this.inner().geoFilters().clear();
}
return this;
}
@Override
public CdnEndpointImpl withGeoFilter(String relativePath, GeoFilterActions action, CountryIsoCode countryCode) {
GeoFilter geoFilter = this.createGeoFiltersObject(relativePath, action);
if (geoFilter.countryCodes() == null) {
geoFilter.withCountryCodes(new ArrayList<>());
}
geoFilter.countryCodes().add(countryCode.toString());
this.inner().geoFilters().add(geoFilter);
return this;
}
@Override
public CdnEndpointImpl withGeoFilter(
String relativePath, GeoFilterActions action, Collection<CountryIsoCode> countryCodes) {
GeoFilter geoFilter = this.createGeoFiltersObject(relativePath, action);
if (geoFilter.countryCodes() == null) {
geoFilter.withCountryCodes(new ArrayList<>());
} else {
geoFilter.countryCodes().clear();
}
for (CountryIsoCode countryCode : countryCodes) {
geoFilter.countryCodes().add(countryCode.toString());
}
this.inner().geoFilters().add(geoFilter);
return this;
}
@Override
public CdnEndpointImpl withoutGeoFilter(String relativePath) {
this.inner().geoFilters().removeIf(geoFilter -> geoFilter.relativePath().equals(relativePath));
return this;
}
@Override
public CdnEndpointImpl withCustomDomain(String hostName) {
this.customDomainList.add(new CustomDomainInner().withHostname(hostName));
return this;
}
@Override
public CdnEndpointImpl withoutCustomDomain(String hostName) {
deletedCustomDomainList.add(new CustomDomainInner().withHostname(hostName));
return this;
}
private GeoFilter createGeoFiltersObject(String relativePath, GeoFilterActions action) {
if (this.inner().geoFilters() == null) {
this.inner().withGeoFilters(new ArrayList<>());
}
GeoFilter geoFilter = null;
for (GeoFilter filter : this.inner().geoFilters()) {
if (filter.relativePath().equals(relativePath)) {
geoFilter = filter;
break;
}
}
if (geoFilter == null) {
geoFilter = new GeoFilter();
} else {
this.inner().geoFilters().remove(geoFilter);
}
geoFilter.withRelativePath(relativePath)
.withAction(action);
return geoFilter;
}
} | class CdnEndpointImpl
extends ExternalChildResourceImpl<
CdnEndpoint,
EndpointInner,
CdnProfileImpl,
CdnProfile>
implements CdnEndpoint,
CdnEndpoint.DefinitionStages.Blank.StandardEndpoint<CdnProfile.DefinitionStages.WithStandardCreate>,
CdnEndpoint.DefinitionStages.Blank.PremiumEndpoint<CdnProfile.DefinitionStages.WithPremiumVerizonCreate>,
CdnEndpoint.DefinitionStages.WithStandardAttach<CdnProfile.DefinitionStages.WithStandardCreate>,
CdnEndpoint.DefinitionStages.WithPremiumAttach<CdnProfile.DefinitionStages.WithPremiumVerizonCreate>,
CdnEndpoint.UpdateDefinitionStages.Blank.StandardEndpoint<CdnProfile.Update>,
CdnEndpoint.UpdateDefinitionStages.Blank.PremiumEndpoint<CdnProfile.Update>,
CdnEndpoint.UpdateDefinitionStages.WithStandardAttach<CdnProfile.Update>,
CdnEndpoint.UpdateDefinitionStages.WithPremiumAttach<CdnProfile.Update>,
CdnEndpoint.UpdateStandardEndpoint,
CdnEndpoint.UpdatePremiumEndpoint {
private List<CustomDomainInner> customDomainList;
private List<CustomDomainInner> deletedCustomDomainList;
CdnEndpointImpl(String name, CdnProfileImpl parent, EndpointInner inner) {
super(name, parent, inner);
this.customDomainList = new ArrayList<>();
this.deletedCustomDomainList = new ArrayList<>();
}
@Override
public String id() {
return this.inner().id();
}
@Override
public Mono<CdnEndpoint> createResourceAsync() {
final CdnEndpointImpl self = this;
return this.parent().manager().inner().getEndpoints().createAsync(this.parent().resourceGroupName(),
this.parent().name(),
this.name(),
this.inner())
.flatMap(inner -> {
self.setInner(inner);
return Flux.fromIterable(self.customDomainList)
.flatMapDelayError(customDomainInner -> self.parent().manager().inner()
.getCustomDomains().createAsync(
self.parent().resourceGroupName(),
self.parent().name(),
self.name(),
self.parent().manager().sdkContext().randomResourceName("CustomDomain", 50),
customDomainInner.hostname()), 32, 32)
.then(self.parent().manager().inner()
.getCustomDomains().listByEndpointAsync(
self.parent().resourceGroupName(),
self.parent().name(),
self.name())
.collectList()
.map(customDomainInners -> {
self.customDomainList.addAll(customDomainInners);
return self;
}));
});
}
@Override
@Override
public Mono<Void> deleteResourceAsync() {
return this.parent().manager().inner().getEndpoints().deleteAsync(this.parent().resourceGroupName(),
this.parent().name(),
this.name());
}
@Override
public Mono<CdnEndpoint> refreshAsync() {
final CdnEndpointImpl self = this;
return super.refreshAsync()
.flatMap(cdnEndpoint -> {
self.customDomainList.clear();
self.deletedCustomDomainList.clear();
return self.parent().manager().inner().getCustomDomains().listByEndpointAsync(
self.parent().resourceGroupName(),
self.parent().name(),
self.name()
)
.collectList()
.map(customDomainInners -> {
self.customDomainList.addAll(customDomainInners);
return self;
});
});
}
@Override
protected Mono<EndpointInner> getInnerAsync() {
return this.parent().manager().inner().getEndpoints().getAsync(this.parent().resourceGroupName(),
this.parent().name(),
this.name());
}
@Override
public PagedIterable<ResourceUsage> listResourceUsage() {
return this.parent().manager().inner().getEndpoints().listResourceUsage(
this.parent().resourceGroupName(),
this.parent().name(),
this.name())
.mapPage(ResourceUsage::new);
}
@Override
public CdnProfileImpl attach() {
return this.parent();
}
@Override
public String originHostHeader() {
return this.inner().originHostHeader();
}
@Override
public String originPath() {
return this.inner().originPath();
}
@Override
public Set<String> contentTypesToCompress() {
List<String> contentTypes = this.inner().contentTypesToCompress();
Set<String> set = new HashSet<>();
if (contentTypes != null) {
set.addAll(contentTypes);
}
return Collections.unmodifiableSet(set);
}
@Override
public boolean isCompressionEnabled() {
return this.inner().isCompressionEnabled();
}
@Override
public boolean isHttpAllowed() {
return this.inner().isHttpAllowed();
}
@Override
public boolean isHttpsAllowed() {
return this.inner().isHttpsAllowed();
}
@Override
public QueryStringCachingBehavior queryStringCachingBehavior() {
return this.inner().queryStringCachingBehavior();
}
@Override
public String optimizationType() {
if (this.inner().optimizationType() == null) {
return null;
}
return this.inner().optimizationType().toString();
}
@Override
public List<GeoFilter> geoFilters() {
return this.inner().geoFilters();
}
@Override
public String hostname() {
return this.inner().hostname();
}
@Override
public EndpointResourceState resourceState() {
return this.inner().resourceState();
}
@Override
public String provisioningState() {
return this.inner().provisioningState();
}
@Override
public String originHostName() {
if (this.inner().origins() != null && !this.inner().origins().isEmpty()) {
return this.inner().origins().get(0).hostname();
}
return null;
}
@Override
public int httpPort() {
if (this.inner().origins() != null && !this.inner().origins().isEmpty()) {
Integer httpPort = this.inner().origins().get(0).httpPort();
return (httpPort != null) ? httpPort : 0;
}
return 0;
}
@Override
public int httpsPort() {
if (this.inner().origins() != null && !this.inner().origins().isEmpty()) {
Integer httpsPort = this.inner().origins().get(0).httpsPort();
return (httpsPort != null) ? httpsPort : 0;
}
return 0;
}
@Override
public Set<String> customDomains() {
Set<String> set = new HashSet<>();
for (CustomDomainInner customDomainInner : this.parent().manager().inner().getCustomDomains()
.listByEndpoint(this.parent().resourceGroupName(), this.parent().name(), this.name())) {
set.add(customDomainInner.hostname());
}
return Collections.unmodifiableSet(set);
}
@Override
public void start() {
this.parent().startEndpoint(this.name());
}
@Override
public Mono<Void> startAsync() {
return this.parent().startEndpointAsync(this.name());
}
@Override
public void stop() {
this.stopAsync().block();
}
@Override
public Mono<Void> stopAsync() {
return this.parent().stopEndpointAsync(this.name());
}
@Override
public void purgeContent(Set<String> contentPaths) {
if (contentPaths != null) {
this.purgeContentAsync(contentPaths).block();
}
}
@Override
public Mono<Void> purgeContentAsync(Set<String> contentPaths) {
return this.parent().purgeEndpointContentAsync(this.name(), contentPaths);
}
@Override
public void loadContent(Set<String> contentPaths) {
this.loadContentAsync(contentPaths).block();
}
@Override
public Mono<Void> loadContentAsync(Set<String> contentPaths) {
return this.parent().loadEndpointContentAsync(this.name(), contentPaths);
}
@Override
public CustomDomainValidationResult validateCustomDomain(String hostName) {
return this.validateCustomDomainAsync(hostName).block();
}
@Override
public Mono<CustomDomainValidationResult> validateCustomDomainAsync(String hostName) {
return this.parent().validateEndpointCustomDomainAsync(this.name(), hostName);
}
@Override
public CdnEndpointImpl withOrigin(String originName, String hostname) {
this.inner().origins().add(
new DeepCreatedOrigin()
.withName(originName)
.withHostname(hostname));
return this;
}
@Override
public CdnEndpointImpl withOrigin(String hostname) {
return this.withOrigin("origin", hostname);
}
@Override
public CdnEndpointImpl withPremiumOrigin(String originName, String hostname) {
return this.withOrigin(originName, hostname);
}
@Override
public CdnEndpointImpl withPremiumOrigin(String hostname) {
return this.withOrigin(hostname);
}
@Override
public CdnEndpointImpl withOriginPath(String originPath) {
this.inner().withOriginPath(originPath);
return this;
}
@Override
public CdnEndpointImpl withHttpAllowed(boolean httpAllowed) {
this.inner().withIsHttpAllowed(httpAllowed);
return this;
}
@Override
public CdnEndpointImpl withHttpsAllowed(boolean httpsAllowed) {
this.inner().withIsHttpsAllowed(httpsAllowed);
return this;
}
@Override
public CdnEndpointImpl withHttpPort(int httpPort) {
if (this.inner().origins() != null && !this.inner().origins().isEmpty()) {
this.inner().origins().get(0).withHttpPort(httpPort);
}
return this;
}
@Override
public CdnEndpointImpl withHttpsPort(int httpsPort) {
if (this.inner().origins() != null && !this.inner().origins().isEmpty()) {
this.inner().origins().get(0).withHttpsPort(httpsPort);
}
return this;
}
@Override
public CdnEndpointImpl withHostHeader(String hostHeader) {
this.inner().withOriginHostHeader(hostHeader);
return this;
}
@Override
public CdnEndpointImpl withContentTypesToCompress(Set<String> contentTypesToCompress) {
List<String> list = null;
if (contentTypesToCompress != null) {
list = new ArrayList<>(contentTypesToCompress);
}
this.inner().withContentTypesToCompress(list);
return this;
}
@Override
public CdnEndpointImpl withoutContentTypesToCompress() {
if (this.inner().contentTypesToCompress() != null) {
this.inner().contentTypesToCompress().clear();
}
return this;
}
@Override
public CdnEndpointImpl withContentTypeToCompress(String contentTypeToCompress) {
if (this.inner().contentTypesToCompress() == null) {
this.inner().withContentTypesToCompress(new ArrayList<>());
}
this.inner().contentTypesToCompress().add(contentTypeToCompress);
return this;
}
@Override
public CdnEndpointImpl withoutContentTypeToCompress(String contentTypeToCompress) {
if (this.inner().contentTypesToCompress() != null) {
this.inner().contentTypesToCompress().remove(contentTypeToCompress);
}
return this;
}
@Override
public CdnEndpointImpl withCompressionEnabled(boolean compressionEnabled) {
this.inner().withIsCompressionEnabled(compressionEnabled);
return this;
}
@Override
public CdnEndpointImpl withQueryStringCachingBehavior(QueryStringCachingBehavior cachingBehavior) {
this.inner().withQueryStringCachingBehavior(cachingBehavior);
return this;
}
@Override
public CdnEndpointImpl withGeoFilters(Collection<GeoFilter> geoFilters) {
List<GeoFilter> list = null;
if (geoFilters != null) {
list = new ArrayList<>(geoFilters);
}
this.inner().withGeoFilters(list);
return this;
}
@Override
public CdnEndpointImpl withoutGeoFilters() {
if (this.inner().geoFilters() != null) {
this.inner().geoFilters().clear();
}
return this;
}
@Override
public CdnEndpointImpl withGeoFilter(String relativePath, GeoFilterActions action, CountryIsoCode countryCode) {
GeoFilter geoFilter = this.createGeoFiltersObject(relativePath, action);
if (geoFilter.countryCodes() == null) {
geoFilter.withCountryCodes(new ArrayList<>());
}
geoFilter.countryCodes().add(countryCode.toString());
this.inner().geoFilters().add(geoFilter);
return this;
}
@Override
public CdnEndpointImpl withGeoFilter(
String relativePath, GeoFilterActions action, Collection<CountryIsoCode> countryCodes) {
GeoFilter geoFilter = this.createGeoFiltersObject(relativePath, action);
if (geoFilter.countryCodes() == null) {
geoFilter.withCountryCodes(new ArrayList<>());
} else {
geoFilter.countryCodes().clear();
}
for (CountryIsoCode countryCode : countryCodes) {
geoFilter.countryCodes().add(countryCode.toString());
}
this.inner().geoFilters().add(geoFilter);
return this;
}
@Override
public CdnEndpointImpl withoutGeoFilter(String relativePath) {
this.inner().geoFilters().removeIf(geoFilter -> geoFilter.relativePath().equals(relativePath));
return this;
}
@Override
public CdnEndpointImpl withCustomDomain(String hostName) {
this.customDomainList.add(new CustomDomainInner().withHostname(hostName));
return this;
}
@Override
public CdnEndpointImpl withoutCustomDomain(String hostName) {
deletedCustomDomainList.add(new CustomDomainInner().withHostname(hostName));
return this;
}
private GeoFilter createGeoFiltersObject(String relativePath, GeoFilterActions action) {
if (this.inner().geoFilters() == null) {
this.inner().withGeoFilters(new ArrayList<>());
}
GeoFilter geoFilter = null;
for (GeoFilter filter : this.inner().geoFilters()) {
if (filter.relativePath().equals(relativePath)) {
geoFilter = filter;
break;
}
}
if (geoFilter == null) {
geoFilter = new GeoFilter();
} else {
this.inner().geoFilters().remove(geoFilter);
}
geoFilter.withRelativePath(relativePath)
.withAction(action);
return geoFilter;
}
} |
If no order needed, use `Flux.mergeDelayError(customDomainTask.then(), originUpdateTask.then(), endpointUpdateTask)`, for parallel | public Mono<CdnEndpoint> updateResourceAsync() {
final CdnEndpointImpl self = this;
EndpointUpdateParameters endpointUpdateParameters = new EndpointUpdateParameters();
endpointUpdateParameters.withIsHttpAllowed(this.inner().isHttpAllowed())
.withIsHttpsAllowed(this.inner().isHttpsAllowed())
.withOriginPath(this.inner().originPath())
.withOriginHostHeader(this.inner().originHostHeader())
.withIsCompressionEnabled(this.inner().isCompressionEnabled())
.withContentTypesToCompress(this.inner().contentTypesToCompress())
.withGeoFilters(this.inner().geoFilters())
.withOptimizationType(this.inner().optimizationType())
.withQueryStringCachingBehavior(this.inner().queryStringCachingBehavior())
.withTags(this.inner().tags());
DeepCreatedOrigin originInner = this.inner().origins().get(0);
OriginUpdateParameters originUpdateParameters = new OriginUpdateParameters()
.withHostname(originInner.hostname())
.withHttpPort(originInner.httpPort())
.withHttpsPort(originInner.httpsPort());
Mono<OriginInner> originUpdateTask = this.parent().manager().inner().getOrigins().updateAsync(
this.parent().resourceGroupName(),
this.parent().name(),
this.name(),
originInner.name(),
originUpdateParameters);
Mono<EndpointInner> endpointUpdateTask = this.parent().manager().inner().getEndpoints().updateAsync(
this.parent().resourceGroupName(),
this.parent().name(),
this.name(),
endpointUpdateParameters);
Flux<CustomDomainInner> customDomainCreateTask = Flux.fromIterable(this.customDomainList)
.flatMapDelayError(itemToCreate -> this.parent().manager().inner().getCustomDomains().createAsync(
this.parent().resourceGroupName(),
this.parent().name(),
this.name(),
self.parent().manager().sdkContext().randomResourceName("CustomDomain", 50),
itemToCreate.hostname()
), 32, 32);
Flux<CustomDomainInner> customDomainDeleteTask = Flux.fromIterable(this.deletedCustomDomainList)
.flatMapDelayError(itemToDelete -> this.parent().manager().inner().getCustomDomains().deleteAsync(
this.parent().resourceGroupName(),
this.parent().name(),
this.name(),
itemToDelete.name()
), 32, 32);
Flux<CustomDomainInner> customDomainTask = Flux.concat(customDomainCreateTask, customDomainDeleteTask);
return customDomainTask.then(originUpdateTask).then(endpointUpdateTask)
.map(inner -> {
self.setInner(inner);
self.customDomainList.clear();
self.deletedCustomDomainList.clear();
return self;
});
} | return customDomainTask.then(originUpdateTask).then(endpointUpdateTask) | public Mono<CdnEndpoint> updateResourceAsync() {
final CdnEndpointImpl self = this;
EndpointUpdateParameters endpointUpdateParameters = new EndpointUpdateParameters();
endpointUpdateParameters.withIsHttpAllowed(this.inner().isHttpAllowed())
.withIsHttpsAllowed(this.inner().isHttpsAllowed())
.withOriginPath(this.inner().originPath())
.withOriginHostHeader(this.inner().originHostHeader())
.withIsCompressionEnabled(this.inner().isCompressionEnabled())
.withContentTypesToCompress(this.inner().contentTypesToCompress())
.withGeoFilters(this.inner().geoFilters())
.withOptimizationType(this.inner().optimizationType())
.withQueryStringCachingBehavior(this.inner().queryStringCachingBehavior())
.withTags(this.inner().tags());
DeepCreatedOrigin originInner = this.inner().origins().get(0);
OriginUpdateParameters originUpdateParameters = new OriginUpdateParameters()
.withHostname(originInner.hostname())
.withHttpPort(originInner.httpPort())
.withHttpsPort(originInner.httpsPort());
Mono<EndpointInner> originUpdateTask = this.parent().manager().inner().getOrigins().updateAsync(
this.parent().resourceGroupName(),
this.parent().name(),
this.name(),
originInner.name(),
originUpdateParameters)
.then(Mono.empty());
Mono<EndpointInner> endpointUpdateTask = this.parent().manager().inner().getEndpoints().updateAsync(
this.parent().resourceGroupName(),
this.parent().name(),
this.name(),
endpointUpdateParameters);
Flux<CustomDomainInner> customDomainCreateTask = Flux.fromIterable(this.customDomainList)
.flatMapDelayError(itemToCreate -> this.parent().manager().inner().getCustomDomains().createAsync(
this.parent().resourceGroupName(),
this.parent().name(),
this.name(),
self.parent().manager().sdkContext().randomResourceName("CustomDomain", 50),
itemToCreate.hostname()
), 32, 32);
Flux<CustomDomainInner> customDomainDeleteTask = Flux.fromIterable(this.deletedCustomDomainList)
.flatMapDelayError(itemToDelete -> this.parent().manager().inner().getCustomDomains().deleteAsync(
this.parent().resourceGroupName(),
this.parent().name(),
this.name(),
itemToDelete.name()
), 32, 32);
Mono<EndpointInner> customDomainTask = Flux.concat(customDomainCreateTask, customDomainDeleteTask)
.then(Mono.empty());
return Flux.mergeDelayError(32, customDomainTask, originUpdateTask, endpointUpdateTask)
.last()
.map(inner -> {
self.setInner(inner);
self.customDomainList.clear();
self.deletedCustomDomainList.clear();
return self;
});
} | class CdnEndpointImpl
extends ExternalChildResourceImpl<
CdnEndpoint,
EndpointInner,
CdnProfileImpl,
CdnProfile>
implements CdnEndpoint,
CdnEndpoint.DefinitionStages.Blank.StandardEndpoint<CdnProfile.DefinitionStages.WithStandardCreate>,
CdnEndpoint.DefinitionStages.Blank.PremiumEndpoint<CdnProfile.DefinitionStages.WithPremiumVerizonCreate>,
CdnEndpoint.DefinitionStages.WithStandardAttach<CdnProfile.DefinitionStages.WithStandardCreate>,
CdnEndpoint.DefinitionStages.WithPremiumAttach<CdnProfile.DefinitionStages.WithPremiumVerizonCreate>,
CdnEndpoint.UpdateDefinitionStages.Blank.StandardEndpoint<CdnProfile.Update>,
CdnEndpoint.UpdateDefinitionStages.Blank.PremiumEndpoint<CdnProfile.Update>,
CdnEndpoint.UpdateDefinitionStages.WithStandardAttach<CdnProfile.Update>,
CdnEndpoint.UpdateDefinitionStages.WithPremiumAttach<CdnProfile.Update>,
CdnEndpoint.UpdateStandardEndpoint,
CdnEndpoint.UpdatePremiumEndpoint {
private List<CustomDomainInner> customDomainList;
private List<CustomDomainInner> deletedCustomDomainList;
CdnEndpointImpl(String name, CdnProfileImpl parent, EndpointInner inner) {
super(name, parent, inner);
this.customDomainList = new ArrayList<>();
this.deletedCustomDomainList = new ArrayList<>();
}
@Override
public String id() {
return this.inner().id();
}
@Override
public Mono<CdnEndpoint> createResourceAsync() {
final CdnEndpointImpl self = this;
return this.parent().manager().inner().getEndpoints().createAsync(this.parent().resourceGroupName(),
this.parent().name(),
this.name(),
this.inner())
.flatMap(inner -> {
self.setInner(inner);
return Flux.fromIterable(self.customDomainList)
.flatMapDelayError(customDomainInner -> self.parent().manager().inner()
.getCustomDomains().createAsync(
self.parent().resourceGroupName(),
self.parent().name(),
self.name(),
self.parent().manager().sdkContext().randomResourceName("CustomDomain", 50),
customDomainInner.hostname()), 32, 32)
.then(self.parent().manager().inner()
.getCustomDomains().listByEndpointAsync(
self.parent().resourceGroupName(),
self.parent().name(),
self.name())
.collectList()
.map(customDomainInners -> {
self.customDomainList.addAll(customDomainInners);
return self;
}));
});
}
@Override
@Override
public Mono<Void> deleteResourceAsync() {
return this.parent().manager().inner().getEndpoints().deleteAsync(this.parent().resourceGroupName(),
this.parent().name(),
this.name());
}
@Override
public Mono<CdnEndpoint> refreshAsync() {
final CdnEndpointImpl self = this;
return super.refreshAsync()
.flatMap(cdnEndpoint -> {
self.customDomainList.clear();
self.deletedCustomDomainList.clear();
return self.parent().manager().inner().getCustomDomains().listByEndpointAsync(
self.parent().resourceGroupName(),
self.parent().name(),
self.name()
)
.collectList()
.map(customDomainInners -> {
self.customDomainList.addAll(customDomainInners);
return self;
});
});
}
@Override
protected Mono<EndpointInner> getInnerAsync() {
return this.parent().manager().inner().getEndpoints().getAsync(this.parent().resourceGroupName(),
this.parent().name(),
this.name());
}
@Override
public PagedIterable<ResourceUsage> listResourceUsage() {
return this.parent().manager().inner().getEndpoints().listResourceUsage(
this.parent().resourceGroupName(),
this.parent().name(),
this.name())
.mapPage(ResourceUsage::new);
}
@Override
public CdnProfileImpl attach() {
return this.parent();
}
@Override
public String originHostHeader() {
return this.inner().originHostHeader();
}
@Override
public String originPath() {
return this.inner().originPath();
}
@Override
public Set<String> contentTypesToCompress() {
List<String> contentTypes = this.inner().contentTypesToCompress();
Set<String> set = new HashSet<>();
if (contentTypes != null) {
set.addAll(contentTypes);
}
return Collections.unmodifiableSet(set);
}
@Override
public boolean isCompressionEnabled() {
return this.inner().isCompressionEnabled();
}
@Override
public boolean isHttpAllowed() {
return this.inner().isHttpAllowed();
}
@Override
public boolean isHttpsAllowed() {
return this.inner().isHttpsAllowed();
}
@Override
public QueryStringCachingBehavior queryStringCachingBehavior() {
return this.inner().queryStringCachingBehavior();
}
@Override
public String optimizationType() {
if (this.inner().optimizationType() == null) {
return null;
}
return this.inner().optimizationType().toString();
}
@Override
public List<GeoFilter> geoFilters() {
return this.inner().geoFilters();
}
@Override
public String hostname() {
return this.inner().hostname();
}
@Override
public EndpointResourceState resourceState() {
return this.inner().resourceState();
}
@Override
public String provisioningState() {
return this.inner().provisioningState();
}
@Override
public String originHostName() {
if (this.inner().origins() != null && !this.inner().origins().isEmpty()) {
return this.inner().origins().get(0).hostname();
}
return null;
}
@Override
public int httpPort() {
if (this.inner().origins() != null && !this.inner().origins().isEmpty()) {
Integer httpPort = this.inner().origins().get(0).httpPort();
return (httpPort != null) ? httpPort : 0;
}
return 0;
}
@Override
public int httpsPort() {
if (this.inner().origins() != null && !this.inner().origins().isEmpty()) {
Integer httpsPort = this.inner().origins().get(0).httpsPort();
return (httpsPort != null) ? httpsPort : 0;
}
return 0;
}
@Override
public Set<String> customDomains() {
Set<String> set = new HashSet<>();
for (CustomDomainInner customDomainInner : this.parent().manager().inner().getCustomDomains()
.listByEndpoint(this.parent().resourceGroupName(), this.parent().name(), this.name())) {
set.add(customDomainInner.hostname());
}
return Collections.unmodifiableSet(set);
}
@Override
public void start() {
this.parent().startEndpoint(this.name());
}
@Override
public Mono<Void> startAsync() {
return this.parent().startEndpointAsync(this.name());
}
@Override
public void stop() {
this.stopAsync().block();
}
@Override
public Mono<Void> stopAsync() {
return this.parent().stopEndpointAsync(this.name());
}
@Override
public void purgeContent(Set<String> contentPaths) {
if (contentPaths != null) {
this.purgeContentAsync(contentPaths).block();
}
}
@Override
public Mono<Void> purgeContentAsync(Set<String> contentPaths) {
return this.parent().purgeEndpointContentAsync(this.name(), contentPaths);
}
@Override
public void loadContent(Set<String> contentPaths) {
this.loadContentAsync(contentPaths).block();
}
@Override
public Mono<Void> loadContentAsync(Set<String> contentPaths) {
return this.parent().loadEndpointContentAsync(this.name(), contentPaths);
}
@Override
public CustomDomainValidationResult validateCustomDomain(String hostName) {
return this.validateCustomDomainAsync(hostName).block();
}
@Override
public Mono<CustomDomainValidationResult> validateCustomDomainAsync(String hostName) {
return this.parent().validateEndpointCustomDomainAsync(this.name(), hostName);
}
@Override
public CdnEndpointImpl withOrigin(String originName, String hostname) {
this.inner().origins().add(
new DeepCreatedOrigin()
.withName(originName)
.withHostname(hostname));
return this;
}
@Override
public CdnEndpointImpl withOrigin(String hostname) {
return this.withOrigin("origin", hostname);
}
@Override
public CdnEndpointImpl withPremiumOrigin(String originName, String hostname) {
return this.withOrigin(originName, hostname);
}
@Override
public CdnEndpointImpl withPremiumOrigin(String hostname) {
return this.withOrigin(hostname);
}
@Override
public CdnEndpointImpl withOriginPath(String originPath) {
this.inner().withOriginPath(originPath);
return this;
}
@Override
public CdnEndpointImpl withHttpAllowed(boolean httpAllowed) {
this.inner().withIsHttpAllowed(httpAllowed);
return this;
}
@Override
public CdnEndpointImpl withHttpsAllowed(boolean httpsAllowed) {
this.inner().withIsHttpsAllowed(httpsAllowed);
return this;
}
@Override
public CdnEndpointImpl withHttpPort(int httpPort) {
if (this.inner().origins() != null && !this.inner().origins().isEmpty()) {
this.inner().origins().get(0).withHttpPort(httpPort);
}
return this;
}
@Override
public CdnEndpointImpl withHttpsPort(int httpsPort) {
if (this.inner().origins() != null && !this.inner().origins().isEmpty()) {
this.inner().origins().get(0).withHttpsPort(httpsPort);
}
return this;
}
@Override
public CdnEndpointImpl withHostHeader(String hostHeader) {
this.inner().withOriginHostHeader(hostHeader);
return this;
}
@Override
public CdnEndpointImpl withContentTypesToCompress(Set<String> contentTypesToCompress) {
List<String> list = null;
if (contentTypesToCompress != null) {
list = new ArrayList<>(contentTypesToCompress);
}
this.inner().withContentTypesToCompress(list);
return this;
}
@Override
public CdnEndpointImpl withoutContentTypesToCompress() {
if (this.inner().contentTypesToCompress() != null) {
this.inner().contentTypesToCompress().clear();
}
return this;
}
@Override
public CdnEndpointImpl withContentTypeToCompress(String contentTypeToCompress) {
if (this.inner().contentTypesToCompress() == null) {
this.inner().withContentTypesToCompress(new ArrayList<>());
}
this.inner().contentTypesToCompress().add(contentTypeToCompress);
return this;
}
@Override
public CdnEndpointImpl withoutContentTypeToCompress(String contentTypeToCompress) {
if (this.inner().contentTypesToCompress() != null) {
this.inner().contentTypesToCompress().remove(contentTypeToCompress);
}
return this;
}
@Override
public CdnEndpointImpl withCompressionEnabled(boolean compressionEnabled) {
this.inner().withIsCompressionEnabled(compressionEnabled);
return this;
}
@Override
public CdnEndpointImpl withQueryStringCachingBehavior(QueryStringCachingBehavior cachingBehavior) {
this.inner().withQueryStringCachingBehavior(cachingBehavior);
return this;
}
@Override
public CdnEndpointImpl withGeoFilters(Collection<GeoFilter> geoFilters) {
List<GeoFilter> list = null;
if (geoFilters != null) {
list = new ArrayList<>(geoFilters);
}
this.inner().withGeoFilters(list);
return this;
}
@Override
public CdnEndpointImpl withoutGeoFilters() {
if (this.inner().geoFilters() != null) {
this.inner().geoFilters().clear();
}
return this;
}
@Override
public CdnEndpointImpl withGeoFilter(String relativePath, GeoFilterActions action, CountryIsoCode countryCode) {
GeoFilter geoFilter = this.createGeoFiltersObject(relativePath, action);
if (geoFilter.countryCodes() == null) {
geoFilter.withCountryCodes(new ArrayList<>());
}
geoFilter.countryCodes().add(countryCode.toString());
this.inner().geoFilters().add(geoFilter);
return this;
}
@Override
public CdnEndpointImpl withGeoFilter(
String relativePath, GeoFilterActions action, Collection<CountryIsoCode> countryCodes) {
GeoFilter geoFilter = this.createGeoFiltersObject(relativePath, action);
if (geoFilter.countryCodes() == null) {
geoFilter.withCountryCodes(new ArrayList<>());
} else {
geoFilter.countryCodes().clear();
}
for (CountryIsoCode countryCode : countryCodes) {
geoFilter.countryCodes().add(countryCode.toString());
}
this.inner().geoFilters().add(geoFilter);
return this;
}
@Override
public CdnEndpointImpl withoutGeoFilter(String relativePath) {
this.inner().geoFilters().removeIf(geoFilter -> geoFilter.relativePath().equals(relativePath));
return this;
}
@Override
public CdnEndpointImpl withCustomDomain(String hostName) {
this.customDomainList.add(new CustomDomainInner().withHostname(hostName));
return this;
}
@Override
public CdnEndpointImpl withoutCustomDomain(String hostName) {
deletedCustomDomainList.add(new CustomDomainInner().withHostname(hostName));
return this;
}
private GeoFilter createGeoFiltersObject(String relativePath, GeoFilterActions action) {
if (this.inner().geoFilters() == null) {
this.inner().withGeoFilters(new ArrayList<>());
}
GeoFilter geoFilter = null;
for (GeoFilter filter : this.inner().geoFilters()) {
if (filter.relativePath().equals(relativePath)) {
geoFilter = filter;
break;
}
}
if (geoFilter == null) {
geoFilter = new GeoFilter();
} else {
this.inner().geoFilters().remove(geoFilter);
}
geoFilter.withRelativePath(relativePath)
.withAction(action);
return geoFilter;
}
} | class CdnEndpointImpl
extends ExternalChildResourceImpl<
CdnEndpoint,
EndpointInner,
CdnProfileImpl,
CdnProfile>
implements CdnEndpoint,
CdnEndpoint.DefinitionStages.Blank.StandardEndpoint<CdnProfile.DefinitionStages.WithStandardCreate>,
CdnEndpoint.DefinitionStages.Blank.PremiumEndpoint<CdnProfile.DefinitionStages.WithPremiumVerizonCreate>,
CdnEndpoint.DefinitionStages.WithStandardAttach<CdnProfile.DefinitionStages.WithStandardCreate>,
CdnEndpoint.DefinitionStages.WithPremiumAttach<CdnProfile.DefinitionStages.WithPremiumVerizonCreate>,
CdnEndpoint.UpdateDefinitionStages.Blank.StandardEndpoint<CdnProfile.Update>,
CdnEndpoint.UpdateDefinitionStages.Blank.PremiumEndpoint<CdnProfile.Update>,
CdnEndpoint.UpdateDefinitionStages.WithStandardAttach<CdnProfile.Update>,
CdnEndpoint.UpdateDefinitionStages.WithPremiumAttach<CdnProfile.Update>,
CdnEndpoint.UpdateStandardEndpoint,
CdnEndpoint.UpdatePremiumEndpoint {
private List<CustomDomainInner> customDomainList;
private List<CustomDomainInner> deletedCustomDomainList;
CdnEndpointImpl(String name, CdnProfileImpl parent, EndpointInner inner) {
super(name, parent, inner);
this.customDomainList = new ArrayList<>();
this.deletedCustomDomainList = new ArrayList<>();
}
@Override
public String id() {
return this.inner().id();
}
@Override
public Mono<CdnEndpoint> createResourceAsync() {
final CdnEndpointImpl self = this;
return this.parent().manager().inner().getEndpoints().createAsync(this.parent().resourceGroupName(),
this.parent().name(),
this.name(),
this.inner())
.flatMap(inner -> {
self.setInner(inner);
return Flux.fromIterable(self.customDomainList)
.flatMapDelayError(customDomainInner -> self.parent().manager().inner()
.getCustomDomains().createAsync(
self.parent().resourceGroupName(),
self.parent().name(),
self.name(),
self.parent().manager().sdkContext().randomResourceName("CustomDomain", 50),
customDomainInner.hostname()), 32, 32)
.then(self.parent().manager().inner()
.getCustomDomains().listByEndpointAsync(
self.parent().resourceGroupName(),
self.parent().name(),
self.name())
.collectList()
.map(customDomainInners -> {
self.customDomainList.addAll(customDomainInners);
return self;
}));
});
}
@Override
@Override
public Mono<Void> deleteResourceAsync() {
return this.parent().manager().inner().getEndpoints().deleteAsync(this.parent().resourceGroupName(),
this.parent().name(),
this.name());
}
@Override
public Mono<CdnEndpoint> refreshAsync() {
final CdnEndpointImpl self = this;
return super.refreshAsync()
.flatMap(cdnEndpoint -> {
self.customDomainList.clear();
self.deletedCustomDomainList.clear();
return self.parent().manager().inner().getCustomDomains().listByEndpointAsync(
self.parent().resourceGroupName(),
self.parent().name(),
self.name()
)
.collectList()
.map(customDomainInners -> {
self.customDomainList.addAll(customDomainInners);
return self;
});
});
}
@Override
protected Mono<EndpointInner> getInnerAsync() {
return this.parent().manager().inner().getEndpoints().getAsync(this.parent().resourceGroupName(),
this.parent().name(),
this.name());
}
@Override
public PagedIterable<ResourceUsage> listResourceUsage() {
return this.parent().manager().inner().getEndpoints().listResourceUsage(
this.parent().resourceGroupName(),
this.parent().name(),
this.name())
.mapPage(ResourceUsage::new);
}
@Override
public CdnProfileImpl attach() {
return this.parent();
}
@Override
public String originHostHeader() {
return this.inner().originHostHeader();
}
@Override
public String originPath() {
return this.inner().originPath();
}
@Override
public Set<String> contentTypesToCompress() {
List<String> contentTypes = this.inner().contentTypesToCompress();
Set<String> set = new HashSet<>();
if (contentTypes != null) {
set.addAll(contentTypes);
}
return Collections.unmodifiableSet(set);
}
@Override
public boolean isCompressionEnabled() {
return this.inner().isCompressionEnabled();
}
@Override
public boolean isHttpAllowed() {
return this.inner().isHttpAllowed();
}
@Override
public boolean isHttpsAllowed() {
return this.inner().isHttpsAllowed();
}
@Override
public QueryStringCachingBehavior queryStringCachingBehavior() {
return this.inner().queryStringCachingBehavior();
}
@Override
public String optimizationType() {
if (this.inner().optimizationType() == null) {
return null;
}
return this.inner().optimizationType().toString();
}
@Override
public List<GeoFilter> geoFilters() {
return this.inner().geoFilters();
}
@Override
public String hostname() {
return this.inner().hostname();
}
@Override
public EndpointResourceState resourceState() {
return this.inner().resourceState();
}
@Override
public String provisioningState() {
return this.inner().provisioningState();
}
@Override
public String originHostName() {
if (this.inner().origins() != null && !this.inner().origins().isEmpty()) {
return this.inner().origins().get(0).hostname();
}
return null;
}
@Override
public int httpPort() {
if (this.inner().origins() != null && !this.inner().origins().isEmpty()) {
Integer httpPort = this.inner().origins().get(0).httpPort();
return (httpPort != null) ? httpPort : 0;
}
return 0;
}
@Override
public int httpsPort() {
if (this.inner().origins() != null && !this.inner().origins().isEmpty()) {
Integer httpsPort = this.inner().origins().get(0).httpsPort();
return (httpsPort != null) ? httpsPort : 0;
}
return 0;
}
@Override
public Set<String> customDomains() {
Set<String> set = new HashSet<>();
for (CustomDomainInner customDomainInner : this.parent().manager().inner().getCustomDomains()
.listByEndpoint(this.parent().resourceGroupName(), this.parent().name(), this.name())) {
set.add(customDomainInner.hostname());
}
return Collections.unmodifiableSet(set);
}
@Override
public void start() {
this.parent().startEndpoint(this.name());
}
@Override
public Mono<Void> startAsync() {
return this.parent().startEndpointAsync(this.name());
}
@Override
public void stop() {
this.stopAsync().block();
}
@Override
public Mono<Void> stopAsync() {
return this.parent().stopEndpointAsync(this.name());
}
@Override
public void purgeContent(Set<String> contentPaths) {
if (contentPaths != null) {
this.purgeContentAsync(contentPaths).block();
}
}
@Override
public Mono<Void> purgeContentAsync(Set<String> contentPaths) {
return this.parent().purgeEndpointContentAsync(this.name(), contentPaths);
}
@Override
public void loadContent(Set<String> contentPaths) {
this.loadContentAsync(contentPaths).block();
}
@Override
public Mono<Void> loadContentAsync(Set<String> contentPaths) {
return this.parent().loadEndpointContentAsync(this.name(), contentPaths);
}
@Override
public CustomDomainValidationResult validateCustomDomain(String hostName) {
return this.validateCustomDomainAsync(hostName).block();
}
@Override
public Mono<CustomDomainValidationResult> validateCustomDomainAsync(String hostName) {
return this.parent().validateEndpointCustomDomainAsync(this.name(), hostName);
}
@Override
public CdnEndpointImpl withOrigin(String originName, String hostname) {
this.inner().origins().add(
new DeepCreatedOrigin()
.withName(originName)
.withHostname(hostname));
return this;
}
@Override
public CdnEndpointImpl withOrigin(String hostname) {
return this.withOrigin("origin", hostname);
}
@Override
public CdnEndpointImpl withPremiumOrigin(String originName, String hostname) {
return this.withOrigin(originName, hostname);
}
@Override
public CdnEndpointImpl withPremiumOrigin(String hostname) {
return this.withOrigin(hostname);
}
@Override
public CdnEndpointImpl withOriginPath(String originPath) {
this.inner().withOriginPath(originPath);
return this;
}
@Override
public CdnEndpointImpl withHttpAllowed(boolean httpAllowed) {
this.inner().withIsHttpAllowed(httpAllowed);
return this;
}
@Override
public CdnEndpointImpl withHttpsAllowed(boolean httpsAllowed) {
this.inner().withIsHttpsAllowed(httpsAllowed);
return this;
}
@Override
public CdnEndpointImpl withHttpPort(int httpPort) {
if (this.inner().origins() != null && !this.inner().origins().isEmpty()) {
this.inner().origins().get(0).withHttpPort(httpPort);
}
return this;
}
@Override
public CdnEndpointImpl withHttpsPort(int httpsPort) {
if (this.inner().origins() != null && !this.inner().origins().isEmpty()) {
this.inner().origins().get(0).withHttpsPort(httpsPort);
}
return this;
}
@Override
public CdnEndpointImpl withHostHeader(String hostHeader) {
this.inner().withOriginHostHeader(hostHeader);
return this;
}
@Override
public CdnEndpointImpl withContentTypesToCompress(Set<String> contentTypesToCompress) {
List<String> list = null;
if (contentTypesToCompress != null) {
list = new ArrayList<>(contentTypesToCompress);
}
this.inner().withContentTypesToCompress(list);
return this;
}
@Override
public CdnEndpointImpl withoutContentTypesToCompress() {
if (this.inner().contentTypesToCompress() != null) {
this.inner().contentTypesToCompress().clear();
}
return this;
}
@Override
public CdnEndpointImpl withContentTypeToCompress(String contentTypeToCompress) {
if (this.inner().contentTypesToCompress() == null) {
this.inner().withContentTypesToCompress(new ArrayList<>());
}
this.inner().contentTypesToCompress().add(contentTypeToCompress);
return this;
}
@Override
public CdnEndpointImpl withoutContentTypeToCompress(String contentTypeToCompress) {
if (this.inner().contentTypesToCompress() != null) {
this.inner().contentTypesToCompress().remove(contentTypeToCompress);
}
return this;
}
@Override
public CdnEndpointImpl withCompressionEnabled(boolean compressionEnabled) {
this.inner().withIsCompressionEnabled(compressionEnabled);
return this;
}
@Override
public CdnEndpointImpl withQueryStringCachingBehavior(QueryStringCachingBehavior cachingBehavior) {
this.inner().withQueryStringCachingBehavior(cachingBehavior);
return this;
}
@Override
public CdnEndpointImpl withGeoFilters(Collection<GeoFilter> geoFilters) {
List<GeoFilter> list = null;
if (geoFilters != null) {
list = new ArrayList<>(geoFilters);
}
this.inner().withGeoFilters(list);
return this;
}
@Override
public CdnEndpointImpl withoutGeoFilters() {
if (this.inner().geoFilters() != null) {
this.inner().geoFilters().clear();
}
return this;
}
@Override
public CdnEndpointImpl withGeoFilter(String relativePath, GeoFilterActions action, CountryIsoCode countryCode) {
GeoFilter geoFilter = this.createGeoFiltersObject(relativePath, action);
if (geoFilter.countryCodes() == null) {
geoFilter.withCountryCodes(new ArrayList<>());
}
geoFilter.countryCodes().add(countryCode.toString());
this.inner().geoFilters().add(geoFilter);
return this;
}
@Override
public CdnEndpointImpl withGeoFilter(
String relativePath, GeoFilterActions action, Collection<CountryIsoCode> countryCodes) {
GeoFilter geoFilter = this.createGeoFiltersObject(relativePath, action);
if (geoFilter.countryCodes() == null) {
geoFilter.withCountryCodes(new ArrayList<>());
} else {
geoFilter.countryCodes().clear();
}
for (CountryIsoCode countryCode : countryCodes) {
geoFilter.countryCodes().add(countryCode.toString());
}
this.inner().geoFilters().add(geoFilter);
return this;
}
@Override
public CdnEndpointImpl withoutGeoFilter(String relativePath) {
this.inner().geoFilters().removeIf(geoFilter -> geoFilter.relativePath().equals(relativePath));
return this;
}
@Override
public CdnEndpointImpl withCustomDomain(String hostName) {
this.customDomainList.add(new CustomDomainInner().withHostname(hostName));
return this;
}
@Override
public CdnEndpointImpl withoutCustomDomain(String hostName) {
deletedCustomDomainList.add(new CustomDomainInner().withHostname(hostName));
return this;
}
private GeoFilter createGeoFiltersObject(String relativePath, GeoFilterActions action) {
if (this.inner().geoFilters() == null) {
this.inner().withGeoFilters(new ArrayList<>());
}
GeoFilter geoFilter = null;
for (GeoFilter filter : this.inner().geoFilters()) {
if (filter.relativePath().equals(relativePath)) {
geoFilter = filter;
break;
}
}
if (geoFilter == null) {
geoFilter = new GeoFilter();
} else {
this.inner().geoFilters().remove(geoFilter);
}
geoFilter.withRelativePath(relativePath)
.withAction(action);
return geoFilter;
}
} |
The concern to have concat came from [Azure/azure-libraries-for-net#891](https://github.com/Azure/azure-libraries-for-net/issues/891). For safe, I just concat the custom domain tasks. For tasks of different resources, we can use merge. | public Mono<CdnEndpoint> updateResourceAsync() {
final CdnEndpointImpl self = this;
EndpointUpdateParameters endpointUpdateParameters = new EndpointUpdateParameters();
endpointUpdateParameters.withIsHttpAllowed(this.inner().isHttpAllowed())
.withIsHttpsAllowed(this.inner().isHttpsAllowed())
.withOriginPath(this.inner().originPath())
.withOriginHostHeader(this.inner().originHostHeader())
.withIsCompressionEnabled(this.inner().isCompressionEnabled())
.withContentTypesToCompress(this.inner().contentTypesToCompress())
.withGeoFilters(this.inner().geoFilters())
.withOptimizationType(this.inner().optimizationType())
.withQueryStringCachingBehavior(this.inner().queryStringCachingBehavior())
.withTags(this.inner().tags());
DeepCreatedOrigin originInner = this.inner().origins().get(0);
OriginUpdateParameters originUpdateParameters = new OriginUpdateParameters()
.withHostname(originInner.hostname())
.withHttpPort(originInner.httpPort())
.withHttpsPort(originInner.httpsPort());
Mono<OriginInner> originUpdateTask = this.parent().manager().inner().getOrigins().updateAsync(
this.parent().resourceGroupName(),
this.parent().name(),
this.name(),
originInner.name(),
originUpdateParameters);
Mono<EndpointInner> endpointUpdateTask = this.parent().manager().inner().getEndpoints().updateAsync(
this.parent().resourceGroupName(),
this.parent().name(),
this.name(),
endpointUpdateParameters);
Flux<CustomDomainInner> customDomainCreateTask = Flux.fromIterable(this.customDomainList)
.flatMapDelayError(itemToCreate -> this.parent().manager().inner().getCustomDomains().createAsync(
this.parent().resourceGroupName(),
this.parent().name(),
this.name(),
self.parent().manager().sdkContext().randomResourceName("CustomDomain", 50),
itemToCreate.hostname()
), 32, 32);
Flux<CustomDomainInner> customDomainDeleteTask = Flux.fromIterable(this.deletedCustomDomainList)
.flatMapDelayError(itemToDelete -> this.parent().manager().inner().getCustomDomains().deleteAsync(
this.parent().resourceGroupName(),
this.parent().name(),
this.name(),
itemToDelete.name()
), 32, 32);
Flux<CustomDomainInner> customDomainTask = Flux.concat(customDomainCreateTask, customDomainDeleteTask);
return customDomainTask.then(originUpdateTask).then(endpointUpdateTask)
.map(inner -> {
self.setInner(inner);
self.customDomainList.clear();
self.deletedCustomDomainList.clear();
return self;
});
} | Flux<CustomDomainInner> customDomainTask = Flux.concat(customDomainCreateTask, customDomainDeleteTask); | public Mono<CdnEndpoint> updateResourceAsync() {
final CdnEndpointImpl self = this;
EndpointUpdateParameters endpointUpdateParameters = new EndpointUpdateParameters();
endpointUpdateParameters.withIsHttpAllowed(this.inner().isHttpAllowed())
.withIsHttpsAllowed(this.inner().isHttpsAllowed())
.withOriginPath(this.inner().originPath())
.withOriginHostHeader(this.inner().originHostHeader())
.withIsCompressionEnabled(this.inner().isCompressionEnabled())
.withContentTypesToCompress(this.inner().contentTypesToCompress())
.withGeoFilters(this.inner().geoFilters())
.withOptimizationType(this.inner().optimizationType())
.withQueryStringCachingBehavior(this.inner().queryStringCachingBehavior())
.withTags(this.inner().tags());
DeepCreatedOrigin originInner = this.inner().origins().get(0);
OriginUpdateParameters originUpdateParameters = new OriginUpdateParameters()
.withHostname(originInner.hostname())
.withHttpPort(originInner.httpPort())
.withHttpsPort(originInner.httpsPort());
Mono<EndpointInner> originUpdateTask = this.parent().manager().inner().getOrigins().updateAsync(
this.parent().resourceGroupName(),
this.parent().name(),
this.name(),
originInner.name(),
originUpdateParameters)
.then(Mono.empty());
Mono<EndpointInner> endpointUpdateTask = this.parent().manager().inner().getEndpoints().updateAsync(
this.parent().resourceGroupName(),
this.parent().name(),
this.name(),
endpointUpdateParameters);
Flux<CustomDomainInner> customDomainCreateTask = Flux.fromIterable(this.customDomainList)
.flatMapDelayError(itemToCreate -> this.parent().manager().inner().getCustomDomains().createAsync(
this.parent().resourceGroupName(),
this.parent().name(),
this.name(),
self.parent().manager().sdkContext().randomResourceName("CustomDomain", 50),
itemToCreate.hostname()
), 32, 32);
Flux<CustomDomainInner> customDomainDeleteTask = Flux.fromIterable(this.deletedCustomDomainList)
.flatMapDelayError(itemToDelete -> this.parent().manager().inner().getCustomDomains().deleteAsync(
this.parent().resourceGroupName(),
this.parent().name(),
this.name(),
itemToDelete.name()
), 32, 32);
Mono<EndpointInner> customDomainTask = Flux.concat(customDomainCreateTask, customDomainDeleteTask)
.then(Mono.empty());
return Flux.mergeDelayError(32, customDomainTask, originUpdateTask, endpointUpdateTask)
.last()
.map(inner -> {
self.setInner(inner);
self.customDomainList.clear();
self.deletedCustomDomainList.clear();
return self;
});
} | class CdnEndpointImpl
extends ExternalChildResourceImpl<
CdnEndpoint,
EndpointInner,
CdnProfileImpl,
CdnProfile>
implements CdnEndpoint,
CdnEndpoint.DefinitionStages.Blank.StandardEndpoint<CdnProfile.DefinitionStages.WithStandardCreate>,
CdnEndpoint.DefinitionStages.Blank.PremiumEndpoint<CdnProfile.DefinitionStages.WithPremiumVerizonCreate>,
CdnEndpoint.DefinitionStages.WithStandardAttach<CdnProfile.DefinitionStages.WithStandardCreate>,
CdnEndpoint.DefinitionStages.WithPremiumAttach<CdnProfile.DefinitionStages.WithPremiumVerizonCreate>,
CdnEndpoint.UpdateDefinitionStages.Blank.StandardEndpoint<CdnProfile.Update>,
CdnEndpoint.UpdateDefinitionStages.Blank.PremiumEndpoint<CdnProfile.Update>,
CdnEndpoint.UpdateDefinitionStages.WithStandardAttach<CdnProfile.Update>,
CdnEndpoint.UpdateDefinitionStages.WithPremiumAttach<CdnProfile.Update>,
CdnEndpoint.UpdateStandardEndpoint,
CdnEndpoint.UpdatePremiumEndpoint {
private List<CustomDomainInner> customDomainList;
private List<CustomDomainInner> deletedCustomDomainList;
CdnEndpointImpl(String name, CdnProfileImpl parent, EndpointInner inner) {
super(name, parent, inner);
this.customDomainList = new ArrayList<>();
this.deletedCustomDomainList = new ArrayList<>();
}
@Override
public String id() {
return this.inner().id();
}
@Override
public Mono<CdnEndpoint> createResourceAsync() {
final CdnEndpointImpl self = this;
return this.parent().manager().inner().getEndpoints().createAsync(this.parent().resourceGroupName(),
this.parent().name(),
this.name(),
this.inner())
.flatMap(inner -> {
self.setInner(inner);
return Flux.fromIterable(self.customDomainList)
.flatMapDelayError(customDomainInner -> self.parent().manager().inner()
.getCustomDomains().createAsync(
self.parent().resourceGroupName(),
self.parent().name(),
self.name(),
self.parent().manager().sdkContext().randomResourceName("CustomDomain", 50),
customDomainInner.hostname()), 32, 32)
.then(self.parent().manager().inner()
.getCustomDomains().listByEndpointAsync(
self.parent().resourceGroupName(),
self.parent().name(),
self.name())
.collectList()
.map(customDomainInners -> {
self.customDomainList.addAll(customDomainInners);
return self;
}));
});
}
@Override
@Override
public Mono<Void> deleteResourceAsync() {
return this.parent().manager().inner().getEndpoints().deleteAsync(this.parent().resourceGroupName(),
this.parent().name(),
this.name());
}
@Override
public Mono<CdnEndpoint> refreshAsync() {
final CdnEndpointImpl self = this;
return super.refreshAsync()
.flatMap(cdnEndpoint -> {
self.customDomainList.clear();
self.deletedCustomDomainList.clear();
return self.parent().manager().inner().getCustomDomains().listByEndpointAsync(
self.parent().resourceGroupName(),
self.parent().name(),
self.name()
)
.collectList()
.map(customDomainInners -> {
self.customDomainList.addAll(customDomainInners);
return self;
});
});
}
@Override
protected Mono<EndpointInner> getInnerAsync() {
return this.parent().manager().inner().getEndpoints().getAsync(this.parent().resourceGroupName(),
this.parent().name(),
this.name());
}
@Override
public PagedIterable<ResourceUsage> listResourceUsage() {
return this.parent().manager().inner().getEndpoints().listResourceUsage(
this.parent().resourceGroupName(),
this.parent().name(),
this.name())
.mapPage(ResourceUsage::new);
}
@Override
public CdnProfileImpl attach() {
return this.parent();
}
@Override
public String originHostHeader() {
return this.inner().originHostHeader();
}
@Override
public String originPath() {
return this.inner().originPath();
}
@Override
public Set<String> contentTypesToCompress() {
List<String> contentTypes = this.inner().contentTypesToCompress();
Set<String> set = new HashSet<>();
if (contentTypes != null) {
set.addAll(contentTypes);
}
return Collections.unmodifiableSet(set);
}
@Override
public boolean isCompressionEnabled() {
return this.inner().isCompressionEnabled();
}
@Override
public boolean isHttpAllowed() {
return this.inner().isHttpAllowed();
}
@Override
public boolean isHttpsAllowed() {
return this.inner().isHttpsAllowed();
}
@Override
public QueryStringCachingBehavior queryStringCachingBehavior() {
return this.inner().queryStringCachingBehavior();
}
@Override
public String optimizationType() {
if (this.inner().optimizationType() == null) {
return null;
}
return this.inner().optimizationType().toString();
}
@Override
public List<GeoFilter> geoFilters() {
return this.inner().geoFilters();
}
@Override
public String hostname() {
return this.inner().hostname();
}
@Override
public EndpointResourceState resourceState() {
return this.inner().resourceState();
}
@Override
public String provisioningState() {
return this.inner().provisioningState();
}
@Override
public String originHostName() {
if (this.inner().origins() != null && !this.inner().origins().isEmpty()) {
return this.inner().origins().get(0).hostname();
}
return null;
}
@Override
public int httpPort() {
if (this.inner().origins() != null && !this.inner().origins().isEmpty()) {
Integer httpPort = this.inner().origins().get(0).httpPort();
return (httpPort != null) ? httpPort : 0;
}
return 0;
}
@Override
public int httpsPort() {
if (this.inner().origins() != null && !this.inner().origins().isEmpty()) {
Integer httpsPort = this.inner().origins().get(0).httpsPort();
return (httpsPort != null) ? httpsPort : 0;
}
return 0;
}
@Override
public Set<String> customDomains() {
Set<String> set = new HashSet<>();
for (CustomDomainInner customDomainInner : this.parent().manager().inner().getCustomDomains()
.listByEndpoint(this.parent().resourceGroupName(), this.parent().name(), this.name())) {
set.add(customDomainInner.hostname());
}
return Collections.unmodifiableSet(set);
}
@Override
public void start() {
this.parent().startEndpoint(this.name());
}
@Override
public Mono<Void> startAsync() {
return this.parent().startEndpointAsync(this.name());
}
@Override
public void stop() {
this.stopAsync().block();
}
@Override
public Mono<Void> stopAsync() {
return this.parent().stopEndpointAsync(this.name());
}
@Override
public void purgeContent(Set<String> contentPaths) {
if (contentPaths != null) {
this.purgeContentAsync(contentPaths).block();
}
}
@Override
public Mono<Void> purgeContentAsync(Set<String> contentPaths) {
return this.parent().purgeEndpointContentAsync(this.name(), contentPaths);
}
@Override
public void loadContent(Set<String> contentPaths) {
this.loadContentAsync(contentPaths).block();
}
@Override
public Mono<Void> loadContentAsync(Set<String> contentPaths) {
return this.parent().loadEndpointContentAsync(this.name(), contentPaths);
}
@Override
public CustomDomainValidationResult validateCustomDomain(String hostName) {
return this.validateCustomDomainAsync(hostName).block();
}
@Override
public Mono<CustomDomainValidationResult> validateCustomDomainAsync(String hostName) {
return this.parent().validateEndpointCustomDomainAsync(this.name(), hostName);
}
@Override
public CdnEndpointImpl withOrigin(String originName, String hostname) {
this.inner().origins().add(
new DeepCreatedOrigin()
.withName(originName)
.withHostname(hostname));
return this;
}
@Override
public CdnEndpointImpl withOrigin(String hostname) {
return this.withOrigin("origin", hostname);
}
@Override
public CdnEndpointImpl withPremiumOrigin(String originName, String hostname) {
return this.withOrigin(originName, hostname);
}
@Override
public CdnEndpointImpl withPremiumOrigin(String hostname) {
return this.withOrigin(hostname);
}
@Override
public CdnEndpointImpl withOriginPath(String originPath) {
this.inner().withOriginPath(originPath);
return this;
}
@Override
public CdnEndpointImpl withHttpAllowed(boolean httpAllowed) {
this.inner().withIsHttpAllowed(httpAllowed);
return this;
}
@Override
public CdnEndpointImpl withHttpsAllowed(boolean httpsAllowed) {
this.inner().withIsHttpsAllowed(httpsAllowed);
return this;
}
@Override
public CdnEndpointImpl withHttpPort(int httpPort) {
if (this.inner().origins() != null && !this.inner().origins().isEmpty()) {
this.inner().origins().get(0).withHttpPort(httpPort);
}
return this;
}
@Override
public CdnEndpointImpl withHttpsPort(int httpsPort) {
if (this.inner().origins() != null && !this.inner().origins().isEmpty()) {
this.inner().origins().get(0).withHttpsPort(httpsPort);
}
return this;
}
@Override
public CdnEndpointImpl withHostHeader(String hostHeader) {
this.inner().withOriginHostHeader(hostHeader);
return this;
}
@Override
public CdnEndpointImpl withContentTypesToCompress(Set<String> contentTypesToCompress) {
List<String> list = null;
if (contentTypesToCompress != null) {
list = new ArrayList<>(contentTypesToCompress);
}
this.inner().withContentTypesToCompress(list);
return this;
}
@Override
public CdnEndpointImpl withoutContentTypesToCompress() {
if (this.inner().contentTypesToCompress() != null) {
this.inner().contentTypesToCompress().clear();
}
return this;
}
@Override
public CdnEndpointImpl withContentTypeToCompress(String contentTypeToCompress) {
if (this.inner().contentTypesToCompress() == null) {
this.inner().withContentTypesToCompress(new ArrayList<>());
}
this.inner().contentTypesToCompress().add(contentTypeToCompress);
return this;
}
@Override
public CdnEndpointImpl withoutContentTypeToCompress(String contentTypeToCompress) {
if (this.inner().contentTypesToCompress() != null) {
this.inner().contentTypesToCompress().remove(contentTypeToCompress);
}
return this;
}
@Override
public CdnEndpointImpl withCompressionEnabled(boolean compressionEnabled) {
this.inner().withIsCompressionEnabled(compressionEnabled);
return this;
}
@Override
public CdnEndpointImpl withQueryStringCachingBehavior(QueryStringCachingBehavior cachingBehavior) {
this.inner().withQueryStringCachingBehavior(cachingBehavior);
return this;
}
@Override
public CdnEndpointImpl withGeoFilters(Collection<GeoFilter> geoFilters) {
List<GeoFilter> list = null;
if (geoFilters != null) {
list = new ArrayList<>(geoFilters);
}
this.inner().withGeoFilters(list);
return this;
}
@Override
public CdnEndpointImpl withoutGeoFilters() {
if (this.inner().geoFilters() != null) {
this.inner().geoFilters().clear();
}
return this;
}
@Override
public CdnEndpointImpl withGeoFilter(String relativePath, GeoFilterActions action, CountryIsoCode countryCode) {
GeoFilter geoFilter = this.createGeoFiltersObject(relativePath, action);
if (geoFilter.countryCodes() == null) {
geoFilter.withCountryCodes(new ArrayList<>());
}
geoFilter.countryCodes().add(countryCode.toString());
this.inner().geoFilters().add(geoFilter);
return this;
}
@Override
public CdnEndpointImpl withGeoFilter(
String relativePath, GeoFilterActions action, Collection<CountryIsoCode> countryCodes) {
GeoFilter geoFilter = this.createGeoFiltersObject(relativePath, action);
if (geoFilter.countryCodes() == null) {
geoFilter.withCountryCodes(new ArrayList<>());
} else {
geoFilter.countryCodes().clear();
}
for (CountryIsoCode countryCode : countryCodes) {
geoFilter.countryCodes().add(countryCode.toString());
}
this.inner().geoFilters().add(geoFilter);
return this;
}
@Override
public CdnEndpointImpl withoutGeoFilter(String relativePath) {
this.inner().geoFilters().removeIf(geoFilter -> geoFilter.relativePath().equals(relativePath));
return this;
}
@Override
public CdnEndpointImpl withCustomDomain(String hostName) {
this.customDomainList.add(new CustomDomainInner().withHostname(hostName));
return this;
}
@Override
public CdnEndpointImpl withoutCustomDomain(String hostName) {
deletedCustomDomainList.add(new CustomDomainInner().withHostname(hostName));
return this;
}
private GeoFilter createGeoFiltersObject(String relativePath, GeoFilterActions action) {
if (this.inner().geoFilters() == null) {
this.inner().withGeoFilters(new ArrayList<>());
}
GeoFilter geoFilter = null;
for (GeoFilter filter : this.inner().geoFilters()) {
if (filter.relativePath().equals(relativePath)) {
geoFilter = filter;
break;
}
}
if (geoFilter == null) {
geoFilter = new GeoFilter();
} else {
this.inner().geoFilters().remove(geoFilter);
}
geoFilter.withRelativePath(relativePath)
.withAction(action);
return geoFilter;
}
} | class CdnEndpointImpl
extends ExternalChildResourceImpl<
CdnEndpoint,
EndpointInner,
CdnProfileImpl,
CdnProfile>
implements CdnEndpoint,
CdnEndpoint.DefinitionStages.Blank.StandardEndpoint<CdnProfile.DefinitionStages.WithStandardCreate>,
CdnEndpoint.DefinitionStages.Blank.PremiumEndpoint<CdnProfile.DefinitionStages.WithPremiumVerizonCreate>,
CdnEndpoint.DefinitionStages.WithStandardAttach<CdnProfile.DefinitionStages.WithStandardCreate>,
CdnEndpoint.DefinitionStages.WithPremiumAttach<CdnProfile.DefinitionStages.WithPremiumVerizonCreate>,
CdnEndpoint.UpdateDefinitionStages.Blank.StandardEndpoint<CdnProfile.Update>,
CdnEndpoint.UpdateDefinitionStages.Blank.PremiumEndpoint<CdnProfile.Update>,
CdnEndpoint.UpdateDefinitionStages.WithStandardAttach<CdnProfile.Update>,
CdnEndpoint.UpdateDefinitionStages.WithPremiumAttach<CdnProfile.Update>,
CdnEndpoint.UpdateStandardEndpoint,
CdnEndpoint.UpdatePremiumEndpoint {
private List<CustomDomainInner> customDomainList;
private List<CustomDomainInner> deletedCustomDomainList;
CdnEndpointImpl(String name, CdnProfileImpl parent, EndpointInner inner) {
super(name, parent, inner);
this.customDomainList = new ArrayList<>();
this.deletedCustomDomainList = new ArrayList<>();
}
@Override
public String id() {
return this.inner().id();
}
@Override
public Mono<CdnEndpoint> createResourceAsync() {
final CdnEndpointImpl self = this;
return this.parent().manager().inner().getEndpoints().createAsync(this.parent().resourceGroupName(),
this.parent().name(),
this.name(),
this.inner())
.flatMap(inner -> {
self.setInner(inner);
return Flux.fromIterable(self.customDomainList)
.flatMapDelayError(customDomainInner -> self.parent().manager().inner()
.getCustomDomains().createAsync(
self.parent().resourceGroupName(),
self.parent().name(),
self.name(),
self.parent().manager().sdkContext().randomResourceName("CustomDomain", 50),
customDomainInner.hostname()), 32, 32)
.then(self.parent().manager().inner()
.getCustomDomains().listByEndpointAsync(
self.parent().resourceGroupName(),
self.parent().name(),
self.name())
.collectList()
.map(customDomainInners -> {
self.customDomainList.addAll(customDomainInners);
return self;
}));
});
}
@Override
@Override
public Mono<Void> deleteResourceAsync() {
return this.parent().manager().inner().getEndpoints().deleteAsync(this.parent().resourceGroupName(),
this.parent().name(),
this.name());
}
@Override
public Mono<CdnEndpoint> refreshAsync() {
final CdnEndpointImpl self = this;
return super.refreshAsync()
.flatMap(cdnEndpoint -> {
self.customDomainList.clear();
self.deletedCustomDomainList.clear();
return self.parent().manager().inner().getCustomDomains().listByEndpointAsync(
self.parent().resourceGroupName(),
self.parent().name(),
self.name()
)
.collectList()
.map(customDomainInners -> {
self.customDomainList.addAll(customDomainInners);
return self;
});
});
}
@Override
protected Mono<EndpointInner> getInnerAsync() {
return this.parent().manager().inner().getEndpoints().getAsync(this.parent().resourceGroupName(),
this.parent().name(),
this.name());
}
@Override
public PagedIterable<ResourceUsage> listResourceUsage() {
return this.parent().manager().inner().getEndpoints().listResourceUsage(
this.parent().resourceGroupName(),
this.parent().name(),
this.name())
.mapPage(ResourceUsage::new);
}
@Override
public CdnProfileImpl attach() {
return this.parent();
}
@Override
public String originHostHeader() {
return this.inner().originHostHeader();
}
@Override
public String originPath() {
return this.inner().originPath();
}
@Override
public Set<String> contentTypesToCompress() {
List<String> contentTypes = this.inner().contentTypesToCompress();
Set<String> set = new HashSet<>();
if (contentTypes != null) {
set.addAll(contentTypes);
}
return Collections.unmodifiableSet(set);
}
@Override
public boolean isCompressionEnabled() {
return this.inner().isCompressionEnabled();
}
@Override
public boolean isHttpAllowed() {
return this.inner().isHttpAllowed();
}
@Override
public boolean isHttpsAllowed() {
return this.inner().isHttpsAllowed();
}
@Override
public QueryStringCachingBehavior queryStringCachingBehavior() {
return this.inner().queryStringCachingBehavior();
}
@Override
public String optimizationType() {
if (this.inner().optimizationType() == null) {
return null;
}
return this.inner().optimizationType().toString();
}
@Override
public List<GeoFilter> geoFilters() {
return this.inner().geoFilters();
}
@Override
public String hostname() {
return this.inner().hostname();
}
@Override
public EndpointResourceState resourceState() {
return this.inner().resourceState();
}
@Override
public String provisioningState() {
return this.inner().provisioningState();
}
@Override
public String originHostName() {
if (this.inner().origins() != null && !this.inner().origins().isEmpty()) {
return this.inner().origins().get(0).hostname();
}
return null;
}
@Override
public int httpPort() {
if (this.inner().origins() != null && !this.inner().origins().isEmpty()) {
Integer httpPort = this.inner().origins().get(0).httpPort();
return (httpPort != null) ? httpPort : 0;
}
return 0;
}
@Override
public int httpsPort() {
if (this.inner().origins() != null && !this.inner().origins().isEmpty()) {
Integer httpsPort = this.inner().origins().get(0).httpsPort();
return (httpsPort != null) ? httpsPort : 0;
}
return 0;
}
@Override
public Set<String> customDomains() {
Set<String> set = new HashSet<>();
for (CustomDomainInner customDomainInner : this.parent().manager().inner().getCustomDomains()
.listByEndpoint(this.parent().resourceGroupName(), this.parent().name(), this.name())) {
set.add(customDomainInner.hostname());
}
return Collections.unmodifiableSet(set);
}
@Override
public void start() {
this.parent().startEndpoint(this.name());
}
@Override
public Mono<Void> startAsync() {
return this.parent().startEndpointAsync(this.name());
}
@Override
public void stop() {
this.stopAsync().block();
}
@Override
public Mono<Void> stopAsync() {
return this.parent().stopEndpointAsync(this.name());
}
@Override
public void purgeContent(Set<String> contentPaths) {
if (contentPaths != null) {
this.purgeContentAsync(contentPaths).block();
}
}
@Override
public Mono<Void> purgeContentAsync(Set<String> contentPaths) {
return this.parent().purgeEndpointContentAsync(this.name(), contentPaths);
}
@Override
public void loadContent(Set<String> contentPaths) {
this.loadContentAsync(contentPaths).block();
}
@Override
public Mono<Void> loadContentAsync(Set<String> contentPaths) {
return this.parent().loadEndpointContentAsync(this.name(), contentPaths);
}
@Override
public CustomDomainValidationResult validateCustomDomain(String hostName) {
return this.validateCustomDomainAsync(hostName).block();
}
@Override
public Mono<CustomDomainValidationResult> validateCustomDomainAsync(String hostName) {
return this.parent().validateEndpointCustomDomainAsync(this.name(), hostName);
}
@Override
public CdnEndpointImpl withOrigin(String originName, String hostname) {
this.inner().origins().add(
new DeepCreatedOrigin()
.withName(originName)
.withHostname(hostname));
return this;
}
@Override
public CdnEndpointImpl withOrigin(String hostname) {
return this.withOrigin("origin", hostname);
}
@Override
public CdnEndpointImpl withPremiumOrigin(String originName, String hostname) {
return this.withOrigin(originName, hostname);
}
@Override
public CdnEndpointImpl withPremiumOrigin(String hostname) {
return this.withOrigin(hostname);
}
@Override
public CdnEndpointImpl withOriginPath(String originPath) {
this.inner().withOriginPath(originPath);
return this;
}
@Override
public CdnEndpointImpl withHttpAllowed(boolean httpAllowed) {
this.inner().withIsHttpAllowed(httpAllowed);
return this;
}
@Override
public CdnEndpointImpl withHttpsAllowed(boolean httpsAllowed) {
this.inner().withIsHttpsAllowed(httpsAllowed);
return this;
}
@Override
public CdnEndpointImpl withHttpPort(int httpPort) {
if (this.inner().origins() != null && !this.inner().origins().isEmpty()) {
this.inner().origins().get(0).withHttpPort(httpPort);
}
return this;
}
@Override
public CdnEndpointImpl withHttpsPort(int httpsPort) {
if (this.inner().origins() != null && !this.inner().origins().isEmpty()) {
this.inner().origins().get(0).withHttpsPort(httpsPort);
}
return this;
}
@Override
public CdnEndpointImpl withHostHeader(String hostHeader) {
this.inner().withOriginHostHeader(hostHeader);
return this;
}
@Override
public CdnEndpointImpl withContentTypesToCompress(Set<String> contentTypesToCompress) {
List<String> list = null;
if (contentTypesToCompress != null) {
list = new ArrayList<>(contentTypesToCompress);
}
this.inner().withContentTypesToCompress(list);
return this;
}
@Override
public CdnEndpointImpl withoutContentTypesToCompress() {
if (this.inner().contentTypesToCompress() != null) {
this.inner().contentTypesToCompress().clear();
}
return this;
}
@Override
public CdnEndpointImpl withContentTypeToCompress(String contentTypeToCompress) {
if (this.inner().contentTypesToCompress() == null) {
this.inner().withContentTypesToCompress(new ArrayList<>());
}
this.inner().contentTypesToCompress().add(contentTypeToCompress);
return this;
}
@Override
public CdnEndpointImpl withoutContentTypeToCompress(String contentTypeToCompress) {
if (this.inner().contentTypesToCompress() != null) {
this.inner().contentTypesToCompress().remove(contentTypeToCompress);
}
return this;
}
@Override
public CdnEndpointImpl withCompressionEnabled(boolean compressionEnabled) {
this.inner().withIsCompressionEnabled(compressionEnabled);
return this;
}
@Override
public CdnEndpointImpl withQueryStringCachingBehavior(QueryStringCachingBehavior cachingBehavior) {
this.inner().withQueryStringCachingBehavior(cachingBehavior);
return this;
}
@Override
public CdnEndpointImpl withGeoFilters(Collection<GeoFilter> geoFilters) {
List<GeoFilter> list = null;
if (geoFilters != null) {
list = new ArrayList<>(geoFilters);
}
this.inner().withGeoFilters(list);
return this;
}
@Override
public CdnEndpointImpl withoutGeoFilters() {
if (this.inner().geoFilters() != null) {
this.inner().geoFilters().clear();
}
return this;
}
@Override
public CdnEndpointImpl withGeoFilter(String relativePath, GeoFilterActions action, CountryIsoCode countryCode) {
GeoFilter geoFilter = this.createGeoFiltersObject(relativePath, action);
if (geoFilter.countryCodes() == null) {
geoFilter.withCountryCodes(new ArrayList<>());
}
geoFilter.countryCodes().add(countryCode.toString());
this.inner().geoFilters().add(geoFilter);
return this;
}
@Override
public CdnEndpointImpl withGeoFilter(
String relativePath, GeoFilterActions action, Collection<CountryIsoCode> countryCodes) {
GeoFilter geoFilter = this.createGeoFiltersObject(relativePath, action);
if (geoFilter.countryCodes() == null) {
geoFilter.withCountryCodes(new ArrayList<>());
} else {
geoFilter.countryCodes().clear();
}
for (CountryIsoCode countryCode : countryCodes) {
geoFilter.countryCodes().add(countryCode.toString());
}
this.inner().geoFilters().add(geoFilter);
return this;
}
@Override
public CdnEndpointImpl withoutGeoFilter(String relativePath) {
this.inner().geoFilters().removeIf(geoFilter -> geoFilter.relativePath().equals(relativePath));
return this;
}
@Override
public CdnEndpointImpl withCustomDomain(String hostName) {
this.customDomainList.add(new CustomDomainInner().withHostname(hostName));
return this;
}
@Override
public CdnEndpointImpl withoutCustomDomain(String hostName) {
deletedCustomDomainList.add(new CustomDomainInner().withHostname(hostName));
return this;
}
private GeoFilter createGeoFiltersObject(String relativePath, GeoFilterActions action) {
if (this.inner().geoFilters() == null) {
this.inner().withGeoFilters(new ArrayList<>());
}
GeoFilter geoFilter = null;
for (GeoFilter filter : this.inner().geoFilters()) {
if (filter.relativePath().equals(relativePath)) {
geoFilter = filter;
break;
}
}
if (geoFilter == null) {
geoFilter = new GeoFilter();
} else {
this.inner().geoFilters().remove(geoFilter);
}
geoFilter.withRelativePath(relativePath)
.withAction(action);
return geoFilter;
}
} |
Updated. | public Mono<CdnEndpoint> updateResourceAsync() {
final CdnEndpointImpl self = this;
EndpointUpdateParameters endpointUpdateParameters = new EndpointUpdateParameters();
endpointUpdateParameters.withIsHttpAllowed(this.inner().isHttpAllowed())
.withIsHttpsAllowed(this.inner().isHttpsAllowed())
.withOriginPath(this.inner().originPath())
.withOriginHostHeader(this.inner().originHostHeader())
.withIsCompressionEnabled(this.inner().isCompressionEnabled())
.withContentTypesToCompress(this.inner().contentTypesToCompress())
.withGeoFilters(this.inner().geoFilters())
.withOptimizationType(this.inner().optimizationType())
.withQueryStringCachingBehavior(this.inner().queryStringCachingBehavior())
.withTags(this.inner().tags());
DeepCreatedOrigin originInner = this.inner().origins().get(0);
OriginUpdateParameters originUpdateParameters = new OriginUpdateParameters()
.withHostname(originInner.hostname())
.withHttpPort(originInner.httpPort())
.withHttpsPort(originInner.httpsPort());
Mono<OriginInner> originUpdateTask = this.parent().manager().inner().getOrigins().updateAsync(
this.parent().resourceGroupName(),
this.parent().name(),
this.name(),
originInner.name(),
originUpdateParameters);
Mono<EndpointInner> endpointUpdateTask = this.parent().manager().inner().getEndpoints().updateAsync(
this.parent().resourceGroupName(),
this.parent().name(),
this.name(),
endpointUpdateParameters);
Flux<CustomDomainInner> customDomainCreateTask = Flux.fromIterable(this.customDomainList)
.flatMapDelayError(itemToCreate -> this.parent().manager().inner().getCustomDomains().createAsync(
this.parent().resourceGroupName(),
this.parent().name(),
this.name(),
self.parent().manager().sdkContext().randomResourceName("CustomDomain", 50),
itemToCreate.hostname()
), 32, 32);
Flux<CustomDomainInner> customDomainDeleteTask = Flux.fromIterable(this.deletedCustomDomainList)
.flatMapDelayError(itemToDelete -> this.parent().manager().inner().getCustomDomains().deleteAsync(
this.parent().resourceGroupName(),
this.parent().name(),
this.name(),
itemToDelete.name()
), 32, 32);
Flux<CustomDomainInner> customDomainTask = Flux.concat(customDomainCreateTask, customDomainDeleteTask);
return customDomainTask.then(originUpdateTask).then(endpointUpdateTask)
.map(inner -> {
self.setInner(inner);
self.customDomainList.clear();
self.deletedCustomDomainList.clear();
return self;
});
} | return customDomainTask.then(originUpdateTask).then(endpointUpdateTask) | public Mono<CdnEndpoint> updateResourceAsync() {
final CdnEndpointImpl self = this;
EndpointUpdateParameters endpointUpdateParameters = new EndpointUpdateParameters();
endpointUpdateParameters.withIsHttpAllowed(this.inner().isHttpAllowed())
.withIsHttpsAllowed(this.inner().isHttpsAllowed())
.withOriginPath(this.inner().originPath())
.withOriginHostHeader(this.inner().originHostHeader())
.withIsCompressionEnabled(this.inner().isCompressionEnabled())
.withContentTypesToCompress(this.inner().contentTypesToCompress())
.withGeoFilters(this.inner().geoFilters())
.withOptimizationType(this.inner().optimizationType())
.withQueryStringCachingBehavior(this.inner().queryStringCachingBehavior())
.withTags(this.inner().tags());
DeepCreatedOrigin originInner = this.inner().origins().get(0);
OriginUpdateParameters originUpdateParameters = new OriginUpdateParameters()
.withHostname(originInner.hostname())
.withHttpPort(originInner.httpPort())
.withHttpsPort(originInner.httpsPort());
Mono<EndpointInner> originUpdateTask = this.parent().manager().inner().getOrigins().updateAsync(
this.parent().resourceGroupName(),
this.parent().name(),
this.name(),
originInner.name(),
originUpdateParameters)
.then(Mono.empty());
Mono<EndpointInner> endpointUpdateTask = this.parent().manager().inner().getEndpoints().updateAsync(
this.parent().resourceGroupName(),
this.parent().name(),
this.name(),
endpointUpdateParameters);
Flux<CustomDomainInner> customDomainCreateTask = Flux.fromIterable(this.customDomainList)
.flatMapDelayError(itemToCreate -> this.parent().manager().inner().getCustomDomains().createAsync(
this.parent().resourceGroupName(),
this.parent().name(),
this.name(),
self.parent().manager().sdkContext().randomResourceName("CustomDomain", 50),
itemToCreate.hostname()
), 32, 32);
Flux<CustomDomainInner> customDomainDeleteTask = Flux.fromIterable(this.deletedCustomDomainList)
.flatMapDelayError(itemToDelete -> this.parent().manager().inner().getCustomDomains().deleteAsync(
this.parent().resourceGroupName(),
this.parent().name(),
this.name(),
itemToDelete.name()
), 32, 32);
Mono<EndpointInner> customDomainTask = Flux.concat(customDomainCreateTask, customDomainDeleteTask)
.then(Mono.empty());
return Flux.mergeDelayError(32, customDomainTask, originUpdateTask, endpointUpdateTask)
.last()
.map(inner -> {
self.setInner(inner);
self.customDomainList.clear();
self.deletedCustomDomainList.clear();
return self;
});
} | class CdnEndpointImpl
extends ExternalChildResourceImpl<
CdnEndpoint,
EndpointInner,
CdnProfileImpl,
CdnProfile>
implements CdnEndpoint,
CdnEndpoint.DefinitionStages.Blank.StandardEndpoint<CdnProfile.DefinitionStages.WithStandardCreate>,
CdnEndpoint.DefinitionStages.Blank.PremiumEndpoint<CdnProfile.DefinitionStages.WithPremiumVerizonCreate>,
CdnEndpoint.DefinitionStages.WithStandardAttach<CdnProfile.DefinitionStages.WithStandardCreate>,
CdnEndpoint.DefinitionStages.WithPremiumAttach<CdnProfile.DefinitionStages.WithPremiumVerizonCreate>,
CdnEndpoint.UpdateDefinitionStages.Blank.StandardEndpoint<CdnProfile.Update>,
CdnEndpoint.UpdateDefinitionStages.Blank.PremiumEndpoint<CdnProfile.Update>,
CdnEndpoint.UpdateDefinitionStages.WithStandardAttach<CdnProfile.Update>,
CdnEndpoint.UpdateDefinitionStages.WithPremiumAttach<CdnProfile.Update>,
CdnEndpoint.UpdateStandardEndpoint,
CdnEndpoint.UpdatePremiumEndpoint {
private List<CustomDomainInner> customDomainList;
private List<CustomDomainInner> deletedCustomDomainList;
CdnEndpointImpl(String name, CdnProfileImpl parent, EndpointInner inner) {
super(name, parent, inner);
this.customDomainList = new ArrayList<>();
this.deletedCustomDomainList = new ArrayList<>();
}
@Override
public String id() {
return this.inner().id();
}
@Override
public Mono<CdnEndpoint> createResourceAsync() {
final CdnEndpointImpl self = this;
return this.parent().manager().inner().getEndpoints().createAsync(this.parent().resourceGroupName(),
this.parent().name(),
this.name(),
this.inner())
.flatMap(inner -> {
self.setInner(inner);
return Flux.fromIterable(self.customDomainList)
.flatMapDelayError(customDomainInner -> self.parent().manager().inner()
.getCustomDomains().createAsync(
self.parent().resourceGroupName(),
self.parent().name(),
self.name(),
self.parent().manager().sdkContext().randomResourceName("CustomDomain", 50),
customDomainInner.hostname()), 32, 32)
.then(self.parent().manager().inner()
.getCustomDomains().listByEndpointAsync(
self.parent().resourceGroupName(),
self.parent().name(),
self.name())
.collectList()
.map(customDomainInners -> {
self.customDomainList.addAll(customDomainInners);
return self;
}));
});
}
@Override
@Override
public Mono<Void> deleteResourceAsync() {
return this.parent().manager().inner().getEndpoints().deleteAsync(this.parent().resourceGroupName(),
this.parent().name(),
this.name());
}
@Override
public Mono<CdnEndpoint> refreshAsync() {
final CdnEndpointImpl self = this;
return super.refreshAsync()
.flatMap(cdnEndpoint -> {
self.customDomainList.clear();
self.deletedCustomDomainList.clear();
return self.parent().manager().inner().getCustomDomains().listByEndpointAsync(
self.parent().resourceGroupName(),
self.parent().name(),
self.name()
)
.collectList()
.map(customDomainInners -> {
self.customDomainList.addAll(customDomainInners);
return self;
});
});
}
@Override
protected Mono<EndpointInner> getInnerAsync() {
return this.parent().manager().inner().getEndpoints().getAsync(this.parent().resourceGroupName(),
this.parent().name(),
this.name());
}
@Override
public PagedIterable<ResourceUsage> listResourceUsage() {
return this.parent().manager().inner().getEndpoints().listResourceUsage(
this.parent().resourceGroupName(),
this.parent().name(),
this.name())
.mapPage(ResourceUsage::new);
}
@Override
public CdnProfileImpl attach() {
return this.parent();
}
@Override
public String originHostHeader() {
return this.inner().originHostHeader();
}
@Override
public String originPath() {
return this.inner().originPath();
}
@Override
public Set<String> contentTypesToCompress() {
List<String> contentTypes = this.inner().contentTypesToCompress();
Set<String> set = new HashSet<>();
if (contentTypes != null) {
set.addAll(contentTypes);
}
return Collections.unmodifiableSet(set);
}
@Override
public boolean isCompressionEnabled() {
return this.inner().isCompressionEnabled();
}
@Override
public boolean isHttpAllowed() {
return this.inner().isHttpAllowed();
}
@Override
public boolean isHttpsAllowed() {
return this.inner().isHttpsAllowed();
}
@Override
public QueryStringCachingBehavior queryStringCachingBehavior() {
return this.inner().queryStringCachingBehavior();
}
@Override
public String optimizationType() {
if (this.inner().optimizationType() == null) {
return null;
}
return this.inner().optimizationType().toString();
}
@Override
public List<GeoFilter> geoFilters() {
return this.inner().geoFilters();
}
@Override
public String hostname() {
return this.inner().hostname();
}
@Override
public EndpointResourceState resourceState() {
return this.inner().resourceState();
}
@Override
public String provisioningState() {
return this.inner().provisioningState();
}
@Override
public String originHostName() {
if (this.inner().origins() != null && !this.inner().origins().isEmpty()) {
return this.inner().origins().get(0).hostname();
}
return null;
}
@Override
public int httpPort() {
if (this.inner().origins() != null && !this.inner().origins().isEmpty()) {
Integer httpPort = this.inner().origins().get(0).httpPort();
return (httpPort != null) ? httpPort : 0;
}
return 0;
}
@Override
public int httpsPort() {
if (this.inner().origins() != null && !this.inner().origins().isEmpty()) {
Integer httpsPort = this.inner().origins().get(0).httpsPort();
return (httpsPort != null) ? httpsPort : 0;
}
return 0;
}
@Override
public Set<String> customDomains() {
Set<String> set = new HashSet<>();
for (CustomDomainInner customDomainInner : this.parent().manager().inner().getCustomDomains()
.listByEndpoint(this.parent().resourceGroupName(), this.parent().name(), this.name())) {
set.add(customDomainInner.hostname());
}
return Collections.unmodifiableSet(set);
}
@Override
public void start() {
this.parent().startEndpoint(this.name());
}
@Override
public Mono<Void> startAsync() {
return this.parent().startEndpointAsync(this.name());
}
@Override
public void stop() {
this.stopAsync().block();
}
@Override
public Mono<Void> stopAsync() {
return this.parent().stopEndpointAsync(this.name());
}
@Override
public void purgeContent(Set<String> contentPaths) {
if (contentPaths != null) {
this.purgeContentAsync(contentPaths).block();
}
}
@Override
public Mono<Void> purgeContentAsync(Set<String> contentPaths) {
return this.parent().purgeEndpointContentAsync(this.name(), contentPaths);
}
@Override
public void loadContent(Set<String> contentPaths) {
this.loadContentAsync(contentPaths).block();
}
@Override
public Mono<Void> loadContentAsync(Set<String> contentPaths) {
return this.parent().loadEndpointContentAsync(this.name(), contentPaths);
}
@Override
public CustomDomainValidationResult validateCustomDomain(String hostName) {
return this.validateCustomDomainAsync(hostName).block();
}
@Override
public Mono<CustomDomainValidationResult> validateCustomDomainAsync(String hostName) {
return this.parent().validateEndpointCustomDomainAsync(this.name(), hostName);
}
@Override
public CdnEndpointImpl withOrigin(String originName, String hostname) {
this.inner().origins().add(
new DeepCreatedOrigin()
.withName(originName)
.withHostname(hostname));
return this;
}
@Override
public CdnEndpointImpl withOrigin(String hostname) {
return this.withOrigin("origin", hostname);
}
@Override
public CdnEndpointImpl withPremiumOrigin(String originName, String hostname) {
return this.withOrigin(originName, hostname);
}
@Override
public CdnEndpointImpl withPremiumOrigin(String hostname) {
return this.withOrigin(hostname);
}
@Override
public CdnEndpointImpl withOriginPath(String originPath) {
this.inner().withOriginPath(originPath);
return this;
}
@Override
public CdnEndpointImpl withHttpAllowed(boolean httpAllowed) {
this.inner().withIsHttpAllowed(httpAllowed);
return this;
}
@Override
public CdnEndpointImpl withHttpsAllowed(boolean httpsAllowed) {
this.inner().withIsHttpsAllowed(httpsAllowed);
return this;
}
@Override
public CdnEndpointImpl withHttpPort(int httpPort) {
if (this.inner().origins() != null && !this.inner().origins().isEmpty()) {
this.inner().origins().get(0).withHttpPort(httpPort);
}
return this;
}
@Override
public CdnEndpointImpl withHttpsPort(int httpsPort) {
if (this.inner().origins() != null && !this.inner().origins().isEmpty()) {
this.inner().origins().get(0).withHttpsPort(httpsPort);
}
return this;
}
@Override
public CdnEndpointImpl withHostHeader(String hostHeader) {
this.inner().withOriginHostHeader(hostHeader);
return this;
}
@Override
public CdnEndpointImpl withContentTypesToCompress(Set<String> contentTypesToCompress) {
List<String> list = null;
if (contentTypesToCompress != null) {
list = new ArrayList<>(contentTypesToCompress);
}
this.inner().withContentTypesToCompress(list);
return this;
}
@Override
public CdnEndpointImpl withoutContentTypesToCompress() {
if (this.inner().contentTypesToCompress() != null) {
this.inner().contentTypesToCompress().clear();
}
return this;
}
@Override
public CdnEndpointImpl withContentTypeToCompress(String contentTypeToCompress) {
if (this.inner().contentTypesToCompress() == null) {
this.inner().withContentTypesToCompress(new ArrayList<>());
}
this.inner().contentTypesToCompress().add(contentTypeToCompress);
return this;
}
@Override
public CdnEndpointImpl withoutContentTypeToCompress(String contentTypeToCompress) {
if (this.inner().contentTypesToCompress() != null) {
this.inner().contentTypesToCompress().remove(contentTypeToCompress);
}
return this;
}
@Override
public CdnEndpointImpl withCompressionEnabled(boolean compressionEnabled) {
this.inner().withIsCompressionEnabled(compressionEnabled);
return this;
}
@Override
public CdnEndpointImpl withQueryStringCachingBehavior(QueryStringCachingBehavior cachingBehavior) {
this.inner().withQueryStringCachingBehavior(cachingBehavior);
return this;
}
@Override
public CdnEndpointImpl withGeoFilters(Collection<GeoFilter> geoFilters) {
List<GeoFilter> list = null;
if (geoFilters != null) {
list = new ArrayList<>(geoFilters);
}
this.inner().withGeoFilters(list);
return this;
}
@Override
public CdnEndpointImpl withoutGeoFilters() {
if (this.inner().geoFilters() != null) {
this.inner().geoFilters().clear();
}
return this;
}
@Override
public CdnEndpointImpl withGeoFilter(String relativePath, GeoFilterActions action, CountryIsoCode countryCode) {
GeoFilter geoFilter = this.createGeoFiltersObject(relativePath, action);
if (geoFilter.countryCodes() == null) {
geoFilter.withCountryCodes(new ArrayList<>());
}
geoFilter.countryCodes().add(countryCode.toString());
this.inner().geoFilters().add(geoFilter);
return this;
}
@Override
public CdnEndpointImpl withGeoFilter(
String relativePath, GeoFilterActions action, Collection<CountryIsoCode> countryCodes) {
GeoFilter geoFilter = this.createGeoFiltersObject(relativePath, action);
if (geoFilter.countryCodes() == null) {
geoFilter.withCountryCodes(new ArrayList<>());
} else {
geoFilter.countryCodes().clear();
}
for (CountryIsoCode countryCode : countryCodes) {
geoFilter.countryCodes().add(countryCode.toString());
}
this.inner().geoFilters().add(geoFilter);
return this;
}
@Override
public CdnEndpointImpl withoutGeoFilter(String relativePath) {
this.inner().geoFilters().removeIf(geoFilter -> geoFilter.relativePath().equals(relativePath));
return this;
}
@Override
public CdnEndpointImpl withCustomDomain(String hostName) {
this.customDomainList.add(new CustomDomainInner().withHostname(hostName));
return this;
}
@Override
public CdnEndpointImpl withoutCustomDomain(String hostName) {
deletedCustomDomainList.add(new CustomDomainInner().withHostname(hostName));
return this;
}
private GeoFilter createGeoFiltersObject(String relativePath, GeoFilterActions action) {
if (this.inner().geoFilters() == null) {
this.inner().withGeoFilters(new ArrayList<>());
}
GeoFilter geoFilter = null;
for (GeoFilter filter : this.inner().geoFilters()) {
if (filter.relativePath().equals(relativePath)) {
geoFilter = filter;
break;
}
}
if (geoFilter == null) {
geoFilter = new GeoFilter();
} else {
this.inner().geoFilters().remove(geoFilter);
}
geoFilter.withRelativePath(relativePath)
.withAction(action);
return geoFilter;
}
} | class CdnEndpointImpl
extends ExternalChildResourceImpl<
CdnEndpoint,
EndpointInner,
CdnProfileImpl,
CdnProfile>
implements CdnEndpoint,
CdnEndpoint.DefinitionStages.Blank.StandardEndpoint<CdnProfile.DefinitionStages.WithStandardCreate>,
CdnEndpoint.DefinitionStages.Blank.PremiumEndpoint<CdnProfile.DefinitionStages.WithPremiumVerizonCreate>,
CdnEndpoint.DefinitionStages.WithStandardAttach<CdnProfile.DefinitionStages.WithStandardCreate>,
CdnEndpoint.DefinitionStages.WithPremiumAttach<CdnProfile.DefinitionStages.WithPremiumVerizonCreate>,
CdnEndpoint.UpdateDefinitionStages.Blank.StandardEndpoint<CdnProfile.Update>,
CdnEndpoint.UpdateDefinitionStages.Blank.PremiumEndpoint<CdnProfile.Update>,
CdnEndpoint.UpdateDefinitionStages.WithStandardAttach<CdnProfile.Update>,
CdnEndpoint.UpdateDefinitionStages.WithPremiumAttach<CdnProfile.Update>,
CdnEndpoint.UpdateStandardEndpoint,
CdnEndpoint.UpdatePremiumEndpoint {
private List<CustomDomainInner> customDomainList;
private List<CustomDomainInner> deletedCustomDomainList;
CdnEndpointImpl(String name, CdnProfileImpl parent, EndpointInner inner) {
super(name, parent, inner);
this.customDomainList = new ArrayList<>();
this.deletedCustomDomainList = new ArrayList<>();
}
@Override
public String id() {
return this.inner().id();
}
@Override
public Mono<CdnEndpoint> createResourceAsync() {
final CdnEndpointImpl self = this;
return this.parent().manager().inner().getEndpoints().createAsync(this.parent().resourceGroupName(),
this.parent().name(),
this.name(),
this.inner())
.flatMap(inner -> {
self.setInner(inner);
return Flux.fromIterable(self.customDomainList)
.flatMapDelayError(customDomainInner -> self.parent().manager().inner()
.getCustomDomains().createAsync(
self.parent().resourceGroupName(),
self.parent().name(),
self.name(),
self.parent().manager().sdkContext().randomResourceName("CustomDomain", 50),
customDomainInner.hostname()), 32, 32)
.then(self.parent().manager().inner()
.getCustomDomains().listByEndpointAsync(
self.parent().resourceGroupName(),
self.parent().name(),
self.name())
.collectList()
.map(customDomainInners -> {
self.customDomainList.addAll(customDomainInners);
return self;
}));
});
}
@Override
@Override
public Mono<Void> deleteResourceAsync() {
return this.parent().manager().inner().getEndpoints().deleteAsync(this.parent().resourceGroupName(),
this.parent().name(),
this.name());
}
@Override
public Mono<CdnEndpoint> refreshAsync() {
final CdnEndpointImpl self = this;
return super.refreshAsync()
.flatMap(cdnEndpoint -> {
self.customDomainList.clear();
self.deletedCustomDomainList.clear();
return self.parent().manager().inner().getCustomDomains().listByEndpointAsync(
self.parent().resourceGroupName(),
self.parent().name(),
self.name()
)
.collectList()
.map(customDomainInners -> {
self.customDomainList.addAll(customDomainInners);
return self;
});
});
}
@Override
protected Mono<EndpointInner> getInnerAsync() {
return this.parent().manager().inner().getEndpoints().getAsync(this.parent().resourceGroupName(),
this.parent().name(),
this.name());
}
@Override
public PagedIterable<ResourceUsage> listResourceUsage() {
return this.parent().manager().inner().getEndpoints().listResourceUsage(
this.parent().resourceGroupName(),
this.parent().name(),
this.name())
.mapPage(ResourceUsage::new);
}
@Override
public CdnProfileImpl attach() {
return this.parent();
}
@Override
public String originHostHeader() {
return this.inner().originHostHeader();
}
@Override
public String originPath() {
return this.inner().originPath();
}
@Override
public Set<String> contentTypesToCompress() {
List<String> contentTypes = this.inner().contentTypesToCompress();
Set<String> set = new HashSet<>();
if (contentTypes != null) {
set.addAll(contentTypes);
}
return Collections.unmodifiableSet(set);
}
@Override
public boolean isCompressionEnabled() {
return this.inner().isCompressionEnabled();
}
@Override
public boolean isHttpAllowed() {
return this.inner().isHttpAllowed();
}
@Override
public boolean isHttpsAllowed() {
return this.inner().isHttpsAllowed();
}
@Override
public QueryStringCachingBehavior queryStringCachingBehavior() {
return this.inner().queryStringCachingBehavior();
}
@Override
public String optimizationType() {
if (this.inner().optimizationType() == null) {
return null;
}
return this.inner().optimizationType().toString();
}
@Override
public List<GeoFilter> geoFilters() {
return this.inner().geoFilters();
}
@Override
public String hostname() {
return this.inner().hostname();
}
@Override
public EndpointResourceState resourceState() {
return this.inner().resourceState();
}
@Override
public String provisioningState() {
return this.inner().provisioningState();
}
@Override
public String originHostName() {
if (this.inner().origins() != null && !this.inner().origins().isEmpty()) {
return this.inner().origins().get(0).hostname();
}
return null;
}
@Override
public int httpPort() {
if (this.inner().origins() != null && !this.inner().origins().isEmpty()) {
Integer httpPort = this.inner().origins().get(0).httpPort();
return (httpPort != null) ? httpPort : 0;
}
return 0;
}
@Override
public int httpsPort() {
if (this.inner().origins() != null && !this.inner().origins().isEmpty()) {
Integer httpsPort = this.inner().origins().get(0).httpsPort();
return (httpsPort != null) ? httpsPort : 0;
}
return 0;
}
@Override
public Set<String> customDomains() {
Set<String> set = new HashSet<>();
for (CustomDomainInner customDomainInner : this.parent().manager().inner().getCustomDomains()
.listByEndpoint(this.parent().resourceGroupName(), this.parent().name(), this.name())) {
set.add(customDomainInner.hostname());
}
return Collections.unmodifiableSet(set);
}
@Override
public void start() {
this.parent().startEndpoint(this.name());
}
@Override
public Mono<Void> startAsync() {
return this.parent().startEndpointAsync(this.name());
}
@Override
public void stop() {
this.stopAsync().block();
}
@Override
public Mono<Void> stopAsync() {
return this.parent().stopEndpointAsync(this.name());
}
@Override
public void purgeContent(Set<String> contentPaths) {
if (contentPaths != null) {
this.purgeContentAsync(contentPaths).block();
}
}
@Override
public Mono<Void> purgeContentAsync(Set<String> contentPaths) {
return this.parent().purgeEndpointContentAsync(this.name(), contentPaths);
}
@Override
public void loadContent(Set<String> contentPaths) {
this.loadContentAsync(contentPaths).block();
}
@Override
public Mono<Void> loadContentAsync(Set<String> contentPaths) {
return this.parent().loadEndpointContentAsync(this.name(), contentPaths);
}
@Override
public CustomDomainValidationResult validateCustomDomain(String hostName) {
return this.validateCustomDomainAsync(hostName).block();
}
@Override
public Mono<CustomDomainValidationResult> validateCustomDomainAsync(String hostName) {
return this.parent().validateEndpointCustomDomainAsync(this.name(), hostName);
}
@Override
public CdnEndpointImpl withOrigin(String originName, String hostname) {
this.inner().origins().add(
new DeepCreatedOrigin()
.withName(originName)
.withHostname(hostname));
return this;
}
@Override
public CdnEndpointImpl withOrigin(String hostname) {
return this.withOrigin("origin", hostname);
}
@Override
public CdnEndpointImpl withPremiumOrigin(String originName, String hostname) {
return this.withOrigin(originName, hostname);
}
@Override
public CdnEndpointImpl withPremiumOrigin(String hostname) {
return this.withOrigin(hostname);
}
@Override
public CdnEndpointImpl withOriginPath(String originPath) {
this.inner().withOriginPath(originPath);
return this;
}
@Override
public CdnEndpointImpl withHttpAllowed(boolean httpAllowed) {
this.inner().withIsHttpAllowed(httpAllowed);
return this;
}
@Override
public CdnEndpointImpl withHttpsAllowed(boolean httpsAllowed) {
this.inner().withIsHttpsAllowed(httpsAllowed);
return this;
}
@Override
public CdnEndpointImpl withHttpPort(int httpPort) {
if (this.inner().origins() != null && !this.inner().origins().isEmpty()) {
this.inner().origins().get(0).withHttpPort(httpPort);
}
return this;
}
@Override
public CdnEndpointImpl withHttpsPort(int httpsPort) {
if (this.inner().origins() != null && !this.inner().origins().isEmpty()) {
this.inner().origins().get(0).withHttpsPort(httpsPort);
}
return this;
}
@Override
public CdnEndpointImpl withHostHeader(String hostHeader) {
this.inner().withOriginHostHeader(hostHeader);
return this;
}
@Override
public CdnEndpointImpl withContentTypesToCompress(Set<String> contentTypesToCompress) {
List<String> list = null;
if (contentTypesToCompress != null) {
list = new ArrayList<>(contentTypesToCompress);
}
this.inner().withContentTypesToCompress(list);
return this;
}
@Override
public CdnEndpointImpl withoutContentTypesToCompress() {
if (this.inner().contentTypesToCompress() != null) {
this.inner().contentTypesToCompress().clear();
}
return this;
}
@Override
public CdnEndpointImpl withContentTypeToCompress(String contentTypeToCompress) {
if (this.inner().contentTypesToCompress() == null) {
this.inner().withContentTypesToCompress(new ArrayList<>());
}
this.inner().contentTypesToCompress().add(contentTypeToCompress);
return this;
}
@Override
public CdnEndpointImpl withoutContentTypeToCompress(String contentTypeToCompress) {
if (this.inner().contentTypesToCompress() != null) {
this.inner().contentTypesToCompress().remove(contentTypeToCompress);
}
return this;
}
@Override
public CdnEndpointImpl withCompressionEnabled(boolean compressionEnabled) {
this.inner().withIsCompressionEnabled(compressionEnabled);
return this;
}
@Override
public CdnEndpointImpl withQueryStringCachingBehavior(QueryStringCachingBehavior cachingBehavior) {
this.inner().withQueryStringCachingBehavior(cachingBehavior);
return this;
}
@Override
public CdnEndpointImpl withGeoFilters(Collection<GeoFilter> geoFilters) {
List<GeoFilter> list = null;
if (geoFilters != null) {
list = new ArrayList<>(geoFilters);
}
this.inner().withGeoFilters(list);
return this;
}
@Override
public CdnEndpointImpl withoutGeoFilters() {
if (this.inner().geoFilters() != null) {
this.inner().geoFilters().clear();
}
return this;
}
@Override
public CdnEndpointImpl withGeoFilter(String relativePath, GeoFilterActions action, CountryIsoCode countryCode) {
GeoFilter geoFilter = this.createGeoFiltersObject(relativePath, action);
if (geoFilter.countryCodes() == null) {
geoFilter.withCountryCodes(new ArrayList<>());
}
geoFilter.countryCodes().add(countryCode.toString());
this.inner().geoFilters().add(geoFilter);
return this;
}
@Override
public CdnEndpointImpl withGeoFilter(
String relativePath, GeoFilterActions action, Collection<CountryIsoCode> countryCodes) {
GeoFilter geoFilter = this.createGeoFiltersObject(relativePath, action);
if (geoFilter.countryCodes() == null) {
geoFilter.withCountryCodes(new ArrayList<>());
} else {
geoFilter.countryCodes().clear();
}
for (CountryIsoCode countryCode : countryCodes) {
geoFilter.countryCodes().add(countryCode.toString());
}
this.inner().geoFilters().add(geoFilter);
return this;
}
@Override
public CdnEndpointImpl withoutGeoFilter(String relativePath) {
this.inner().geoFilters().removeIf(geoFilter -> geoFilter.relativePath().equals(relativePath));
return this;
}
@Override
public CdnEndpointImpl withCustomDomain(String hostName) {
this.customDomainList.add(new CustomDomainInner().withHostname(hostName));
return this;
}
@Override
public CdnEndpointImpl withoutCustomDomain(String hostName) {
deletedCustomDomainList.add(new CustomDomainInner().withHostname(hostName));
return this;
}
private GeoFilter createGeoFiltersObject(String relativePath, GeoFilterActions action) {
if (this.inner().geoFilters() == null) {
this.inner().withGeoFilters(new ArrayList<>());
}
GeoFilter geoFilter = null;
for (GeoFilter filter : this.inner().geoFilters()) {
if (filter.relativePath().equals(relativePath)) {
geoFilter = filter;
break;
}
}
if (geoFilter == null) {
geoFilter = new GeoFilter();
} else {
this.inner().geoFilters().remove(geoFilter);
}
geoFilter.withRelativePath(relativePath)
.withAction(action);
return geoFilter;
}
} |
does `queryNextPage` need the query string again? | public PagedFlux<String> query(String query) {
return new PagedFlux<>(
() -> withContext(context -> queryFirstPage(query, context)),
nextLink -> withContext(context -> queryNextPage(query, nextLink, context)));
} | nextLink -> withContext(context -> queryNextPage(query, nextLink, context))); | public PagedFlux<String> query(String query) {
return new PagedFlux<>(
() -> withContext(context -> queryFirstPage(query, context)),
nextLink -> withContext(context -> queryNextPage(nextLink, context)));
} | class to deserialize the application/json component into.
* @param <T> The generic type to deserialize the component to.
* @return A {@link DigitalTwinsResponse} | class to deserialize the application/json component into.
* @param <T> The generic type to deserialize the component to.
* @return A {@link DigitalTwinsResponse} |
Doesn't `QuerySpecification` have fluent setters? | Mono<PagedResponse<String>> queryFirstPage(String query, Context context) {
QuerySpecification querySpecification = new QuerySpecification();
querySpecification
.setQuery(query);
return protocolLayer
.getQueries()
.queryTwinsWithResponseAsync(querySpecification, context)
.map(objectPagedResponse -> new PagedResponseBase<>(
objectPagedResponse.getRequest(),
objectPagedResponse.getStatusCode(),
objectPagedResponse.getHeaders(),
objectPagedResponse.getValue().getItems().stream()
.map(object -> {
try {
return mapper.writeValueAsString(object);
} catch (JsonProcessingException e) {
logger.error("JsonProcessingException occurred while retrieving query result items: ", e);
throw new RuntimeException("JsonProcessingException occurred while retrieving query result items", e);
}
})
.filter(Objects::nonNull)
.collect(Collectors.toList()),
objectPagedResponse.getValue().getContinuationToken(),
objectPagedResponse.getDeserializedHeaders()));
} | querySpecification | new QuerySpecification().setQuery(query);
return protocolLayer
.getQueries()
.queryTwinsWithResponseAsync(querySpecification, context)
.map(objectPagedResponse -> new PagedResponseBase<>(
objectPagedResponse.getRequest(),
objectPagedResponse.getStatusCode(),
objectPagedResponse.getHeaders(),
objectPagedResponse.getValue().getItems().stream()
.map(object -> {
try {
return mapper.writeValueAsString(object);
} catch (JsonProcessingException e) {
logger.error("JsonProcessingException occurred while retrieving query result items: ", e);
throw new RuntimeException("JsonProcessingException occurred while retrieving query result items", e);
}
} | class to convert the query response to.
* @param <T> The generic type to convert the query response to.
* @return A {@link PagedFlux} | class to convert the query response to.
* @param <T> The generic type to convert the query response to.
* @return A {@link PagedFlux} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.