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 |
|---|---|---|---|---|---|
Instead of casting it here twice (here and below), let's cast it in the `createFeedResponseFromGroupingTable` itself and return `FeedResponse<T>` What if it is null the very first time ? Casting will throw a NPE. | public Flux<FeedResponse<T>> drainAsync(int maxPageSize) {
return this.component.drainAsync(maxPageSize)
.collectList()
.map(superList -> {
double requestCharge = 0;
HashMap<String, String> headers = new HashMap<>();
List<Document> documentList = new ArrayList<>();
/* Do groupBy stuff here */
for (FeedResponse<T> page ... | return (FeedResponse<T>)createFeedResponseFromGroupingTable(maxPageSize, requestCharge); | Drain the groupings fully from all continuation and all partitions
for (FeedResponse<T> page : superList) {
List<Document> results = (List<Document>) page.getResults();
documentList.addAll(results);
requestCharge += page.getRequestCharge();
} | class GroupByDocumentQueryExecutionContext<T extends Resource> implements
IDocumentQueryExecutionComponent<T> {
public static final String CONTINUATION_TOKEN_NOT_SUPPORTED_WITH_GROUP_BY = "Continuation token is not supported " +
"for queries with GROUP BY." +
"Do not use continuation token" +
" or remove the GROUP BY "... | class GroupByDocumentQueryExecutionContext<T extends Resource> implements
IDocumentQueryExecutionComponent<T> {
public static final String CONTINUATION_TOKEN_NOT_SUPPORTED_WITH_GROUP_BY = "Continuation token is not supported " +
"for queries with GROUP BY." +
"Do not use continuation token" +
" or remove the GROUP BY "... |
Please add some comments to expand (explaining how it will be called second time onwards) | public Flux<FeedResponse<T>> drainAsync(int maxPageSize) {
return this.component.drainAsync(maxPageSize)
.collectList()
.map(superList -> {
double requestCharge = 0;
HashMap<String, String> headers = new HashMap<>();
List<Document> documentList = new ArrayList<>();
/* Do groupBy stuff here */
for (FeedResponse<T> page ... | Drain the groupings fully from all continuation and all partitions
for (FeedResponse<T> page : superList) {
List<Document> results = (List<Document>) page.getResults();
documentList.addAll(results);
requestCharge += page.getRequestCharge();
} | class GroupByDocumentQueryExecutionContext<T extends Resource> implements
IDocumentQueryExecutionComponent<T> {
public static final String CONTINUATION_TOKEN_NOT_SUPPORTED_WITH_GROUP_BY = "Continuation token is not supported " +
"for queries with GROUP BY." +
"Do not use continuation token" +
" or remove the GROUP BY "... | class GroupByDocumentQueryExecutionContext<T extends Resource> implements
IDocumentQueryExecutionComponent<T> {
public static final String CONTINUATION_TOKEN_NOT_SUPPORTED_WITH_GROUP_BY = "Continuation token is not supported " +
"for queries with GROUP BY." +
"Do not use continuation token" +
" or remove the GROUP BY "... | |
You can do the same thing here, what you did down below, return an empty Mono to avoid NPE. | public Flux<FeedResponse<T>> drainAsync(int maxPageSize) {
return this.component.drainAsync(maxPageSize)
.collectList()
.map(superList -> {
double requestCharge = 0;
HashMap<String, String> headers = new HashMap<>();
List<Document> documentList = new ArrayList<>();
/* Do groupBy stuff here */
for (FeedResponse<T> page ... | return (FeedResponse<T>)createFeedResponseFromGroupingTable(maxPageSize, requestCharge); | Drain the groupings fully from all continuation and all partitions
for (FeedResponse<T> page : superList) {
List<Document> results = (List<Document>) page.getResults();
documentList.addAll(results);
requestCharge += page.getRequestCharge();
} | class GroupByDocumentQueryExecutionContext<T extends Resource> implements
IDocumentQueryExecutionComponent<T> {
public static final String CONTINUATION_TOKEN_NOT_SUPPORTED_WITH_GROUP_BY = "Continuation token is not supported " +
"for queries with GROUP BY." +
"Do not use continuation token" +
" or remove the GROUP BY "... | class GroupByDocumentQueryExecutionContext<T extends Resource> implements
IDocumentQueryExecutionComponent<T> {
public static final String CONTINUATION_TOKEN_NOT_SUPPORTED_WITH_GROUP_BY = "Continuation token is not supported " +
"for queries with GROUP BY." +
"Do not use continuation token" +
" or remove the GROUP BY "... |
Updated | public Flux<FeedResponse<T>> drainAsync(int maxPageSize) {
return this.component.drainAsync(maxPageSize)
.collectList()
.map(superList -> {
double requestCharge = 0;
HashMap<String, String> headers = new HashMap<>();
List<Document> documentList = new ArrayList<>();
/* Do groupBy stuff here */
for (FeedResponse<T> page ... | Drain the groupings fully from all continuation and all partitions
for (FeedResponse<T> page : superList) {
List<Document> results = (List<Document>) page.getResults();
documentList.addAll(results);
requestCharge += page.getRequestCharge();
} | class GroupByDocumentQueryExecutionContext<T extends Resource> implements
IDocumentQueryExecutionComponent<T> {
public static final String CONTINUATION_TOKEN_NOT_SUPPORTED_WITH_GROUP_BY = "Continuation token is not supported " +
"for queries with GROUP BY." +
"Do not use continuation token" +
" or remove the GROUP BY "... | class GroupByDocumentQueryExecutionContext<T extends Resource> implements
IDocumentQueryExecutionComponent<T> {
public static final String CONTINUATION_TOKEN_NOT_SUPPORTED_WITH_GROUP_BY = "Continuation token is not supported " +
"for queries with GROUP BY." +
"Do not use continuation token" +
" or remove the GROUP BY "... | |
changed to update in the createFeedResponseFromGroupingTable | public Flux<FeedResponse<T>> drainAsync(int maxPageSize) {
return this.component.drainAsync(maxPageSize)
.collectList()
.map(superList -> {
double requestCharge = 0;
HashMap<String, String> headers = new HashMap<>();
List<Document> documentList = new ArrayList<>();
/* Do groupBy stuff here */
for (FeedResponse<T> page ... | return (FeedResponse<T>)createFeedResponseFromGroupingTable(maxPageSize, requestCharge); | Drain the groupings fully from all continuation and all partitions
for (FeedResponse<T> page : superList) {
List<Document> results = (List<Document>) page.getResults();
documentList.addAll(results);
requestCharge += page.getRequestCharge();
} | class GroupByDocumentQueryExecutionContext<T extends Resource> implements
IDocumentQueryExecutionComponent<T> {
public static final String CONTINUATION_TOKEN_NOT_SUPPORTED_WITH_GROUP_BY = "Continuation token is not supported " +
"for queries with GROUP BY." +
"Do not use continuation token" +
" or remove the GROUP BY "... | class GroupByDocumentQueryExecutionContext<T extends Resource> implements
IDocumentQueryExecutionComponent<T> {
public static final String CONTINUATION_TOKEN_NOT_SUPPORTED_WITH_GROUP_BY = "Continuation token is not supported " +
"for queries with GROUP BY." +
"Do not use continuation token" +
" or remove the GROUP BY "... |
Are tokens guaranteed to be ASCII only? If not it may be better to use `StandardCharset.UTF_8` here as the `defaultCharset` is specific to the machine. Linux and Mac will default `UTF-8` while Windows defaults `CP1252`. | private void mockForMSICodeFlow(String tokenJson) throws Exception {
URL u = PowerMockito.mock(URL.class);
whenNew(URL.class).withAnyArguments().thenReturn(u);
HttpURLConnection huc = PowerMockito.mock(HttpURLConnection.class);
when(u.openConnection()).thenReturn(huc);
PowerMockito.doNothing().when(huc).setRequestMetho... | InputStream inputStream = new ByteArrayInputStream(tokenJson.getBytes(Charset.defaultCharset())); | private void mockForMSICodeFlow(String tokenJson) throws Exception {
URL u = PowerMockito.mock(URL.class);
whenNew(URL.class).withAnyArguments().thenReturn(u);
HttpURLConnection huc = PowerMockito.mock(HttpURLConnection.class);
when(u.openConnection()).thenReturn(huc);
PowerMockito.doNothing().when(huc).setRequestMetho... | class IdentityClientTests {
private static final String TENANT_ID = "contoso.com";
private static final String CLIENT_ID = UUID.randomUUID().toString();
@Test
public void testValidSecret() throws Exception {
String secret = "secret";
String accessToken = "token";
TokenRequestContext request = new TokenRequestContext().... | class IdentityClientTests {
private static final String TENANT_ID = "contoso.com";
private static final String CLIENT_ID = UUID.randomUUID().toString();
@Test
public void testValidSecret() throws Exception {
String secret = "secret";
String accessToken = "token";
TokenRequestContext request = new TokenRequestContext().... |
yeah, ASCII covers tokens char range. This is test code. So, if any failures are ever encountered, it'd interesting to look at and we can fix it. | private void mockForMSICodeFlow(String tokenJson) throws Exception {
URL u = PowerMockito.mock(URL.class);
whenNew(URL.class).withAnyArguments().thenReturn(u);
HttpURLConnection huc = PowerMockito.mock(HttpURLConnection.class);
when(u.openConnection()).thenReturn(huc);
PowerMockito.doNothing().when(huc).setRequestMetho... | InputStream inputStream = new ByteArrayInputStream(tokenJson.getBytes(Charset.defaultCharset())); | private void mockForMSICodeFlow(String tokenJson) throws Exception {
URL u = PowerMockito.mock(URL.class);
whenNew(URL.class).withAnyArguments().thenReturn(u);
HttpURLConnection huc = PowerMockito.mock(HttpURLConnection.class);
when(u.openConnection()).thenReturn(huc);
PowerMockito.doNothing().when(huc).setRequestMetho... | class IdentityClientTests {
private static final String TENANT_ID = "contoso.com";
private static final String CLIENT_ID = UUID.randomUUID().toString();
@Test
public void testValidSecret() throws Exception {
String secret = "secret";
String accessToken = "token";
TokenRequestContext request = new TokenRequestContext().... | class IdentityClientTests {
private static final String TENANT_ID = "contoso.com";
private static final String CLIENT_ID = UUID.randomUUID().toString();
@Test
public void testValidSecret() throws Exception {
String secret = "secret";
String accessToken = "token";
TokenRequestContext request = new TokenRequestContext().... |
I don't think we need to do this. We should deprecate the HttpLogOptions one, and have it take lower precedence to the clientOptions one (so we only use it when the clientOptions one is not set). | private HttpPipeline createPipeline() {
if (pipeline != null) {
return pipeline;
}
final Configuration buildConfiguration = configuration == null
? Configuration.getGlobalConfiguration().clone()
: configuration;
final List<HttpPipelinePolicy> httpPolicies = new ArrayList<>();
final String clientName = properties.getOrD... | new IllegalStateException("applicationId should be same in httpLogOptions and clientOptions.")); | private HttpPipeline createPipeline() {
if (pipeline != null) {
return pipeline;
}
final Configuration buildConfiguration = configuration == null
? Configuration.getGlobalConfiguration().clone()
: configuration;
final List<HttpPipelinePolicy> httpPolicies = new ArrayList<>();
final String clientName = properties.getOrD... | class ServiceBusAdministrationClientBuilder {
private final ClientLogger logger = new ClientLogger(ServiceBusAdministrationClientBuilder.class);
private final ServiceBusManagementSerializer serializer = new ServiceBusManagementSerializer();
private final List<HttpPipelinePolicy> userPolicies = new ArrayList<>();
privat... | class ServiceBusAdministrationClientBuilder {
private final ClientLogger logger = new ClientLogger(ServiceBusAdministrationClientBuilder.class);
private final ServiceBusManagementSerializer serializer = new ServiceBusManagementSerializer();
private final List<HttpPipelinePolicy> userPolicies = new ArrayList<>();
privat... |
nit: I'm not a fan of multiple nested if statements because it makes things harder to read if it's not necessary. Can we bounce early? ```java if (CoreUtils.isNullorEmpty(applicationId)) { return this; } ... // other stuff. ``` | public ClientOptions setApplicationId(String applicationId) {
if (!CoreUtils.isNullOrEmpty(applicationId)) {
if (applicationId.length() > MAX_APPLICATION_ID_LENGTH) {
throw logger
.logExceptionAsError(new IllegalArgumentException("'applicationId' length cannot be greater than "
+ MAX_APPLICATION_ID_LENGTH));
} else if ... | if (!CoreUtils.isNullOrEmpty(applicationId)) { | public ClientOptions setApplicationId(String applicationId) {
if (CoreUtils.isNullOrEmpty(applicationId)) {
this.applicationId = applicationId;
return this;
}
if (applicationId.length() > MAX_APPLICATION_ID_LENGTH) {
throw logger
.logExceptionAsError(new IllegalArgumentException("'applicationId' length cannot be greate... | class ClientOptions {
private final ClientLogger logger = new ClientLogger(ClientOptions.class);
private final Map<String, Header> headers = new ConcurrentHashMap<>();
private static final int MAX_APPLICATION_ID_LENGTH = 24;
private String applicationId;
/**
* Gets the applicationId.
*
* @return The applicationId.
*/
p... | class ClientOptions {
private static final int MAX_APPLICATION_ID_LENGTH = 24;
private final ClientLogger logger = new
ClientLogger(ClientOptions.class);
private Iterable<Header> headers;
private String applicationId;
/**
* Gets the applicationId.
* @return The applicationId.
*/
public String getApplicationId() {
retur... |
If `value` is `null` does this return `name:` or `name:null`? | public String toString() {
return name + ":" + value;
} | return name + ":" + value; | public String toString() {
return name + ":" + value;
} | class Header {
private final String name;
private String value;
/**
* Create a Header instance using the provided name and value.
*
* @param name the name
* @param value the value
* @throws NullPointerException if {@code name} or {@code value} is null.
*/
public Header(String name, String value) {
Objects.requireNonNul... | class Header {
private final String name;
private String value;
/**
* Create a Header instance using the provided name and value.
*
* @param name the name of the header.
* @param value the value of the header.
* @throws NullPointerException if {@code name} is null.
*/
public Header(String name, String value) {
Objects.... |
It should show `name:null`, Same way how HttpHeader shows. | public String toString() {
return name + ":" + value;
} | return name + ":" + value; | public String toString() {
return name + ":" + value;
} | class Header {
private final String name;
private String value;
/**
* Create a Header instance using the provided name and value.
*
* @param name the name
* @param value the value
* @throws NullPointerException if {@code name} or {@code value} is null.
*/
public Header(String name, String value) {
Objects.requireNonNul... | class Header {
private final String name;
private String value;
/**
* Create a Header instance using the provided name and value.
*
* @param name the name of the header.
* @param value the value of the header.
* @throws NullPointerException if {@code name} is null.
*/
public Header(String name, String value) {
Objects.... |
Rather than return a new arraylist - just return an empty iterable, e.g. `return Collections.emptyList();` | public Iterable<Header> getHeaders() {
if (headers == null) {
headers = new ArrayList<>();
}
return headers;
} | headers = new ArrayList<>(); | public Iterable<Header> getHeaders() {
if (headers == null) {
return Collections.emptyList();
}
return headers;
} | class ClientOptions {
private static final int MAX_APPLICATION_ID_LENGTH = 24;
private final ClientLogger logger = new ClientLogger(ClientOptions.class);
private Iterable<Header> headers;
private String applicationId;
/**
* Gets the applicationId.
* @return The applicationId.
*/
public String getApplicationId() {
retur... | class ClientOptions {
private static final int MAX_APPLICATION_ID_LENGTH = 24;
private final ClientLogger logger = new
ClientLogger(ClientOptions.class);
private Iterable<Header> headers;
private String applicationId;
/**
* Gets the applicationId.
* @return The applicationId.
*/
public String getApplicationId() {
retur... |
Yeah, this creates a new instance of ArrayList each time. Instead, using Collections.emptyList() will return a static singleton list instance. | public Iterable<Header> getHeaders() {
if (headers == null) {
headers = new ArrayList<>();
}
return headers;
} | headers = new ArrayList<>(); | public Iterable<Header> getHeaders() {
if (headers == null) {
return Collections.emptyList();
}
return headers;
} | class ClientOptions {
private static final int MAX_APPLICATION_ID_LENGTH = 24;
private final ClientLogger logger = new ClientLogger(ClientOptions.class);
private Iterable<Header> headers;
private String applicationId;
/**
* Gets the applicationId.
* @return The applicationId.
*/
public String getApplicationId() {
retur... | class ClientOptions {
private static final int MAX_APPLICATION_ID_LENGTH = 24;
private final ClientLogger logger = new
ClientLogger(ClientOptions.class);
private Iterable<Header> headers;
private String applicationId;
/**
* Gets the applicationId.
* @return The applicationId.
*/
public String getApplicationId() {
retur... |
If we set negative values to these numbers, We should validate these values. | void createQueue() {
final String queueName = "some-queue";
final CreateQueueOptions expected = new CreateQueueOptions(queueName)
.setAutoDeleteOnIdle(Duration.ofSeconds(15))
.setDefaultMessageTimeToLive(Duration.ofSeconds(50))
.setDeadLetteringOnMessageExpiration(true)
.setDuplicateDetectionHistoryTimeWindow(Duration.... | .setMaxSizeInMegabytes(2048) | void createQueue() {
final String queueName = "some-queue";
final CreateQueueOptions expected = new CreateQueueOptions(queueName)
.setAutoDeleteOnIdle(Duration.ofSeconds(15))
.setDefaultMessageTimeToLive(Duration.ofSeconds(50))
.setDeadLetteringOnMessageExpiration(true)
.setDuplicateDetectionHistoryTimeWindow(Duration.... | class EntityHelperTest {
@Test
@Test
void setQueueName() {
final String newName = "I'm a new name";
final CreateQueueOptions options = new CreateQueueOptions("some name");
final QueueProperties properties = EntityHelper.createQueue(options);
EntityHelper.setQueueName(properties, newName);
assertEquals(newName, properti... | class EntityHelperTest {
@Test
@Test
void setQueueName() {
final String newName = "I'm a new name";
final CreateQueueOptions options = new CreateQueueOptions("some name");
final QueueProperties properties = EntityHelper.toModel(EntityHelper.getQueueDescription(options));
EntityHelper.setQueueName(properties, newName);
... |
I see that generally, there is no Null check, is this by design ? | public CreateQueueOptions setDuplicateDetectionHistoryTimeWindow(Duration duplicateDetectionHistoryTimeWindow) {
this.duplicateDetectionHistoryTimeWindow = duplicateDetectionHistoryTimeWindow;
return this;
} | this.duplicateDetectionHistoryTimeWindow = duplicateDetectionHistoryTimeWindow; | public CreateQueueOptions setDuplicateDetectionHistoryTimeWindow(Duration duplicateDetectionHistoryTimeWindow) {
this.duplicateDetectionHistoryTimeWindow = duplicateDetectionHistoryTimeWindow;
return this;
} | class CreateQueueOptions {
private final String name;
private Duration autoDeleteOnIdle;
private Duration defaultMessageTimeToLive;
private boolean deadLetteringOnMessageExpiration;
private Duration duplicateDetectionHistoryTimeWindow;
private boolean enableBatchedOperations;
private boolean enablePartitioning;
private... | class CreateQueueOptions {
private final String name;
private Duration autoDeleteOnIdle;
private Duration defaultMessageTimeToLive;
private boolean deadLetteringOnMessageExpiration;
private Duration duplicateDetectionHistoryTimeWindow;
private boolean enableBatchedOperations;
private boolean enablePartitioning;
private... |
Yes. I try to do as little client validation if the service can do it. No value is === "use the default service value". It's not an invalid value. | public CreateQueueOptions setDuplicateDetectionHistoryTimeWindow(Duration duplicateDetectionHistoryTimeWindow) {
this.duplicateDetectionHistoryTimeWindow = duplicateDetectionHistoryTimeWindow;
return this;
} | this.duplicateDetectionHistoryTimeWindow = duplicateDetectionHistoryTimeWindow; | public CreateQueueOptions setDuplicateDetectionHistoryTimeWindow(Duration duplicateDetectionHistoryTimeWindow) {
this.duplicateDetectionHistoryTimeWindow = duplicateDetectionHistoryTimeWindow;
return this;
} | class CreateQueueOptions {
private final String name;
private Duration autoDeleteOnIdle;
private Duration defaultMessageTimeToLive;
private boolean deadLetteringOnMessageExpiration;
private Duration duplicateDetectionHistoryTimeWindow;
private boolean enableBatchedOperations;
private boolean enablePartitioning;
private... | class CreateQueueOptions {
private final String name;
private Duration autoDeleteOnIdle;
private Duration defaultMessageTimeToLive;
private boolean deadLetteringOnMessageExpiration;
private Duration duplicateDetectionHistoryTimeWindow;
private boolean enableBatchedOperations;
private boolean enablePartitioning;
private... |
Our guidelines say to do as little validation as possible and offset it to the service. I'd expect the service to do this validation and throw. | void createQueue() {
final String queueName = "some-queue";
final CreateQueueOptions expected = new CreateQueueOptions(queueName)
.setAutoDeleteOnIdle(Duration.ofSeconds(15))
.setDefaultMessageTimeToLive(Duration.ofSeconds(50))
.setDeadLetteringOnMessageExpiration(true)
.setDuplicateDetectionHistoryTimeWindow(Duration.... | .setMaxSizeInMegabytes(2048) | void createQueue() {
final String queueName = "some-queue";
final CreateQueueOptions expected = new CreateQueueOptions(queueName)
.setAutoDeleteOnIdle(Duration.ofSeconds(15))
.setDefaultMessageTimeToLive(Duration.ofSeconds(50))
.setDeadLetteringOnMessageExpiration(true)
.setDuplicateDetectionHistoryTimeWindow(Duration.... | class EntityHelperTest {
@Test
@Test
void setQueueName() {
final String newName = "I'm a new name";
final CreateQueueOptions options = new CreateQueueOptions("some name");
final QueueProperties properties = EntityHelper.createQueue(options);
EntityHelper.setQueueName(properties, newName);
assertEquals(newName, properti... | class EntityHelperTest {
@Test
@Test
void setQueueName() {
final String newName = "I'm a new name";
final CreateQueueOptions options = new CreateQueueOptions("some name");
final QueueProperties properties = EntityHelper.toModel(EntityHelper.getQueueDescription(options));
EntityHelper.setQueueName(properties, newName);
... |
negative value check ? | public CreateSubscriptionOptions setMaxDeliveryCount(int maxDeliveryCount) {
this.maxDeliveryCount = maxDeliveryCount;
return this;
} | return this; | public CreateSubscriptionOptions setMaxDeliveryCount(int maxDeliveryCount) {
this.maxDeliveryCount = maxDeliveryCount;
return this;
} | class CreateSubscriptionOptions {
private final String topicName;
private final String subscriptionName;
private Duration lockDuration;
private boolean requiresSession;
private Duration defaultMessageTimeToLive;
private boolean deadLetteringOnMessageExpiration;
private boolean deadLetteringOnFilterEvaluationExceptions;... | class CreateSubscriptionOptions {
private final String topicName;
private final String subscriptionName;
private Duration autoDeleteOnIdle;
private Duration defaultMessageTimeToLive;
private boolean deadLetteringOnMessageExpiration;
private boolean deadLetteringOnFilterEvaluationExceptions;
private boolean enableBatche... |
Do we need to collect this into a list if we're doing anything on the output? | private void renewOwnership(Map<String, PartitionOwnership> partitionOwnershipMap) {
checkpointStore.claimOwnership(partitionPumpManager.getPartitionPumps().keySet()
.stream()
.filter(
partitionId -> partitionOwnershipMap.containsKey(partitionId) && partitionOwnershipMap.get(partitionId)
.equals(this.ownerId))
.map(par... | .collect(Collectors.toList())) | private void renewOwnership(Map<String, PartitionOwnership> partitionOwnershipMap) {
checkpointStore.claimOwnership(partitionPumpManager.getPartitionPumps().keySet()
.stream()
.filter(
partitionId -> partitionOwnershipMap.containsKey(partitionId) && partitionOwnershipMap.get(partitionId)
.getOwnerId().equals(this.owner... | class PartitionBasedLoadBalancer {
private static final Random RANDOM = new Random();
private final ClientLogger logger = new ClientLogger(PartitionBasedLoadBalancer.class);
private final String eventHubName;
private final String consumerGroupName;
private final CheckpointStore checkpointStore;
private final EventHubAs... | class PartitionBasedLoadBalancer {
private static final Random RANDOM = new Random();
private final ClientLogger logger = new ClientLogger(PartitionBasedLoadBalancer.class);
private final String eventHubName;
private final String consumerGroupName;
private final CheckpointStore checkpointStore;
private final EventHubAs... |
Is it possible to have a test for this? 🤔 | private Mono<Void> loadBalance(final Tuple2<Map<String, PartitionOwnership>, List<String>> tuple) {
return Mono.fromRunnable(() -> {
Map<String, PartitionOwnership> partitionOwnershipMap = tuple.getT1();
List<String> partitionIds = tuple.getT2();
if (CoreUtils.isNullOrEmpty(partitionIds)) {
throw logger.logExceptionAsE... | renewOwnership(partitionOwnershipMap); | private Mono<Void> loadBalance(final Tuple2<Map<String, PartitionOwnership>, List<String>> tuple) {
return Mono.fromRunnable(() -> {
Map<String, PartitionOwnership> partitionOwnershipMap = tuple.getT1();
List<String> partitionIds = tuple.getT2();
if (CoreUtils.isNullOrEmpty(partitionIds)) {
throw logger.logExceptionAsE... | class PartitionBasedLoadBalancer {
private static final Random RANDOM = new Random();
private final ClientLogger logger = new ClientLogger(PartitionBasedLoadBalancer.class);
private final String eventHubName;
private final String consumerGroupName;
private final CheckpointStore checkpointStore;
private final EventHubAs... | class PartitionBasedLoadBalancer {
private static final Random RANDOM = new Random();
private final ClientLogger logger = new ClientLogger(PartitionBasedLoadBalancer.class);
private final String eventHubName;
private final String consumerGroupName;
private final CheckpointStore checkpointStore;
private final EventHubAs... |
As I mentioned before, here we create CosmosConfig instance with database name, can we use the same instance to create different cosmos template? see [secondaryReactiveCosmosTemplate](https://github.com/Azure/azure-sdk-for-java/pull/13756/files#diff-254b2abc35cb0feeba0f6eeb236386b9R109) and [secondaryReactiveCosmosTemp... | public CosmosConfig getCosmosConfig() {
return CosmosConfig.builder()
.enableQueryMetrics(true)
.responseDiagnosticsProcessor(new ResponseDiagnosticsProcessorImplementation())
.database(secondaryProperties.getDatabase())
.build();
} | .build(); | public CosmosConfig getCosmosConfig() {
return CosmosConfig.builder()
.enableQueryMetrics(true)
.responseDiagnosticsProcessor(new ResponseDiagnosticsProcessorImplementation())
.build();
} | class PrimaryDataSourceConfiguration2 {
@Bean
public ReactiveCosmosTemplate primaryReactiveCosmosTemplate(CosmosAsyncClient cosmosAsyncClient, CosmosConfig cosmosConfig, MappingCosmosConverter mappingCosmosConverter) {
return new ReactiveCosmosTemplate(cosmosAsyncClient, "test1_2", cosmosConfig, mappingCosmosConverter,... | class PrimaryDataSourceConfiguration2 {
@Bean
public ReactiveCosmosTemplate primaryReactiveCosmosTemplate(CosmosAsyncClient cosmosAsyncClient, CosmosConfig cosmosConfig, MappingCosmosConverter mappingCosmosConverter) {
return new ReactiveCosmosTemplate(cosmosAsyncClient, "test1_2", cosmosConfig, mappingCosmosConverter,... |
Customers can still use the same `cosmosConfig` instance. Since they will anyway pass the `databaseName` to create `CosmosTemplate` - which then picks up the database from `CosmosFactory` here : From `CosmosTemplate` constructor - `this.databaseName = cosmosFactory.getDatabaseName();` | public CosmosConfig getCosmosConfig() {
return CosmosConfig.builder()
.enableQueryMetrics(true)
.responseDiagnosticsProcessor(new ResponseDiagnosticsProcessorImplementation())
.database(secondaryProperties.getDatabase())
.build();
} | .build(); | public CosmosConfig getCosmosConfig() {
return CosmosConfig.builder()
.enableQueryMetrics(true)
.responseDiagnosticsProcessor(new ResponseDiagnosticsProcessorImplementation())
.build();
} | class PrimaryDataSourceConfiguration2 {
@Bean
public ReactiveCosmosTemplate primaryReactiveCosmosTemplate(CosmosAsyncClient cosmosAsyncClient, CosmosConfig cosmosConfig, MappingCosmosConverter mappingCosmosConverter) {
return new ReactiveCosmosTemplate(cosmosAsyncClient, "test1_2", cosmosConfig, mappingCosmosConverter,... | class PrimaryDataSourceConfiguration2 {
@Bean
public ReactiveCosmosTemplate primaryReactiveCosmosTemplate(CosmosAsyncClient cosmosAsyncClient, CosmosConfig cosmosConfig, MappingCosmosConverter mappingCosmosConverter) {
return new ReactiveCosmosTemplate(cosmosAsyncClient, "test1_2", cosmosConfig, mappingCosmosConverter,... |
it's ok, but I think it's a bit confusing, actually, database2 can use the same CosmosConfig instance which created with database1. so the CosmosConfig is not really directly related to the database name. @saragluna do you have any other ideas? | public CosmosConfig getCosmosConfig() {
return CosmosConfig.builder()
.enableQueryMetrics(true)
.responseDiagnosticsProcessor(new ResponseDiagnosticsProcessorImplementation())
.database(secondaryProperties.getDatabase())
.build();
} | .build(); | public CosmosConfig getCosmosConfig() {
return CosmosConfig.builder()
.enableQueryMetrics(true)
.responseDiagnosticsProcessor(new ResponseDiagnosticsProcessorImplementation())
.build();
} | class PrimaryDataSourceConfiguration2 {
@Bean
public ReactiveCosmosTemplate primaryReactiveCosmosTemplate(CosmosAsyncClient cosmosAsyncClient, CosmosConfig cosmosConfig, MappingCosmosConverter mappingCosmosConverter) {
return new ReactiveCosmosTemplate(cosmosAsyncClient, "test1_2", cosmosConfig, mappingCosmosConverter,... | class PrimaryDataSourceConfiguration2 {
@Bean
public ReactiveCosmosTemplate primaryReactiveCosmosTemplate(CosmosAsyncClient cosmosAsyncClient, CosmosConfig cosmosConfig, MappingCosmosConverter mappingCosmosConverter) {
return new ReactiveCosmosTemplate(cosmosAsyncClient, "test1_2", cosmosConfig, mappingCosmosConverter,... |
Yes, that is true. `CosmosConfig` is not directly related to the database name. In fact, I was also wondering, if we can completely get rid of `database` from `CosmosConfig` and customers can directly override the method `getDatabaseName()` from `CosmosConfigurationSupport` class. That's what spring-data-mongodb does... | public CosmosConfig getCosmosConfig() {
return CosmosConfig.builder()
.enableQueryMetrics(true)
.responseDiagnosticsProcessor(new ResponseDiagnosticsProcessorImplementation())
.database(secondaryProperties.getDatabase())
.build();
} | .build(); | public CosmosConfig getCosmosConfig() {
return CosmosConfig.builder()
.enableQueryMetrics(true)
.responseDiagnosticsProcessor(new ResponseDiagnosticsProcessorImplementation())
.build();
} | class PrimaryDataSourceConfiguration2 {
@Bean
public ReactiveCosmosTemplate primaryReactiveCosmosTemplate(CosmosAsyncClient cosmosAsyncClient, CosmosConfig cosmosConfig, MappingCosmosConverter mappingCosmosConverter) {
return new ReactiveCosmosTemplate(cosmosAsyncClient, "test1_2", cosmosConfig, mappingCosmosConverter,... | class PrimaryDataSourceConfiguration2 {
@Bean
public ReactiveCosmosTemplate primaryReactiveCosmosTemplate(CosmosAsyncClient cosmosAsyncClient, CosmosConfig cosmosConfig, MappingCosmosConverter mappingCosmosConverter) {
return new ReactiveCosmosTemplate(cosmosAsyncClient, "test1_2", cosmosConfig, mappingCosmosConverter,... |
@kushagraThapar in my opinion, since `CosmosConfig` is not directly related to the database name so I vote for getting rid of it. Do you know in which case will the user try to get the database name? | public CosmosConfig getCosmosConfig() {
return CosmosConfig.builder()
.enableQueryMetrics(true)
.responseDiagnosticsProcessor(new ResponseDiagnosticsProcessorImplementation())
.database(secondaryProperties.getDatabase())
.build();
} | .build(); | public CosmosConfig getCosmosConfig() {
return CosmosConfig.builder()
.enableQueryMetrics(true)
.responseDiagnosticsProcessor(new ResponseDiagnosticsProcessorImplementation())
.build();
} | class PrimaryDataSourceConfiguration2 {
@Bean
public ReactiveCosmosTemplate primaryReactiveCosmosTemplate(CosmosAsyncClient cosmosAsyncClient, CosmosConfig cosmosConfig, MappingCosmosConverter mappingCosmosConverter) {
return new ReactiveCosmosTemplate(cosmosAsyncClient, "test1_2", cosmosConfig, mappingCosmosConverter,... | class PrimaryDataSourceConfiguration2 {
@Bean
public ReactiveCosmosTemplate primaryReactiveCosmosTemplate(CosmosAsyncClient cosmosAsyncClient, CosmosConfig cosmosConfig, MappingCosmosConverter mappingCosmosConverter) {
return new ReactiveCosmosTemplate(cosmosAsyncClient, "test1_2", cosmosConfig, mappingCosmosConverter,... |
@saragluna - in case of custom query execution. take a look at this example - https://github.com/kushagraThapar/azure-sdk-for-java/blob/update_cosmos_config_spring_data_cosmos/sdk/cosmos/azure-spring-data-cosmos/src/test/java/com/azure/spring/data/cosmos/repository/integration/PageableAddressRepositoryIT.java#L165 So... | public CosmosConfig getCosmosConfig() {
return CosmosConfig.builder()
.enableQueryMetrics(true)
.responseDiagnosticsProcessor(new ResponseDiagnosticsProcessorImplementation())
.database(secondaryProperties.getDatabase())
.build();
} | .build(); | public CosmosConfig getCosmosConfig() {
return CosmosConfig.builder()
.enableQueryMetrics(true)
.responseDiagnosticsProcessor(new ResponseDiagnosticsProcessorImplementation())
.build();
} | class PrimaryDataSourceConfiguration2 {
@Bean
public ReactiveCosmosTemplate primaryReactiveCosmosTemplate(CosmosAsyncClient cosmosAsyncClient, CosmosConfig cosmosConfig, MappingCosmosConverter mappingCosmosConverter) {
return new ReactiveCosmosTemplate(cosmosAsyncClient, "test1_2", cosmosConfig, mappingCosmosConverter,... | class PrimaryDataSourceConfiguration2 {
@Bean
public ReactiveCosmosTemplate primaryReactiveCosmosTemplate(CosmosAsyncClient cosmosAsyncClient, CosmosConfig cosmosConfig, MappingCosmosConverter mappingCosmosConverter) {
return new ReactiveCosmosTemplate(cosmosAsyncClient, "test1_2", cosmosConfig, mappingCosmosConverter,... |
@saragluna - I did some more testing, and I found out that in above specific case, customer can get it from `CosmosFactory`. So I am good to remove `database` from `CosmosConfig` | public CosmosConfig getCosmosConfig() {
return CosmosConfig.builder()
.enableQueryMetrics(true)
.responseDiagnosticsProcessor(new ResponseDiagnosticsProcessorImplementation())
.database(secondaryProperties.getDatabase())
.build();
} | .build(); | public CosmosConfig getCosmosConfig() {
return CosmosConfig.builder()
.enableQueryMetrics(true)
.responseDiagnosticsProcessor(new ResponseDiagnosticsProcessorImplementation())
.build();
} | class PrimaryDataSourceConfiguration2 {
@Bean
public ReactiveCosmosTemplate primaryReactiveCosmosTemplate(CosmosAsyncClient cosmosAsyncClient, CosmosConfig cosmosConfig, MappingCosmosConverter mappingCosmosConverter) {
return new ReactiveCosmosTemplate(cosmosAsyncClient, "test1_2", cosmosConfig, mappingCosmosConverter,... | class PrimaryDataSourceConfiguration2 {
@Bean
public ReactiveCosmosTemplate primaryReactiveCosmosTemplate(CosmosAsyncClient cosmosAsyncClient, CosmosConfig cosmosConfig, MappingCosmosConverter mappingCosmosConverter) {
return new ReactiveCosmosTemplate(cosmosAsyncClient, "test1_2", cosmosConfig, mappingCosmosConverter,... |
This isn't reactive to have to create a new Mono operation everytime a message come in. How about a combination of `Flux.swithOnNext(publisher).takeUntil(notCancelled)` where a new item is emitted from the `publisher` if there is a next message? And for each item emitted, delay at an interval. So if the item is emitted... | void next(ServiceBusReceivedMessageContext message) {
try {
if (timeoutBeforeNextMessageOperation != null && !timeoutBeforeNextMessageOperation.isDisposed()) {
timeoutBeforeNextMessageOperation.dispose();
}
emitter.next(message);
remaining.decrementAndGet();
timeoutBeforeNextMessageOperation = getShortTimeoutBetweenMes... | if (timeoutBeforeNextMessageOperation != null && !timeoutBeforeNextMessageOperation.isDisposed()) { | void next(ServiceBusReceivedMessageContext message) {
try {
emitter.next(message);
messageReceivedSink.next(message);
remaining.decrementAndGet();
} catch (Exception e) {
logger.warning("Exception occurred while publishing downstream.", e);
error(e);
}
} | class SynchronousReceiveWork {
private final ClientLogger logger = new ClientLogger(SynchronousReceiveWork.class);
private final long id;
private final AtomicInteger remaining;
private final int numberToReceive;
private final Duration timeout;
private final FluxSink<ServiceBusReceivedMessageContext> emitter;
private bo... | class SynchronousReceiveWork implements AutoCloseable {
/* When we have received at-least one message and next message does not arrive in this time. The work will
complete.*/
private static final Duration TIMEOUT_BETWEEN_MESSAGES = Duration.ofMillis(1000);
private final ClientLogger logger = new ClientLogger(Synchronou... |
is the null check necessary? Isn't this always set in the constructor. You can just call dispose. | public void close() {
if (nextMessageSubscriber != null && !nextMessageSubscriber.isDisposed()) {
nextMessageSubscriber.dispose();
}
} | if (nextMessageSubscriber != null && !nextMessageSubscriber.isDisposed()) { | public void close() {
if (!nextMessageSubscriber.isDisposed()) {
nextMessageSubscriber.dispose();
}
} | class SynchronousReceiveWork implements AutoCloseable {
/* When we have received at-least one message and next message does not arrive in this time. The work will
complete.*/
private static final Duration SHORT_TIMEOUT_BETWEEN_MESSAGES = Duration.ofMillis(1000);
private final ClientLogger logger = new ClientLogger(Sync... | class SynchronousReceiveWork implements AutoCloseable {
/* When we have received at-least one message and next message does not arrive in this time. The work will
complete.*/
private static final Duration TIMEOUT_BETWEEN_MESSAGES = Duration.ofMillis(1000);
private final ClientLogger logger = new ClientLogger(Synchronou... |
If you send another iteration, can we please use variable itself in logger for canUseMultipleWriteLocations , instead of true and false | private ShouldRetryResult shouldRetryOnSessionNotAvailable() {
this.sessionTokenRetryCount++;
if (!this.enableEndpointDiscovery) {
logger.warn("SessionNotAvailable: no retry due to enableEndpointDiscovery=false");
return ShouldRetryResult.noRetry();
} else {
if (this.canUseMultipleWriteLocations) {
UnmodifiableList<URL... | logger.warn("SessionNotAvailable: canUseMultipleWriteLocations = false, sessionTokenRetryCount = {}, no more retries", sessionTokenRetryCount); | private ShouldRetryResult shouldRetryOnSessionNotAvailable() {
this.sessionTokenRetryCount++;
if (!this.enableEndpointDiscovery) {
logger.warn("SessionNotAvailable: no retry due to enableEndpointDiscovery=false");
return ShouldRetryResult.noRetry();
} else {
if (this.canUseMultipleWriteLocations) {
UnmodifiableList<URL... | class ClientRetryPolicy implements IDocumentClientRetryPolicy {
private final static Logger logger = LoggerFactory.getLogger(ClientRetryPolicy.class);
final static int RetryIntervalInMS = 1000;
final static int MaxRetryCount = 120;
private final IDocumentClientRetryPolicy throttlingRetry;
private final GlobalEndpointMa... | class ClientRetryPolicy implements IDocumentClientRetryPolicy {
private final static Logger logger = LoggerFactory.getLogger(ClientRetryPolicy.class);
final static int RetryIntervalInMS = 1000;
final static int MaxRetryCount = 120;
private final IDocumentClientRetryPolicy throttlingRetry;
private final GlobalEndpointMa... |
what's the advantage? in the if branch the value is deterministic | private ShouldRetryResult shouldRetryOnSessionNotAvailable() {
this.sessionTokenRetryCount++;
if (!this.enableEndpointDiscovery) {
logger.warn("SessionNotAvailable: no retry due to enableEndpointDiscovery=false");
return ShouldRetryResult.noRetry();
} else {
if (this.canUseMultipleWriteLocations) {
UnmodifiableList<URL... | logger.warn("SessionNotAvailable: canUseMultipleWriteLocations = false, sessionTokenRetryCount = {}, no more retries", sessionTokenRetryCount); | private ShouldRetryResult shouldRetryOnSessionNotAvailable() {
this.sessionTokenRetryCount++;
if (!this.enableEndpointDiscovery) {
logger.warn("SessionNotAvailable: no retry due to enableEndpointDiscovery=false");
return ShouldRetryResult.noRetry();
} else {
if (this.canUseMultipleWriteLocations) {
UnmodifiableList<URL... | class ClientRetryPolicy implements IDocumentClientRetryPolicy {
private final static Logger logger = LoggerFactory.getLogger(ClientRetryPolicy.class);
final static int RetryIntervalInMS = 1000;
final static int MaxRetryCount = 120;
private final IDocumentClientRetryPolicy throttlingRetry;
private final GlobalEndpointMa... | class ClientRetryPolicy implements IDocumentClientRetryPolicy {
private final static Logger logger = LoggerFactory.getLogger(ClientRetryPolicy.class);
final static int RetryIntervalInMS = 1000;
final static int MaxRetryCount = 120;
private final IDocumentClientRetryPolicy throttlingRetry;
private final GlobalEndpointMa... |
Since these are specifically for Walmart, why not use DEBUG and not warn, since warning logs will be difficult to diagnose, as they are a lot. | private ShouldRetryResult shouldRetryOnSessionNotAvailable() {
this.sessionTokenRetryCount++;
if (!this.enableEndpointDiscovery) {
logger.warn("SessionNotAvailable: no retry due to enableEndpointDiscovery=false");
return ShouldRetryResult.noRetry();
} else {
if (this.canUseMultipleWriteLocations) {
UnmodifiableList<URL... | logger.warn("SessionNotAvailable: no retry due to enableEndpointDiscovery=false"); | private ShouldRetryResult shouldRetryOnSessionNotAvailable() {
this.sessionTokenRetryCount++;
if (!this.enableEndpointDiscovery) {
logger.warn("SessionNotAvailable: no retry due to enableEndpointDiscovery=false");
return ShouldRetryResult.noRetry();
} else {
if (this.canUseMultipleWriteLocations) {
UnmodifiableList<URL... | class ClientRetryPolicy implements IDocumentClientRetryPolicy {
private final static Logger logger = LoggerFactory.getLogger(ClientRetryPolicy.class);
final static int RetryIntervalInMS = 1000;
final static int MaxRetryCount = 120;
private final IDocumentClientRetryPolicy throttlingRetry;
private final GlobalEndpointMa... | class ClientRetryPolicy implements IDocumentClientRetryPolicy {
private final static Logger logger = LoggerFactory.getLogger(ClientRetryPolicy.class);
final static int RetryIntervalInMS = 1000;
final static int MaxRetryCount = 120;
private final IDocumentClientRetryPolicy throttlingRetry;
private final GlobalEndpointMa... |
Same here. | private ShouldRetryResult shouldRetryOnSessionNotAvailable() {
this.sessionTokenRetryCount++;
if (!this.enableEndpointDiscovery) {
logger.warn("SessionNotAvailable: no retry due to enableEndpointDiscovery=false");
return ShouldRetryResult.noRetry();
} else {
if (this.canUseMultipleWriteLocations) {
UnmodifiableList<URL... | logger.warn("SessionNotAvailable: canUseMultipleWriteLocations = true, sessionTokenRetryCount = {}, retried all locations. retry exhausted!", sessionTokenRetryCount); | private ShouldRetryResult shouldRetryOnSessionNotAvailable() {
this.sessionTokenRetryCount++;
if (!this.enableEndpointDiscovery) {
logger.warn("SessionNotAvailable: no retry due to enableEndpointDiscovery=false");
return ShouldRetryResult.noRetry();
} else {
if (this.canUseMultipleWriteLocations) {
UnmodifiableList<URL... | class ClientRetryPolicy implements IDocumentClientRetryPolicy {
private final static Logger logger = LoggerFactory.getLogger(ClientRetryPolicy.class);
final static int RetryIntervalInMS = 1000;
final static int MaxRetryCount = 120;
private final IDocumentClientRetryPolicy throttlingRetry;
private final GlobalEndpointMa... | class ClientRetryPolicy implements IDocumentClientRetryPolicy {
private final static Logger logger = LoggerFactory.getLogger(ClientRetryPolicy.class);
final static int RetryIntervalInMS = 1000;
final static int MaxRetryCount = 120;
private final IDocumentClientRetryPolicy throttlingRetry;
private final GlobalEndpointMa... |
Good point @simplynaveen20 | private ShouldRetryResult shouldRetryOnSessionNotAvailable() {
this.sessionTokenRetryCount++;
if (!this.enableEndpointDiscovery) {
logger.warn("SessionNotAvailable: no retry due to enableEndpointDiscovery=false");
return ShouldRetryResult.noRetry();
} else {
if (this.canUseMultipleWriteLocations) {
UnmodifiableList<URL... | logger.warn("SessionNotAvailable: canUseMultipleWriteLocations = false, sessionTokenRetryCount = {}, no more retries", sessionTokenRetryCount); | private ShouldRetryResult shouldRetryOnSessionNotAvailable() {
this.sessionTokenRetryCount++;
if (!this.enableEndpointDiscovery) {
logger.warn("SessionNotAvailable: no retry due to enableEndpointDiscovery=false");
return ShouldRetryResult.noRetry();
} else {
if (this.canUseMultipleWriteLocations) {
UnmodifiableList<URL... | class ClientRetryPolicy implements IDocumentClientRetryPolicy {
private final static Logger logger = LoggerFactory.getLogger(ClientRetryPolicy.class);
final static int RetryIntervalInMS = 1000;
final static int MaxRetryCount = 120;
private final IDocumentClientRetryPolicy throttlingRetry;
private final GlobalEndpointMa... | class ClientRetryPolicy implements IDocumentClientRetryPolicy {
private final static Logger logger = LoggerFactory.getLogger(ClientRetryPolicy.class);
final static int RetryIntervalInMS = 1000;
final static int MaxRetryCount = 120;
private final IDocumentClientRetryPolicy throttlingRetry;
private final GlobalEndpointMa... |
Same here - let's use the variable | private ShouldRetryResult shouldRetryOnSessionNotAvailable() {
this.sessionTokenRetryCount++;
if (!this.enableEndpointDiscovery) {
logger.warn("SessionNotAvailable: no retry due to enableEndpointDiscovery=false");
return ShouldRetryResult.noRetry();
} else {
if (this.canUseMultipleWriteLocations) {
UnmodifiableList<URL... | logger.info("SessionNotAvailable: canUseMultipleWriteLocations = false, sessionTokenRetryCount = {}, going to retry", sessionTokenRetryCount); | private ShouldRetryResult shouldRetryOnSessionNotAvailable() {
this.sessionTokenRetryCount++;
if (!this.enableEndpointDiscovery) {
logger.warn("SessionNotAvailable: no retry due to enableEndpointDiscovery=false");
return ShouldRetryResult.noRetry();
} else {
if (this.canUseMultipleWriteLocations) {
UnmodifiableList<URL... | class ClientRetryPolicy implements IDocumentClientRetryPolicy {
private final static Logger logger = LoggerFactory.getLogger(ClientRetryPolicy.class);
final static int RetryIntervalInMS = 1000;
final static int MaxRetryCount = 120;
private final IDocumentClientRetryPolicy throttlingRetry;
private final GlobalEndpointMa... | class ClientRetryPolicy implements IDocumentClientRetryPolicy {
private final static Logger logger = LoggerFactory.getLogger(ClientRetryPolicy.class);
final static int RetryIntervalInMS = 1000;
final static int MaxRetryCount = 120;
private final IDocumentClientRetryPolicy throttlingRetry;
private final GlobalEndpointMa... |
DEBUG is not feasible. | private ShouldRetryResult shouldRetryOnSessionNotAvailable() {
this.sessionTokenRetryCount++;
if (!this.enableEndpointDiscovery) {
logger.warn("SessionNotAvailable: no retry due to enableEndpointDiscovery=false");
return ShouldRetryResult.noRetry();
} else {
if (this.canUseMultipleWriteLocations) {
UnmodifiableList<URL... | logger.warn("SessionNotAvailable: no retry due to enableEndpointDiscovery=false"); | private ShouldRetryResult shouldRetryOnSessionNotAvailable() {
this.sessionTokenRetryCount++;
if (!this.enableEndpointDiscovery) {
logger.warn("SessionNotAvailable: no retry due to enableEndpointDiscovery=false");
return ShouldRetryResult.noRetry();
} else {
if (this.canUseMultipleWriteLocations) {
UnmodifiableList<URL... | class ClientRetryPolicy implements IDocumentClientRetryPolicy {
private final static Logger logger = LoggerFactory.getLogger(ClientRetryPolicy.class);
final static int RetryIntervalInMS = 1000;
final static int MaxRetryCount = 120;
private final IDocumentClientRetryPolicy throttlingRetry;
private final GlobalEndpointMa... | class ClientRetryPolicy implements IDocumentClientRetryPolicy {
private final static Logger logger = LoggerFactory.getLogger(ClientRetryPolicy.class);
final static int RetryIntervalInMS = 1000;
final static int MaxRetryCount = 120;
private final IDocumentClientRetryPolicy throttlingRetry;
private final GlobalEndpointMa... |
DEBUG is not feasible. | private ShouldRetryResult shouldRetryOnSessionNotAvailable() {
this.sessionTokenRetryCount++;
if (!this.enableEndpointDiscovery) {
logger.warn("SessionNotAvailable: no retry due to enableEndpointDiscovery=false");
return ShouldRetryResult.noRetry();
} else {
if (this.canUseMultipleWriteLocations) {
UnmodifiableList<URL... | logger.warn("SessionNotAvailable: canUseMultipleWriteLocations = true, sessionTokenRetryCount = {}, retried all locations. retry exhausted!", sessionTokenRetryCount); | private ShouldRetryResult shouldRetryOnSessionNotAvailable() {
this.sessionTokenRetryCount++;
if (!this.enableEndpointDiscovery) {
logger.warn("SessionNotAvailable: no retry due to enableEndpointDiscovery=false");
return ShouldRetryResult.noRetry();
} else {
if (this.canUseMultipleWriteLocations) {
UnmodifiableList<URL... | class ClientRetryPolicy implements IDocumentClientRetryPolicy {
private final static Logger logger = LoggerFactory.getLogger(ClientRetryPolicy.class);
final static int RetryIntervalInMS = 1000;
final static int MaxRetryCount = 120;
private final IDocumentClientRetryPolicy throttlingRetry;
private final GlobalEndpointMa... | class ClientRetryPolicy implements IDocumentClientRetryPolicy {
private final static Logger logger = LoggerFactory.getLogger(ClientRetryPolicy.class);
final static int RetryIntervalInMS = 1000;
final static int MaxRetryCount = 120;
private final IDocumentClientRetryPolicy throttlingRetry;
private final GlobalEndpointMa... |
intellj gives a recommendation in general to use ```java if (flag) { func(true) } ``` instead of ```java if (flag) { func(flag) } ``` that's why I am not using a variable here. | private ShouldRetryResult shouldRetryOnSessionNotAvailable() {
this.sessionTokenRetryCount++;
if (!this.enableEndpointDiscovery) {
logger.warn("SessionNotAvailable: no retry due to enableEndpointDiscovery=false");
return ShouldRetryResult.noRetry();
} else {
if (this.canUseMultipleWriteLocations) {
UnmodifiableList<URL... | logger.warn("SessionNotAvailable: canUseMultipleWriteLocations = false, sessionTokenRetryCount = {}, no more retries", sessionTokenRetryCount); | private ShouldRetryResult shouldRetryOnSessionNotAvailable() {
this.sessionTokenRetryCount++;
if (!this.enableEndpointDiscovery) {
logger.warn("SessionNotAvailable: no retry due to enableEndpointDiscovery=false");
return ShouldRetryResult.noRetry();
} else {
if (this.canUseMultipleWriteLocations) {
UnmodifiableList<URL... | class ClientRetryPolicy implements IDocumentClientRetryPolicy {
private final static Logger logger = LoggerFactory.getLogger(ClientRetryPolicy.class);
final static int RetryIntervalInMS = 1000;
final static int MaxRetryCount = 120;
private final IDocumentClientRetryPolicy throttlingRetry;
private final GlobalEndpointMa... | class ClientRetryPolicy implements IDocumentClientRetryPolicy {
private final static Logger logger = LoggerFactory.getLogger(ClientRetryPolicy.class);
final static int RetryIntervalInMS = 1000;
final static int MaxRetryCount = 120;
private final IDocumentClientRetryPolicy throttlingRetry;
private final GlobalEndpointMa... |
We only use record policy in RECORD mode. Should exclude LIVE test mode here as well. Same as below | HttpPipeline getHttpPipeline(HttpClient httpClient, CryptographyServiceVersion serviceVersion) {
TokenCredential credential = null;
if (!interceptorManager.isPlaybackMode()) {
String clientId = System.getenv("ARM_CLIENTID");
String clientKey = System.getenv("ARM_CLIENTKEY");
String tenantId = System.getenv("AZURE_TENAN... | if (!interceptorManager.isPlaybackMode()) { | HttpPipeline getHttpPipeline(HttpClient httpClient, CryptographyServiceVersion serviceVersion) {
TokenCredential credential = null;
if (!interceptorManager.isPlaybackMode()) {
String clientId = System.getenv("ARM_CLIENTID");
String clientKey = System.getenv("ARM_CLIENTKEY");
String tenantId = System.getenv("AZURE_TENAN... | class KeyEncryptionKeyClientTestBase extends TestBase {
private static final String SDK_NAME = "client_name";
private static final String SDK_VERSION = "client_version";
@Override
protected String getTestName() {
return "";
}
void beforeTestSetup() {
}
@Test
public abstract void wrapUnwrapSymmetricAK128(HttpClient http... | class KeyEncryptionKeyClientTestBase extends TestBase {
private static final String SDK_NAME = "client_name";
private static final String SDK_VERSION = "client_version";
@Override
protected String getTestName() {
return "";
}
void beforeTestSetup() {
}
@Test
public abstract void wrapUnwrapSymmetricAK128(HttpClient http... |
@sima-zhu We probably should modify the other `TestBase` classes in our repository if that's the case. They currently use a record policy when **not** in playback mode. | HttpPipeline getHttpPipeline(HttpClient httpClient, CryptographyServiceVersion serviceVersion) {
TokenCredential credential = null;
if (!interceptorManager.isPlaybackMode()) {
String clientId = System.getenv("ARM_CLIENTID");
String clientKey = System.getenv("ARM_CLIENTKEY");
String tenantId = System.getenv("AZURE_TENAN... | if (!interceptorManager.isPlaybackMode()) { | HttpPipeline getHttpPipeline(HttpClient httpClient, CryptographyServiceVersion serviceVersion) {
TokenCredential credential = null;
if (!interceptorManager.isPlaybackMode()) {
String clientId = System.getenv("ARM_CLIENTID");
String clientKey = System.getenv("ARM_CLIENTKEY");
String tenantId = System.getenv("AZURE_TENAN... | class KeyEncryptionKeyClientTestBase extends TestBase {
private static final String SDK_NAME = "client_name";
private static final String SDK_VERSION = "client_version";
@Override
protected String getTestName() {
return "";
}
void beforeTestSetup() {
}
@Test
public abstract void wrapUnwrapSymmetricAK128(HttpClient http... | class KeyEncryptionKeyClientTestBase extends TestBase {
private static final String SDK_NAME = "client_name";
private static final String SDK_VERSION = "client_version";
@Override
protected String getTestName() {
return "";
}
void beforeTestSetup() {
}
@Test
public abstract void wrapUnwrapSymmetricAK128(HttpClient http... |
Could you point out the place mentioned use RecordPolicy when not playback. We introduce LIVE mode slightly later than the other modes, so it might not up-to-date. | HttpPipeline getHttpPipeline(HttpClient httpClient, CryptographyServiceVersion serviceVersion) {
TokenCredential credential = null;
if (!interceptorManager.isPlaybackMode()) {
String clientId = System.getenv("ARM_CLIENTID");
String clientKey = System.getenv("ARM_CLIENTKEY");
String tenantId = System.getenv("AZURE_TENAN... | if (!interceptorManager.isPlaybackMode()) { | HttpPipeline getHttpPipeline(HttpClient httpClient, CryptographyServiceVersion serviceVersion) {
TokenCredential credential = null;
if (!interceptorManager.isPlaybackMode()) {
String clientId = System.getenv("ARM_CLIENTID");
String clientKey = System.getenv("ARM_CLIENTKEY");
String tenantId = System.getenv("AZURE_TENAN... | class KeyEncryptionKeyClientTestBase extends TestBase {
private static final String SDK_NAME = "client_name";
private static final String SDK_VERSION = "client_version";
@Override
protected String getTestName() {
return "";
}
void beforeTestSetup() {
}
@Test
public abstract void wrapUnwrapSymmetricAK128(HttpClient http... | class KeyEncryptionKeyClientTestBase extends TestBase {
private static final String SDK_NAME = "client_name";
private static final String SDK_VERSION = "client_version";
@Override
protected String getTestName() {
return "";
}
void beforeTestSetup() {
}
@Test
public abstract void wrapUnwrapSymmetricAK128(HttpClient http... |
Besides the two classes included in this PR, in KeyVault you can find this in the following classes: - [CertificateClientTestBase](https://github.com/Azure/azure-sdk-for-java/blob/2e2b719ddd9106c0b4a7c046a5ac8513612ff0b1/sdk/keyvault/azure-security-keyvault-certificates/src/test/java/com/azure/security/keyvault/certifi... | HttpPipeline getHttpPipeline(HttpClient httpClient, CryptographyServiceVersion serviceVersion) {
TokenCredential credential = null;
if (!interceptorManager.isPlaybackMode()) {
String clientId = System.getenv("ARM_CLIENTID");
String clientKey = System.getenv("ARM_CLIENTKEY");
String tenantId = System.getenv("AZURE_TENAN... | if (!interceptorManager.isPlaybackMode()) { | HttpPipeline getHttpPipeline(HttpClient httpClient, CryptographyServiceVersion serviceVersion) {
TokenCredential credential = null;
if (!interceptorManager.isPlaybackMode()) {
String clientId = System.getenv("ARM_CLIENTID");
String clientKey = System.getenv("ARM_CLIENTKEY");
String tenantId = System.getenv("AZURE_TENAN... | class KeyEncryptionKeyClientTestBase extends TestBase {
private static final String SDK_NAME = "client_name";
private static final String SDK_VERSION = "client_version";
@Override
protected String getTestName() {
return "";
}
void beforeTestSetup() {
}
@Test
public abstract void wrapUnwrapSymmetricAK128(HttpClient http... | class KeyEncryptionKeyClientTestBase extends TestBase {
private static final String SDK_NAME = "client_name";
private static final String SDK_VERSION = "client_version";
@Override
protected String getTestName() {
return "";
}
void beforeTestSetup() {
}
@Test
public abstract void wrapUnwrapSymmetricAK128(HttpClient http... |
Add some tests where the property name also contains `get` and `set`. | public void testPropertyNameOnMethodNameWithoutGetSet() throws NoSuchMethodException {
class LocalHotel {
String hotelName;
public String hotelName1() {
return hotelName;
}
public void hotelName2(String hotelName) {
this.hotelName = hotelName;
}
}
Method getterM = LocalHotel.class.getDeclaredMethod("hotelName1");
asser... | Method getterM = LocalHotel.class.getDeclaredMethod("hotelName1"); | public void testPropertyNameOnMethodNameWithoutGetSet() throws NoSuchMethodException {
class LocalHotel {
String hotelName;
public String hotelName1() {
return hotelName;
}
public void hotelName2(String hotelName) {
this.hotelName = hotelName;
}
}
Method getterM = LocalHotel.class.getDeclaredMethod("hotelName1");
asser... | class LocalHotel {
String hotelName;
public String getHotelName() {
return hotelName;
}
public void setHotelName(String hotelName) {
this.hotelName = hotelName;
}
} | class LocalHotel {
String hotelName;
boolean flag;
public String getHotelName() {
return hotelName;
}
public void setHotelName(String hotelName) {
this.hotelName = hotelName;
}
public boolean isFlag() {
return flag;
}
public void setFlag(boolean flag) {
this.flag = flag;
}
} |
More test coverage now | public void testPropertyNameOnMethodNameWithoutGetSet() throws NoSuchMethodException {
class LocalHotel {
String hotelName;
public String hotelName1() {
return hotelName;
}
public void hotelName2(String hotelName) {
this.hotelName = hotelName;
}
}
Method getterM = LocalHotel.class.getDeclaredMethod("hotelName1");
asser... | Method getterM = LocalHotel.class.getDeclaredMethod("hotelName1"); | public void testPropertyNameOnMethodNameWithoutGetSet() throws NoSuchMethodException {
class LocalHotel {
String hotelName;
public String hotelName1() {
return hotelName;
}
public void hotelName2(String hotelName) {
this.hotelName = hotelName;
}
}
Method getterM = LocalHotel.class.getDeclaredMethod("hotelName1");
asser... | class LocalHotel {
String hotelName;
public String getHotelName() {
return hotelName;
}
public void setHotelName(String hotelName) {
this.hotelName = hotelName;
}
} | class LocalHotel {
String hotelName;
boolean flag;
public String getHotelName() {
return hotelName;
}
public void setHotelName(String hotelName) {
this.hotelName = hotelName;
}
public boolean isFlag() {
return flag;
}
public void setFlag(boolean flag) {
this.flag = flag;
}
} |
is this just cleanup? or what is the motivation for these changes | static DetectLanguageResultCollection getExpectedBatchDetectedLanguages() {
final TextDocumentBatchStatistics textDocumentBatchStatistics = new TextDocumentBatchStatistics(3, 3, 0, 3);
final List<DetectLanguageResult> detectLanguageResultList = Arrays.asList(
new DetectLanguageResult("0", new TextDocumentStatistics(26,... | final TextDocumentBatchStatistics textDocumentBatchStatistics = new TextDocumentBatchStatistics(3, 3, 0, 3); | static DetectLanguageResultCollection getExpectedBatchDetectedLanguages() {
final TextDocumentBatchStatistics textDocumentBatchStatistics = new TextDocumentBatchStatistics(3, 3, 0, 3);
final List<DetectLanguageResult> detectLanguageResultList = Arrays.asList(
new DetectLanguageResult("0", new TextDocumentStatistics(26,... | 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";
stati... | 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";
stati... |
To add getDetectedLanguageEnglish(), getDetectedLanguageSpanish(), and getUnknownDetectedLanguage() helper methods. These result repeatedly used over many place, such as atomic operation. | static DetectLanguageResultCollection getExpectedBatchDetectedLanguages() {
final TextDocumentBatchStatistics textDocumentBatchStatistics = new TextDocumentBatchStatistics(3, 3, 0, 3);
final List<DetectLanguageResult> detectLanguageResultList = Arrays.asList(
new DetectLanguageResult("0", new TextDocumentStatistics(26,... | final TextDocumentBatchStatistics textDocumentBatchStatistics = new TextDocumentBatchStatistics(3, 3, 0, 3); | static DetectLanguageResultCollection getExpectedBatchDetectedLanguages() {
final TextDocumentBatchStatistics textDocumentBatchStatistics = new TextDocumentBatchStatistics(3, 3, 0, 3);
final List<DetectLanguageResult> detectLanguageResultList = Arrays.asList(
new DetectLanguageResult("0", new TextDocumentStatistics(26,... | 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";
stati... | 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";
stati... |
Instead of using blocking calls, since now we are going asynchronous, please try using `StepVerifier` from reactor-test. Its actually built in for testing async APIs. We have used it in azure-spring-data-cosmos-test and also in azure-cosmos. Please take a look at `VeryLargeDocumentQueryTest.java` and any reactive tes... | public void asyncCreateItemEncrypt_readItemDecrypt() throws Exception {
EncryptionItemRequestOptions requestOptions = new EncryptionItemRequestOptions();
EncryptionOptions encryptionOptions = new EncryptionOptions();
encryptionOptions.setPathsToEncrypt(ImmutableList.of("/Sensitive"));
encryptionOptions.setDataEncryptio... | TestDoc properties = getItem(UUID.randomUUID().toString()); | public void asyncCreateItemEncrypt_readItemDecrypt() throws Exception {
EncryptionItemRequestOptions requestOptions = new EncryptionItemRequestOptions();
EncryptionOptions encryptionOptions = new EncryptionOptions();
encryptionOptions.setPathsToEncrypt(ImmutableList.of("/Sensitive"));
encryptionOptions.setDataEncryptio... | class TestDoc {
public static List<String> PathsToEncrypt = ImmutableList.of("/Sensitive");
public static List<String> AllPath = ImmutableList.of("/Sensitive", "/id", "/PK", "/NonSensitive");
@JsonProperty("id")
public String id;
@JsonProperty("PK")
public String pk;
@JsonProperty("NonSensitive")
public String nonSensi... | class TestDoc {
public static List<String> PathsToEncrypt = ImmutableList.of("/Sensitive");
public static List<String> AllPath = ImmutableList.of("/Sensitive", "/id", "/PK", "/NonSensitive");
@JsonProperty("id")
public String id;
@JsonProperty("PK")
public String pk;
@JsonProperty("NonSensitive")
public String nonSensi... |
good suggestion. Moved to `StepVerifier` for test validation. | public void asyncCreateItemEncrypt_readItemDecrypt() throws Exception {
EncryptionItemRequestOptions requestOptions = new EncryptionItemRequestOptions();
EncryptionOptions encryptionOptions = new EncryptionOptions();
encryptionOptions.setPathsToEncrypt(ImmutableList.of("/Sensitive"));
encryptionOptions.setDataEncryptio... | TestDoc properties = getItem(UUID.randomUUID().toString()); | public void asyncCreateItemEncrypt_readItemDecrypt() throws Exception {
EncryptionItemRequestOptions requestOptions = new EncryptionItemRequestOptions();
EncryptionOptions encryptionOptions = new EncryptionOptions();
encryptionOptions.setPathsToEncrypt(ImmutableList.of("/Sensitive"));
encryptionOptions.setDataEncryptio... | class TestDoc {
public static List<String> PathsToEncrypt = ImmutableList.of("/Sensitive");
public static List<String> AllPath = ImmutableList.of("/Sensitive", "/id", "/PK", "/NonSensitive");
@JsonProperty("id")
public String id;
@JsonProperty("PK")
public String pk;
@JsonProperty("NonSensitive")
public String nonSensi... | class TestDoc {
public static List<String> PathsToEncrypt = ImmutableList.of("/Sensitive");
public static List<String> AllPath = ImmutableList.of("/Sensitive", "/id", "/PK", "/NonSensitive");
@JsonProperty("id")
public String id;
@JsonProperty("PK")
public String pk;
@JsonProperty("NonSensitive")
public String nonSensi... |
ditto, for the`SPACE`, the only constant we should use here is the `HttpConstants.Versions.SDK_VERSION` | private String getUserAgentFixedPart() {
String osName = System.getProperty("os.name");
if (osName == null) {
osName = "Unknown";
}
osName = osName.replaceAll("\\s", "");
String geteUserAgentFixedPart =
UserAgentContainer.AZSDK_USERAGENT_PREFIX +
"cosmos" +
"/" +
HttpConstants.Versions.SDK_VERSION +
SPACE +
osName +
"/... | SPACE + | private String getUserAgentFixedPart() {
String osName = System.getProperty("os.name");
if (osName == null) {
osName = "Unknown";
}
osName = osName.replaceAll("\\s", "");
String geteUserAgentFixedPart = "azsdk-java-" +
"cosmos" +
"/" +
HttpConstants.Versions.SDK_VERSION +
SPACE +
osName +
"/" +
System.getProperty("os.v... | class UserAgentContainerTest {
private final static String SPACE = " ";
private final static int TIMEOUT = 40000;
@Test(groups = {"unit"})
public void userAgentContainerSetSuffix() {
String expectedStringFixedPart = getUserAgentFixedPart();
String userProvidedSuffix = "test-application-id";
UserAgentContainer userAgent... | class UserAgentContainerTest {
private final static String SPACE = " ";
private final static int TIMEOUT = 40000;
@Test(groups = {"unit"})
public void userAgentContainerSetSuffix() {
String expectedStringFixedPart = getUserAgentFixedPart();
String userProvidedSuffix = "test-application-id";
UserAgentContainer userAgent... |
Why can't we change the name directly in hotel json file but to modify here after serialization? There are two other test classes which have the similar structure, SuggestSyncTests and SearchSyncTest. | public static void setupClass() {
TestBase.setupClass();
if (TEST_MODE == TestMode.PLAYBACK) {
return;
}
Reader indexData = new InputStreamReader(Objects.requireNonNull(AutocompleteSyncTests.class
.getClassLoader()
.getResourceAsStream(HOTELS_TESTS_INDEX_DATA_JSON)));
try {
SearchIndex index = new ObjectMapper().readVa... | searchIndexName.set(index, INDEX_NAME); | public static void setupClass() {
TestBase.setupClass();
if (TEST_MODE == TestMode.PLAYBACK) {
return;
}
searchIndexClient = setupSharedIndex(INDEX_NAME);
} | class AutocompleteSyncTests extends SearchTestBase {
private static final String HOTELS_DATA_JSON = "HotelsDataArray.json";
private static final String INDEX_NAME = "azsearch-autocomplete-shared-instance";
private static SearchIndexClient searchIndexClient;
private SearchClient client;
@BeforeAll
@Override
protected vo... | class AutocompleteSyncTests extends SearchTestBase {
private static final String HOTELS_DATA_JSON = "HotelsDataArray.json";
private static final String INDEX_NAME = "azsearch-autocomplete-shared-instance";
private static SearchIndexClient searchIndexClient;
private SearchClient client;
@BeforeAll
@Override
protected vo... |
Updated Search and Suggest test which are able to share an instance. The name is changed using reflection as many tests use this file so it won't be safe to make it a global name. | public static void setupClass() {
TestBase.setupClass();
if (TEST_MODE == TestMode.PLAYBACK) {
return;
}
Reader indexData = new InputStreamReader(Objects.requireNonNull(AutocompleteSyncTests.class
.getClassLoader()
.getResourceAsStream(HOTELS_TESTS_INDEX_DATA_JSON)));
try {
SearchIndex index = new ObjectMapper().readVa... | searchIndexName.set(index, INDEX_NAME); | public static void setupClass() {
TestBase.setupClass();
if (TEST_MODE == TestMode.PLAYBACK) {
return;
}
searchIndexClient = setupSharedIndex(INDEX_NAME);
} | class AutocompleteSyncTests extends SearchTestBase {
private static final String HOTELS_DATA_JSON = "HotelsDataArray.json";
private static final String INDEX_NAME = "azsearch-autocomplete-shared-instance";
private static SearchIndexClient searchIndexClient;
private SearchClient client;
@BeforeAll
@Override
protected vo... | class AutocompleteSyncTests extends SearchTestBase {
private static final String HOTELS_DATA_JSON = "HotelsDataArray.json";
private static final String INDEX_NAME = "azsearch-autocomplete-shared-instance";
private static SearchIndexClient searchIndexClient;
private SearchClient client;
@BeforeAll
@Override
protected vo... |
I would keep the original testing scenarios commented too. | static void validatePrimaryLanguage(DetectedLanguage expectedLanguage, DetectedLanguage actualLanguage) {
assertNotNull(actualLanguage.getIso6391Name());
assertNotNull(actualLanguage.getName());
assertNotNull(actualLanguage.getConfidenceScore());
} | static void validatePrimaryLanguage(DetectedLanguage expectedLanguage, DetectedLanguage actualLanguage) {
assertNotNull(actualLanguage.getIso6391Name());
assertNotNull(actualLanguage.getName());
assertNotNull(actualLanguage.getConfidenceScore());
} | class TextAnalyticsClientTestBase extends TestBase {
static final String BATCH_ERROR_EXCEPTION_MESSAGE = "Error in accessing the property on document id: 2, when RecognizeEntitiesResult returned with an error: Document text is empty. ErrorCodeValue: {invalidDocument}";
static final String EXCEEDED_ALLOWED_DOCUMENTS_LIM... | class TextAnalyticsClientTestBase extends TestBase {
static final String BATCH_ERROR_EXCEPTION_MESSAGE = "Error in accessing the property on document id: 2, when RecognizeEntitiesResult returned with an error: Document text is empty. ErrorCodeValue: {invalidDocument}";
static final String EXCEEDED_ALLOWED_DOCUMENTS_LIM... | |
please also replace `UserAgentContainer.AZSDK_USERAGENT_PREFIX` with hard coded value for the test | private String getUserAgentFixedPart() {
String osName = System.getProperty("os.name");
if (osName == null) {
osName = "Unknown";
}
osName = osName.replaceAll("\\s", "");
String geteUserAgentFixedPart =
UserAgentContainer.AZSDK_USERAGENT_PREFIX +
"cosmos" +
"/" +
HttpConstants.Versions.SDK_VERSION +
SPACE +
osName +
"/... | UserAgentContainer.AZSDK_USERAGENT_PREFIX + | private String getUserAgentFixedPart() {
String osName = System.getProperty("os.name");
if (osName == null) {
osName = "Unknown";
}
osName = osName.replaceAll("\\s", "");
String geteUserAgentFixedPart = "azsdk-java-" +
"cosmos" +
"/" +
HttpConstants.Versions.SDK_VERSION +
SPACE +
osName +
"/" +
System.getProperty("os.v... | class UserAgentContainerTest {
private final static String SPACE = " ";
private final static int TIMEOUT = 40000;
@Test(groups = {"unit"})
public void userAgentContainerSetSuffix() {
String expectedStringFixedPart = getUserAgentFixedPart();
String userProvidedSuffix = "test-application-id";
UserAgentContainer userAgent... | class UserAgentContainerTest {
private final static String SPACE = " ";
private final static int TIMEOUT = 40000;
@Test(groups = {"unit"})
public void userAgentContainerSetSuffix() {
String expectedStringFixedPart = getUserAgentFixedPart();
String userProvidedSuffix = "test-application-id";
UserAgentContainer userAgent... |
btw, this class, has a test named `UserAgentIntegrationTest()` (from prior useragent PR), please change that to `userAgentIntegration()` to follow test name code style. | private String getUserAgentFixedPart() {
String osName = System.getProperty("os.name");
if (osName == null) {
osName = "Unknown";
}
osName = osName.replaceAll("\\s", "");
String geteUserAgentFixedPart =
UserAgentContainer.AZSDK_USERAGENT_PREFIX +
"cosmos" +
"/" +
HttpConstants.Versions.SDK_VERSION +
SPACE +
osName +
"/... | osName = osName.replaceAll("\\s", ""); | private String getUserAgentFixedPart() {
String osName = System.getProperty("os.name");
if (osName == null) {
osName = "Unknown";
}
osName = osName.replaceAll("\\s", "");
String geteUserAgentFixedPart = "azsdk-java-" +
"cosmos" +
"/" +
HttpConstants.Versions.SDK_VERSION +
SPACE +
osName +
"/" +
System.getProperty("os.v... | class UserAgentContainerTest {
private final static String SPACE = " ";
private final static int TIMEOUT = 40000;
@Test(groups = {"unit"})
public void userAgentContainerSetSuffix() {
String expectedStringFixedPart = getUserAgentFixedPart();
String userProvidedSuffix = "test-application-id";
UserAgentContainer userAgent... | class UserAgentContainerTest {
private final static String SPACE = " ";
private final static int TIMEOUT = 40000;
@Test(groups = {"unit"})
public void userAgentContainerSetSuffix() {
String expectedStringFixedPart = getUserAgentFixedPart();
String userProvidedSuffix = "test-application-id";
UserAgentContainer userAgent... |
isZero() | isNegative() ? | private Disposable getRenewLockOperation(Instant initialLockedUntil, Duration maxLockRenewalDuration) {
if (maxLockRenewalDuration.isZero()) {
status.set(LockRenewalStatus.COMPLETE);
return Disposables.single();
}
final Instant now = Instant.now();
Duration initialInterval = Duration.between(now, initialLockedUntil);
i... | if (maxLockRenewalDuration.isZero()) { | private Disposable getRenewLockOperation(Instant initialLockedUntil, Duration maxLockRenewalDuration) {
if (maxLockRenewalDuration.isZero()) {
status.set(LockRenewalStatus.COMPLETE);
return Disposables.single();
}
final Instant now = Instant.now();
Duration initialInterval = Duration.between(now, initialLockedUntil);
i... | class LockRenewalOperation implements AutoCloseable {
private final ClientLogger logger = new ClientLogger(LockRenewalOperation.class);
private final AtomicBoolean isDisposed = new AtomicBoolean();
private final AtomicReference<Instant> lockedUntil = new AtomicReference<>();
private final AtomicReference<Throwable> thr... | class LockRenewalOperation implements AutoCloseable {
private final ClientLogger logger = new ClientLogger(LockRenewalOperation.class);
private final AtomicBoolean isDisposed = new AtomicBoolean();
private final AtomicReference<Instant> lockedUntil = new AtomicReference<>();
private final AtomicReference<Throwable> thr... |
is this messaging correct ?, the lockToken can be for Message Lock or session id. | private Disposable getRenewLockOperation(Instant initialLockedUntil, Duration maxLockRenewalDuration) {
if (maxLockRenewalDuration.isZero()) {
status.set(LockRenewalStatus.COMPLETE);
return Disposables.single();
}
final Instant now = Instant.now();
Duration initialInterval = Duration.between(now, initialLockedUntil);
i... | return Mono.error(new IllegalStateException("Cannot renew session lock without session id.")); | private Disposable getRenewLockOperation(Instant initialLockedUntil, Duration maxLockRenewalDuration) {
if (maxLockRenewalDuration.isZero()) {
status.set(LockRenewalStatus.COMPLETE);
return Disposables.single();
}
final Instant now = Instant.now();
Duration initialInterval = Duration.between(now, initialLockedUntil);
i... | class LockRenewalOperation implements AutoCloseable {
private final ClientLogger logger = new ClientLogger(LockRenewalOperation.class);
private final AtomicBoolean isDisposed = new AtomicBoolean();
private final AtomicReference<Instant> lockedUntil = new AtomicReference<>();
private final AtomicReference<Throwable> thr... | class LockRenewalOperation implements AutoCloseable {
private final ClientLogger logger = new ClientLogger(LockRenewalOperation.class);
private final AtomicBoolean isDisposed = new AtomicBoolean();
private final AtomicReference<Instant> lockedUntil = new AtomicReference<>();
private final AtomicReference<Throwable> thr... |
Shouldn't we check for empty or null session id and throw Exception as needed? | public LockRenewalOperation getAutoRenewSessionLock(String sessionId, Duration maxLockRenewalDuration) {
if (isDisposed.get()) {
throw logger.logThrowableAsError(new IllegalStateException(
String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "getAutoRenewSessionLock")));
} else if (!receiverOptions.isSessionReceiver()) {... | String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "getAutoRenewSessionLock"))); | public LockRenewalOperation getAutoRenewSessionLock(String sessionId, Duration maxLockRenewalDuration) {
if (isDisposed.get()) {
throw logger.logExceptionAsError(new IllegalStateException(
String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "getAutoRenewSessionLock")));
} else if (!receiverOptions.isSessionReceiver()) {... | class ServiceBusReceiverAsyncClient implements AutoCloseable {
private static final DeadLetterOptions DEFAULT_DEAD_LETTER_OPTIONS = new DeadLetterOptions();
private static final String TRANSACTION_LINK_NAME = "coordinator";
private final AtomicBoolean isDisposed = new AtomicBoolean();
private final MessageLockContainer... | class ServiceBusReceiverAsyncClient implements AutoCloseable {
private static final DeadLetterOptions DEFAULT_DEAD_LETTER_OPTIONS = new DeadLetterOptions();
private static final String TRANSACTION_LINK_NAME = "coordinator";
private final LockContainer<LockRenewalOperation> renewalContainer;
private final AtomicBoolean ... |
The other code in the builder allows for `retryPolicy` to be `null`. I would remove the `null` check and just document that if this is `null` a default `RetryPolicy` will be used. | public DigitalTwinsClientBuilder retryOptions(RetryPolicy retryPolicy) {
this.retryPolicy = Objects.requireNonNull(retryPolicy, "'retryPolicy' cannot be null.");
return this;
} | this.retryPolicy = Objects.requireNonNull(retryPolicy, "'retryPolicy' cannot be null."); | public DigitalTwinsClientBuilder retryOptions(RetryPolicy retryPolicy) {
this.retryPolicy = Objects.requireNonNull(retryPolicy, "'retryPolicy' cannot be null.");
return this;
} | class DigitalTwinsClientBuilder {
private final List<HttpPipelinePolicy> additionalPolicies = new ArrayList<>();
private String endpoint;
private TokenCredential tokenCredential;
private DigitalTwinsServiceVersion serviceVersion;
private HttpPipeline httpPipeline;
private HttpClient httpClient;
private HttpLogOptions l... | class DigitalTwinsClientBuilder {
private static final String[] adtPublicScope = new String[]{"https:
private final List<HttpPipelinePolicy> additionalPolicies = new ArrayList<>();
private String endpoint;
private TokenCredential tokenCredential;
private DigitalTwinsServiceVersion serviceVersion;
private HttpPipeline h... |
Are we also taking care of situation when , user complete a message but renew operation still try to renew and keep getting error in logs. After settlement of the message by user, How does that lock is not renewing automatically in background and filling the logs ? | void errors() throws InterruptedException {
final boolean isSession = true;
final Duration renewalPeriod = Duration.ofSeconds(2);
final Instant lockedUntil = Instant.now().plus(renewalPeriod);
final Duration maxDuration = Duration.ofSeconds(6);
final Duration totalSleepPeriod = renewalPeriod.plus(renewalPeriod).plusMil... | void errors() throws InterruptedException {
final boolean isSession = true;
final Duration renewalPeriod = Duration.ofSeconds(2);
final Instant lockedUntil = Instant.now().plus(renewalPeriod);
final Duration maxDuration = Duration.ofSeconds(6);
final Duration totalSleepPeriod = renewalPeriod.plus(renewalPeriod).plusMil... | class LockRenewalOperationTest {
private static final String A_LOCK_TOKEN = "a-lock-token";
private final ClientLogger logger = new ClientLogger(LockRenewalOperationTest.class);
private LockRenewalOperation operation;
@Mock
private Function<String, Mono<Instant>> renewalOperation;
@BeforeEach
void beforeEach() {
Mockit... | class LockRenewalOperationTest {
private static final String A_LOCK_TOKEN = "a-lock-token";
private final ClientLogger logger = new ClientLogger(LockRenewalOperationTest.class);
private LockRenewalOperation operation;
@Mock
private Function<String, Mono<Instant>> renewalOperation;
@BeforeEach
void beforeEach() {
Mockit... | |
IsNegative is an invalid operation. I'll throw before it even gets here. | private Disposable getRenewLockOperation(Instant initialLockedUntil, Duration maxLockRenewalDuration) {
if (maxLockRenewalDuration.isZero()) {
status.set(LockRenewalStatus.COMPLETE);
return Disposables.single();
}
final Instant now = Instant.now();
Duration initialInterval = Duration.between(now, initialLockedUntil);
i... | if (maxLockRenewalDuration.isZero()) { | private Disposable getRenewLockOperation(Instant initialLockedUntil, Duration maxLockRenewalDuration) {
if (maxLockRenewalDuration.isZero()) {
status.set(LockRenewalStatus.COMPLETE);
return Disposables.single();
}
final Instant now = Instant.now();
Duration initialInterval = Duration.between(now, initialLockedUntil);
i... | class LockRenewalOperation implements AutoCloseable {
private final ClientLogger logger = new ClientLogger(LockRenewalOperation.class);
private final AtomicBoolean isDisposed = new AtomicBoolean();
private final AtomicReference<Instant> lockedUntil = new AtomicReference<>();
private final AtomicReference<Throwable> thr... | class LockRenewalOperation implements AutoCloseable {
private final ClientLogger logger = new ClientLogger(LockRenewalOperation.class);
private final AtomicBoolean isDisposed = new AtomicBoolean();
private final AtomicReference<Instant> lockedUntil = new AtomicReference<>();
private final AtomicReference<Throwable> thr... |
It's checked in the constructor for LockRenewalOperation. | public LockRenewalOperation getAutoRenewSessionLock(String sessionId, Duration maxLockRenewalDuration) {
if (isDisposed.get()) {
throw logger.logThrowableAsError(new IllegalStateException(
String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "getAutoRenewSessionLock")));
} else if (!receiverOptions.isSessionReceiver()) {... | String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "getAutoRenewSessionLock"))); | public LockRenewalOperation getAutoRenewSessionLock(String sessionId, Duration maxLockRenewalDuration) {
if (isDisposed.get()) {
throw logger.logExceptionAsError(new IllegalStateException(
String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "getAutoRenewSessionLock")));
} else if (!receiverOptions.isSessionReceiver()) {... | class ServiceBusReceiverAsyncClient implements AutoCloseable {
private static final DeadLetterOptions DEFAULT_DEAD_LETTER_OPTIONS = new DeadLetterOptions();
private static final String TRANSACTION_LINK_NAME = "coordinator";
private final AtomicBoolean isDisposed = new AtomicBoolean();
private final MessageLockContainer... | class ServiceBusReceiverAsyncClient implements AutoCloseable {
private static final DeadLetterOptions DEFAULT_DEAD_LETTER_OPTIONS = new DeadLetterOptions();
private static final String TRANSACTION_LINK_NAME = "coordinator";
private final LockContainer<LockRenewalOperation> renewalContainer;
private final AtomicBoolean ... |
👍 | public DigitalTwinsAsyncClient buildAsyncClient() {
Objects.requireNonNull(tokenCredential, "'tokenCredential' cannot be null.");
Objects.requireNonNull(endpoint, "'endpoint' cannot be null");
this.serviceVersion = this.serviceVersion != null ? this.serviceVersion : DigitalTwinsServiceVersion.getLatest();
this.retryPol... | this.retryPolicy = this.retryPolicy != null ? this.retryPolicy : new RetryPolicy(); | public DigitalTwinsAsyncClient buildAsyncClient() {
Objects.requireNonNull(tokenCredential, "'tokenCredential' cannot be null.");
Objects.requireNonNull(endpoint, "'endpoint' cannot be null");
this.serviceVersion = this.serviceVersion != null ? this.serviceVersion : DigitalTwinsServiceVersion.getLatest();
this.retryPol... | class DigitalTwinsClientBuilder {
private final List<HttpPipelinePolicy> additionalPolicies = new ArrayList<>();
private String endpoint;
private TokenCredential tokenCredential;
private DigitalTwinsServiceVersion serviceVersion;
private HttpPipeline httpPipeline;
private HttpClient httpClient;
private HttpLogOptions l... | class DigitalTwinsClientBuilder {
private final List<HttpPipelinePolicy> additionalPolicies = new ArrayList<>();
private String endpoint;
private TokenCredential tokenCredential;
private DigitalTwinsServiceVersion serviceVersion;
private HttpPipeline httpPipeline;
private HttpClient httpClient;
private HttpLogOptions l... |
can we split this into multiple lines and add tab support? | public DigitalTwinsAsyncClient buildAsyncClient() {
Objects.requireNonNull(tokenCredential, "'tokenCredential' cannot be null.");
Objects.requireNonNull(endpoint, "'endpoint' cannot be null");
this.serviceVersion = this.serviceVersion != null ? this.serviceVersion : DigitalTwinsServiceVersion.getLatest();
this.retryPol... | this.httpPipeline = this.httpPipeline != null ? httpPipeline : buildPipeline(this.tokenCredential, this.endpoint, this.logOptions, this.httpClient, this.additionalPolicies, this.retryPolicy); | public DigitalTwinsAsyncClient buildAsyncClient() {
Objects.requireNonNull(tokenCredential, "'tokenCredential' cannot be null.");
Objects.requireNonNull(endpoint, "'endpoint' cannot be null");
this.serviceVersion = this.serviceVersion != null ? this.serviceVersion : DigitalTwinsServiceVersion.getLatest();
this.retryPol... | class DigitalTwinsClientBuilder {
private final List<HttpPipelinePolicy> additionalPolicies = new ArrayList<>();
private String endpoint;
private TokenCredential tokenCredential;
private DigitalTwinsServiceVersion serviceVersion;
private HttpPipeline httpPipeline;
private HttpClient httpClient;
private HttpLogOptions l... | class DigitalTwinsClientBuilder {
private final List<HttpPipelinePolicy> additionalPolicies = new ArrayList<>();
private String endpoint;
private TokenCredential tokenCredential;
private DigitalTwinsServiceVersion serviceVersion;
private HttpPipeline httpPipeline;
private HttpClient httpClient;
private HttpLogOptions l... |
Sure, since this line in particular is a bit long | public DigitalTwinsAsyncClient buildAsyncClient() {
Objects.requireNonNull(tokenCredential, "'tokenCredential' cannot be null.");
Objects.requireNonNull(endpoint, "'endpoint' cannot be null");
this.serviceVersion = this.serviceVersion != null ? this.serviceVersion : DigitalTwinsServiceVersion.getLatest();
this.retryPol... | this.httpPipeline = this.httpPipeline != null ? httpPipeline : buildPipeline(this.tokenCredential, this.endpoint, this.logOptions, this.httpClient, this.additionalPolicies, this.retryPolicy); | public DigitalTwinsAsyncClient buildAsyncClient() {
Objects.requireNonNull(tokenCredential, "'tokenCredential' cannot be null.");
Objects.requireNonNull(endpoint, "'endpoint' cannot be null");
this.serviceVersion = this.serviceVersion != null ? this.serviceVersion : DigitalTwinsServiceVersion.getLatest();
this.retryPol... | class DigitalTwinsClientBuilder {
private final List<HttpPipelinePolicy> additionalPolicies = new ArrayList<>();
private String endpoint;
private TokenCredential tokenCredential;
private DigitalTwinsServiceVersion serviceVersion;
private HttpPipeline httpPipeline;
private HttpClient httpClient;
private HttpLogOptions l... | class DigitalTwinsClientBuilder {
private final List<HttpPipelinePolicy> additionalPolicies = new ArrayList<>();
private String endpoint;
private TokenCredential tokenCredential;
private DigitalTwinsServiceVersion serviceVersion;
private HttpPipeline httpPipeline;
private HttpClient httpClient;
private HttpLogOptions l... |
It would be useful log a warning if the method has any annotation but is non-public. It will let the users know that the visibility of the method is the reason for ignoring it. Same for field too. | public String convertMemberName(Member member) {
if (Modifier.isTransient(member.getModifiers())) {
return null;
}
VisibilityChecker<?> visibilityChecker = mapper.getVisibilityChecker();
if (member instanceof Field) {
Field f = (Field) member;
if (f.isAnnotationPresent(JsonIgnore.class) || !visibilityChecker.isFieldVis... | || !visibilityChecker.isGetterVisible(m)) { | public String convertMemberName(Member member) {
if (Modifier.isTransient(member.getModifiers())) {
return null;
}
VisibilityChecker<?> visibilityChecker = mapper.getVisibilityChecker();
if (member instanceof Field) {
Field f = (Field) member;
if (f.isAnnotationPresent(JsonIgnore.class) || !visibilityChecker.isFieldVis... | class JacksonJsonSerializer implements JsonSerializer, MemberNameConverter {
private final ClientLogger logger = new ClientLogger(JacksonJsonSerializer.class);
private final ObjectMapper mapper;
private final TypeFactory typeFactory;
/**
* Constructs a {@link JsonSerializer} using the passed Jackson serializer.
*
* @pa... | class JacksonJsonSerializer implements JsonSerializer, MemberNameConverter {
private final ClientLogger logger = new ClientLogger(JacksonJsonSerializer.class);
private final ObjectMapper mapper;
private final TypeFactory typeFactory;
/**
* Constructs a {@link JsonSerializer} using the passed Jackson serializer.
*
* @pa... |
I will make code changes after the first round of team review, I will make a note of this comment. | public DigitalTwinsClientBuilder retryOptions(RetryPolicy retryPolicy) {
this.retryPolicy = Objects.requireNonNull(retryPolicy, "'retryPolicy' cannot be null.");
return this;
} | this.retryPolicy = Objects.requireNonNull(retryPolicy, "'retryPolicy' cannot be null."); | public DigitalTwinsClientBuilder retryOptions(RetryPolicy retryPolicy) {
this.retryPolicy = Objects.requireNonNull(retryPolicy, "'retryPolicy' cannot be null.");
return this;
} | class DigitalTwinsClientBuilder {
private final List<HttpPipelinePolicy> additionalPolicies = new ArrayList<>();
private String endpoint;
private TokenCredential tokenCredential;
private DigitalTwinsServiceVersion serviceVersion;
private HttpPipeline httpPipeline;
private HttpClient httpClient;
private HttpLogOptions l... | class DigitalTwinsClientBuilder {
private static final String[] adtPublicScope = new String[]{"https:
private final List<HttpPipelinePolicy> additionalPolicies = new ArrayList<>();
private String endpoint;
private TokenCredential tokenCredential;
private DigitalTwinsServiceVersion serviceVersion;
private HttpPipeline h... |
Only log in the instance of the method/field being ignored due to visibility and not due to annotations? | public String convertMemberName(Member member) {
if (Modifier.isTransient(member.getModifiers())) {
return null;
}
VisibilityChecker<?> visibilityChecker = mapper.getVisibilityChecker();
if (member instanceof Field) {
Field f = (Field) member;
if (f.isAnnotationPresent(JsonIgnore.class) || !visibilityChecker.isFieldVis... | || !visibilityChecker.isGetterVisible(m)) { | public String convertMemberName(Member member) {
if (Modifier.isTransient(member.getModifiers())) {
return null;
}
VisibilityChecker<?> visibilityChecker = mapper.getVisibilityChecker();
if (member instanceof Field) {
Field f = (Field) member;
if (f.isAnnotationPresent(JsonIgnore.class) || !visibilityChecker.isFieldVis... | class JacksonJsonSerializer implements JsonSerializer, MemberNameConverter {
private final ClientLogger logger = new ClientLogger(JacksonJsonSerializer.class);
private final ObjectMapper mapper;
private final TypeFactory typeFactory;
/**
* Constructs a {@link JsonSerializer} using the passed Jackson serializer.
*
* @pa... | class JacksonJsonSerializer implements JsonSerializer, MemberNameConverter {
private final ClientLogger logger = new ClientLogger(JacksonJsonSerializer.class);
private final ObjectMapper mapper;
private final TypeFactory typeFactory;
/**
* Constructs a {@link JsonSerializer} using the passed Jackson serializer.
*
* @pa... |
```suggestion if (this.httpPipeline == null) { ``` | public DigitalTwinsAsyncClient buildAsyncClient() {
Objects.requireNonNull(tokenCredential, "'tokenCredential' cannot be null.");
Objects.requireNonNull(endpoint, "'endpoint' cannot be null");
this.serviceVersion = this.serviceVersion != null ? this.serviceVersion : DigitalTwinsServiceVersion.getLatest();
this.retryPol... | { | public DigitalTwinsAsyncClient buildAsyncClient() {
Objects.requireNonNull(tokenCredential, "'tokenCredential' cannot be null.");
Objects.requireNonNull(endpoint, "'endpoint' cannot be null");
this.serviceVersion = this.serviceVersion != null ? this.serviceVersion : DigitalTwinsServiceVersion.getLatest();
this.retryPol... | class DigitalTwinsClientBuilder {
private final List<HttpPipelinePolicy> additionalPolicies = new ArrayList<>();
private String endpoint;
private TokenCredential tokenCredential;
private DigitalTwinsServiceVersion serviceVersion;
private HttpPipeline httpPipeline;
private HttpClient httpClient;
private HttpLogOptions l... | class DigitalTwinsClientBuilder {
private static final String[] adtPublicScope = new String[]{"https:
private final List<HttpPipelinePolicy> additionalPolicies = new ArrayList<>();
private String endpoint;
private TokenCredential tokenCredential;
private DigitalTwinsServiceVersion serviceVersion;
private HttpPipeline h... |
`HttpLoggingPolicy` allows for `null` `HttpLogOptions` to effectively be a no-op, don't think it needs to be `null` checked here. | public DigitalTwinsClientBuilder httpLogOptions(HttpLogOptions logOptions) {
this.logOptions = Objects.requireNonNull(logOptions, "'logOptions' cannot be null.");
return this;
} | this.logOptions = Objects.requireNonNull(logOptions, "'logOptions' cannot be null."); | public DigitalTwinsClientBuilder httpLogOptions(HttpLogOptions logOptions) {
this.logOptions = logOptions;
return this;
} | class DigitalTwinsClientBuilder {
private final List<HttpPipelinePolicy> additionalPolicies = new ArrayList<>();
private String endpoint;
private TokenCredential tokenCredential;
private DigitalTwinsServiceVersion serviceVersion;
private HttpPipeline httpPipeline;
private HttpClient httpClient;
private HttpLogOptions l... | class DigitalTwinsClientBuilder {
private static final String[] adtPublicScope = new String[]{"https:
private final List<HttpPipelinePolicy> additionalPolicies = new ArrayList<>();
private String endpoint;
private TokenCredential tokenCredential;
private DigitalTwinsServiceVersion serviceVersion;
private HttpPipeline h... |
Another fake LRO? | public Mono<RedisCache> updateResourceAsync() {
updateParameters.withTags(this.inner().tags());
return this.manager().inner().getRedis().updateAsync(resourceGroupName(), name(), updateParameters)
.map(innerToFluentMap(this))
.filter(redisCache -> !redisCache.provisioningState().equalsIgnoreCase(ProvisioningState.SUCCEE... | return this.manager().inner().getRedis().getByResourceGroupAsync(resourceGroupName(), name()) | public Mono<RedisCache> updateResourceAsync() {
updateParameters.withTags(this.inner().tags());
this.patchScheduleAdded = false;
return this
.manager()
.inner()
.getRedis()
.updateAsync(resourceGroupName(), name(), updateParameters)
.map(innerToFluentMap(this))
.filter(
redisCache -> !redisCache.provisioningState().equ... | class RedisCacheImpl
extends GroupableResourceImpl<
RedisCache,
RedisResourceInner,
RedisCacheImpl,
RedisManager>
implements
RedisCache,
RedisCachePremium,
RedisCache.Definition,
RedisCache.Update {
private RedisAccessKeys cachedAccessKeys;
private RedisCreateParameters createParameters;
private RedisUpdateParameters u... | class RedisCacheImpl extends GroupableResourceImpl<RedisCache, RedisResourceInner, RedisCacheImpl, RedisManager>
implements RedisCache, RedisCachePremium, RedisCache.Definition, RedisCache.Update {
private final ClientLogger logger = new ClientLogger(getClass());
private RedisAccessKeys cachedAccessKeys;
private RedisC... |
Yes, the redis doesn't go through official LRO, like cosmos | public Mono<RedisCache> updateResourceAsync() {
updateParameters.withTags(this.inner().tags());
return this.manager().inner().getRedis().updateAsync(resourceGroupName(), name(), updateParameters)
.map(innerToFluentMap(this))
.filter(redisCache -> !redisCache.provisioningState().equalsIgnoreCase(ProvisioningState.SUCCEE... | return this.manager().inner().getRedis().getByResourceGroupAsync(resourceGroupName(), name()) | public Mono<RedisCache> updateResourceAsync() {
updateParameters.withTags(this.inner().tags());
this.patchScheduleAdded = false;
return this
.manager()
.inner()
.getRedis()
.updateAsync(resourceGroupName(), name(), updateParameters)
.map(innerToFluentMap(this))
.filter(
redisCache -> !redisCache.provisioningState().equ... | class RedisCacheImpl
extends GroupableResourceImpl<
RedisCache,
RedisResourceInner,
RedisCacheImpl,
RedisManager>
implements
RedisCache,
RedisCachePremium,
RedisCache.Definition,
RedisCache.Update {
private RedisAccessKeys cachedAccessKeys;
private RedisCreateParameters createParameters;
private RedisUpdateParameters u... | class RedisCacheImpl extends GroupableResourceImpl<RedisCache, RedisResourceInner, RedisCacheImpl, RedisManager>
implements RedisCache, RedisCachePremium, RedisCache.Definition, RedisCache.Update {
private final ClientLogger logger = new ClientLogger(getClass());
private RedisAccessKeys cachedAccessKeys;
private RedisC... |
Should we use `delaySubscription` + `repeat`? https://github.com/Azure/azure-sdk-for-java/blob/master/sdk/core/azure-core/src/main/java/com/azure/core/util/polling/PollerFlux.java#L214-L238 | public Mono<RedisCache> updateResourceAsync() {
updateParameters.withTags(this.inner().tags());
return this.manager().inner().getRedis().updateAsync(resourceGroupName(), name(), updateParameters)
.map(innerToFluentMap(this))
.filter(redisCache -> !redisCache.provisioningState().equalsIgnoreCase(ProvisioningState.SUCCEE... | SdkContext.sleep(30 * 1000); | public Mono<RedisCache> updateResourceAsync() {
updateParameters.withTags(this.inner().tags());
this.patchScheduleAdded = false;
return this
.manager()
.inner()
.getRedis()
.updateAsync(resourceGroupName(), name(), updateParameters)
.map(innerToFluentMap(this))
.filter(
redisCache -> !redisCache.provisioningState().equ... | class RedisCacheImpl
extends GroupableResourceImpl<
RedisCache,
RedisResourceInner,
RedisCacheImpl,
RedisManager>
implements
RedisCache,
RedisCachePremium,
RedisCache.Definition,
RedisCache.Update {
private RedisAccessKeys cachedAccessKeys;
private RedisCreateParameters createParameters;
private RedisUpdateParameters u... | class RedisCacheImpl extends GroupableResourceImpl<RedisCache, RedisResourceInner, RedisCacheImpl, RedisManager>
implements RedisCache, RedisCachePremium, RedisCache.Definition, RedisCache.Update {
private final ClientLogger logger = new ClientLogger(getClass());
private RedisAccessKeys cachedAccessKeys;
private RedisC... |
done | public Mono<RedisCache> updateResourceAsync() {
updateParameters.withTags(this.inner().tags());
return this.manager().inner().getRedis().updateAsync(resourceGroupName(), name(), updateParameters)
.map(innerToFluentMap(this))
.filter(redisCache -> !redisCache.provisioningState().equalsIgnoreCase(ProvisioningState.SUCCEE... | SdkContext.sleep(30 * 1000); | public Mono<RedisCache> updateResourceAsync() {
updateParameters.withTags(this.inner().tags());
this.patchScheduleAdded = false;
return this
.manager()
.inner()
.getRedis()
.updateAsync(resourceGroupName(), name(), updateParameters)
.map(innerToFluentMap(this))
.filter(
redisCache -> !redisCache.provisioningState().equ... | class RedisCacheImpl
extends GroupableResourceImpl<
RedisCache,
RedisResourceInner,
RedisCacheImpl,
RedisManager>
implements
RedisCache,
RedisCachePremium,
RedisCache.Definition,
RedisCache.Update {
private RedisAccessKeys cachedAccessKeys;
private RedisCreateParameters createParameters;
private RedisUpdateParameters u... | class RedisCacheImpl extends GroupableResourceImpl<RedisCache, RedisResourceInner, RedisCacheImpl, RedisManager>
implements RedisCache, RedisCachePremium, RedisCache.Definition, RedisCache.Update {
private final ClientLogger logger = new ClientLogger(getClass());
private RedisAccessKeys cachedAccessKeys;
private RedisC... |
Can we create a constant and name it as `DEFAULT_POLL_DURATION`? | Duration getPollDuration() {
return Duration.ofSeconds(1);
} | return Duration.ofSeconds(1); | Duration getPollDuration() {
return DEFAULT_POLL_DURATION;
} | class CertificateAsyncClient {
private final String apiVersion;
static final String ACCEPT_LANGUAGE = "en-US";
static final int DEFAULT_MAX_PAGE_RESULTS = 25;
static final String CONTENT_TYPE_HEADER_VALUE = "application/json";
static final String KEY_VAULT_SCOPE = "https:
private static final String KEYVAULT_TRACING_NA... | class CertificateAsyncClient {
private final String apiVersion;
static final String ACCEPT_LANGUAGE = "en-US";
static final int DEFAULT_MAX_PAGE_RESULTS = 25;
static final String CONTENT_TYPE_HEADER_VALUE = "application/json";
static final String KEY_VAULT_SCOPE = "https:
private static final String KEYVAULT_TRACING_NA... |
Done | Duration getPollDuration() {
return Duration.ofSeconds(1);
} | return Duration.ofSeconds(1); | Duration getPollDuration() {
return DEFAULT_POLL_DURATION;
} | class CertificateAsyncClient {
private final String apiVersion;
static final String ACCEPT_LANGUAGE = "en-US";
static final int DEFAULT_MAX_PAGE_RESULTS = 25;
static final String CONTENT_TYPE_HEADER_VALUE = "application/json";
static final String KEY_VAULT_SCOPE = "https:
private static final String KEYVAULT_TRACING_NA... | class CertificateAsyncClient {
private final String apiVersion;
static final String ACCEPT_LANGUAGE = "en-US";
static final int DEFAULT_MAX_PAGE_RESULTS = 25;
static final String CONTENT_TYPE_HEADER_VALUE = "application/json";
static final String KEY_VAULT_SCOPE = "https:
private static final String KEYVAULT_TRACING_NA... |
please use the following instead: `ConsistencyLevel.fromServiceSerializedFormat(.)` if the method is not accessible from this package use: `BridgeInternal.fromServiceSerializedFormat()` | public ConsistencyLevel getDefaultConsistencyLevel() {
if (this.cachedConsistencyLevel == null) {
ConsistencyLevel result = ConsistencyPolicy.DEFAULT_DEFAULT_CONSISTENCY_LEVEL;
String consistencyLevelString = super.getString(Constants.Properties.DEFAULT_CONSISTENCY_LEVEL);
try {
result = ConsistencyLevel
.valueOf(CaseF... | .valueOf(CaseFormat.UPPER_CAMEL.to(CaseFormat.UPPER_UNDERSCORE, consistencyLevelString)); | public ConsistencyLevel getDefaultConsistencyLevel() {
if (this.consistencyLevel == null) {
ConsistencyLevel result = ConsistencyPolicy.DEFAULT_DEFAULT_CONSISTENCY_LEVEL;
String consistencyLevelString = super.getString(Constants.Properties.DEFAULT_CONSISTENCY_LEVEL);
try {
result = BridgeInternal.fromServiceSerializedF... | class ConsistencyPolicy extends JsonSerializable {
private static final ConsistencyLevel DEFAULT_DEFAULT_CONSISTENCY_LEVEL =
ConsistencyLevel.SESSION;
private static final int DEFAULT_MAX_STALENESS_INTERVAL = 5;
private static final int DEFAULT_MAX_STALENESS_PREFIX = 100;
/**
* Constructor.
*/
public ConsistencyPolicy(... | class ConsistencyPolicy extends JsonSerializable {
private static final ConsistencyLevel DEFAULT_DEFAULT_CONSISTENCY_LEVEL =
ConsistencyLevel.SESSION;
private static final int DEFAULT_MAX_STALENESS_INTERVAL = 5;
private static final int DEFAULT_MAX_STALENESS_PREFIX = 100;
/**
* Constructor.
*/
public ConsistencyPolicy(... |
you don't need `ConsistencyLeve.valueOf()` here. | public ConsistencyLevel getDefaultConsistencyLevel() {
if (this.consistencyLevel == null) {
ConsistencyLevel result = ConsistencyPolicy.DEFAULT_DEFAULT_CONSISTENCY_LEVEL;
String consistencyLevelString = super.getString(Constants.Properties.DEFAULT_CONSISTENCY_LEVEL);
try {
result = ConsistencyLevel
.valueOf(BridgeInter... | .valueOf(BridgeInternal.fromServiceSerializedFormat(consistencyLevelString)); | public ConsistencyLevel getDefaultConsistencyLevel() {
if (this.consistencyLevel == null) {
ConsistencyLevel result = ConsistencyPolicy.DEFAULT_DEFAULT_CONSISTENCY_LEVEL;
String consistencyLevelString = super.getString(Constants.Properties.DEFAULT_CONSISTENCY_LEVEL);
try {
result = BridgeInternal.fromServiceSerializedF... | class ConsistencyPolicy extends JsonSerializable {
private static final ConsistencyLevel DEFAULT_DEFAULT_CONSISTENCY_LEVEL =
ConsistencyLevel.SESSION;
private static final int DEFAULT_MAX_STALENESS_INTERVAL = 5;
private static final int DEFAULT_MAX_STALENESS_PREFIX = 100;
/**
* Constructor.
*/
public ConsistencyPolicy(... | class ConsistencyPolicy extends JsonSerializable {
private static final ConsistencyLevel DEFAULT_DEFAULT_CONSISTENCY_LEVEL =
ConsistencyLevel.SESSION;
private static final int DEFAULT_MAX_STALENESS_INTERVAL = 5;
private static final int DEFAULT_MAX_STALENESS_PREFIX = 100;
/**
* Constructor.
*/
public ConsistencyPolicy(... |
please change to ```java result = BridgeInternal.fromServiceSerializedFormat(consistencyLevelString) ``` | public ConsistencyLevel getDefaultConsistencyLevel() {
if (this.consistencyLevel == null) {
ConsistencyLevel result = ConsistencyPolicy.DEFAULT_DEFAULT_CONSISTENCY_LEVEL;
String consistencyLevelString = super.getString(Constants.Properties.DEFAULT_CONSISTENCY_LEVEL);
try {
result = ConsistencyLevel
.valueOf(BridgeInter... | .valueOf(BridgeInternal.fromServiceSerializedFormat(consistencyLevelString)); | public ConsistencyLevel getDefaultConsistencyLevel() {
if (this.consistencyLevel == null) {
ConsistencyLevel result = ConsistencyPolicy.DEFAULT_DEFAULT_CONSISTENCY_LEVEL;
String consistencyLevelString = super.getString(Constants.Properties.DEFAULT_CONSISTENCY_LEVEL);
try {
result = BridgeInternal.fromServiceSerializedF... | class ConsistencyPolicy extends JsonSerializable {
private static final ConsistencyLevel DEFAULT_DEFAULT_CONSISTENCY_LEVEL =
ConsistencyLevel.SESSION;
private static final int DEFAULT_MAX_STALENESS_INTERVAL = 5;
private static final int DEFAULT_MAX_STALENESS_PREFIX = 100;
/**
* Constructor.
*/
public ConsistencyPolicy(... | class ConsistencyPolicy extends JsonSerializable {
private static final ConsistencyLevel DEFAULT_DEFAULT_CONSISTENCY_LEVEL =
ConsistencyLevel.SESSION;
private static final int DEFAULT_MAX_STALENESS_INTERVAL = 5;
private static final int DEFAULT_MAX_STALENESS_PREFIX = 100;
/**
* Constructor.
*/
public ConsistencyPolicy(... |
I am concerned about this synchronized code piece, since this will be called on every request. My concern is this will slow down things. Do we need `synchronized` block here even though `credential` is volatile now ? | private Mac getMacInstance() {
int masterKeyLatestHashCode = this.credential.getKey().hashCode();
if (masterKeyLatestHashCode != this.masterKeyHashCode) {
synchronized (this.credential) {
if (masterKeyLatestHashCode != this.masterKeyHashCode) {
byte[] masterKeyBytes = this.credential.getKey().getBytes(StandardCharsets.... | synchronized (this.credential) { | private Mac getMacInstance() {
reInitializeIfPossible();
try {
return (Mac)this.macInstance.clone();
} catch (CloneNotSupportedException e) {
throw new IllegalStateException(e);
}
} | class BaseAuthorizationTokenProvider implements AuthorizationTokenProvider {
private static final String AUTH_PREFIX = "type=master&ver=1.0&sig=";
private final AzureKeyCredential credential;
private volatile Mac macInstance;
private volatile int masterKeyHashCode;
public BaseAuthorizationTokenProvider(AzureKeyCredenti... | class BaseAuthorizationTokenProvider implements AuthorizationTokenProvider {
private static final String AUTH_PREFIX = "type=master&ver=1.0&sig=";
private final AzureKeyCredential credential;
private volatile Mac macInstance;
private final Lock macInstanceLock = new ReentrantLock();
private volatile int masterKeyHashCo... |
this is very valid point. I also think will have perf impact | private Mac getMacInstance() {
int masterKeyLatestHashCode = this.credential.getKey().hashCode();
if (masterKeyLatestHashCode != this.masterKeyHashCode) {
synchronized (this.credential) {
if (masterKeyLatestHashCode != this.masterKeyHashCode) {
byte[] masterKeyBytes = this.credential.getKey().getBytes(StandardCharsets.... | synchronized (this.credential) { | private Mac getMacInstance() {
reInitializeIfPossible();
try {
return (Mac)this.macInstance.clone();
} catch (CloneNotSupportedException e) {
throw new IllegalStateException(e);
}
} | class BaseAuthorizationTokenProvider implements AuthorizationTokenProvider {
private static final String AUTH_PREFIX = "type=master&ver=1.0&sig=";
private final AzureKeyCredential credential;
private volatile Mac macInstance;
private volatile int masterKeyHashCode;
public BaseAuthorizationTokenProvider(AzureKeyCredenti... | class BaseAuthorizationTokenProvider implements AuthorizationTokenProvider {
private static final String AUTH_PREFIX = "type=master&ver=1.0&sig=";
private final AzureKeyCredential credential;
private volatile Mac macInstance;
private final Lock macInstanceLock = new ReentrantLock();
private volatile int masterKeyHashCo... |
Only when the hashcode is different is when this code path hits. Few triggering points are - new client creation starting point - key-changed If the assumption is that its a both credentials are valid for a good period of time, the refresh can be asynchronous. Can we make that assumption? | private Mac getMacInstance() {
int masterKeyLatestHashCode = this.credential.getKey().hashCode();
if (masterKeyLatestHashCode != this.masterKeyHashCode) {
synchronized (this.credential) {
if (masterKeyLatestHashCode != this.masterKeyHashCode) {
byte[] masterKeyBytes = this.credential.getKey().getBytes(StandardCharsets.... | synchronized (this.credential) { | private Mac getMacInstance() {
reInitializeIfPossible();
try {
return (Mac)this.macInstance.clone();
} catch (CloneNotSupportedException e) {
throw new IllegalStateException(e);
}
} | class BaseAuthorizationTokenProvider implements AuthorizationTokenProvider {
private static final String AUTH_PREFIX = "type=master&ver=1.0&sig=";
private final AzureKeyCredential credential;
private volatile Mac macInstance;
private volatile int masterKeyHashCode;
public BaseAuthorizationTokenProvider(AzureKeyCredenti... | class BaseAuthorizationTokenProvider implements AuthorizationTokenProvider {
private static final String AUTH_PREFIX = "type=master&ver=1.0&sig=";
private final AzureKeyCredential credential;
private volatile Mac macInstance;
private final Lock macInstanceLock = new ReentrantLock();
private volatile int masterKeyHashCo... |
Yes, that is correct assumption. We can proceed with this PR. looks good to me. | private Mac getMacInstance() {
int masterKeyLatestHashCode = this.credential.getKey().hashCode();
if (masterKeyLatestHashCode != this.masterKeyHashCode) {
synchronized (this.credential) {
if (masterKeyLatestHashCode != this.masterKeyHashCode) {
byte[] masterKeyBytes = this.credential.getKey().getBytes(StandardCharsets.... | synchronized (this.credential) { | private Mac getMacInstance() {
reInitializeIfPossible();
try {
return (Mac)this.macInstance.clone();
} catch (CloneNotSupportedException e) {
throw new IllegalStateException(e);
}
} | class BaseAuthorizationTokenProvider implements AuthorizationTokenProvider {
private static final String AUTH_PREFIX = "type=master&ver=1.0&sig=";
private final AzureKeyCredential credential;
private volatile Mac macInstance;
private volatile int masterKeyHashCode;
public BaseAuthorizationTokenProvider(AzureKeyCredenti... | class BaseAuthorizationTokenProvider implements AuthorizationTokenProvider {
private static final String AUTH_PREFIX = "type=master&ver=1.0&sig=";
private final AzureKeyCredential credential;
private volatile Mac macInstance;
private final Lock macInstanceLock = new ReentrantLock();
private volatile int masterKeyHashCo... |
Refreshed the implementation to eventually move to the new key. One thread will try to refresh where as others will move forward with current key. | private Mac getMacInstance() {
int masterKeyLatestHashCode = this.credential.getKey().hashCode();
if (masterKeyLatestHashCode != this.masterKeyHashCode) {
synchronized (this.credential) {
if (masterKeyLatestHashCode != this.masterKeyHashCode) {
byte[] masterKeyBytes = this.credential.getKey().getBytes(StandardCharsets.... | synchronized (this.credential) { | private Mac getMacInstance() {
reInitializeIfPossible();
try {
return (Mac)this.macInstance.clone();
} catch (CloneNotSupportedException e) {
throw new IllegalStateException(e);
}
} | class BaseAuthorizationTokenProvider implements AuthorizationTokenProvider {
private static final String AUTH_PREFIX = "type=master&ver=1.0&sig=";
private final AzureKeyCredential credential;
private volatile Mac macInstance;
private volatile int masterKeyHashCode;
public BaseAuthorizationTokenProvider(AzureKeyCredenti... | class BaseAuthorizationTokenProvider implements AuthorizationTokenProvider {
private static final String AUTH_PREFIX = "type=master&ver=1.0&sig=";
private final AzureKeyCredential credential;
private volatile Mac macInstance;
private final Lock macInstanceLock = new ReentrantLock();
private volatile int masterKeyHashCo... |
what is the benefit of using ReentrantLock here? key rotation doesn't happen often and this adds a bit to complexity. Why aren't we simply using synchronized? | private void reInitializeIfPossible() {
int masterKeyLatestHashCode = this.credential.getKey().hashCode();
if (masterKeyLatestHashCode != this.masterKeyHashCode) {
boolean lockAcquired = this.macInstanceLock.tryLock();
if (lockAcquired) {
try {
if (masterKeyLatestHashCode != this.masterKeyHashCode) {
byte[] masterKeyBy... | boolean lockAcquired = this.macInstanceLock.tryLock(); | private void reInitializeIfPossible() {
int masterKeyLatestHashCode = this.credential.getKey().hashCode();
if (masterKeyLatestHashCode != this.masterKeyHashCode) {
boolean lockAcquired = this.macInstanceLock.tryLock();
if (lockAcquired) {
try {
if (masterKeyLatestHashCode != this.masterKeyHashCode) {
byte[] masterKeyBy... | class BaseAuthorizationTokenProvider implements AuthorizationTokenProvider {
private static final String AUTH_PREFIX = "type=master&ver=1.0&sig=";
private final AzureKeyCredential credential;
private volatile Mac macInstance;
private final Lock macInstanceLock = new ReentrantLock();
private volatile int masterKeyHashCo... | class BaseAuthorizationTokenProvider implements AuthorizationTokenProvider {
private static final String AUTH_PREFIX = "type=master&ver=1.0&sig=";
private final AzureKeyCredential credential;
private volatile Mac macInstance;
private final Lock macInstanceLock = new ReentrantLock();
private volatile int masterKeyHashCo... |
reEntrant lock comes into picture only when there is change detected. Otherwise no impact, no? | private void reInitializeIfPossible() {
int masterKeyLatestHashCode = this.credential.getKey().hashCode();
if (masterKeyLatestHashCode != this.masterKeyHashCode) {
boolean lockAcquired = this.macInstanceLock.tryLock();
if (lockAcquired) {
try {
if (masterKeyLatestHashCode != this.masterKeyHashCode) {
byte[] masterKeyBy... | boolean lockAcquired = this.macInstanceLock.tryLock(); | private void reInitializeIfPossible() {
int masterKeyLatestHashCode = this.credential.getKey().hashCode();
if (masterKeyLatestHashCode != this.masterKeyHashCode) {
boolean lockAcquired = this.macInstanceLock.tryLock();
if (lockAcquired) {
try {
if (masterKeyLatestHashCode != this.masterKeyHashCode) {
byte[] masterKeyBy... | class BaseAuthorizationTokenProvider implements AuthorizationTokenProvider {
private static final String AUTH_PREFIX = "type=master&ver=1.0&sig=";
private final AzureKeyCredential credential;
private volatile Mac macInstance;
private final Lock macInstanceLock = new ReentrantLock();
private volatile int masterKeyHashCo... | class BaseAuthorizationTokenProvider implements AuthorizationTokenProvider {
private static final String AUTH_PREFIX = "type=master&ver=1.0&sig=";
private final AzureKeyCredential credential;
private volatile Mac macInstance;
private final Lock macInstanceLock = new ReentrantLock();
private volatile int masterKeyHashCo... |
that's correct. my question is: isn't `synchronized(.)` easier to use? what's the benefit of reEntrant lock here? I don't think you will get any benefit and its usage is slightly more complicated than using `synchronized(.)` is there any benefit in using reEntrant lock over `synchrnozied()`? | private void reInitializeIfPossible() {
int masterKeyLatestHashCode = this.credential.getKey().hashCode();
if (masterKeyLatestHashCode != this.masterKeyHashCode) {
boolean lockAcquired = this.macInstanceLock.tryLock();
if (lockAcquired) {
try {
if (masterKeyLatestHashCode != this.masterKeyHashCode) {
byte[] masterKeyBy... | boolean lockAcquired = this.macInstanceLock.tryLock(); | private void reInitializeIfPossible() {
int masterKeyLatestHashCode = this.credential.getKey().hashCode();
if (masterKeyLatestHashCode != this.masterKeyHashCode) {
boolean lockAcquired = this.macInstanceLock.tryLock();
if (lockAcquired) {
try {
if (masterKeyLatestHashCode != this.masterKeyHashCode) {
byte[] masterKeyBy... | class BaseAuthorizationTokenProvider implements AuthorizationTokenProvider {
private static final String AUTH_PREFIX = "type=master&ver=1.0&sig=";
private final AzureKeyCredential credential;
private volatile Mac macInstance;
private final Lock macInstanceLock = new ReentrantLock();
private volatile int masterKeyHashCo... | class BaseAuthorizationTokenProvider implements AuthorizationTokenProvider {
private static final String AUTH_PREFIX = "type=master&ver=1.0&sig=";
private final AzureKeyCredential credential;
private volatile Mac macInstance;
private final Lock macInstanceLock = new ReentrantLock();
private volatile int masterKeyHashCo... |
synchronized is blocking, where as reEntry.TryLock is enabling non-blocking. So only one thread will go into re-initialization. | private void reInitializeIfPossible() {
int masterKeyLatestHashCode = this.credential.getKey().hashCode();
if (masterKeyLatestHashCode != this.masterKeyHashCode) {
boolean lockAcquired = this.macInstanceLock.tryLock();
if (lockAcquired) {
try {
if (masterKeyLatestHashCode != this.masterKeyHashCode) {
byte[] masterKeyBy... | boolean lockAcquired = this.macInstanceLock.tryLock(); | private void reInitializeIfPossible() {
int masterKeyLatestHashCode = this.credential.getKey().hashCode();
if (masterKeyLatestHashCode != this.masterKeyHashCode) {
boolean lockAcquired = this.macInstanceLock.tryLock();
if (lockAcquired) {
try {
if (masterKeyLatestHashCode != this.masterKeyHashCode) {
byte[] masterKeyBy... | class BaseAuthorizationTokenProvider implements AuthorizationTokenProvider {
private static final String AUTH_PREFIX = "type=master&ver=1.0&sig=";
private final AzureKeyCredential credential;
private volatile Mac macInstance;
private final Lock macInstanceLock = new ReentrantLock();
private volatile int masterKeyHashCo... | class BaseAuthorizationTokenProvider implements AuthorizationTokenProvider {
private static final String AUTH_PREFIX = "type=master&ver=1.0&sig=";
private final AzureKeyCredential credential;
private volatile Mac macInstance;
private final Lock macInstanceLock = new ReentrantLock();
private volatile int masterKeyHashCo... |
if the key is rotated, then shouldn't the threads attempting to get a new macInstance wait and block till a new macInstance generated? Is the old macInstance value returned to the threads which don't get the lock a valid macInstance in the key-rotation scenario? | private void reInitializeIfPossible() {
int masterKeyLatestHashCode = this.credential.getKey().hashCode();
if (masterKeyLatestHashCode != this.masterKeyHashCode) {
boolean lockAcquired = this.macInstanceLock.tryLock();
if (lockAcquired) {
try {
if (masterKeyLatestHashCode != this.masterKeyHashCode) {
byte[] masterKeyBy... | boolean lockAcquired = this.macInstanceLock.tryLock(); | private void reInitializeIfPossible() {
int masterKeyLatestHashCode = this.credential.getKey().hashCode();
if (masterKeyLatestHashCode != this.masterKeyHashCode) {
boolean lockAcquired = this.macInstanceLock.tryLock();
if (lockAcquired) {
try {
if (masterKeyLatestHashCode != this.masterKeyHashCode) {
byte[] masterKeyBy... | class BaseAuthorizationTokenProvider implements AuthorizationTokenProvider {
private static final String AUTH_PREFIX = "type=master&ver=1.0&sig=";
private final AzureKeyCredential credential;
private volatile Mac macInstance;
private final Lock macInstanceLock = new ReentrantLock();
private volatile int masterKeyHashCo... | class BaseAuthorizationTokenProvider implements AuthorizationTokenProvider {
private static final String AUTH_PREFIX = "type=master&ver=1.0&sig=";
private final AzureKeyCredential credential;
private volatile Mac macInstance;
private final Lock macInstanceLock = new ReentrantLock();
private volatile int masterKeyHashCo... |
made the change in cc20c0521dbed11c5ffc661c23de8ed1ff65e9b4 | private List<UserGroup> loadUserGroups(String graphApiToken) throws IOException {
String responseInJson = getUserMemberships(graphApiToken, Optional.empty());
final List<UserGroup> lUserGroups = new ArrayList<>();
final ObjectMapper objectMapper = JacksonObjectMapperFactory.getInstance();
objectMapper.registerModule(ne... | objectMapper.registerModule(new Jdk8Module()); | private List<UserGroup> loadUserGroups(String graphApiToken) throws IOException {
String responseInJson = getUserMemberships(graphApiToken, null);
final List<UserGroup> lUserGroups = new ArrayList<>();
final ObjectMapper objectMapper = JacksonObjectMapperFactory.getInstance();
UserGroups groupsFromJson = objectMapper.r... | class AzureADGraphClient {
private static final Logger LOGGER = LoggerFactory.getLogger(AzureADGraphClient.class);
private static final SimpleGrantedAuthority DEFAULT_AUTHORITY = new SimpleGrantedAuthority("ROLE_USER");
private static final String DEFAULT_ROLE_PREFIX = "ROLE_";
private static final String MICROSOFT_GRA... | class AzureADGraphClient {
private static final Logger LOGGER = LoggerFactory.getLogger(AzureADGraphClient.class);
private static final SimpleGrantedAuthority DEFAULT_AUTHORITY = new SimpleGrantedAuthority("ROLE_USER");
private static final String DEFAULT_ROLE_PREFIX = "ROLE_";
private static final String MICROSOFT_GRA... |
If it is not used, just delete the code. | private ResourceManager(HttpPipeline httpPipeline, AzureProfile profile, SdkContext sdkContext) {
super(null, profile, sdkContext);
super.withResourceManager(this);
this.resourceManagementClient = new ResourceManagementClientBuilder()
.pipeline(httpPipeline)
.endpoint(profile.environment().getResourceManagerEndpoint())... | .endpoint(profile.environment().getResourceManagerEndpoint()) | private ResourceManager(HttpPipeline httpPipeline, AzureProfile profile, SdkContext sdkContext) {
super(null, profile, sdkContext);
super.withResourceManager(this);
this.resourceManagementClient = new ResourceManagementClientBuilder()
.pipeline(httpPipeline)
.endpoint(profile.environment().getResourceManagerEndpoint())... | class AuthenticatedImpl implements Authenticated {
private final HttpPipeline httpPipeline;
private AzureProfile profile;
private SdkContext sdkContext;
private final SubscriptionClient subscriptionClient;
private Subscriptions subscriptions;
private Tenants tenants;
AuthenticatedImpl(HttpPipeline httpPipeline, AzurePr... | class AuthenticatedImpl implements Authenticated {
private final HttpPipeline httpPipeline;
private AzureProfile profile;
private SdkContext sdkContext;
private final SubscriptionClient subscriptionClient;
private Subscriptions subscriptions;
private Tenants tenants;
AuthenticatedImpl(HttpPipeline httpPipeline, AzurePr... |
it is used in this code. | private ResourceManager(HttpPipeline httpPipeline, AzureProfile profile, SdkContext sdkContext) {
super(null, profile, sdkContext);
super.withResourceManager(this);
this.resourceManagementClient = new ResourceManagementClientBuilder()
.pipeline(httpPipeline)
.endpoint(profile.environment().getResourceManagerEndpoint())... | .endpoint(profile.environment().getResourceManagerEndpoint()) | private ResourceManager(HttpPipeline httpPipeline, AzureProfile profile, SdkContext sdkContext) {
super(null, profile, sdkContext);
super.withResourceManager(this);
this.resourceManagementClient = new ResourceManagementClientBuilder()
.pipeline(httpPipeline)
.endpoint(profile.environment().getResourceManagerEndpoint())... | class AuthenticatedImpl implements Authenticated {
private final HttpPipeline httpPipeline;
private AzureProfile profile;
private SdkContext sdkContext;
private final SubscriptionClient subscriptionClient;
private Subscriptions subscriptions;
private Tenants tenants;
AuthenticatedImpl(HttpPipeline httpPipeline, AzurePr... | class AuthenticatedImpl implements Authenticated {
private final HttpPipeline httpPipeline;
private AzureProfile profile;
private SdkContext sdkContext;
private final SubscriptionClient subscriptionClient;
private Subscriptions subscriptions;
private Tenants tenants;
AuthenticatedImpl(HttpPipeline httpPipeline, AzurePr... |
I mean the codes that you've commented out. | private ResourceManager(HttpPipeline httpPipeline, AzureProfile profile, SdkContext sdkContext) {
super(null, profile, sdkContext);
super.withResourceManager(this);
this.resourceManagementClient = new ResourceManagementClientBuilder()
.pipeline(httpPipeline)
.endpoint(profile.environment().getResourceManagerEndpoint())... | .endpoint(profile.environment().getResourceManagerEndpoint()) | private ResourceManager(HttpPipeline httpPipeline, AzureProfile profile, SdkContext sdkContext) {
super(null, profile, sdkContext);
super.withResourceManager(this);
this.resourceManagementClient = new ResourceManagementClientBuilder()
.pipeline(httpPipeline)
.endpoint(profile.environment().getResourceManagerEndpoint())... | class AuthenticatedImpl implements Authenticated {
private final HttpPipeline httpPipeline;
private AzureProfile profile;
private SdkContext sdkContext;
private final SubscriptionClient subscriptionClient;
private Subscriptions subscriptions;
private Tenants tenants;
AuthenticatedImpl(HttpPipeline httpPipeline, AzurePr... | class AuthenticatedImpl implements Authenticated {
private final HttpPipeline httpPipeline;
private AzureProfile profile;
private SdkContext sdkContext;
private final SubscriptionClient subscriptionClient;
private Subscriptions subscriptions;
private Tenants tenants;
AuthenticatedImpl(HttpPipeline httpPipeline, AzurePr... |
Consider putting this in a constant | public void deleteModelValidModelIdWithResponse(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) {
client = getFormTrainingAsyncClient(httpClient, serviceVersion);
beginTrainingLabeledRunner((trainingFilesUrl, useTrainingLabels) -> {
SyncPoller<FormRecognizerOperationResult, CustomFormModel> syncPoll... | assertEquals("1022", errorInformation.getErrorCode()); | public void deleteModelValidModelIdWithResponse(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) {
client = getFormTrainingAsyncClient(httpClient, serviceVersion);
beginTrainingLabeledRunner((trainingFilesUrl, useTrainingLabels) -> {
SyncPoller<FormRecognizerOperationResult, CustomFormModel> syncPoll... | class FormTrainingAsyncClientTest extends FormTrainingClientTestBase {
static final String EXPECTED_COPY_REQUEST_INVALID_TARGET_RESOURCE_REGION = "Status code 400, \"{\"error\":{\"code\":\"1002\",\"message\":\"Copy request is invalid. Field 'TargetResourceRegion' must be a valid Azure region name.\"}}\"";
private FormT... | class FormTrainingAsyncClientTest extends FormTrainingClientTestBase {
static final String EXPECTED_COPY_REQUEST_INVALID_TARGET_RESOURCE_REGION = "Status code 400, \"{\"error\":{\"code\":\"1002\",\"message\":\"Copy request is invalid. Field 'TargetResourceRegion' must be a valid Azure region name.\"}}\"";
private FormT... |
In the configurations client code, their builder never overwrites the values of the instance variables in the builder. Instead it creates local copies that can be altered instead | public DigitalTwinsAsyncClient buildAsyncClient() {
Objects.requireNonNull(tokenCredential, "'tokenCredential' cannot be null.");
Objects.requireNonNull(endpoint, "'endpoint' cannot be null");
Configuration buildConfiguration = this.configuration;
if (buildConfiguration == null)
{
buildConfiguration = Configuration.get... | } | public DigitalTwinsAsyncClient buildAsyncClient() {
Objects.requireNonNull(tokenCredential, "'tokenCredential' cannot be null.");
Objects.requireNonNull(endpoint, "'endpoint' cannot be null");
Configuration buildConfiguration = this.configuration;
if (buildConfiguration == null)
{
buildConfiguration = Configuration.get... | class DigitalTwinsClientBuilder {
private static final Pattern ADT_PUBLIC_SCOPE_VALIDATION_PATTERN = Pattern.compile("(ppe|azure)\\.net");
private static final String[] ADT_PUBLIC_SCOPE = new String[]{"https:
private static final String DIGITAL_TWINS_PROPERTIES = "azure-digital-twins.properties";
private static final S... | class DigitalTwinsClientBuilder {
private static final Pattern ADT_PUBLIC_SCOPE_VALIDATION_PATTERN = Pattern.compile("(ppe|azure)\\.net");
private static final String[] ADT_PUBLIC_SCOPE = new String[]{"https:
private static final String DIGITAL_TWINS_PROPERTIES = "azure-digital-twins.properties";
private static final S... |
Do we know why? Is this more efficient, or is it the defined process? | public DigitalTwinsAsyncClient buildAsyncClient() {
Objects.requireNonNull(tokenCredential, "'tokenCredential' cannot be null.");
Objects.requireNonNull(endpoint, "'endpoint' cannot be null");
Configuration buildConfiguration = this.configuration;
if (buildConfiguration == null)
{
buildConfiguration = Configuration.get... | } | public DigitalTwinsAsyncClient buildAsyncClient() {
Objects.requireNonNull(tokenCredential, "'tokenCredential' cannot be null.");
Objects.requireNonNull(endpoint, "'endpoint' cannot be null");
Configuration buildConfiguration = this.configuration;
if (buildConfiguration == null)
{
buildConfiguration = Configuration.get... | class DigitalTwinsClientBuilder {
private static final Pattern ADT_PUBLIC_SCOPE_VALIDATION_PATTERN = Pattern.compile("(ppe|azure)\\.net");
private static final String[] ADT_PUBLIC_SCOPE = new String[]{"https:
private static final String DIGITAL_TWINS_PROPERTIES = "azure-digital-twins.properties";
private static final S... | class DigitalTwinsClientBuilder {
private static final Pattern ADT_PUBLIC_SCOPE_VALIDATION_PATTERN = Pattern.compile("(ppe|azure)\\.net");
private static final String[] ADT_PUBLIC_SCOPE = new String[]{"https:
private static final String DIGITAL_TWINS_PROPERTIES = "azure-digital-twins.properties";
private static final S... |
nit: not sure if we want to rename the sample file to reflect the change. | public static void main(String[] args) {
FormRecognizerClient client = new FormRecognizerClientBuilder()
.credential(new AzureKeyCredential("{key}"))
.endpoint("https:
.buildClient();
String modelId = "{model_Id}";
String formUrl = "{form_url}";
SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> recognizeF... | System.out.printf("------- Recognizing info on page %s of Form ------- %n", i1); | public static void main(String[] args) {
FormRecognizerClient client = new FormRecognizerClientBuilder()
.credential(new AzureKeyCredential("{key}"))
.endpoint("https:
.buildClient();
String modelId = "{model_Id}";
String formUrl = "{form_url}";
SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> recognizeF... | class GetBoundingBoxes {
/**
* Main method to invoke this demo.
*
* @param args Unused arguments to the program.
*/
} | class GetBoundingBoxes {
/**
* Main method to invoke this demo.
*
* @param args Unused arguments to the program.
*/
} |
Should we put `Pattern.compile("\\w+\\.\\w+/([^;]+);(\\d+)")` to a static, to save runtime cost to do it every time? | public ResourceManagerThrottlingInfo(HttpHeaders headers) {
commonRateLimits = new HashMap<>();
for (String header : COMMON_RATE_LIMIT_HEADERS) {
String value = headers.getValue(header);
if (value != null && !value.isEmpty()) {
commonRateLimits.put(header, value);
}
}
resourceRateLimit = headers.getValue(RESOURCE_RATE_... | Matcher matcher = Pattern.compile("\\w+\\.\\w+/([^;]+);(\\d+)").matcher(resourceRateLimit); | public ResourceManagerThrottlingInfo(HttpHeaders headers) {
commonRateLimits = new HashMap<>();
for (String header : COMMON_RATE_LIMIT_HEADERS) {
String value = headers.getValue(header);
if (value != null && !value.isEmpty()) {
commonRateLimits.put(header, value);
}
}
resourceRateLimit = headers.getValue(RESOURCE_RATE_... | class from response headers
* @param headers the response headers
*/ | class from response headers
* @param headers the response headers
*/ |
done | public ResourceManagerThrottlingInfo(HttpHeaders headers) {
commonRateLimits = new HashMap<>();
for (String header : COMMON_RATE_LIMIT_HEADERS) {
String value = headers.getValue(header);
if (value != null && !value.isEmpty()) {
commonRateLimits.put(header, value);
}
}
resourceRateLimit = headers.getValue(RESOURCE_RATE_... | Matcher matcher = Pattern.compile("\\w+\\.\\w+/([^;]+);(\\d+)").matcher(resourceRateLimit); | public ResourceManagerThrottlingInfo(HttpHeaders headers) {
commonRateLimits = new HashMap<>();
for (String header : COMMON_RATE_LIMIT_HEADERS) {
String value = headers.getValue(header);
if (value != null && !value.isEmpty()) {
commonRateLimits.put(header, value);
}
}
resourceRateLimit = headers.getValue(RESOURCE_RATE_... | class from response headers
* @param headers the response headers
*/ | class from response headers
* @param headers the response headers
*/ |
Is `Jdk8Module` is used for support `Optional` type in json? Can we use null instead of `Optional`? | private List<UserGroup> loadUserGroups(String graphApiToken) throws IOException {
String responseInJson = getUserMemberships(graphApiToken, Optional.empty());
final List<UserGroup> lUserGroups = new ArrayList<>();
final ObjectMapper objectMapper = JacksonObjectMapperFactory.getInstance();
objectMapper.registerModule(ne... | objectMapper.registerModule(new Jdk8Module()); | private List<UserGroup> loadUserGroups(String graphApiToken) throws IOException {
String responseInJson = getUserMemberships(graphApiToken, null);
final List<UserGroup> lUserGroups = new ArrayList<>();
final ObjectMapper objectMapper = JacksonObjectMapperFactory.getInstance();
UserGroups groupsFromJson = objectMapper.r... | class AzureADGraphClient {
private static final Logger LOGGER = LoggerFactory.getLogger(AzureADGraphClient.class);
private static final SimpleGrantedAuthority DEFAULT_AUTHORITY = new SimpleGrantedAuthority("ROLE_USER");
private static final String DEFAULT_ROLE_PREFIX = "ROLE_";
private static final String MICROSOFT_GRA... | class AzureADGraphClient {
private static final Logger LOGGER = LoggerFactory.getLogger(AzureADGraphClient.class);
private static final SimpleGrantedAuthority DEFAULT_AUTHORITY = new SimpleGrantedAuthority("ROLE_USER");
private static final String DEFAULT_ROLE_PREFIX = "ROLE_";
private static final String MICROSOFT_GRA... |
I debugged in my localhost, `groupsFromJson.getOdataNextLink()` will return `null`, not `Optional.empty()`, so `groupsFromJson.getOdataNextLink().isPresent()` will throw `NullPointerExceotion`. Json:  Screen... | private List<UserGroup> loadUserGroups(String graphApiToken) throws IOException {
String responseInJson = getUserMemberships(graphApiToken, Optional.empty());
final List<UserGroup> lUserGroups = new ArrayList<>();
final ObjectMapper objectMapper = JacksonObjectMapperFactory.getInstance();
objectMapper.registerModule(ne... | while (groupsFromJson.getOdataNextLink().isPresent()) { | private List<UserGroup> loadUserGroups(String graphApiToken) throws IOException {
String responseInJson = getUserMemberships(graphApiToken, null);
final List<UserGroup> lUserGroups = new ArrayList<>();
final ObjectMapper objectMapper = JacksonObjectMapperFactory.getInstance();
UserGroups groupsFromJson = objectMapper.r... | class AzureADGraphClient {
private static final Logger LOGGER = LoggerFactory.getLogger(AzureADGraphClient.class);
private static final SimpleGrantedAuthority DEFAULT_AUTHORITY = new SimpleGrantedAuthority("ROLE_USER");
private static final String DEFAULT_ROLE_PREFIX = "ROLE_";
private static final String MICROSOFT_GRA... | class AzureADGraphClient {
private static final Logger LOGGER = LoggerFactory.getLogger(AzureADGraphClient.class);
private static final SimpleGrantedAuthority DEFAULT_AUTHORITY = new SimpleGrantedAuthority("ROLE_USER");
private static final String DEFAULT_ROLE_PREFIX = "ROLE_";
private static final String MICROSOFT_GRA... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.