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 |
|---|---|---|---|---|---|
```suggestion // So it is okay to return an empty Flux. ``` | void loadBalance() {
/*
* Retrieve current partition ownership details from the datastore.
*/
final Mono<Map<String, PartitionOwnership>> partitionOwnershipMono = checkpointStore
.listOwnership(fullyQualifiedNamespace, eventHubName, consumerGroupName)
.timeout(Duration.ofMinutes(1))
.collectMap(PartitionOwnership::getP... | void loadBalance() {
/*
* Retrieve current partition ownership details from the datastore.
*/
final Mono<Map<String, PartitionOwnership>> partitionOwnershipMono = checkpointStore
.listOwnership(fullyQualifiedNamespace, eventHubName, consumerGroupName)
.timeout(Duration.ofMinutes(1))
.collectMap(PartitionOwnership::getP... | 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... | |
ideally you can use xml parser to get the path of the filed of interest anyway, not a big deal for a test and may not worth the time. Thank you. | private String getVersionFromPomFile() {
String fileName = "pom.xml";
String versionStartTag = "<version>";
String versionEndTag = "</version>";
File file = new File(fileName);
try {
BufferedReader bufferedReader = new BufferedReader(new FileReader(file));
String line;
while((line = bufferedReader.readLine()) != null) ... | try { | private String getVersionFromPomFile() {
String fileName = "pom.xml";
String versionStartTag = "<version>";
String versionEndTag = "</version>";
File file = new File(fileName);
try {
BufferedReader bufferedReader = new BufferedReader(new FileReader(file));
String line;
while((line = bufferedReader.readLine()) != null) ... | class AzureCosmosPropertiesTest {
@Test(groups = "unit")
public void verifyAzureCosmosProperties() {
Map<String, String> properties =
CoreUtils.getProperties(HttpConstants.Versions.AZURE_COSMOS_PROPERTIES_FILE_NAME);
assertThat(properties).isNotNull();
assertThat(properties).isNotEmpty();
assertThat(properties.get("ver... | class AzureCosmosPropertiesTest {
@Test(groups = "unit")
public void verifyAzureCosmosProperties() {
Map<String, String> properties =
CoreUtils.getProperties(HttpConstants.Versions.AZURE_COSMOS_PROPERTIES_FILE_NAME);
assertThat(properties).isNotNull();
assertThat(properties).isNotEmpty();
assertThat(properties.get("ver... |
Yeah, didn't want to add extra dependency :) but yes, I agree. We could use that. | private String getVersionFromPomFile() {
String fileName = "pom.xml";
String versionStartTag = "<version>";
String versionEndTag = "</version>";
File file = new File(fileName);
try {
BufferedReader bufferedReader = new BufferedReader(new FileReader(file));
String line;
while((line = bufferedReader.readLine()) != null) ... | try { | private String getVersionFromPomFile() {
String fileName = "pom.xml";
String versionStartTag = "<version>";
String versionEndTag = "</version>";
File file = new File(fileName);
try {
BufferedReader bufferedReader = new BufferedReader(new FileReader(file));
String line;
while((line = bufferedReader.readLine()) != null) ... | class AzureCosmosPropertiesTest {
@Test(groups = "unit")
public void verifyAzureCosmosProperties() {
Map<String, String> properties =
CoreUtils.getProperties(HttpConstants.Versions.AZURE_COSMOS_PROPERTIES_FILE_NAME);
assertThat(properties).isNotNull();
assertThat(properties).isNotEmpty();
assertThat(properties.get("ver... | class AzureCosmosPropertiesTest {
@Test(groups = "unit")
public void verifyAzureCosmosProperties() {
Map<String, String> properties =
CoreUtils.getProperties(HttpConstants.Versions.AZURE_COSMOS_PROPERTIES_FILE_NAME);
assertThat(properties).isNotNull();
assertThat(properties).isNotEmpty();
assertThat(properties.get("ver... |
This is cool. We do additional regex testing to test over the version format. | public void verifyProjectVersion() {
assertThat(HttpConstants.Versions.SDK_VERSION).isNotNull();
String pomFileVersion = getVersionFromPomFile();
assertThat(HttpConstants.Versions.SDK_VERSION).isEqualTo(pomFileVersion);
} | assertThat(HttpConstants.Versions.SDK_VERSION).isEqualTo(pomFileVersion); | public void verifyProjectVersion() {
assertThat(HttpConstants.Versions.SDK_VERSION).isNotNull();
String pomFileVersion = getVersionFromPomFile();
assertThat(HttpConstants.Versions.SDK_VERSION).isEqualTo(pomFileVersion);
} | class AzureCosmosPropertiesTest {
@Test(groups = "unit")
public void verifyAzureCosmosProperties() {
Map<String, String> properties =
CoreUtils.getProperties(HttpConstants.Versions.AZURE_COSMOS_PROPERTIES_FILE_NAME);
assertThat(properties).isNotNull();
assertThat(properties).isNotEmpty();
assertThat(properties.get("ver... | class AzureCosmosPropertiesTest {
@Test(groups = "unit")
public void verifyAzureCosmosProperties() {
Map<String, String> properties =
CoreUtils.getProperties(HttpConstants.Versions.AZURE_COSMOS_PROPERTIES_FILE_NAME);
assertThat(properties).isNotNull();
assertThat(properties).isNotEmpty();
assertThat(properties.get("ver... |
This recomputes the cmp, instead you can use signum | public int compare(OrderByRowResult<T> r1, OrderByRowResult<T> r2) {
try {
List<QueryItem> result1 = r1.getOrderByItems();
List<QueryItem> result2 = r2.getOrderByItems();
if (result1.size() != result2.size()) {
throw new IllegalStateException("OrderByItems cannot have different sizes.");
}
if (result1.size() != this.so... | return ItemComparator.getInstance().compare(result2.get(i).getItem(), result1.get(i).getItem()); | public int compare(OrderByRowResult<T> r1, OrderByRowResult<T> r2) {
try {
List<QueryItem> result1 = r1.getOrderByItems();
List<QueryItem> result2 = r2.getOrderByItems();
if (result1.size() != result2.size()) {
throw new IllegalStateException("OrderByItems cannot have different sizes.");
}
if (result1.size() != this.so... | class OrderbyRowComparer<T> implements Comparator<OrderByRowResult<T>>, Serializable {
private static final Logger logger = LoggerFactory.getLogger(OrderbyRowComparer.class);
private static final long serialVersionUID = 7296627879628897315L;
private final List<SortOrder> sortOrders;
private volatile List<ItemType> item... | class OrderbyRowComparer<T> implements Comparator<OrderByRowResult<T>>, Serializable {
private static final Logger logger = LoggerFactory.getLogger(OrderbyRowComparer.class);
private static final long serialVersionUID = 7296627879628897315L;
private final List<SortOrder> sortOrders;
private volatile List<ItemType> item... |
Yes, I was debating the same if I should recompute or use +1/-1. Using signum is a good idea. I've made the change. I've changed the Ascending case as well to keep the result consistent. Please let me know if the change looks good. | public int compare(OrderByRowResult<T> r1, OrderByRowResult<T> r2) {
try {
List<QueryItem> result1 = r1.getOrderByItems();
List<QueryItem> result2 = r2.getOrderByItems();
if (result1.size() != result2.size()) {
throw new IllegalStateException("OrderByItems cannot have different sizes.");
}
if (result1.size() != this.so... | return ItemComparator.getInstance().compare(result2.get(i).getItem(), result1.get(i).getItem()); | public int compare(OrderByRowResult<T> r1, OrderByRowResult<T> r2) {
try {
List<QueryItem> result1 = r1.getOrderByItems();
List<QueryItem> result2 = r2.getOrderByItems();
if (result1.size() != result2.size()) {
throw new IllegalStateException("OrderByItems cannot have different sizes.");
}
if (result1.size() != this.so... | class OrderbyRowComparer<T> implements Comparator<OrderByRowResult<T>>, Serializable {
private static final Logger logger = LoggerFactory.getLogger(OrderbyRowComparer.class);
private static final long serialVersionUID = 7296627879628897315L;
private final List<SortOrder> sortOrders;
private volatile List<ItemType> item... | class OrderbyRowComparer<T> implements Comparator<OrderByRowResult<T>>, Serializable {
private static final Logger logger = LoggerFactory.getLogger(OrderbyRowComparer.class);
private static final long serialVersionUID = 7296627879628897315L;
private final List<SortOrder> sortOrders;
private volatile List<ItemType> item... |
why do we need these overridden methods? the implementation is the same as parent class. | public Object get(String propertyName) {
return super.get(propertyName);
} | return super.get(propertyName); | public Object get(String propertyName) {
return super.get(propertyName);
} | class DatabaseAccount extends Resource {
private ConsistencyPolicy consistencyPolicy;
private long maxMediaStorageUsageInMB;
private long mediaStorageUsageInMB;
private ReplicationPolicy replicationPolicy;
private ReplicationPolicy systemReplicationPolicy;
private Map<String, Object> queryEngineConfiguration;
/**
* Con... | class DatabaseAccount extends Resource {
private ConsistencyPolicy consistencyPolicy;
private long maxMediaStorageUsageInMB;
private long mediaStorageUsageInMB;
private ReplicationPolicy replicationPolicy;
private ReplicationPolicy systemReplicationPolicy;
private Map<String, Object> queryEngineConfiguration;
/**
* Con... |
Javadoc missing for these methods. Also, look at other model classes in public package to ensure all of them have javadocs. | public Float getConfidence() {
return super.getConfidence();
} | return super.getConfidence(); | public Float getConfidence() {
return super.getConfidence();
} | class StringValue extends FieldValue<String> {
/*
* String value.
*/
private String valueString;
/**
* Constructs a StringValue.
*
* @param text The text content of the extracted field.
* @param boundingBox Bounding box of the field value.
* @param valueString String value.
*/
public StringValue(String text, BoundingBo... | class StringValue extends FieldValue<String> {
/*
* String value.
*/
private final String valueString;
/*
* Type of the FieldValue.
*/
private final FieldValueType fieldValueType;
/**
* Constructs a StringValue.
*
* @param text The text content of the extracted field.
* @param boundingBox Bounding box of the field valu... |
Let's move this above any other work | public FormRecognizerAsyncClient buildAsyncClient() {
final Configuration buildConfiguration = (configuration == null)
? Configuration.getGlobalConfiguration().clone() : configuration;
final FormRecognizerServiceVersion serviceVersion =
version != null ? version : FormRecognizerServiceVersion.getLatest();
Objects.requi... | Objects.requireNonNull(endpoint, "'Endpoint' is required and can not be null."); | public FormRecognizerAsyncClient buildAsyncClient() {
Objects.requireNonNull(endpoint, "'Endpoint' is required and can not be null.");
final Configuration buildConfiguration = (configuration == null)
? Configuration.getGlobalConfiguration().clone() : configuration;
final FormRecognizerServiceVersion serviceVersion =
ve... | class FormRecognizerClientBuilder {
private static final String ECHO_REQUEST_ID_HEADER = "x-ms-return-client-request-id";
private static final String CONTENT_TYPE_HEADER_VALUE = "application/json";
private static final String ACCEPT_HEADER = "Accept";
private static final String FORM_RECOGNIZER_PROPERTIES = "azure-ai-f... | class FormRecognizerClientBuilder {
private static final String ECHO_REQUEST_ID_HEADER = "x-ms-return-client-request-id";
private static final String CONTENT_TYPE_HEADER_VALUE = ContentType.APPLICATION_JSON;
private static final String ACCEPT_HEADER = "Accept";
private static final String FORM_RECOGNIZER_PROPERTIES = "... |
Should move this after the retry policy | public FormRecognizerAsyncClient buildAsyncClient() {
final Configuration buildConfiguration = (configuration == null)
? Configuration.getGlobalConfiguration().clone() : configuration;
final FormRecognizerServiceVersion serviceVersion =
version != null ? version : FormRecognizerServiceVersion.getLatest();
Objects.requi... | policies.add(new AddDatePolicy()); | public FormRecognizerAsyncClient buildAsyncClient() {
Objects.requireNonNull(endpoint, "'Endpoint' is required and can not be null.");
final Configuration buildConfiguration = (configuration == null)
? Configuration.getGlobalConfiguration().clone() : configuration;
final FormRecognizerServiceVersion serviceVersion =
ve... | class FormRecognizerClientBuilder {
private static final String ECHO_REQUEST_ID_HEADER = "x-ms-return-client-request-id";
private static final String CONTENT_TYPE_HEADER_VALUE = "application/json";
private static final String ACCEPT_HEADER = "Accept";
private static final String FORM_RECOGNIZER_PROPERTIES = "azure-ai-f... | class FormRecognizerClientBuilder {
private static final String ECHO_REQUEST_ID_HEADER = "x-ms-return-client-request-id";
private static final String CONTENT_TYPE_HEADER_VALUE = ContentType.APPLICATION_JSON;
private static final String ACCEPT_HEADER = "Accept";
private static final String FORM_RECOGNIZER_PROPERTIES = "... |
Is it likely that there will be additional keys added in the future? If so, what is the plan to ensure this remains up to date when changes are made? Is there any possibility this could be made more generic and flexible to support additional keys? | static IterableStream<ExtractedReceipt> toReceipt(AnalyzeResult analyzeResult, boolean includeTextDetails) {
List<ReadResult> readResults = analyzeResult.getReadResults();
List<DocumentResult> documentResult = analyzeResult.getDocumentResults();
List<ExtractedReceipt> extractedReceiptList = new ArrayList<>();
for (int ... | break; | static IterableStream<ExtractedReceipt> toReceipt(AnalyzeResult analyzeResult, boolean includeTextDetails) {
List<ReadResult> readResults = analyzeResult.getReadResults();
List<DocumentResult> documentResult = analyzeResult.getDocumentResults();
List<ExtractedReceipt> extractedReceiptList = new ArrayList<>();
for (int ... | class Transforms {
private static final ClientLogger LOGGER = new ClientLogger(Transforms.class);
private static final Pattern COMPILE = Pattern.compile("[^0-9]+");
private Transforms() {
}
private static FieldValue<?> setFieldValue(com.azure.ai.formrecognizer.implementation.models.FieldValue fieldValue,
List<ReadResul... | class Transforms {
private static final ClientLogger LOGGER = new ClientLogger(Transforms.class);
private static final Pattern COMPILE = Pattern.compile("[^0-9]+");
private Transforms() {
}
/**
* Helper method to convert the {@link com.azure.ai.formrecognizer.implementation.models.AnalyzeOperationResult}
* service leve... |
Do we want to convert the entire `InputStream` to a `ByteBuffer` in a single go or should this be chunked as downstream requests more elements? Could we have scenarios where a large file is being read that wouldn't fit into memory? | private static ByteBuffer toByteArray(InputStream in) throws IOException {
ByteArrayOutputStream os = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len;
while ((len = in.read(buffer)) != -1) {
os.write(buffer, 0, len);
}
return ByteBuffer.wrap(os.toByteArray());
} | } | private static ByteBuffer toByteArray(InputStream in) {
try {
ByteArrayOutputStream os = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len;
while ((len = in.read(buffer)) != -1) {
os.write(buffer, 0, len);
}
return ByteBuffer.wrap(os.toByteArray());
} catch (IOException e) {
throw LOGGER.logException... | class Utility {
private static final ClientLogger LOGGER = new ClientLogger(Utility.class);
/**
* A utility method for converting the input stream to Flux of ByteBuffer.
*
* @param data The input data which needs to convert to ByteBuffer.
*
* @return {@link ByteBuffer} which contains the input data.
* @throws RuntimeEx... | class Utility {
private static final ClientLogger LOGGER = new ClientLogger(Utility.class);
private Utility() {
}
/**
* A utility method for converting the input stream to Flux of ByteBuffer.
*
* @param data The input data which needs to convert to ByteBuffer.
*
* @return {@link ByteBuffer} which contains the input dat... |
Should put in a fake key, this will throw an exception. | public static void main(final String[] args) {
final FormRecognizerAsyncClient client = new FormRecognizerClientBuilder()
.apiKey(new AzureKeyCredential(""))
.endpoint("https:
.buildAsyncClient();
String receiptUrl = "https:
PollerFlux<OperationResult, IterableStream<ExtractedReceipt>> analyzeReceiptPoller =
client.beg... | .apiKey(new AzureKeyCredential("")) | public static void main(final String[] args) {
FormRecognizerAsyncClient client = new FormRecognizerClientBuilder()
.apiKey(new AzureKeyCredential("{api_key}"))
.endpoint("https:
.buildAsyncClient();
String receiptUrl = "https:
PollerFlux<OperationResult, IterableStream<ExtractedReceipt>> analyzeReceiptPoller =
client.... | class ExtractPrebuiltReceiptAsync {
} | class ExtractPrebuiltReceiptAsync {
/**
* Sample for extracting receipt information using input stream.
*
* @param args Unused. Arguments to the program.
*/
} |
Why do we sleep here for 20 seconds? The captured `trainingOperationResponse` won't change during the sleep period. | public static void main(final String[] args) {
final FormRecognizerAsyncClient client = new FormRecognizerClientBuilder()
.apiKey(new AzureKeyCredential(""))
.endpoint("https:
.buildAsyncClient();
String receiptUrl = "https:
PollerFlux<OperationResult, IterableStream<ExtractedReceipt>> analyzeReceiptPoller =
client.beg... | Thread.sleep(20000); | public static void main(final String[] args) {
FormRecognizerAsyncClient client = new FormRecognizerClientBuilder()
.apiKey(new AzureKeyCredential("{api_key}"))
.endpoint("https:
.buildAsyncClient();
String receiptUrl = "https:
PollerFlux<OperationResult, IterableStream<ExtractedReceipt>> analyzeReceiptPoller =
client.... | class ExtractPrebuiltReceiptAsync {
} | class ExtractPrebuiltReceiptAsync {
/**
* Sample for extracting receipt information using input stream.
*
* @param args Unused. Arguments to the program.
*/
} |
Will discuss offline on this one with you. | public Mono<CosmosAsyncUserDefinedFunctionResponse> replace(CosmosUserDefinedFunctionProperties udfSettings) {
return container.getDatabase()
.getDocClientWrapper()
.replaceUserDefinedFunction(new UserDefinedFunction(ModelBridgeInternal.toJsonFromJsonSerializable(udfSettings)), null)
.map(response -> ModelBridgeInterna... | .replaceUserDefinedFunction(new UserDefinedFunction(ModelBridgeInternal.toJsonFromJsonSerializable(udfSettings)), null) | public Mono<CosmosAsyncUserDefinedFunctionResponse> replace(CosmosUserDefinedFunctionProperties udfSettings) {
return container.getDatabase()
.getDocClientWrapper()
.replaceUserDefinedFunction(new UserDefinedFunction(ModelBridgeInternal.toJsonFromJsonSerializable(udfSettings)), null)
.map(response -> ModelBridgeInterna... | class CosmosAsyncUserDefinedFunction {
@SuppressWarnings("EnforceFinalFields")
private final CosmosAsyncContainer container;
private String id;
CosmosAsyncUserDefinedFunction(String id, CosmosAsyncContainer container) {
this.id = id;
this.container = container;
}
/**
* Get the id of the {@link CosmosAsyncUserDefinedFun... | class CosmosAsyncUserDefinedFunction {
@SuppressWarnings("EnforceFinalFields")
private final CosmosAsyncContainer container;
private String id;
CosmosAsyncUserDefinedFunction(String id, CosmosAsyncContainer container) {
this.id = id;
this.container = container;
}
/**
* Get the id of the {@link CosmosAsyncUserDefinedFun... |
This could be injected into the `flatMap` lambda. | public static void main(final String[] args) {
final FormRecognizerAsyncClient client = new FormRecognizerClientBuilder()
.apiKey(new AzureKeyCredential(""))
.endpoint("https:
.buildAsyncClient();
String receiptUrl = "https:
PollerFlux<OperationResult, IterableStream<ExtractedReceipt>> analyzeReceiptPoller =
client.beg... | for (ExtractedReceipt extractedReceiptItem : receiptPageResults) { | public static void main(final String[] args) {
FormRecognizerAsyncClient client = new FormRecognizerClientBuilder()
.apiKey(new AzureKeyCredential("{api_key}"))
.endpoint("https:
.buildAsyncClient();
String receiptUrl = "https:
PollerFlux<OperationResult, IterableStream<ExtractedReceipt>> analyzeReceiptPoller =
client.... | class ExtractPrebuiltReceiptAsync {
} | class ExtractPrebuiltReceiptAsync {
/**
* Sample for extracting receipt information using input stream.
*
* @param args Unused. Arguments to the program.
*/
} |
Should put in a fake key, this will throw an exception. | public static void main(final String[] args) throws IOException {
final FormRecognizerClient client = new FormRecognizerClientBuilder()
.apiKey(new AzureKeyCredential(""))
.endpoint("https:
.buildClient();
File sourceFile = new File("
byte[] fileContent = Files.readAllBytes(sourceFile.toPath());
InputStream targetStrea... | .apiKey(new AzureKeyCredential("")) | public static void main(final String[] args) throws IOException {
FormRecognizerClient client = new FormRecognizerClientBuilder()
.apiKey(new AzureKeyCredential("{api_key}"))
.endpoint("https:
.buildClient();
File sourceFile = new File("
byte[] fileContent = Files.readAllBytes(sourceFile.toPath());
InputStream targetSt... | class ExtractPrebuiltReceiptSync {
/**
* Sample for extracting receipt information using input stream.
*
* @param args Unused. Arguments to the program.
* @throws IOException Exception thrown when there is an error in reading all the bytes from the File.
*/
} | class ExtractPrebuiltReceiptSync {
/**
* Sample for extracting receipt information using input stream.
*
* @param args Unused. Arguments to the program.
* @throws IOException Exception thrown when there is an error in reading all the bytes from the File.
*/
} |
As this being a trained model, it would be unlikely to have additional keys or to expect this to be updated very often. Further, for any new introductions from the service side to keep this up to date this will have to go through updates accordingly. Also, with such specific string matching, I am not sure how we could ... | static IterableStream<ExtractedReceipt> toReceipt(AnalyzeResult analyzeResult, boolean includeTextDetails) {
List<ReadResult> readResults = analyzeResult.getReadResults();
List<DocumentResult> documentResult = analyzeResult.getDocumentResults();
List<ExtractedReceipt> extractedReceiptList = new ArrayList<>();
for (int ... | break; | static IterableStream<ExtractedReceipt> toReceipt(AnalyzeResult analyzeResult, boolean includeTextDetails) {
List<ReadResult> readResults = analyzeResult.getReadResults();
List<DocumentResult> documentResult = analyzeResult.getDocumentResults();
List<ExtractedReceipt> extractedReceiptList = new ArrayList<>();
for (int ... | class Transforms {
private static final ClientLogger LOGGER = new ClientLogger(Transforms.class);
private static final Pattern COMPILE = Pattern.compile("[^0-9]+");
private Transforms() {
}
private static FieldValue<?> setFieldValue(com.azure.ai.formrecognizer.implementation.models.FieldValue fieldValue,
List<ReadResul... | class Transforms {
private static final ClientLogger LOGGER = new ClientLogger(Transforms.class);
private static final Pattern COMPILE = Pattern.compile("[^0-9]+");
private Transforms() {
}
/**
* Helper method to convert the {@link com.azure.ai.formrecognizer.implementation.models.AnalyzeOperationResult}
* service leve... |
I have added a separate issue to track this #9690 And if it helps, the service docs do mention a size limit specification >Image file size must be less than 20 MB. I will also add it to our javadocs. | private static ByteBuffer toByteArray(InputStream in) throws IOException {
ByteArrayOutputStream os = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len;
while ((len = in.read(buffer)) != -1) {
os.write(buffer, 0, len);
}
return ByteBuffer.wrap(os.toByteArray());
} | } | private static ByteBuffer toByteArray(InputStream in) {
try {
ByteArrayOutputStream os = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len;
while ((len = in.read(buffer)) != -1) {
os.write(buffer, 0, len);
}
return ByteBuffer.wrap(os.toByteArray());
} catch (IOException e) {
throw LOGGER.logException... | class Utility {
private static final ClientLogger LOGGER = new ClientLogger(Utility.class);
/**
* A utility method for converting the input stream to Flux of ByteBuffer.
*
* @param data The input data which needs to convert to ByteBuffer.
*
* @return {@link ByteBuffer} which contains the input data.
* @throws RuntimeEx... | class Utility {
private static final ClientLogger LOGGER = new ClientLogger(Utility.class);
private Utility() {
}
/**
* A utility method for converting the input stream to Flux of ByteBuffer.
*
* @param data The input data which needs to convert to ByteBuffer.
*
* @return {@link ByteBuffer} which contains the input dat... |
If these keys are not going to be updated frequently, can this be an ExpandableStringEnum? | static IterableStream<ExtractedReceipt> toReceipt(AnalyzeResult analyzeResult, boolean includeTextDetails) {
List<ReadResult> readResults = analyzeResult.getReadResults();
List<DocumentResult> documentResult = analyzeResult.getDocumentResults();
List<ExtractedReceipt> extractedReceiptList = new ArrayList<>();
for (int ... | break; | static IterableStream<ExtractedReceipt> toReceipt(AnalyzeResult analyzeResult, boolean includeTextDetails) {
List<ReadResult> readResults = analyzeResult.getReadResults();
List<DocumentResult> documentResult = analyzeResult.getDocumentResults();
List<ExtractedReceipt> extractedReceiptList = new ArrayList<>();
for (int ... | class Transforms {
private static final ClientLogger LOGGER = new ClientLogger(Transforms.class);
private static final Pattern COMPILE = Pattern.compile("[^0-9]+");
private Transforms() {
}
private static FieldValue<?> setFieldValue(com.azure.ai.formrecognizer.implementation.models.FieldValue fieldValue,
List<ReadResul... | class Transforms {
private static final ClientLogger LOGGER = new ClientLogger(Transforms.class);
private static final Pattern COMPILE = Pattern.compile("[^0-9]+");
private Transforms() {
}
/**
* Helper method to convert the {@link com.azure.ai.formrecognizer.implementation.models.AnalyzeOperationResult}
* service leve... |
Instead of silently skipping over unknown keys, if the known set of keys are limited and new keys are not added frequently, this should throw an exception when the key is unknown. And when a new key is added, it should be accompanied by a service version update too right? | static IterableStream<ExtractedReceipt> toReceipt(AnalyzeResult analyzeResult, boolean includeTextDetails) {
List<ReadResult> readResults = analyzeResult.getReadResults();
List<DocumentResult> documentResult = analyzeResult.getDocumentResults();
List<ExtractedReceipt> extractedReceiptList = new ArrayList<>();
for (int ... | break; | static IterableStream<ExtractedReceipt> toReceipt(AnalyzeResult analyzeResult, boolean includeTextDetails) {
List<ReadResult> readResults = analyzeResult.getReadResults();
List<DocumentResult> documentResult = analyzeResult.getDocumentResults();
List<ExtractedReceipt> extractedReceiptList = new ArrayList<>();
for (int ... | class Transforms {
private static final ClientLogger LOGGER = new ClientLogger(Transforms.class);
private static final Pattern COMPILE = Pattern.compile("[^0-9]+");
private Transforms() {
}
/**
* Helper method to convert the {@link com.azure.ai.formrecognizer.implementation.models.AnalyzeOperationResult}
* service leve... | class Transforms {
private static final ClientLogger LOGGER = new ClientLogger(Transforms.class);
private static final Pattern COMPILE = Pattern.compile("[^0-9]+");
private Transforms() {
}
/**
* Helper method to convert the {@link com.azure.ai.formrecognizer.implementation.models.AnalyzeOperationResult}
* service leve... |
outside of scope of this PR. we can come back to this later. I fixed double serialization for point read item operation but not the udf, etc. | public Mono<CosmosAsyncUserDefinedFunctionResponse> replace(CosmosUserDefinedFunctionProperties udfSettings) {
return container.getDatabase()
.getDocClientWrapper()
.replaceUserDefinedFunction(new UserDefinedFunction(ModelBridgeInternal.toJsonFromJsonSerializable(udfSettings)), null)
.map(response -> ModelBridgeInterna... | .replaceUserDefinedFunction(new UserDefinedFunction(ModelBridgeInternal.toJsonFromJsonSerializable(udfSettings)), null) | public Mono<CosmosAsyncUserDefinedFunctionResponse> replace(CosmosUserDefinedFunctionProperties udfSettings) {
return container.getDatabase()
.getDocClientWrapper()
.replaceUserDefinedFunction(new UserDefinedFunction(ModelBridgeInternal.toJsonFromJsonSerializable(udfSettings)), null)
.map(response -> ModelBridgeInterna... | class CosmosAsyncUserDefinedFunction {
@SuppressWarnings("EnforceFinalFields")
private final CosmosAsyncContainer container;
private String id;
CosmosAsyncUserDefinedFunction(String id, CosmosAsyncContainer container) {
this.id = id;
this.container = container;
}
/**
* Get the id of the {@link CosmosAsyncUserDefinedFun... | class CosmosAsyncUserDefinedFunction {
@SuppressWarnings("EnforceFinalFields")
private final CosmosAsyncContainer container;
private String id;
CosmosAsyncUserDefinedFunction(String id, CosmosAsyncContainer container) {
this.id = id;
this.container = container;
}
/**
* Get the id of the {@link CosmosAsyncUserDefinedFun... |
The service will only accept files of 20MB, so anything larger is an exception, but nothing is stopping me from sends a 2GB file by accident. | private static ByteBuffer toByteArray(InputStream in) throws IOException {
ByteArrayOutputStream os = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len;
while ((len = in.read(buffer)) != -1) {
os.write(buffer, 0, len);
}
return ByteBuffer.wrap(os.toByteArray());
} | } | private static ByteBuffer toByteArray(InputStream in) {
try {
ByteArrayOutputStream os = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len;
while ((len = in.read(buffer)) != -1) {
os.write(buffer, 0, len);
}
return ByteBuffer.wrap(os.toByteArray());
} catch (IOException e) {
throw LOGGER.logException... | class Utility {
private static final ClientLogger LOGGER = new ClientLogger(Utility.class);
/**
* A utility method for converting the input stream to Flux of ByteBuffer.
*
* @param data The input data which needs to convert to ByteBuffer.
*
* @return {@link ByteBuffer} which contains the input data.
* @throws RuntimeEx... | class Utility {
private static final ClientLogger LOGGER = new ClientLogger(Utility.class);
private Utility() {
}
/**
* A utility method for converting the input stream to Flux of ByteBuffer.
*
* @param data The input data which needs to convert to ByteBuffer.
*
* @return {@link ByteBuffer} which contains the input dat... |
Updating this implementation in #9690 | private static ByteBuffer toByteArray(InputStream in) throws IOException {
ByteArrayOutputStream os = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len;
while ((len = in.read(buffer)) != -1) {
os.write(buffer, 0, len);
}
return ByteBuffer.wrap(os.toByteArray());
} | } | private static ByteBuffer toByteArray(InputStream in) {
try {
ByteArrayOutputStream os = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len;
while ((len = in.read(buffer)) != -1) {
os.write(buffer, 0, len);
}
return ByteBuffer.wrap(os.toByteArray());
} catch (IOException e) {
throw LOGGER.logException... | class Utility {
private static final ClientLogger LOGGER = new ClientLogger(Utility.class);
/**
* A utility method for converting the input stream to Flux of ByteBuffer.
*
* @param data The input data which needs to convert to ByteBuffer.
*
* @return {@link ByteBuffer} which contains the input data.
* @throws RuntimeEx... | class Utility {
private static final ClientLogger LOGGER = new ClientLogger(Utility.class);
private Utility() {
}
/**
* A utility method for converting the input stream to Flux of ByteBuffer.
*
* @param data The input data which needs to convert to ByteBuffer.
*
* @return {@link ByteBuffer} which contains the input dat... |
The leftover keys would be put in a `Map<String, FieldValue> extractedFields` to still be able to capture them and not ignore. >if the known set of keys are limited and new keys are not added frequently. The service currently wants to have the ability to add fields in between service updates. These would be made avai... | static IterableStream<ExtractedReceipt> toReceipt(AnalyzeResult analyzeResult, boolean includeTextDetails) {
List<ReadResult> readResults = analyzeResult.getReadResults();
List<DocumentResult> documentResult = analyzeResult.getDocumentResults();
List<ExtractedReceipt> extractedReceiptList = new ArrayList<>();
for (int ... | break; | static IterableStream<ExtractedReceipt> toReceipt(AnalyzeResult analyzeResult, boolean includeTextDetails) {
List<ReadResult> readResults = analyzeResult.getReadResults();
List<DocumentResult> documentResult = analyzeResult.getDocumentResults();
List<ExtractedReceipt> extractedReceiptList = new ArrayList<>();
for (int ... | class Transforms {
private static final ClientLogger LOGGER = new ClientLogger(Transforms.class);
private static final Pattern COMPILE = Pattern.compile("[^0-9]+");
private Transforms() {
}
/**
* Helper method to convert the {@link com.azure.ai.formrecognizer.implementation.models.AnalyzeOperationResult}
* service leve... | class Transforms {
private static final ClientLogger LOGGER = new ClientLogger(Transforms.class);
private static final Pattern COMPILE = Pattern.compile("[^0-9]+");
private Transforms() {
}
/**
* Helper method to convert the {@link com.azure.ai.formrecognizer.implementation.models.AnalyzeOperationResult}
* service leve... |
Can the keys be converted to expandable enums? | static IterableStream<ExtractedReceipt> toReceipt(AnalyzeResult analyzeResult, boolean includeTextDetails) {
List<ReadResult> readResults = analyzeResult.getReadResults();
List<DocumentResult> documentResult = analyzeResult.getDocumentResults();
List<ExtractedReceipt> extractedReceiptList = new ArrayList<>();
for (int ... | break; | static IterableStream<ExtractedReceipt> toReceipt(AnalyzeResult analyzeResult, boolean includeTextDetails) {
List<ReadResult> readResults = analyzeResult.getReadResults();
List<DocumentResult> documentResult = analyzeResult.getDocumentResults();
List<ExtractedReceipt> extractedReceiptList = new ArrayList<>();
for (int ... | class Transforms {
private static final ClientLogger LOGGER = new ClientLogger(Transforms.class);
private static final Pattern COMPILE = Pattern.compile("[^0-9]+");
private Transforms() {
}
private static FieldValue<?> setFieldValue(com.azure.ai.formrecognizer.implementation.models.FieldValue fieldValue,
List<ReadResul... | class Transforms {
private static final ClientLogger LOGGER = new ClientLogger(Transforms.class);
private static final Pattern COMPILE = Pattern.compile("[^0-9]+");
private Transforms() {
}
/**
* Helper method to convert the {@link com.azure.ai.formrecognizer.implementation.models.AnalyzeOperationResult}
* service leve... |
ditto, here and other places for the new methods, the implementation is the same as parent class why are they needed in every child class? | public String getString(String propertyName) {
return super.getString(propertyName);
} | return super.getString(propertyName); | public String getString(String propertyName) {
return super.getString(propertyName);
} | class Offer extends Resource {
/**
* Initialize an new instance of the Offer object.
*
* @param offerThroughput the throughput value for this offer.
*/
public Offer(int offerThroughput) {
super();
this.setOfferVersion(Constants.Properties.OFFER_VERSION_V2);
this.setOfferType("");
ObjectNode content = Utils.getSimpleObj... | class Offer extends Resource {
/**
* Initialize an new instance of the Offer object.
*
* @param offerThroughput the throughput value for this offer.
*/
public Offer(int offerThroughput) {
super();
this.setOfferVersion(Constants.Properties.OFFER_VERSION_V2);
this.setOfferType("");
ObjectNode content = Utils.getSimpleObj... |
ditto | public String toJson() {
return super.toJson();
} | return super.toJson(); | public String toJson() {
return super.toJson();
} | class PartitionKeyRange extends Resource {
public static final String MINIMUM_INCLUSIVE_EFFECTIVE_PARTITION_KEY = "";
public static final String MAXIMUM_EXCLUSIVE_EFFECTIVE_PARTITION_KEY = "FF";
public static final String MASTER_PARTITION_KEY_RANGE_ID = "M";
/**
* Constructor.
*
* @param objectNode the {@link ObjectNod... | class PartitionKeyRange extends Resource {
public static final String MINIMUM_INCLUSIVE_EFFECTIVE_PARTITION_KEY = "";
public static final String MAXIMUM_EXCLUSIVE_EFFECTIVE_PARTITION_KEY = "FF";
public static final String MASTER_PARTITION_KEY_RANGE_ID = "M";
/**
* Constructor.
*
* @param objectNode the {@link ObjectNod... |
ditto | public Object get(String propertyName) {
return super.get(propertyName);
} | return super.get(propertyName); | public Object get(String propertyName) {
return super.get(propertyName);
} | class Address extends Resource {
/**
* Constructor.
*
* @param objectNode the {@link ObjectNode} that represent the
* {@link JsonSerializable}
*/
public Address(ObjectNode objectNode) {
super(objectNode);
}
/**
* Initialize an offer object.
*/
public Address() {
super();
}
/**
* Initialize an address object from json s... | class Address extends Resource {
/**
* Constructor.
*
* @param objectNode the {@link ObjectNode} that represent the
* {@link JsonSerializable}
*/
public Address(ObjectNode objectNode) {
super(objectNode);
}
/**
* Initialize an offer object.
*/
public Address() {
super();
}
/**
* Initialize an address object from json s... |
discussed offline. | public Object get(String propertyName) {
return super.get(propertyName);
} | return super.get(propertyName); | public Object get(String propertyName) {
return super.get(propertyName);
} | class DatabaseAccount extends Resource {
private ConsistencyPolicy consistencyPolicy;
private long maxMediaStorageUsageInMB;
private long mediaStorageUsageInMB;
private ReplicationPolicy replicationPolicy;
private ReplicationPolicy systemReplicationPolicy;
private Map<String, Object> queryEngineConfiguration;
/**
* Con... | class DatabaseAccount extends Resource {
private ConsistencyPolicy consistencyPolicy;
private long maxMediaStorageUsageInMB;
private long mediaStorageUsageInMB;
private ReplicationPolicy replicationPolicy;
private ReplicationPolicy systemReplicationPolicy;
private Map<String, Object> queryEngineConfiguration;
/**
* Con... |
(Could be out of scope of this PR) Potential double serialization. Instead of converting toJson and again back from Json, we could just use the propertybag to get UDF by using Resource(ObjectNode) overload. | public Mono<CosmosAsyncUserDefinedFunctionResponse> replace(CosmosUserDefinedFunctionProperties udfSettings) {
return container.getDatabase()
.getDocClientWrapper()
.replaceUserDefinedFunction(new UserDefinedFunction(ModelBridgeInternal.toJsonFromJsonSerializable(udfSettings)), null)
.map(response -> ModelBridgeInterna... | .replaceUserDefinedFunction(new UserDefinedFunction(ModelBridgeInternal.toJsonFromJsonSerializable(udfSettings)), null) | public Mono<CosmosAsyncUserDefinedFunctionResponse> replace(CosmosUserDefinedFunctionProperties udfSettings) {
return container.getDatabase()
.getDocClientWrapper()
.replaceUserDefinedFunction(new UserDefinedFunction(ModelBridgeInternal.toJsonFromJsonSerializable(udfSettings)), null)
.map(response -> ModelBridgeInterna... | class CosmosAsyncUserDefinedFunction {
@SuppressWarnings("EnforceFinalFields")
private final CosmosAsyncContainer container;
private String id;
CosmosAsyncUserDefinedFunction(String id, CosmosAsyncContainer container) {
this.id = id;
this.container = container;
}
/**
* Get the id of the {@link CosmosAsyncUserDefinedFun... | class CosmosAsyncUserDefinedFunction {
@SuppressWarnings("EnforceFinalFields")
private final CosmosAsyncContainer container;
private String id;
CosmosAsyncUserDefinedFunction(String id, CosmosAsyncContainer container) {
this.id = id;
this.container = container;
}
/**
* Get the id of the {@link CosmosAsyncUserDefinedFun... |
nit: use `final` | return isAuthorized(RECEIVE_BY_SEQUENCE_NUMBER_OPERATION).thenMany(createRequestResponse.flatMap(channel -> {
final Message message = createManagementMessage(RECEIVE_BY_SEQUENCE_NUMBER_OPERATION,
channel.getReceiveLinkName());
HashMap<String, Object> requestBodyMap = new HashMap<>();
requestBodyMap.put(SEQUENCE_NUMBERS... | HashMap<String, Object> requestBodyMap = new HashMap<>(); | return isAuthorized(RECEIVE_BY_SEQUENCE_NUMBER_OPERATION).thenMany(createRequestResponse.flatMap(channel -> {
final Message message = createManagementMessage(RECEIVE_BY_SEQUENCE_NUMBER_OPERATION,
channel.getReceiveLinkName());
HashMap<String, Object> requestBodyMap = new HashMap<>();
requestBodyMap.put(SEQUENCE_NUMBERS... | class ManagementChannel implements ServiceBusManagementNode {
private final Scheduler scheduler;
private final MessageSerializer messageSerializer;
private final TokenManager tokenManager;
private final Duration operationTimeout;
private final Mono<RequestResponseChannel> createRequestResponse;
private final String ful... | class ManagementChannel implements ServiceBusManagementNode {
private final Scheduler scheduler;
private final MessageSerializer messageSerializer;
private final TokenManager tokenManager;
private final Duration operationTimeout;
private final Mono<RequestResponseChannel> createRequestResponse;
private final String ful... |
Should we have a timeout? | public Mono<AccessToken> authenticateWithAzureCli(TokenRequestContext request) {
String azCommand = "az account get-access-token --output json --resource ";
StringBuilder command = new StringBuilder();
command.append(azCommand);
String scopes = ScopeUtil.scopesToResource(request.getScopes());
try {
ScopeUtil.validateSc... | process.waitFor(); | public Mono<AccessToken> authenticateWithAzureCli(TokenRequestContext request) {
String azCommand = "az account get-access-token --output json --resource ";
StringBuilder command = new StringBuilder();
command.append(azCommand);
String scopes = ScopeUtil.scopesToResource(request.getScopes());
try {
ScopeUtil.validateSc... | class IdentityClient {
private static final SerializerAdapter SERIALIZER_ADAPTER = JacksonAdapter.createDefaultSerializerAdapter();
private static final Random RANDOM = new Random();
private static final String WINDOWS_STARTER = "cmd.exe";
private static final String LINUX_MAC_STARTER = "/bin/sh";
private static final ... | class IdentityClient {
private static final SerializerAdapter SERIALIZER_ADAPTER = JacksonAdapter.createDefaultSerializerAdapter();
private static final Random RANDOM = new Random();
private static final String WINDOWS_STARTER = "cmd.exe";
private static final String LINUX_MAC_STARTER = "/bin/sh";
private static final ... |
Where is the case with multiple numbers? | void receiveDeferredWithSequenceOneMessage() {
final int fromSequenceNumber = 10;
final ServiceBusReceivedMessage receivedMessage = mock(ServiceBusReceivedMessage.class);
when(managementNode.receiveDeferredMessage(receiveOptions.getReceiveMode(), fromSequenceNumber)).thenReturn(Mono.just(receivedMessage));
StepVerifier... | StepVerifier.create(consumer.receiveDeferredMessage(fromSequenceNumber)) | void receiveDeferredWithSequenceOneMessage() {
final int fromSequenceNumber = 10;
final ServiceBusReceivedMessage receivedMessage = mock(ServiceBusReceivedMessage.class);
when(managementNode.receiveDeferredMessage(receiveOptions.getReceiveMode(), fromSequenceNumber)).thenReturn(Mono.just(receivedMessage));
StepVerifier... | class ServiceBusReceiverAsyncClientTest {
private static final String PAYLOAD = "hello";
private static final byte[] PAYLOAD_BYTES = PAYLOAD.getBytes(UTF_8);
private static final int PREFETCH = 5;
private static final String NAMESPACE = "my-namespace-foo";
private static final String ENTITY_PATH = "queue-name";
private... | class ServiceBusReceiverAsyncClientTest {
private static final String PAYLOAD = "hello";
private static final byte[] PAYLOAD_BYTES = PAYLOAD.getBytes(UTF_8);
private static final int PREFETCH = 5;
private static final String NAMESPACE = "my-namespace-foo";
private static final String ENTITY_PATH = "queue-name";
private... |
* It would be easier to create a static default_dead_letter_options and then pass the arguments in, so that we don't do this extra logic if it is null. | public Mono<Void> deadLetter(ServiceBusReceivedMessage message, DeadLetterOptions deadLetterOptions) {
if (deadLetterOptions != null) {
return updateDisposition(message, DispositionStatus.SUSPENDED, deadLetterOptions.getDeadLetterReason(),
deadLetterOptions.getDeadLetterErrorDescription(), deadLetterOptions.getProperti... | if (deadLetterOptions != null) { | public Mono<Void> deadLetter(ServiceBusReceivedMessage message, DeadLetterOptions deadLetterOptions) {
Objects.requireNonNull(deadLetterOptions, "'deadLetterOptions' cannot be null.");
return updateDisposition(message, DispositionStatus.SUSPENDED, deadLetterOptions.getDeadLetterReason(),
deadLetterOptions.getDeadLetter... | class ServiceBusReceiverAsyncClient implements Closeable {
private final AtomicBoolean isDisposed = new AtomicBoolean();
private final ClientLogger logger = new ClientLogger(ServiceBusReceiverAsyncClient.class);
private final ConcurrentHashMap<UUID, Instant> lockTokenExpirationMap = new ConcurrentHashMap<>();
private f... | class ServiceBusReceiverAsyncClient implements Closeable {
private static final DeadLetterOptions DEFAULT_DEAD_LETTER_OPTIONS = new DeadLetterOptions();
private final AtomicBoolean isDisposed = new AtomicBoolean();
private final ClientLogger logger = new ClientLogger(ServiceBusReceiverAsyncClient.class);
private final... |
Since this is an optional parameter, I expected another overload that just takes the received message and under the covers would pass default_dead_letter_options, that way we can do a null object assertion in this method. | public Mono<Void> deadLetter(ServiceBusReceivedMessage message, DeadLetterOptions deadLetterOptions) {
if (deadLetterOptions != null) {
return updateDisposition(message, DispositionStatus.SUSPENDED, deadLetterOptions.getDeadLetterReason(),
deadLetterOptions.getDeadLetterErrorDescription(), deadLetterOptions.getProperti... | if (deadLetterOptions != null) { | public Mono<Void> deadLetter(ServiceBusReceivedMessage message, DeadLetterOptions deadLetterOptions) {
Objects.requireNonNull(deadLetterOptions, "'deadLetterOptions' cannot be null.");
return updateDisposition(message, DispositionStatus.SUSPENDED, deadLetterOptions.getDeadLetterReason(),
deadLetterOptions.getDeadLetter... | class ServiceBusReceiverAsyncClient implements Closeable {
private final AtomicBoolean isDisposed = new AtomicBoolean();
private final ClientLogger logger = new ClientLogger(ServiceBusReceiverAsyncClient.class);
private final ConcurrentHashMap<UUID, Instant> lockTokenExpirationMap = new ConcurrentHashMap<>();
private f... | class ServiceBusReceiverAsyncClient implements Closeable {
private static final DeadLetterOptions DEFAULT_DEAD_LETTER_OPTIONS = new DeadLetterOptions();
private final AtomicBoolean isDisposed = new AtomicBoolean();
private final ClientLogger logger = new ClientLogger(ServiceBusReceiverAsyncClient.class);
private final... |
We can probably make an educated guess of the longest possible time the sub process would take and fail after that? | public Mono<AccessToken> authenticateWithAzureCli(TokenRequestContext request) {
String azCommand = "az account get-access-token --output json --resource ";
StringBuilder command = new StringBuilder();
command.append(azCommand);
String scopes = ScopeUtil.scopesToResource(request.getScopes());
try {
ScopeUtil.validateSc... | process.waitFor(); | public Mono<AccessToken> authenticateWithAzureCli(TokenRequestContext request) {
String azCommand = "az account get-access-token --output json --resource ";
StringBuilder command = new StringBuilder();
command.append(azCommand);
String scopes = ScopeUtil.scopesToResource(request.getScopes());
try {
ScopeUtil.validateSc... | class IdentityClient {
private static final SerializerAdapter SERIALIZER_ADAPTER = JacksonAdapter.createDefaultSerializerAdapter();
private static final Random RANDOM = new Random();
private static final String WINDOWS_STARTER = "cmd.exe";
private static final String LINUX_MAC_STARTER = "/bin/sh";
private static final ... | class IdentityClient {
private static final SerializerAdapter SERIALIZER_ADAPTER = JacksonAdapter.createDefaultSerializerAdapter();
private static final Random RANDOM = new Random();
private static final String WINDOWS_STARTER = "cmd.exe";
private static final String LINUX_MAC_STARTER = "/bin/sh";
private static final ... |
agreed this must have some default timeout. In .NET I set this to 10 seconds. | public Mono<AccessToken> authenticateWithAzureCli(TokenRequestContext request) {
String azCommand = "az account get-access-token --output json --resource ";
StringBuilder command = new StringBuilder();
command.append(azCommand);
String scopes = ScopeUtil.scopesToResource(request.getScopes());
try {
ScopeUtil.validateSc... | process.waitFor(); | public Mono<AccessToken> authenticateWithAzureCli(TokenRequestContext request) {
String azCommand = "az account get-access-token --output json --resource ";
StringBuilder command = new StringBuilder();
command.append(azCommand);
String scopes = ScopeUtil.scopesToResource(request.getScopes());
try {
ScopeUtil.validateSc... | class IdentityClient {
private static final SerializerAdapter SERIALIZER_ADAPTER = JacksonAdapter.createDefaultSerializerAdapter();
private static final Random RANDOM = new Random();
private static final String WINDOWS_STARTER = "cmd.exe";
private static final String LINUX_MAC_STARTER = "/bin/sh";
private static final ... | class IdentityClient {
private static final SerializerAdapter SERIALIZER_ADAPTER = JacksonAdapter.createDefaultSerializerAdapter();
private static final Random RANDOM = new Random();
private static final String WINDOWS_STARTER = "cmd.exe";
private static final String LINUX_MAC_STARTER = "/bin/sh";
private static final ... |
```suggestion } catch (IOException | InterruptedException e) { throw logger.logExceptionAsError(new IllegalStateException(e)); } ``` | public Mono<AccessToken> authenticateWithAzureCli(TokenRequestContext request) {
String azCommand = "az account get-access-token --output json --resource ";
StringBuilder command = new StringBuilder();
command.append(azCommand);
String scopes = ScopeUtil.scopesToResource(request.getScopes());
try {
ScopeUtil.validateSc... | throw logger.logExceptionAsError(new IllegalStateException(e)); | public Mono<AccessToken> authenticateWithAzureCli(TokenRequestContext request) {
String azCommand = "az account get-access-token --output json --resource ";
StringBuilder command = new StringBuilder();
command.append(azCommand);
String scopes = ScopeUtil.scopesToResource(request.getScopes());
try {
ScopeUtil.validateSc... | class IdentityClient {
private static final SerializerAdapter SERIALIZER_ADAPTER = JacksonAdapter.createDefaultSerializerAdapter();
private static final Random RANDOM = new Random();
private static final String WINDOWS_STARTER = "cmd.exe";
private static final String LINUX_MAC_STARTER = "/bin/sh";
private static final ... | class IdentityClient {
private static final SerializerAdapter SERIALIZER_ADAPTER = JacksonAdapter.createDefaultSerializerAdapter();
private static final Random RANDOM = new Random();
private static final String WINDOWS_STARTER = "cmd.exe";
private static final String LINUX_MAC_STARTER = "/bin/sh";
private static final ... |
added 10 seconds timeout | public Mono<AccessToken> authenticateWithAzureCli(TokenRequestContext request) {
String azCommand = "az account get-access-token --output json --resource ";
StringBuilder command = new StringBuilder();
command.append(azCommand);
String scopes = ScopeUtil.scopesToResource(request.getScopes());
try {
ScopeUtil.validateSc... | process.waitFor(); | public Mono<AccessToken> authenticateWithAzureCli(TokenRequestContext request) {
String azCommand = "az account get-access-token --output json --resource ";
StringBuilder command = new StringBuilder();
command.append(azCommand);
String scopes = ScopeUtil.scopesToResource(request.getScopes());
try {
ScopeUtil.validateSc... | class IdentityClient {
private static final SerializerAdapter SERIALIZER_ADAPTER = JacksonAdapter.createDefaultSerializerAdapter();
private static final Random RANDOM = new Random();
private static final String WINDOWS_STARTER = "cmd.exe";
private static final String LINUX_MAC_STARTER = "/bin/sh";
private static final ... | class IdentityClient {
private static final SerializerAdapter SERIALIZER_ADAPTER = JacksonAdapter.createDefaultSerializerAdapter();
private static final Random RANDOM = new Random();
private static final String WINDOWS_STARTER = "cmd.exe";
private static final String LINUX_MAC_STARTER = "/bin/sh";
private static final ... |
Is there a need to have a short lived clone of the global configuration? If anything it may be better to use it directly as it could load into static memory the environment setting and will be accessed quicker in the future. | public IdentityClientOptions() {
Configuration configuration = Configuration.getGlobalConfiguration().clone();
authorityHost = configuration.contains(configuration.PROPERTY_AZURE_AUTHORITY_HOST)
? configuration.get(configuration.PROPERTY_AZURE_AUTHORITY_HOST) : DEFAULT_AUTHORITY_HOST;
maxRetry = MAX_RETRY_DEFAULT_LIMIT... | Configuration configuration = Configuration.getGlobalConfiguration().clone(); | public IdentityClientOptions() {
Configuration configuration = Configuration.getGlobalConfiguration();
authorityHost = configuration.get(Configuration.PROPERTY_AZURE_AUTHORITY_HOST, KnownAuthorityHosts.AZURE_CLOUD);
maxRetry = MAX_RETRY_DEFAULT_LIMIT;
retryTimeout = i -> Duration.ofSeconds((long) Math.pow(2, i.getSecon... | class IdentityClientOptions {
private static final String DEFAULT_AUTHORITY_HOST = "https:
private static final int MAX_RETRY_DEFAULT_LIMIT = 3;
private String authorityHost;
private int maxRetry;
private Function<Duration, Duration> retryTimeout;
private ProxyOptions proxyOptions;
private HttpPipeline httpPipeline;
/*... | class IdentityClientOptions {
private static final int MAX_RETRY_DEFAULT_LIMIT = 3;
private String authorityHost;
private int maxRetry;
private Function<Duration, Duration> retryTimeout;
private ProxyOptions proxyOptions;
private HttpPipeline httpPipeline;
private ExecutorService executorService;
private Duration token... |
`Configuration` has a `T get(String configurationName, T defaultValue)` method that could simplify this logic. ```java authorityHost = configuration.get(Configuration.PROPERTY_AZURE_AUTHORITY_HOST, DEFAULT_AUTHORITY_HOST); ``` | public IdentityClientOptions() {
Configuration configuration = Configuration.getGlobalConfiguration().clone();
authorityHost = configuration.contains(configuration.PROPERTY_AZURE_AUTHORITY_HOST)
? configuration.get(configuration.PROPERTY_AZURE_AUTHORITY_HOST) : DEFAULT_AUTHORITY_HOST;
maxRetry = MAX_RETRY_DEFAULT_LIMIT... | ? configuration.get(configuration.PROPERTY_AZURE_AUTHORITY_HOST) : DEFAULT_AUTHORITY_HOST; | public IdentityClientOptions() {
Configuration configuration = Configuration.getGlobalConfiguration();
authorityHost = configuration.get(Configuration.PROPERTY_AZURE_AUTHORITY_HOST, KnownAuthorityHosts.AZURE_CLOUD);
maxRetry = MAX_RETRY_DEFAULT_LIMIT;
retryTimeout = i -> Duration.ofSeconds((long) Math.pow(2, i.getSecon... | class IdentityClientOptions {
private static final String DEFAULT_AUTHORITY_HOST = "https:
private static final int MAX_RETRY_DEFAULT_LIMIT = 3;
private String authorityHost;
private int maxRetry;
private Function<Duration, Duration> retryTimeout;
private ProxyOptions proxyOptions;
private HttpPipeline httpPipeline;
/*... | class IdentityClientOptions {
private static final int MAX_RETRY_DEFAULT_LIMIT = 3;
private String authorityHost;
private int maxRetry;
private Function<Duration, Duration> retryTimeout;
private ProxyOptions proxyOptions;
private HttpPipeline httpPipeline;
private ExecutorService executorService;
private Duration token... |
In Arrange, Act, and Assert, this line would be "Act". And the Line 135 would be "Assert" | void createsMessageBatchWithSize() {
int batchSize = 1024;
final CreateBatchOptions options = new CreateBatchOptions().setMaximumSizeInBytes(batchSize);
ServiceBusMessageBatch batch = new ServiceBusMessageBatch(batchSize, null, null,
null);
when(asyncSender.createBatch(options)).thenReturn(Mono.just(batch));
ServiceBu... | ServiceBusMessageBatch messageBatch = sender.createBatch(options); | void createsMessageBatchWithSize() {
int batchSize = 1024;
final CreateBatchOptions options = new CreateBatchOptions().setMaximumSizeInBytes(batchSize);
final ServiceBusMessageBatch batch = new ServiceBusMessageBatch(batchSize, null, null,
null);
when(asyncSender.createBatch(options)).thenReturn(Mono.just(batch));
Serv... | class ServiceBusSenderClientTest {
private static final String NAMESPACE = "my-namespace";
private static final String ENTITY_NAME = "my-servicebus-entity";
@Mock
private ServiceBusSenderAsyncClient asyncSender;
@Captor
private ArgumentCaptor<ServiceBusMessage> singleMessageCaptor;
private ServiceBusSenderClient sender... | class ServiceBusSenderClientTest {
private static final String NAMESPACE = "my-namespace";
private static final String ENTITY_NAME = "my-servicebus-entity";
@Mock
private ServiceBusSenderAsyncClient asyncSender;
@Captor
private ArgumentCaptor<ServiceBusMessage> singleMessageCaptor;
private ServiceBusSenderClient sender... |
I followed they way in SharedTokenCacheCredential,it cloned a configuration in its constructor. | public IdentityClientOptions() {
Configuration configuration = Configuration.getGlobalConfiguration().clone();
authorityHost = configuration.contains(configuration.PROPERTY_AZURE_AUTHORITY_HOST)
? configuration.get(configuration.PROPERTY_AZURE_AUTHORITY_HOST) : DEFAULT_AUTHORITY_HOST;
maxRetry = MAX_RETRY_DEFAULT_LIMIT... | Configuration configuration = Configuration.getGlobalConfiguration().clone(); | public IdentityClientOptions() {
Configuration configuration = Configuration.getGlobalConfiguration();
authorityHost = configuration.get(Configuration.PROPERTY_AZURE_AUTHORITY_HOST, KnownAuthorityHosts.AZURE_CLOUD);
maxRetry = MAX_RETRY_DEFAULT_LIMIT;
retryTimeout = i -> Duration.ofSeconds((long) Math.pow(2, i.getSecon... | class IdentityClientOptions {
private static final String DEFAULT_AUTHORITY_HOST = "https:
private static final int MAX_RETRY_DEFAULT_LIMIT = 3;
private String authorityHost;
private int maxRetry;
private Function<Duration, Duration> retryTimeout;
private ProxyOptions proxyOptions;
private HttpPipeline httpPipeline;
/*... | class IdentityClientOptions {
private static final int MAX_RETRY_DEFAULT_LIMIT = 3;
private String authorityHost;
private int maxRetry;
private Function<Duration, Duration> retryTimeout;
private ProxyOptions proxyOptions;
private HttpPipeline httpPipeline;
private ExecutorService executorService;
private Duration token... |
Removed clone. | public IdentityClientOptions() {
Configuration configuration = Configuration.getGlobalConfiguration().clone();
authorityHost = configuration.contains(configuration.PROPERTY_AZURE_AUTHORITY_HOST)
? configuration.get(configuration.PROPERTY_AZURE_AUTHORITY_HOST) : DEFAULT_AUTHORITY_HOST;
maxRetry = MAX_RETRY_DEFAULT_LIMIT... | Configuration configuration = Configuration.getGlobalConfiguration().clone(); | public IdentityClientOptions() {
Configuration configuration = Configuration.getGlobalConfiguration();
authorityHost = configuration.get(Configuration.PROPERTY_AZURE_AUTHORITY_HOST, KnownAuthorityHosts.AZURE_CLOUD);
maxRetry = MAX_RETRY_DEFAULT_LIMIT;
retryTimeout = i -> Duration.ofSeconds((long) Math.pow(2, i.getSecon... | class IdentityClientOptions {
private static final String DEFAULT_AUTHORITY_HOST = "https:
private static final int MAX_RETRY_DEFAULT_LIMIT = 3;
private String authorityHost;
private int maxRetry;
private Function<Duration, Duration> retryTimeout;
private ProxyOptions proxyOptions;
private HttpPipeline httpPipeline;
/*... | class IdentityClientOptions {
private static final int MAX_RETRY_DEFAULT_LIMIT = 3;
private String authorityHost;
private int maxRetry;
private Function<Duration, Duration> retryTimeout;
private ProxyOptions proxyOptions;
private HttpPipeline httpPipeline;
private ExecutorService executorService;
private Duration token... |
please use logger, not System.out/err. Please do everywhere. | void deleteCollection() {
try {
for (CosmosAsyncClient cosmosAsyncClient : clientDocsMap.keySet()) {
cosmosAsyncClient.getDatabase(configuration.getDatabaseId()).getContainer(configuration.getCollectionId()).delete().block();
}
} catch (CosmosClientException e) {
if (e.getStatusCode() == HttpConstants.StatusCodes.NOTFO... | System.out.println("Container on all client have been deleted successfully"); | void deleteCollection() {
try {
for (CosmosAsyncClient cosmosAsyncClient : clientDocsMap.keySet()) {
cosmosAsyncClient.getDatabase(configuration.getDatabaseId()).getContainer(configuration.getCollectionId()).delete().block();
}
} catch (CosmosClientException e) {
if (e.getStatusCode() == HttpConstants.StatusCodes.NOTFO... | class AsynReadWithMultipleClients<T> {
private final static String PARTITION_KEY = "/pk";
private final Semaphore concurrencyControlSemaphore;
private final Logger logger;
private final Configuration configuration;
private MetricRegistry metricsRegistry = new MetricRegistry();
private ScheduledReporter reporter;
privat... | class AsynReadWithMultipleClients<T> {
private final static String PARTITION_KEY = "/pk";
private final static String ACCOUNT_ENDPOINT_TAG = "AccountEndpoint=";
private final static String ACCOUNT_KEY_TAG = "AccountKey=";
private final Semaphore concurrencyControlSemaphore;
private final Logger logger;
private final Co... |
please don't use System.out/err. use logger here and elsewhere. | private void createClients() {
String csvFile = "clientHostAndKey.txt";
BufferedReader br = null;
String line = "";
String splitBy = ",";
try {
br = new BufferedReader(new FileReader(csvFile));
while ((line = br.readLine()) != null) {
String[] hostAndKey = line.split(splitBy);
if (hostAndKey.length == 2) {
CosmosAsyncC... | e.printStackTrace(); | private void createClients() {
String csvFile = "clientHostAndKey.txt";
String line = "";
String splitBy = ";";
try (BufferedReader br = new BufferedReader(new FileReader(csvFile))) {
while ((line = br.readLine()) != null) {
String[] hostAndKey = line.split(splitBy);
if (hostAndKey.length >= 2) {
String endpoint = host... | class AsynReadWithMultipleClients<T> {
private final static String PARTITION_KEY = "/pk";
private final Semaphore concurrencyControlSemaphore;
private final Logger logger;
private final Configuration configuration;
private MetricRegistry metricsRegistry = new MetricRegistry();
private ScheduledReporter reporter;
privat... | class AsynReadWithMultipleClients<T> {
private final static String PARTITION_KEY = "/pk";
private final static String ACCOUNT_ENDPOINT_TAG = "AccountEndpoint=";
private final static String ACCOUNT_KEY_TAG = "AccountKey=";
private final Semaphore concurrencyControlSemaphore;
private final Logger logger;
private final Co... |
we should be using logger everywhere. Please replace System.out with logger here and elsewhere. | private void createClients() {
String csvFile = "clientHostAndKey.txt";
BufferedReader br = null;
String line = "";
String splitBy = ",";
try {
br = new BufferedReader(new FileReader(csvFile));
while ((line = br.readLine()) != null) {
String[] hostAndKey = line.split(splitBy);
if (hostAndKey.length == 2) {
CosmosAsyncC... | System.out.println("Client have been initialized with data created for host " + hostAndKey[0]); | private void createClients() {
String csvFile = "clientHostAndKey.txt";
String line = "";
String splitBy = ";";
try (BufferedReader br = new BufferedReader(new FileReader(csvFile))) {
while ((line = br.readLine()) != null) {
String[] hostAndKey = line.split(splitBy);
if (hostAndKey.length >= 2) {
String endpoint = host... | class AsynReadWithMultipleClients<T> {
private final static String PARTITION_KEY = "/pk";
private final Semaphore concurrencyControlSemaphore;
private final Logger logger;
private final Configuration configuration;
private MetricRegistry metricsRegistry = new MetricRegistry();
private ScheduledReporter reporter;
privat... | class AsynReadWithMultipleClients<T> {
private final static String PARTITION_KEY = "/pk";
private final static String ACCOUNT_ENDPOINT_TAG = "AccountEndpoint=";
private final static String ACCOUNT_KEY_TAG = "AccountKey=";
private final Semaphore concurrencyControlSemaphore;
private final Logger logger;
private final Co... |
please use try-with-resources to simplify the try/catch pattern: https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html | private void createClients() {
String csvFile = "clientHostAndKey.txt";
BufferedReader br = null;
String line = "";
String splitBy = ",";
try {
br = new BufferedReader(new FileReader(csvFile));
while ((line = br.readLine()) != null) {
String[] hostAndKey = line.split(splitBy);
if (hostAndKey.length == 2) {
CosmosAsyncC... | try { | private void createClients() {
String csvFile = "clientHostAndKey.txt";
String line = "";
String splitBy = ";";
try (BufferedReader br = new BufferedReader(new FileReader(csvFile))) {
while ((line = br.readLine()) != null) {
String[] hostAndKey = line.split(splitBy);
if (hostAndKey.length >= 2) {
String endpoint = host... | class AsynReadWithMultipleClients<T> {
private final static String PARTITION_KEY = "/pk";
private final Semaphore concurrencyControlSemaphore;
private final Logger logger;
private final Configuration configuration;
private MetricRegistry metricsRegistry = new MetricRegistry();
private ScheduledReporter reporter;
privat... | class AsynReadWithMultipleClients<T> {
private final static String PARTITION_KEY = "/pk";
private final static String ACCOUNT_ENDPOINT_TAG = "AccountEndpoint=";
private final static String ACCOUNT_KEY_TAG = "AccountKey=";
private final Semaphore concurrencyControlSemaphore;
private final Logger logger;
private final Co... |
fix code style. | void tryGetValuesFromSystem() {
serviceEndpoint = StringUtils.defaultString(Strings.emptyToNull(System.getenv().get("SERVICE_END_POINT")),
serviceEndpoint);
masterKey = StringUtils.defaultString(Strings.emptyToNull(System.getenv().get("MASTER_KEY")), masterKey);
databaseId = StringUtils.defaultString(Strings.emptyToNul... | String throughPutForMultiClientValue = StringUtils.defaultString( | void tryGetValuesFromSystem() {
serviceEndpoint = StringUtils.defaultString(Strings.emptyToNull(System.getenv().get("SERVICE_END_POINT")),
serviceEndpoint);
masterKey = StringUtils.defaultString(Strings.emptyToNull(System.getenv().get("MASTER_KEY")), masterKey);
databaseId = StringUtils.defaultString(Strings.emptyToNul... | class ConsistencyLevelConverter implements IStringConverter<ConsistencyLevel> {
/*
* (non-Javadoc)
*
* @see com.beust.jcommander.IStringConverter
*/
@Override
public ConsistencyLevel convert(String value) {
ConsistencyLevel ret = fromString(value);
if (ret == null) {
throw new ParameterException("Value " + value + " ca... | class ConsistencyLevelConverter implements IStringConverter<ConsistencyLevel> {
/*
* (non-Javadoc)
*
* @see com.beust.jcommander.IStringConverter
*/
@Override
public ConsistencyLevel convert(String value) {
ConsistencyLevel ret = fromString(value);
if (ret == null) {
throw new ParameterException("Value " + value + " ca... |
it seems you are using `isDeleteCollections` for not only deleting collections but also for creating collection? is that right? the config seems to be overloaded. | private void createClients() {
String csvFile = "clientHostAndKey.txt";
BufferedReader br = null;
String line = "";
String splitBy = ",";
try {
br = new BufferedReader(new FileReader(csvFile));
while ((line = br.readLine()) != null) {
String[] hostAndKey = line.split(splitBy);
if (hostAndKey.length == 2) {
CosmosAsyncC... | if (!configuration.isDeleteCollections()) { | private void createClients() {
String csvFile = "clientHostAndKey.txt";
String line = "";
String splitBy = ";";
try (BufferedReader br = new BufferedReader(new FileReader(csvFile))) {
while ((line = br.readLine()) != null) {
String[] hostAndKey = line.split(splitBy);
if (hostAndKey.length >= 2) {
String endpoint = host... | class AsynReadWithMultipleClients<T> {
private final static String PARTITION_KEY = "/pk";
private final Semaphore concurrencyControlSemaphore;
private final Logger logger;
private final Configuration configuration;
private MetricRegistry metricsRegistry = new MetricRegistry();
private ScheduledReporter reporter;
privat... | class AsynReadWithMultipleClients<T> {
private final static String PARTITION_KEY = "/pk";
private final static String ACCOUNT_ENDPOINT_TAG = "AccountEndpoint=";
private final static String ACCOUNT_KEY_TAG = "AccountKey=";
private final Semaphore concurrencyControlSemaphore;
private final Logger logger;
private final Co... |
meterRegistry is a static setting, why do we need to set it "inside" the for loop? shouldn't this be outside? | private void createClients() {
String csvFile = "clientHostAndKey.txt";
BufferedReader br = null;
String line = "";
String splitBy = ",";
try {
br = new BufferedReader(new FileReader(csvFile));
while ((line = br.readLine()) != null) {
String[] hostAndKey = line.split(splitBy);
if (hostAndKey.length == 2) {
CosmosAsyncC... | BridgeInternal.monitorTelemetry(registry); | private void createClients() {
String csvFile = "clientHostAndKey.txt";
String line = "";
String splitBy = ";";
try (BufferedReader br = new BufferedReader(new FileReader(csvFile))) {
while ((line = br.readLine()) != null) {
String[] hostAndKey = line.split(splitBy);
if (hostAndKey.length >= 2) {
String endpoint = host... | class AsynReadWithMultipleClients<T> {
private final static String PARTITION_KEY = "/pk";
private final Semaphore concurrencyControlSemaphore;
private final Logger logger;
private final Configuration configuration;
private MetricRegistry metricsRegistry = new MetricRegistry();
private ScheduledReporter reporter;
privat... | class AsynReadWithMultipleClients<T> {
private final static String PARTITION_KEY = "/pk";
private final static String ACCOUNT_ENDPOINT_TAG = "AccountEndpoint=";
private final static String ACCOUNT_KEY_TAG = "AccountKey=";
private final Semaphore concurrencyControlSemaphore;
private final Logger logger;
private final Co... |
meterRegistry is a static setting, why do we need to set it "inside" the for loop? shouldn't this be outside? | private void createClients() {
String csvFile = "clientHostAndKey.txt";
BufferedReader br = null;
String line = "";
String splitBy = ",";
try {
br = new BufferedReader(new FileReader(csvFile));
while ((line = br.readLine()) != null) {
String[] hostAndKey = line.split(splitBy);
if (hostAndKey.length == 2) {
CosmosAsyncC... | BridgeInternal.monitorTelemetry(registry); | private void createClients() {
String csvFile = "clientHostAndKey.txt";
String line = "";
String splitBy = ";";
try (BufferedReader br = new BufferedReader(new FileReader(csvFile))) {
while ((line = br.readLine()) != null) {
String[] hostAndKey = line.split(splitBy);
if (hostAndKey.length >= 2) {
String endpoint = host... | class AsynReadWithMultipleClients<T> {
private final static String PARTITION_KEY = "/pk";
private final Semaphore concurrencyControlSemaphore;
private final Logger logger;
private final Configuration configuration;
private MetricRegistry metricsRegistry = new MetricRegistry();
private ScheduledReporter reporter;
privat... | class AsynReadWithMultipleClients<T> {
private final static String PARTITION_KEY = "/pk";
private final static String ACCOUNT_ENDPOINT_TAG = "AccountEndpoint=";
private final static String ACCOUNT_KEY_TAG = "AccountKey=";
private final Semaphore concurrencyControlSemaphore;
private final Logger logger;
private final Co... |
Done | void deleteCollection() {
try {
for (CosmosAsyncClient cosmosAsyncClient : clientDocsMap.keySet()) {
cosmosAsyncClient.getDatabase(configuration.getDatabaseId()).getContainer(configuration.getCollectionId()).delete().block();
}
} catch (CosmosClientException e) {
if (e.getStatusCode() == HttpConstants.StatusCodes.NOTFO... | System.out.println("Container on all client have been deleted successfully"); | void deleteCollection() {
try {
for (CosmosAsyncClient cosmosAsyncClient : clientDocsMap.keySet()) {
cosmosAsyncClient.getDatabase(configuration.getDatabaseId()).getContainer(configuration.getCollectionId()).delete().block();
}
} catch (CosmosClientException e) {
if (e.getStatusCode() == HttpConstants.StatusCodes.NOTFO... | class AsynReadWithMultipleClients<T> {
private final static String PARTITION_KEY = "/pk";
private final Semaphore concurrencyControlSemaphore;
private final Logger logger;
private final Configuration configuration;
private MetricRegistry metricsRegistry = new MetricRegistry();
private ScheduledReporter reporter;
privat... | class AsynReadWithMultipleClients<T> {
private final static String PARTITION_KEY = "/pk";
private final static String ACCOUNT_ENDPOINT_TAG = "AccountEndpoint=";
private final static String ACCOUNT_KEY_TAG = "AccountKey=";
private final Semaphore concurrencyControlSemaphore;
private final Logger logger;
private final Co... |
done | private void createClients() {
String csvFile = "clientHostAndKey.txt";
BufferedReader br = null;
String line = "";
String splitBy = ",";
try {
br = new BufferedReader(new FileReader(csvFile));
while ((line = br.readLine()) != null) {
String[] hostAndKey = line.split(splitBy);
if (hostAndKey.length == 2) {
CosmosAsyncC... | System.out.println("Client have been initialized with data created for host " + hostAndKey[0]); | private void createClients() {
String csvFile = "clientHostAndKey.txt";
String line = "";
String splitBy = ";";
try (BufferedReader br = new BufferedReader(new FileReader(csvFile))) {
while ((line = br.readLine()) != null) {
String[] hostAndKey = line.split(splitBy);
if (hostAndKey.length >= 2) {
String endpoint = host... | class AsynReadWithMultipleClients<T> {
private final static String PARTITION_KEY = "/pk";
private final Semaphore concurrencyControlSemaphore;
private final Logger logger;
private final Configuration configuration;
private MetricRegistry metricsRegistry = new MetricRegistry();
private ScheduledReporter reporter;
privat... | class AsynReadWithMultipleClients<T> {
private final static String PARTITION_KEY = "/pk";
private final static String ACCOUNT_ENDPOINT_TAG = "AccountEndpoint=";
private final static String ACCOUNT_KEY_TAG = "AccountKey=";
private final Semaphore concurrencyControlSemaphore;
private final Logger logger;
private final Co... |
done | void tryGetValuesFromSystem() {
serviceEndpoint = StringUtils.defaultString(Strings.emptyToNull(System.getenv().get("SERVICE_END_POINT")),
serviceEndpoint);
masterKey = StringUtils.defaultString(Strings.emptyToNull(System.getenv().get("MASTER_KEY")), masterKey);
databaseId = StringUtils.defaultString(Strings.emptyToNul... | String throughPutForMultiClientValue = StringUtils.defaultString( | void tryGetValuesFromSystem() {
serviceEndpoint = StringUtils.defaultString(Strings.emptyToNull(System.getenv().get("SERVICE_END_POINT")),
serviceEndpoint);
masterKey = StringUtils.defaultString(Strings.emptyToNull(System.getenv().get("MASTER_KEY")), masterKey);
databaseId = StringUtils.defaultString(Strings.emptyToNul... | class ConsistencyLevelConverter implements IStringConverter<ConsistencyLevel> {
/*
* (non-Javadoc)
*
* @see com.beust.jcommander.IStringConverter
*/
@Override
public ConsistencyLevel convert(String value) {
ConsistencyLevel ret = fromString(value);
if (ret == null) {
throw new ParameterException("Value " + value + " ca... | class ConsistencyLevelConverter implements IStringConverter<ConsistencyLevel> {
/*
* (non-Javadoc)
*
* @see com.beust.jcommander.IStringConverter
*/
@Override
public ConsistencyLevel convert(String value) {
ConsistencyLevel ret = fromString(value);
if (ret == null) {
throw new ParameterException("Value " + value + " ca... |
done | private void createClients() {
String csvFile = "clientHostAndKey.txt";
BufferedReader br = null;
String line = "";
String splitBy = ",";
try {
br = new BufferedReader(new FileReader(csvFile));
while ((line = br.readLine()) != null) {
String[] hostAndKey = line.split(splitBy);
if (hostAndKey.length == 2) {
CosmosAsyncC... | BridgeInternal.monitorTelemetry(registry); | private void createClients() {
String csvFile = "clientHostAndKey.txt";
String line = "";
String splitBy = ";";
try (BufferedReader br = new BufferedReader(new FileReader(csvFile))) {
while ((line = br.readLine()) != null) {
String[] hostAndKey = line.split(splitBy);
if (hostAndKey.length >= 2) {
String endpoint = host... | class AsynReadWithMultipleClients<T> {
private final static String PARTITION_KEY = "/pk";
private final Semaphore concurrencyControlSemaphore;
private final Logger logger;
private final Configuration configuration;
private MetricRegistry metricsRegistry = new MetricRegistry();
private ScheduledReporter reporter;
privat... | class AsynReadWithMultipleClients<T> {
private final static String PARTITION_KEY = "/pk";
private final static String ACCOUNT_ENDPOINT_TAG = "AccountEndpoint=";
private final static String ACCOUNT_KEY_TAG = "AccountKey=";
private final Semaphore concurrencyControlSemaphore;
private final Logger logger;
private final Co... |
done | private void createClients() {
String csvFile = "clientHostAndKey.txt";
BufferedReader br = null;
String line = "";
String splitBy = ",";
try {
br = new BufferedReader(new FileReader(csvFile));
while ((line = br.readLine()) != null) {
String[] hostAndKey = line.split(splitBy);
if (hostAndKey.length == 2) {
CosmosAsyncC... | BridgeInternal.monitorTelemetry(registry); | private void createClients() {
String csvFile = "clientHostAndKey.txt";
String line = "";
String splitBy = ";";
try (BufferedReader br = new BufferedReader(new FileReader(csvFile))) {
while ((line = br.readLine()) != null) {
String[] hostAndKey = line.split(splitBy);
if (hostAndKey.length >= 2) {
String endpoint = host... | class AsynReadWithMultipleClients<T> {
private final static String PARTITION_KEY = "/pk";
private final Semaphore concurrencyControlSemaphore;
private final Logger logger;
private final Configuration configuration;
private MetricRegistry metricsRegistry = new MetricRegistry();
private ScheduledReporter reporter;
privat... | class AsynReadWithMultipleClients<T> {
private final static String PARTITION_KEY = "/pk";
private final static String ACCOUNT_ENDPOINT_TAG = "AccountEndpoint=";
private final static String ACCOUNT_KEY_TAG = "AccountKey=";
private final Semaphore concurrencyControlSemaphore;
private final Logger logger;
private final Co... |
during deleteCollections workload we don't want to create db/collection/data . createClient method during initialization will create client/db/container/data. | private void createClients() {
String csvFile = "clientHostAndKey.txt";
BufferedReader br = null;
String line = "";
String splitBy = ",";
try {
br = new BufferedReader(new FileReader(csvFile));
while ((line = br.readLine()) != null) {
String[] hostAndKey = line.split(splitBy);
if (hostAndKey.length == 2) {
CosmosAsyncC... | if (!configuration.isDeleteCollections()) { | private void createClients() {
String csvFile = "clientHostAndKey.txt";
String line = "";
String splitBy = ";";
try (BufferedReader br = new BufferedReader(new FileReader(csvFile))) {
while ((line = br.readLine()) != null) {
String[] hostAndKey = line.split(splitBy);
if (hostAndKey.length >= 2) {
String endpoint = host... | class AsynReadWithMultipleClients<T> {
private final static String PARTITION_KEY = "/pk";
private final Semaphore concurrencyControlSemaphore;
private final Logger logger;
private final Configuration configuration;
private MetricRegistry metricsRegistry = new MetricRegistry();
private ScheduledReporter reporter;
privat... | class AsynReadWithMultipleClients<T> {
private final static String PARTITION_KEY = "/pk";
private final static String ACCOUNT_ENDPOINT_TAG = "AccountEndpoint=";
private final static String ACCOUNT_KEY_TAG = "AccountKey=";
private final Semaphore concurrencyControlSemaphore;
private final Logger logger;
private final Co... |
done | private void createClients() {
String csvFile = "clientHostAndKey.txt";
BufferedReader br = null;
String line = "";
String splitBy = ",";
try {
br = new BufferedReader(new FileReader(csvFile));
while ((line = br.readLine()) != null) {
String[] hostAndKey = line.split(splitBy);
if (hostAndKey.length == 2) {
CosmosAsyncC... | e.printStackTrace(); | private void createClients() {
String csvFile = "clientHostAndKey.txt";
String line = "";
String splitBy = ";";
try (BufferedReader br = new BufferedReader(new FileReader(csvFile))) {
while ((line = br.readLine()) != null) {
String[] hostAndKey = line.split(splitBy);
if (hostAndKey.length >= 2) {
String endpoint = host... | class AsynReadWithMultipleClients<T> {
private final static String PARTITION_KEY = "/pk";
private final Semaphore concurrencyControlSemaphore;
private final Logger logger;
private final Configuration configuration;
private MetricRegistry metricsRegistry = new MetricRegistry();
private ScheduledReporter reporter;
privat... | class AsynReadWithMultipleClients<T> {
private final static String PARTITION_KEY = "/pk";
private final static String ACCOUNT_ENDPOINT_TAG = "AccountEndpoint=";
private final static String ACCOUNT_KEY_TAG = "AccountKey=";
private final Semaphore concurrencyControlSemaphore;
private final Logger logger;
private final Co... |
done | private void createClients() {
String csvFile = "clientHostAndKey.txt";
BufferedReader br = null;
String line = "";
String splitBy = ",";
try {
br = new BufferedReader(new FileReader(csvFile));
while ((line = br.readLine()) != null) {
String[] hostAndKey = line.split(splitBy);
if (hostAndKey.length == 2) {
CosmosAsyncC... | try { | private void createClients() {
String csvFile = "clientHostAndKey.txt";
String line = "";
String splitBy = ";";
try (BufferedReader br = new BufferedReader(new FileReader(csvFile))) {
while ((line = br.readLine()) != null) {
String[] hostAndKey = line.split(splitBy);
if (hostAndKey.length >= 2) {
String endpoint = host... | class AsynReadWithMultipleClients<T> {
private final static String PARTITION_KEY = "/pk";
private final Semaphore concurrencyControlSemaphore;
private final Logger logger;
private final Configuration configuration;
private MetricRegistry metricsRegistry = new MetricRegistry();
private ScheduledReporter reporter;
privat... | class AsynReadWithMultipleClients<T> {
private final static String PARTITION_KEY = "/pk";
private final static String ACCOUNT_ENDPOINT_TAG = "AccountEndpoint=";
private final static String ACCOUNT_KEY_TAG = "AccountKey=";
private final Semaphore concurrencyControlSemaphore;
private final Logger logger;
private final Co... |
you still have e.printStackTrace() throughout the file. please fix everywhere. | private void createClients() {
String csvFile = "clientHostAndKey.txt";
BufferedReader br = null;
String line = "";
String splitBy = ",";
try {
br = new BufferedReader(new FileReader(csvFile));
while ((line = br.readLine()) != null) {
String[] hostAndKey = line.split(splitBy);
if (hostAndKey.length == 2) {
CosmosAsyncC... | e.printStackTrace(); | private void createClients() {
String csvFile = "clientHostAndKey.txt";
String line = "";
String splitBy = ";";
try (BufferedReader br = new BufferedReader(new FileReader(csvFile))) {
while ((line = br.readLine()) != null) {
String[] hostAndKey = line.split(splitBy);
if (hostAndKey.length >= 2) {
String endpoint = host... | class AsynReadWithMultipleClients<T> {
private final static String PARTITION_KEY = "/pk";
private final Semaphore concurrencyControlSemaphore;
private final Logger logger;
private final Configuration configuration;
private MetricRegistry metricsRegistry = new MetricRegistry();
private ScheduledReporter reporter;
privat... | class AsynReadWithMultipleClients<T> {
private final static String PARTITION_KEY = "/pk";
private final static String ACCOUNT_ENDPOINT_TAG = "AccountEndpoint=";
private final static String ACCOUNT_KEY_TAG = "AccountKey=";
private final Semaphore concurrencyControlSemaphore;
private final Logger logger;
private final Co... |
ditto, we should be using logger.error | private void createClients() {
String csvFile = "clientHostAndKey.txt";
String line = "";
String splitBy = ";";
try (BufferedReader br = new BufferedReader(new FileReader(csvFile))) {
while ((line = br.readLine()) != null) {
String[] hostAndKey = line.split(splitBy);
if (hostAndKey.length >= 2) {
String endpoint = host... | e.printStackTrace(); | private void createClients() {
String csvFile = "clientHostAndKey.txt";
String line = "";
String splitBy = ";";
try (BufferedReader br = new BufferedReader(new FileReader(csvFile))) {
while ((line = br.readLine()) != null) {
String[] hostAndKey = line.split(splitBy);
if (hostAndKey.length >= 2) {
String endpoint = host... | class AsynReadWithMultipleClients<T> {
private final static String PARTITION_KEY = "/pk";
private final static String ACCOUNT_ENDPOINT_TAG = "AccountEndpoint=";
private final static String ACCOUNT_KEY_TAG = "AccountKey=";
private final Semaphore concurrencyControlSemaphore;
private final Logger logger;
private final Co... | class AsynReadWithMultipleClients<T> {
private final static String PARTITION_KEY = "/pk";
private final static String ACCOUNT_ENDPOINT_TAG = "AccountEndpoint=";
private final static String ACCOUNT_KEY_TAG = "AccountKey=";
private final Semaphore concurrencyControlSemaphore;
private final Logger logger;
private final Co... |
code style: you have multiple spaces `String throughputForMultiClientValue` -> `String throughputForMultiClientValue` | void tryGetValuesFromSystem() {
serviceEndpoint = StringUtils.defaultString(Strings.emptyToNull(System.getenv().get("SERVICE_END_POINT")),
serviceEndpoint);
masterKey = StringUtils.defaultString(Strings.emptyToNull(System.getenv().get("MASTER_KEY")), masterKey);
databaseId = StringUtils.defaultString(Strings.emptyToNul... | String throughputForMultiClientValue = StringUtils.defaultString( | void tryGetValuesFromSystem() {
serviceEndpoint = StringUtils.defaultString(Strings.emptyToNull(System.getenv().get("SERVICE_END_POINT")),
serviceEndpoint);
masterKey = StringUtils.defaultString(Strings.emptyToNull(System.getenv().get("MASTER_KEY")), masterKey);
databaseId = StringUtils.defaultString(Strings.emptyToNul... | class ConsistencyLevelConverter implements IStringConverter<ConsistencyLevel> {
/*
* (non-Javadoc)
*
* @see com.beust.jcommander.IStringConverter
*/
@Override
public ConsistencyLevel convert(String value) {
ConsistencyLevel ret = fromString(value);
if (ret == null) {
throw new ParameterException("Value " + value + " ca... | class ConsistencyLevelConverter implements IStringConverter<ConsistencyLevel> {
/*
* (non-Javadoc)
*
* @see com.beust.jcommander.IStringConverter
*/
@Override
public ConsistencyLevel convert(String value) {
ConsistencyLevel ret = fromString(value);
if (ret == null) {
throw new ParameterException("Value " + value + " ca... |
code style: space after comma | void tryGetValuesFromSystem() {
serviceEndpoint = StringUtils.defaultString(Strings.emptyToNull(System.getenv().get("SERVICE_END_POINT")),
serviceEndpoint);
masterKey = StringUtils.defaultString(Strings.emptyToNull(System.getenv().get("MASTER_KEY")), masterKey);
databaseId = StringUtils.defaultString(Strings.emptyToNul... | Strings.emptyToNull(System.getenv().get("THROUGHPUT_MULTICLIENT")),Integer.toString(throughputForMultiClient)); | void tryGetValuesFromSystem() {
serviceEndpoint = StringUtils.defaultString(Strings.emptyToNull(System.getenv().get("SERVICE_END_POINT")),
serviceEndpoint);
masterKey = StringUtils.defaultString(Strings.emptyToNull(System.getenv().get("MASTER_KEY")), masterKey);
databaseId = StringUtils.defaultString(Strings.emptyToNul... | class ConsistencyLevelConverter implements IStringConverter<ConsistencyLevel> {
/*
* (non-Javadoc)
*
* @see com.beust.jcommander.IStringConverter
*/
@Override
public ConsistencyLevel convert(String value) {
ConsistencyLevel ret = fromString(value);
if (ret == null) {
throw new ParameterException("Value " + value + " ca... | class ConsistencyLevelConverter implements IStringConverter<ConsistencyLevel> {
/*
* (non-Javadoc)
*
* @see com.beust.jcommander.IStringConverter
*/
@Override
public ConsistencyLevel convert(String value) {
ConsistencyLevel ret = fromString(value);
if (ret == null) {
throw new ParameterException("Value " + value + " ca... |
this will print the key as well. can we just print the endpoint. ideally we should not log key anywhere in the log. | private void createClients() {
String csvFile = "clientHostAndKey.txt";
String line = "";
String splitBy = ";";
try (BufferedReader br = new BufferedReader(new FileReader(csvFile))) {
while ((line = br.readLine()) != null) {
String[] hostAndKey = line.split(splitBy);
if (hostAndKey.length >= 2) {
String endpoint = host... | logger.info("Client have been initialized with data created for host {}", hostAndKey[0]); | private void createClients() {
String csvFile = "clientHostAndKey.txt";
String line = "";
String splitBy = ";";
try (BufferedReader br = new BufferedReader(new FileReader(csvFile))) {
while ((line = br.readLine()) != null) {
String[] hostAndKey = line.split(splitBy);
if (hostAndKey.length >= 2) {
String endpoint = host... | class AsynReadWithMultipleClients<T> {
private final static String PARTITION_KEY = "/pk";
private final static String ACCOUNT_ENDPOINT_TAG = "AccountEndpoint=";
private final static String ACCOUNT_KEY_TAG = "AccountKey=";
private final Semaphore concurrencyControlSemaphore;
private final Logger logger;
private final Co... | class AsynReadWithMultipleClients<T> {
private final static String PARTITION_KEY = "/pk";
private final static String ACCOUNT_ENDPOINT_TAG = "AccountEndpoint=";
private final static String ACCOUNT_KEY_TAG = "AccountKey=";
private final Semaphore concurrencyControlSemaphore;
private final Logger logger;
private final Co... |
ditto. we should not log the key | private void createClients() {
String csvFile = "clientHostAndKey.txt";
String line = "";
String splitBy = ";";
try (BufferedReader br = new BufferedReader(new FileReader(csvFile))) {
while ((line = br.readLine()) != null) {
String[] hostAndKey = line.split(splitBy);
if (hostAndKey.length >= 2) {
String endpoint = host... | logger.info("Client have been initialized with host {}", hostAndKey[0]); | private void createClients() {
String csvFile = "clientHostAndKey.txt";
String line = "";
String splitBy = ";";
try (BufferedReader br = new BufferedReader(new FileReader(csvFile))) {
while ((line = br.readLine()) != null) {
String[] hostAndKey = line.split(splitBy);
if (hostAndKey.length >= 2) {
String endpoint = host... | class AsynReadWithMultipleClients<T> {
private final static String PARTITION_KEY = "/pk";
private final static String ACCOUNT_ENDPOINT_TAG = "AccountEndpoint=";
private final static String ACCOUNT_KEY_TAG = "AccountKey=";
private final Semaphore concurrencyControlSemaphore;
private final Logger logger;
private final Co... | class AsynReadWithMultipleClients<T> {
private final static String PARTITION_KEY = "/pk";
private final static String ACCOUNT_ENDPOINT_TAG = "AccountEndpoint=";
private final static String ACCOUNT_KEY_TAG = "AccountKey=";
private final Semaphore concurrencyControlSemaphore;
private final Logger logger;
private final Co... |
codestyle: space after comma please use intellij autoformatting on this new file. | private void createClients() {
String csvFile = "clientHostAndKey.txt";
String line = "";
String splitBy = ";";
try (BufferedReader br = new BufferedReader(new FileReader(csvFile))) {
while ((line = br.readLine()) != null) {
String[] hostAndKey = line.split(splitBy);
if (hostAndKey.length >= 2) {
String endpoint = host... | logger.info("Total number of client created for ReadThroughputWithMultipleClient {}",clientDocsMap.size()); | private void createClients() {
String csvFile = "clientHostAndKey.txt";
String line = "";
String splitBy = ";";
try (BufferedReader br = new BufferedReader(new FileReader(csvFile))) {
while ((line = br.readLine()) != null) {
String[] hostAndKey = line.split(splitBy);
if (hostAndKey.length >= 2) {
String endpoint = host... | class AsynReadWithMultipleClients<T> {
private final static String PARTITION_KEY = "/pk";
private final static String ACCOUNT_ENDPOINT_TAG = "AccountEndpoint=";
private final static String ACCOUNT_KEY_TAG = "AccountKey=";
private final Semaphore concurrencyControlSemaphore;
private final Logger logger;
private final Co... | class AsynReadWithMultipleClients<T> {
private final static String PARTITION_KEY = "/pk";
private final static String ACCOUNT_ENDPOINT_TAG = "AccountEndpoint=";
private final static String ACCOUNT_KEY_TAG = "AccountKey=";
private final Semaphore concurrencyControlSemaphore;
private final Logger logger;
private final Co... |
setting metrics registery should be outside of try/catch block. not related to connection string parsing. | private void createClients() {
String csvFile = "clientHostAndKey.txt";
String line = "";
String splitBy = ";";
try (BufferedReader br = new BufferedReader(new FileReader(csvFile))) {
while ((line = br.readLine()) != null) {
String[] hostAndKey = line.split(splitBy);
if (hostAndKey.length >= 2) {
String endpoint = host... | MeterRegistry registry = configuration.getAzureMonitorMeterRegistry(); | private void createClients() {
String csvFile = "clientHostAndKey.txt";
String line = "";
String splitBy = ";";
try (BufferedReader br = new BufferedReader(new FileReader(csvFile))) {
while ((line = br.readLine()) != null) {
String[] hostAndKey = line.split(splitBy);
if (hostAndKey.length >= 2) {
String endpoint = host... | class AsynReadWithMultipleClients<T> {
private final static String PARTITION_KEY = "/pk";
private final static String ACCOUNT_ENDPOINT_TAG = "AccountEndpoint=";
private final static String ACCOUNT_KEY_TAG = "AccountKey=";
private final Semaphore concurrencyControlSemaphore;
private final Logger logger;
private final Co... | class AsynReadWithMultipleClients<T> {
private final static String PARTITION_KEY = "/pk";
private final static String ACCOUNT_ENDPOINT_TAG = "AccountEndpoint=";
private final static String ACCOUNT_KEY_TAG = "AccountKey=";
private final Semaphore concurrencyControlSemaphore;
private final Logger logger;
private final Co... |
if we are creating the collection, we should allow the throughput to be configurable similar to collectionId and databaseId. | private void createClients() {
String csvFile = "clientHostAndKey.txt";
String line = "";
String splitBy = ";";
try (BufferedReader br = new BufferedReader(new FileReader(csvFile))) {
while ((line = br.readLine()) != null) {
String[] hostAndKey = line.split(splitBy);
if (hostAndKey.length >= 2) {
String endpoint = host... | CosmosAsyncContainer cosmosAsyncContainer = cosmosAsyncDatabase.createContainerIfNotExists(configuration.getCollectionId(), PARTITION_KEY, 100000).block().getContainer(); | private void createClients() {
String csvFile = "clientHostAndKey.txt";
String line = "";
String splitBy = ";";
try (BufferedReader br = new BufferedReader(new FileReader(csvFile))) {
while ((line = br.readLine()) != null) {
String[] hostAndKey = line.split(splitBy);
if (hostAndKey.length >= 2) {
String endpoint = host... | class AsynReadWithMultipleClients<T> {
private final static String PARTITION_KEY = "/pk";
private final static String ACCOUNT_ENDPOINT_TAG = "AccountEndpoint=";
private final static String ACCOUNT_KEY_TAG = "AccountKey=";
private final Semaphore concurrencyControlSemaphore;
private final Logger logger;
private final Co... | class AsynReadWithMultipleClients<T> {
private final static String PARTITION_KEY = "/pk";
private final static String ACCOUNT_ENDPOINT_TAG = "AccountEndpoint=";
private final static String ACCOUNT_KEY_TAG = "AccountKey=";
private final Semaphore concurrencyControlSemaphore;
private final Logger logger;
private final Co... |
discussed offline | private void createClients() {
String csvFile = "clientHostAndKey.txt";
String line = "";
String splitBy = ";";
try (BufferedReader br = new BufferedReader(new FileReader(csvFile))) {
while ((line = br.readLine()) != null) {
String[] hostAndKey = line.split(splitBy);
if (hostAndKey.length >= 2) {
String endpoint = host... | logger.info("Client have been initialized with data created for host {}", hostAndKey[0]); | private void createClients() {
String csvFile = "clientHostAndKey.txt";
String line = "";
String splitBy = ";";
try (BufferedReader br = new BufferedReader(new FileReader(csvFile))) {
while ((line = br.readLine()) != null) {
String[] hostAndKey = line.split(splitBy);
if (hostAndKey.length >= 2) {
String endpoint = host... | class AsynReadWithMultipleClients<T> {
private final static String PARTITION_KEY = "/pk";
private final static String ACCOUNT_ENDPOINT_TAG = "AccountEndpoint=";
private final static String ACCOUNT_KEY_TAG = "AccountKey=";
private final Semaphore concurrencyControlSemaphore;
private final Logger logger;
private final Co... | class AsynReadWithMultipleClients<T> {
private final static String PARTITION_KEY = "/pk";
private final static String ACCOUNT_ENDPOINT_TAG = "AccountEndpoint=";
private final static String ACCOUNT_KEY_TAG = "AccountKey=";
private final Semaphore concurrencyControlSemaphore;
private final Logger logger;
private final Co... |
discussed offline | private void createClients() {
String csvFile = "clientHostAndKey.txt";
String line = "";
String splitBy = ";";
try (BufferedReader br = new BufferedReader(new FileReader(csvFile))) {
while ((line = br.readLine()) != null) {
String[] hostAndKey = line.split(splitBy);
if (hostAndKey.length >= 2) {
String endpoint = host... | logger.info("Client have been initialized with host {}", hostAndKey[0]); | private void createClients() {
String csvFile = "clientHostAndKey.txt";
String line = "";
String splitBy = ";";
try (BufferedReader br = new BufferedReader(new FileReader(csvFile))) {
while ((line = br.readLine()) != null) {
String[] hostAndKey = line.split(splitBy);
if (hostAndKey.length >= 2) {
String endpoint = host... | class AsynReadWithMultipleClients<T> {
private final static String PARTITION_KEY = "/pk";
private final static String ACCOUNT_ENDPOINT_TAG = "AccountEndpoint=";
private final static String ACCOUNT_KEY_TAG = "AccountKey=";
private final Semaphore concurrencyControlSemaphore;
private final Logger logger;
private final Co... | class AsynReadWithMultipleClients<T> {
private final static String PARTITION_KEY = "/pk";
private final static String ACCOUNT_ENDPOINT_TAG = "AccountEndpoint=";
private final static String ACCOUNT_KEY_TAG = "AccountKey=";
private final Semaphore concurrencyControlSemaphore;
private final Logger logger;
private final Co... |
it meant to be , had created configuration property for it .It was missed during usage , fixed it . | private void createClients() {
String csvFile = "clientHostAndKey.txt";
String line = "";
String splitBy = ";";
try (BufferedReader br = new BufferedReader(new FileReader(csvFile))) {
while ((line = br.readLine()) != null) {
String[] hostAndKey = line.split(splitBy);
if (hostAndKey.length >= 2) {
String endpoint = host... | CosmosAsyncContainer cosmosAsyncContainer = cosmosAsyncDatabase.createContainerIfNotExists(configuration.getCollectionId(), PARTITION_KEY, 100000).block().getContainer(); | private void createClients() {
String csvFile = "clientHostAndKey.txt";
String line = "";
String splitBy = ";";
try (BufferedReader br = new BufferedReader(new FileReader(csvFile))) {
while ((line = br.readLine()) != null) {
String[] hostAndKey = line.split(splitBy);
if (hostAndKey.length >= 2) {
String endpoint = host... | class AsynReadWithMultipleClients<T> {
private final static String PARTITION_KEY = "/pk";
private final static String ACCOUNT_ENDPOINT_TAG = "AccountEndpoint=";
private final static String ACCOUNT_KEY_TAG = "AccountKey=";
private final Semaphore concurrencyControlSemaphore;
private final Logger logger;
private final Co... | class AsynReadWithMultipleClients<T> {
private final static String PARTITION_KEY = "/pk";
private final static String ACCOUNT_ENDPOINT_TAG = "AccountEndpoint=";
private final static String ACCOUNT_KEY_TAG = "AccountKey=";
private final Semaphore concurrencyControlSemaphore;
private final Logger logger;
private final Co... |
done | private void createClients() {
String csvFile = "clientHostAndKey.txt";
String line = "";
String splitBy = ";";
try (BufferedReader br = new BufferedReader(new FileReader(csvFile))) {
while ((line = br.readLine()) != null) {
String[] hostAndKey = line.split(splitBy);
if (hostAndKey.length >= 2) {
String endpoint = host... | MeterRegistry registry = configuration.getAzureMonitorMeterRegistry(); | private void createClients() {
String csvFile = "clientHostAndKey.txt";
String line = "";
String splitBy = ";";
try (BufferedReader br = new BufferedReader(new FileReader(csvFile))) {
while ((line = br.readLine()) != null) {
String[] hostAndKey = line.split(splitBy);
if (hostAndKey.length >= 2) {
String endpoint = host... | class AsynReadWithMultipleClients<T> {
private final static String PARTITION_KEY = "/pk";
private final static String ACCOUNT_ENDPOINT_TAG = "AccountEndpoint=";
private final static String ACCOUNT_KEY_TAG = "AccountKey=";
private final Semaphore concurrencyControlSemaphore;
private final Logger logger;
private final Co... | class AsynReadWithMultipleClients<T> {
private final static String PARTITION_KEY = "/pk";
private final static String ACCOUNT_ENDPOINT_TAG = "AccountEndpoint=";
private final static String ACCOUNT_KEY_TAG = "AccountKey=";
private final Semaphore concurrencyControlSemaphore;
private final Logger logger;
private final Co... |
discussed offline | private void createClients() {
String csvFile = "clientHostAndKey.txt";
BufferedReader br = null;
String line = "";
String splitBy = ",";
try {
br = new BufferedReader(new FileReader(csvFile));
while ((line = br.readLine()) != null) {
String[] hostAndKey = line.split(splitBy);
if (hostAndKey.length == 2) {
CosmosAsyncC... | if (!configuration.isDeleteCollections()) { | private void createClients() {
String csvFile = "clientHostAndKey.txt";
String line = "";
String splitBy = ";";
try (BufferedReader br = new BufferedReader(new FileReader(csvFile))) {
while ((line = br.readLine()) != null) {
String[] hostAndKey = line.split(splitBy);
if (hostAndKey.length >= 2) {
String endpoint = host... | class AsynReadWithMultipleClients<T> {
private final static String PARTITION_KEY = "/pk";
private final Semaphore concurrencyControlSemaphore;
private final Logger logger;
private final Configuration configuration;
private MetricRegistry metricsRegistry = new MetricRegistry();
private ScheduledReporter reporter;
privat... | class AsynReadWithMultipleClients<T> {
private final static String PARTITION_KEY = "/pk";
private final static String ACCOUNT_ENDPOINT_TAG = "AccountEndpoint=";
private final static String ACCOUNT_KEY_TAG = "AccountKey=";
private final Semaphore concurrencyControlSemaphore;
private final Logger logger;
private final Co... |
Could you use one check of CoreUtil.isNullOrEmpty() here? | public AzureKeyCredential update(String key) {
Objects.requireNonNull(key);
if (key.isEmpty()) {
throw logger.logExceptionAsError(new IllegalArgumentException("'key' cannot be empty."));
}
this.key = key;
return this;
} | if (key.isEmpty()) { | public AzureKeyCredential update(String key) {
Objects.requireNonNull(key, "'key' cannot be null.");
if (key.isEmpty()) {
throw logger.logExceptionAsError(new IllegalArgumentException("'key' cannot be empty."));
}
this.key = key;
return this;
} | class AzureKeyCredential {
private final ClientLogger logger = new ClientLogger(AzureKeyCredential.class);
private String key;
/**
* Creates a credential that authorizes request with the given key.
*
* @param key The key used to authorize requests.
* @throws NullPointerException If {@code key} is {@code null}.
* @throw... | class AzureKeyCredential {
private final ClientLogger logger = new ClientLogger(AzureKeyCredential.class);
private String key;
/**
* Creates a credential that authorizes request with the given key.
*
* @param key The key used to authorize requests.
* @throws NullPointerException If {@code key} is {@code null}.
* @throw... |
Definitely could but our guidelines state if we expect a non-null parameter and we get null a `NullPointerException` should be thrown (the `Objects.requireNonNull` check) and then if we get a value that we don't expect that isn't null throw a `IllegalArgumentException` (the `isEmpty` check). | public AzureKeyCredential update(String key) {
Objects.requireNonNull(key);
if (key.isEmpty()) {
throw logger.logExceptionAsError(new IllegalArgumentException("'key' cannot be empty."));
}
this.key = key;
return this;
} | if (key.isEmpty()) { | public AzureKeyCredential update(String key) {
Objects.requireNonNull(key, "'key' cannot be null.");
if (key.isEmpty()) {
throw logger.logExceptionAsError(new IllegalArgumentException("'key' cannot be empty."));
}
this.key = key;
return this;
} | class AzureKeyCredential {
private final ClientLogger logger = new ClientLogger(AzureKeyCredential.class);
private String key;
/**
* Creates a credential that authorizes request with the given key.
*
* @param key The key used to authorize requests.
* @throws NullPointerException If {@code key} is {@code null}.
* @throw... | class AzureKeyCredential {
private final ClientLogger logger = new ClientLogger(AzureKeyCredential.class);
private String key;
/**
* Creates a credential that authorizes request with the given key.
*
* @param key The key used to authorize requests.
* @throws NullPointerException If {@code key} is {@code null}.
* @throw... |
too much indentation? | public void testExcludeCredentials() throws Exception {
DefaultAzureCredential credential = new DefaultAzureCredentialBuilder()
.excludeEnvironmentCredential()
.excludeAzureCliCredential()
.excludeManagedIdentityCredential()
.excludeSharedTokenCacheCredential()
.build();
} | .excludeEnvironmentCredential() | public void testExcludeCredentials() throws Exception {
DefaultAzureCredential credential = new DefaultAzureCredentialBuilder()
.excludeEnvironmentCredential()
.excludeAzureCliCredential()
.excludeManagedIdentityCredential()
.excludeSharedTokenCacheCredential()
.build();
} | class DefaultAzureCredentialTest {
private final String tenantId = "contoso.com";
private final String clientId = UUID.randomUUID().toString();
@Test
public void testUseEnvironmentCredential() throws Exception {
Configuration configuration = Configuration.getGlobalConfiguration();
try {
String secret = "secret";
String... | class DefaultAzureCredentialTest {
private final String tenantId = "contoso.com";
private final String clientId = UUID.randomUUID().toString();
@Test
public void testUseEnvironmentCredential() throws Exception {
Configuration configuration = Configuration.getGlobalConfiguration();
try {
String secret = "secret";
String... |
This should be synchronized or declare `this.managementChannel` as AtomicReference. | public Mono<EventHubManagementNode> getManagementNode() {
if (isDisposed()) {
return Mono.error(logger.logExceptionAsError(new IllegalStateException(String.format(
"connectionId[%s]: Connection is disposed. Cannot get management instance", connectionId))));
}
return getReactorConnection().then(Mono.fromCallable(() -> {... | if (managementChannel == null) { | public Mono<EventHubManagementNode> getManagementNode() {
if (isDisposed()) {
return Mono.error(logger.logExceptionAsError(new IllegalStateException(String.format(
"connectionId[%s]: Connection is disposed. Cannot get management instance", connectionId))));
}
return getReactorConnection().then(Mono.fromCallable(this::g... | class EventHubReactorAmqpConnection extends ReactorConnection implements EventHubAmqpConnection {
private static final String MANAGEMENT_SESSION_NAME = "mgmt-session";
private static final String MANAGEMENT_LINK_NAME = "mgmt";
private static final String MANAGEMENT_ADDRESS = "$management";
private final ClientLogger lo... | class EventHubReactorAmqpConnection extends ReactorConnection implements EventHubAmqpConnection {
private static final String MANAGEMENT_SESSION_NAME = "mgmt-session";
private static final String MANAGEMENT_LINK_NAME = "mgmt";
private static final String MANAGEMENT_ADDRESS = "$management";
private final ClientLogger lo... |
There is Assertions.assertThrows. | void createBatchWhenSizeTooBigThanOnSendLink() {
int maxLinkSize = 1024;
int batchSize = maxLinkSize + 10;
final CreateBatchOptions options = new CreateBatchOptions().setMaximumSizeInBytes(batchSize);
when(asyncSender.createBatch(options)).thenThrow(new IllegalArgumentException("too large size"));
try {
sender.createBa... | sender.createBatch(options); | void createBatchWhenSizeTooBigThanOnSendLink() {
int maxLinkSize = 1024;
int batchSize = maxLinkSize + 10;
final CreateBatchOptions options = new CreateBatchOptions().setMaximumSizeInBytes(batchSize);
when(asyncSender.createBatch(options)).thenThrow(new IllegalArgumentException("too large size"));
Assertions.assertThro... | class ServiceBusSenderClientTest {
private static final String NAMESPACE = "my-namespace";
private static final String ENTITY_NAME = "my-servicebus-entity";
@Mock
private ErrorContextProvider errorContextProvider;
@Mock
private ServiceBusSenderAsyncClient asyncSender;
@Captor
private ArgumentCaptor<ServiceBusMessage> s... | class ServiceBusSenderClientTest {
private static final String NAMESPACE = "my-namespace";
private static final String ENTITY_NAME = "my-servicebus-entity";
@Mock
private ServiceBusSenderAsyncClient asyncSender;
@Captor
private ArgumentCaptor<ServiceBusMessage> singleMessageCaptor;
private ServiceBusSenderClient sender... |
You don't need all this logic. You can assert that the correct properties for the batch were passed to asyncClient. We assume asyncClient does the right thing | void createsMessageBatchWithSize() {
int maxLinkSize = 10000;
int batchSize = 1024;
int eventOverhead = 46;
int maxEventPayload = batchSize - eventOverhead;
final ServiceBusMessage message = new ServiceBusMessage(new byte[maxEventPayload]);
final ServiceBusMessage tooLargeMessage = new ServiceBusMessage(new byte[maxEve... | int eventOverhead = 46; | void createsMessageBatchWithSize() {
int batchSize = 1024;
final CreateBatchOptions options = new CreateBatchOptions().setMaximumSizeInBytes(batchSize);
final ServiceBusMessageBatch batch = new ServiceBusMessageBatch(batchSize, null, null,
null);
when(asyncSender.createBatch(options)).thenReturn(Mono.just(batch));
Serv... | class ServiceBusSenderClientTest {
private static final String NAMESPACE = "my-namespace";
private static final String ENTITY_NAME = "my-servicebus-entity";
@Mock
private ErrorContextProvider errorContextProvider;
@Mock
private ServiceBusSenderAsyncClient asyncSender;
@Captor
private ArgumentCaptor<ServiceBusMessage> s... | class ServiceBusSenderClientTest {
private static final String NAMESPACE = "my-namespace";
private static final String ENTITY_NAME = "my-servicebus-entity";
@Mock
private ServiceBusSenderAsyncClient asyncSender;
@Captor
private ArgumentCaptor<ServiceBusMessage> singleMessageCaptor;
private ServiceBusSenderClient sender... |
```suggestion final ServiceBusMessageBatch batch = new ServiceBusMessageBatch(batchSize, null, null, ``` | void createsMessageBatchWithSize() {
int batchSize = 1024;
final CreateBatchOptions options = new CreateBatchOptions().setMaximumSizeInBytes(batchSize);
ServiceBusMessageBatch batch = new ServiceBusMessageBatch(batchSize, null, null,
null);
when(asyncSender.createBatch(options)).thenReturn(Mono.just(batch));
ServiceBu... | ServiceBusMessageBatch batch = new ServiceBusMessageBatch(batchSize, null, null, | void createsMessageBatchWithSize() {
int batchSize = 1024;
final CreateBatchOptions options = new CreateBatchOptions().setMaximumSizeInBytes(batchSize);
final ServiceBusMessageBatch batch = new ServiceBusMessageBatch(batchSize, null, null,
null);
when(asyncSender.createBatch(options)).thenReturn(Mono.just(batch));
Serv... | class ServiceBusSenderClientTest {
private static final String NAMESPACE = "my-namespace";
private static final String ENTITY_NAME = "my-servicebus-entity";
@Mock
private ServiceBusSenderAsyncClient asyncSender;
@Captor
private ArgumentCaptor<ServiceBusMessage> singleMessageCaptor;
private ServiceBusSenderClient sender... | class ServiceBusSenderClientTest {
private static final String NAMESPACE = "my-namespace";
private static final String ENTITY_NAME = "my-servicebus-entity";
@Mock
private ServiceBusSenderAsyncClient asyncSender;
@Captor
private ArgumentCaptor<ServiceBusMessage> singleMessageCaptor;
private ServiceBusSenderClient sender... |
Instead of using null, null.. can you use getFullyQualifiedDomainName() and getEventHubName() ? These properties are set in IntegrationTestBase. | public void sendSmallEventsFullBatchPartitionKey() {
final EventDataBatch batch = new EventDataBatch(ClientConstants.MAX_MESSAGE_LENGTH_BYTES, null, PARTITION_KEY, contextProvider,
new TracerProvider(Collections.emptyList()), null, null);
int count = 0;
while (batch.tryAdd(createData())) {
if (count % 100 == 0) {
logge... | new TracerProvider(Collections.emptyList()), null, null); | public void sendSmallEventsFullBatchPartitionKey() {
final EventDataBatch batch = new EventDataBatch(ClientConstants.MAX_MESSAGE_LENGTH_BYTES, null, PARTITION_KEY, contextProvider,
new TracerProvider(Collections.emptyList()), getFullyQualifiedDomainName(), getEventHubName());
int count = 0;
while (batch.tryAdd(createDa... | class EventDataBatchIntegrationTest extends IntegrationTestBase {
private static final String PARTITION_KEY = "PartitionIDCopyFromProducerOption";
private EventHubAsyncClient client;
private EventHubProducerAsyncClient producer;
@Mock
private ErrorContextProvider contextProvider;
public EventDataBatchIntegrationTest() ... | class EventDataBatchIntegrationTest extends IntegrationTestBase {
private static final String PARTITION_KEY = "PartitionIDCopyFromProducerOption";
private EventHubProducerAsyncClient producer;
private EventHubClientBuilder builder;
@Mock
private ErrorContextProvider contextProvider;
public EventDataBatchIntegrationTest... |
updated. | public void sendSmallEventsFullBatchPartitionKey() {
final EventDataBatch batch = new EventDataBatch(ClientConstants.MAX_MESSAGE_LENGTH_BYTES, null, PARTITION_KEY, contextProvider,
new TracerProvider(Collections.emptyList()), null, null);
int count = 0;
while (batch.tryAdd(createData())) {
if (count % 100 == 0) {
logge... | new TracerProvider(Collections.emptyList()), null, null); | public void sendSmallEventsFullBatchPartitionKey() {
final EventDataBatch batch = new EventDataBatch(ClientConstants.MAX_MESSAGE_LENGTH_BYTES, null, PARTITION_KEY, contextProvider,
new TracerProvider(Collections.emptyList()), getFullyQualifiedDomainName(), getEventHubName());
int count = 0;
while (batch.tryAdd(createDa... | class EventDataBatchIntegrationTest extends IntegrationTestBase {
private static final String PARTITION_KEY = "PartitionIDCopyFromProducerOption";
private EventHubAsyncClient client;
private EventHubProducerAsyncClient producer;
@Mock
private ErrorContextProvider contextProvider;
public EventDataBatchIntegrationTest() ... | class EventDataBatchIntegrationTest extends IntegrationTestBase {
private static final String PARTITION_KEY = "PartitionIDCopyFromProducerOption";
private EventHubProducerAsyncClient producer;
private EventHubClientBuilder builder;
@Mock
private ErrorContextProvider contextProvider;
public EventDataBatchIntegrationTest... |
"QUEUE OR TOPIC NAME" | public void sendBatch() {
ServiceBusSenderAsyncClient sender = new ServiceBusClientBuilder()
.connectionString(
"Endpoint={fully-qualified-namespace};SharedAccessKeyName={policy-name};SharedAccessKey={key}")
.buildSenderClientBuilder()
.entityName("<QUEUE-NAME>")
.buildAsyncClient();
sender.createBatch().flatMap(batch ... | .entityName("<QUEUE-NAME>") | public void sendBatch() {
ServiceBusSenderAsyncClient sender = new ServiceBusClientBuilder()
.connectionString(
"Endpoint={fully-qualified-namespace};SharedAccessKeyName={policy-name};SharedAccessKey={key}")
.buildSenderClientBuilder()
.entityName("<QUEUE OR TOPIC NAME>")
.buildAsyncClient();
sender.createBatch().flatM... | class ServiceBusSenderAsyncClientJavaDocCodeSamples {
private final ServiceBusClientBuilder builder = new ServiceBusClientBuilder()
.connectionString("fake-string");
/**
* Code snippet demonstrating how to create an {@link ServiceBusSenderAsyncClient}.
*/
public void instantiate() {
ServiceBusSenderAsyncClient sender =... | class ServiceBusSenderAsyncClientJavaDocCodeSamples {
private final ServiceBusClientBuilder builder = new ServiceBusClientBuilder()
.connectionString("fake-string");
/**
* Code snippet demonstrating how to create an {@link ServiceBusSenderAsyncClient}.
*/
public void instantiate() {
ServiceBusSenderAsyncClient sender =... |
is there a createBatch that takes an int parameter? I think the snippet text is wrong | public void batchSizeLimited() {
final ServiceBusSenderAsyncClient sender = new ServiceBusClientBuilder()
.buildSenderClientBuilder()
.buildAsyncClient();
final ServiceBusMessage firstMessage = new ServiceBusMessage("92".getBytes(UTF_8));
firstMessage.getProperties().put("telemetry", "latency");
final ServiceBusMessage... | public void batchSizeLimited() {
final ServiceBusSenderAsyncClient sender = new ServiceBusClientBuilder()
.buildSenderClientBuilder()
.buildAsyncClient();
final ServiceBusMessage firstMessage = new ServiceBusMessage("92".getBytes(UTF_8));
firstMessage.getProperties().put("telemetry", "latency");
final ServiceBusMessage... | class ServiceBusSenderAsyncClientJavaDocCodeSamples {
private final ServiceBusClientBuilder builder = new ServiceBusClientBuilder()
.connectionString("fake-string");
/**
* Code snippet demonstrating how to create an {@link ServiceBusSenderAsyncClient}.
*/
public void instantiate() {
ServiceBusSenderAsyncClient sender =... | class ServiceBusSenderAsyncClientJavaDocCodeSamples {
private final ServiceBusClientBuilder builder = new ServiceBusClientBuilder()
.connectionString("fake-string");
/**
* Code snippet demonstrating how to create an {@link ServiceBusSenderAsyncClient}.
*/
public void instantiate() {
ServiceBusSenderAsyncClient sender =... | |
you need to specify queueName or topicName + subscription. | public void receiveAll() {
ServiceBusReceiverAsyncClient receiver = new ServiceBusClientBuilder()
.connectionString("fake-string")
.buildReceiverClientBuilder()
.buildAsyncClient();
Disposable subscription = receiver.receive().subscribe(receivedMessage -> {
String messageId = receivedMessage.getMessageId();
System.out.... | .buildAsyncClient(); | public void receiveAll() {
ServiceBusReceiverAsyncClient receiver = new ServiceBusClientBuilder()
.connectionString("fake-string")
.buildReceiverClientBuilder()
.queueName("<QUEUE-NAME>")
.buildAsyncClient();
Disposable subscription = receiver.receive().subscribe(receivedMessage -> {
String messageId = receivedMessage.... | class ServiceBusReceiverAsyncClientJavaDocCodeSamples {
private final ServiceBusReceiverAsyncClient consumer = new ServiceBusClientBuilder()
.connectionString("fake-string")
.buildReceiverClientBuilder()
.queueName("<QUEUE-NAME>")
.buildAsyncClient();
public void initialization() {
ServiceBusReceiverAsyncClient consume... | class ServiceBusReceiverAsyncClientJavaDocCodeSamples {
private final ServiceBusReceiverAsyncClient consumer = new ServiceBusClientBuilder()
.connectionString("fake-string")
.buildReceiverClientBuilder()
.queueName("<QUEUE-NAME>")
.buildAsyncClient();
public void initialization() {
ServiceBusReceiverAsyncClient consume... |
You need to dispose of consumer as well, like you did in other samples. (even if it doesn't appear in the snippet.) | public void receiveAll() {
ServiceBusReceiverAsyncClient receiver = new ServiceBusClientBuilder()
.connectionString("fake-string")
.buildReceiverClientBuilder()
.buildAsyncClient();
Disposable subscription = receiver.receive().subscribe(receivedMessage -> {
String messageId = receivedMessage.getMessageId();
System.out.... | } | public void receiveAll() {
ServiceBusReceiverAsyncClient receiver = new ServiceBusClientBuilder()
.connectionString("fake-string")
.buildReceiverClientBuilder()
.queueName("<QUEUE-NAME>")
.buildAsyncClient();
Disposable subscription = receiver.receive().subscribe(receivedMessage -> {
String messageId = receivedMessage.... | class ServiceBusReceiverAsyncClientJavaDocCodeSamples {
private final ServiceBusReceiverAsyncClient consumer = new ServiceBusClientBuilder()
.connectionString("fake-string")
.buildReceiverClientBuilder()
.queueName("<QUEUE-NAME>")
.buildAsyncClient();
public void initialization() {
ServiceBusReceiverAsyncClient consume... | class ServiceBusReceiverAsyncClientJavaDocCodeSamples {
private final ServiceBusReceiverAsyncClient consumer = new ServiceBusClientBuilder()
.connectionString("fake-string")
.buildReceiverClientBuilder()
.queueName("<QUEUE-NAME>")
.buildAsyncClient();
public void initialization() {
ServiceBusReceiverAsyncClient consume... |
Removed as this should be caught by the check for `Page.class` and should be deserialized through that code path. | private static boolean isReturnTypeDecodable(Type returnType) {
if (returnType == null) {
return false;
}
if (TypeUtil.isTypeOrSubTypeOf(returnType, Mono.class)) {
returnType = TypeUtil.getTypeArgument(returnType);
}
if (TypeUtil.isTypeOrSubTypeOf(returnType, ResponseBase.class)) {
ParameterizedType parameterizedType =... | private static boolean isReturnTypeDecodable(Type returnType) {
if (returnType == null) {
return false;
}
if (TypeUtil.isTypeOrSubTypeOf(returnType, Mono.class)) {
returnType = TypeUtil.getTypeArgument(returnType);
}
if (TypeUtil.isTypeOrSubTypeOf(returnType, ResponseBase.class)) {
ParameterizedType parameterizedType =... | class HttpResponseBodyDecoder {
/**
* Decodes body of a http response.
*
* The content reading and decoding happens when caller subscribe to the returned {@code Mono<Object>}, if the
* response body is not decodable then {@code Mono.empty()} will be returned.
*
* @param body the response body to decode, null for this p... | class HttpResponseBodyDecoder {
/**
* Decodes body of a http response.
*
* The content reading and decoding happens when caller subscribe to the returned {@code Mono<Object>}, if the
* response body is not decodable then {@code Mono.empty()} will be returned.
*
* @param body the response body to decode, null for this p... | |
Should this just be `Objects.requireNonNull`, if `null` is returned here it will eventually lead to a `NullPointerException` in another, less obvious, location. | private static List<String> toLonLatStrings(GeoPoint point) {
if (point == null) {
return null;
}
return Arrays.asList(String.valueOf(point.getLongitude()), String.valueOf(point.getLatitude()));
} | } | private static List<String> toLonLatStrings(GeoPoint point) {
Objects.requireNonNull(point);
return Arrays.asList(String.valueOf(point.getLongitude()), String.valueOf(point.getLatitude()));
} | class with the given name and GeographyPoint value.
*
* @param name Name of the scoring parameter.
* @param value Value of the scoring parameter.
*/
public ScoringParameter(String name, GeoPoint value) {
this(name, toLonLatStrings(value));
} | class with the given name and GeographyPoint value.
*
* @param name Name of the scoring parameter.
* @param value Value of the scoring parameter.
*/
public ScoringParameter(String name, GeoPoint value) {
this(name, toLonLatStrings(value));
} |
Should we describe that these messages are also autocompleted? | public static void main(String[] args) {
String connectionString = System.getenv("AZURE_SERVICEBUS_CONNECTION_STRING");
ServiceBusReceiverAsyncClient receiverAsyncClient = new ServiceBusClientBuilder()
.connectionString(connectionString)
.buildReceiverClientBuilder()
.queueName("<<queue-name>>")
.buildAsyncClient();
Di... | System.out.println("Received Message Id:" + message.getMessageId()); | public static void main(String[] args) {
String connectionString = "Endpoint={fully-qualified-namespace};SharedAccessKeyName={policy-name};"
+ "SharedAccessKey={key}";
ServiceBusReceiverAsyncClient receiverAsyncClient = new ServiceBusClientBuilder()
.connectionString(connectionString)
.receiver()
.queueName("<<queue-na... | class ReceiveMessageAsyncSample {
/**
* Main method to invoke this demo on how to receive an {@link ServiceBusMessage} from an Azure Service Bus
* Queue
*
* @param args Unused arguments to the program.
*/
} | class ReceiveMessageAsyncSample {
/**
* Main method to invoke this demo on how to receive an {@link ServiceBusMessage} from an Azure Service Bus
* Queue
*
* @param args Unused arguments to the program.
*/
} |
Could this or `toLonLatStrings` be changed so the `NullPointerException` thrown from either of these methods instead of the other constructor when `value` is null. | public ScoringParameter(String name, GeoPoint value) {
this(name, toLonLatStrings(value));
} | this(name, toLonLatStrings(value)); | public ScoringParameter(String name, GeoPoint value) {
this(name, toLonLatStrings(value));
} | class with the given name and GeographyPoint value.
*
* @param name Name of the scoring parameter.
* @param value Value of the scoring parameter.
*/ | class with the given name and GeographyPoint value.
*
* @param name Name of the scoring parameter.
* @param value Value of the scoring parameter.
*/ |
Should make sure the constructor and this method follow the same pattern around ensuring the internal values list isn't mutable. Right now the constructor will clone the list, effectively a deep clone based on how Strings work, ensuring it is immutable if the original list changes but this will return a reference to th... | public List<String> getValues() {
return values;
} | return values; | public List<String> getValues() {
return new ArrayList<>(values);
} | class with the given name and GeographyPoint value.
*
* @param name Name of the scoring parameter.
* @param value Value of the scoring parameter.
*/
public ScoringParameter(String name, GeoPoint value) {
this(name, toLonLatStrings(value));
} | class with the given name and GeographyPoint value.
*
* @param name Name of the scoring parameter.
* @param value Value of the scoring parameter.
*/
public ScoringParameter(String name, GeoPoint value) {
this(name, toLonLatStrings(value));
} |
switch to null pointer exception check. | private static List<String> toLonLatStrings(GeoPoint point) {
if (point == null) {
return null;
}
return Arrays.asList(String.valueOf(point.getLongitude()), String.valueOf(point.getLatitude()));
} | } | private static List<String> toLonLatStrings(GeoPoint point) {
Objects.requireNonNull(point);
return Arrays.asList(String.valueOf(point.getLongitude()), String.valueOf(point.getLatitude()));
} | class with the given name and GeographyPoint value.
*
* @param name Name of the scoring parameter.
* @param value Value of the scoring parameter.
*/
public ScoringParameter(String name, GeoPoint value) {
this(name, toLonLatStrings(value));
} | class with the given name and GeographyPoint value.
*
* @param name Name of the scoring parameter.
* @param value Value of the scoring parameter.
*/
public ScoringParameter(String name, GeoPoint value) {
this(name, toLonLatStrings(value));
} |
Why do we need to repeat creating `flattenValue`? This could be simplified to the following: ```java return name + SEPARATOR + flattenValue; ``` | public String toString() {
String flattenValue = values.stream().filter(value -> !CoreUtils.isNullOrEmpty(value))
.map(this::escapeValue).collect(Collectors.joining(COMMA));
if (CoreUtils.isNullOrEmpty(flattenValue)) {
throw logger.logExceptionAsError(
new IllegalArgumentException("There must be at least one valid valu... | .map(this::escapeValue).collect(Collectors.joining(COMMA)); | public String toString() {
String flattenValue = values.stream().filter(value -> !CoreUtils.isNullOrEmpty(value))
.map(ScoringParameter::escapeValue).collect(Collectors.joining(COMMA));
if (CoreUtils.isNullOrEmpty(flattenValue)) {
throw logger.logExceptionAsError(
new IllegalArgumentException("There must be at least on... | class with the given name and GeographyPoint value.
*
* @param name Name of the scoring parameter.
* @param value Value of the scoring parameter.
*/
public ScoringParameter(String name, GeoPoint value) {
this(name, toLonLatStrings(value));
} | class with the given name and GeographyPoint value.
*
* @param name Name of the scoring parameter.
* @param value Value of the scoring parameter.
*/
public ScoringParameter(String name, GeoPoint value) {
this(name, toLonLatStrings(value));
} |
Put the null checking here. | public ScoringParameter(String name, GeoPoint value) {
this(name, toLonLatStrings(value));
} | this(name, toLonLatStrings(value)); | public ScoringParameter(String name, GeoPoint value) {
this(name, toLonLatStrings(value));
} | class with the given name and GeographyPoint value.
*
* @param name Name of the scoring parameter.
* @param value Value of the scoring parameter.
*/ | class with the given name and GeographyPoint value.
*
* @param name Name of the scoring parameter.
* @param value Value of the scoring parameter.
*/ |
Good point. Will deep clone the list. | public List<String> getValues() {
return values;
} | return values; | public List<String> getValues() {
return new ArrayList<>(values);
} | class with the given name and GeographyPoint value.
*
* @param name Name of the scoring parameter.
* @param value Value of the scoring parameter.
*/
public ScoringParameter(String name, GeoPoint value) {
this(name, toLonLatStrings(value));
} | class with the given name and GeographyPoint value.
*
* @param name Name of the scoring parameter.
* @param value Value of the scoring parameter.
*/
public ScoringParameter(String name, GeoPoint value) {
this(name, toLonLatStrings(value));
} |
In our testing subscriptions we can't create a collection with 1M throughput upfront. The workaround we have is to create a collection with 100K throughput and then scale up. Now with this auto deleting collection it means we have to do this manual process everytime. we don't want to always delete the collection. We s... | void shutdown() {
cosmosAsyncContainer.delete().block();
logger.info("Deleted test container {}" , this.configuration.getCollectionId());
cosmosClient.close();
} | cosmosAsyncContainer.delete().block(); | void shutdown() {
if (this.databaseCreated) {
cosmosAsyncDatabase.delete().block();
logger.info("Deleted temporary database {} created for this test", this.configuration.getDatabaseId());
} else if (this.collectionCreated) {
cosmosAsyncContainer.delete().block();
logger.info("Deleted temporary collection {} created for... | class AsyncBenchmark<T> {
private final MetricRegistry metricsRegistry = new MetricRegistry();
private final ScheduledReporter reporter;
private Meter successMeter;
private Meter failureMeter;
final Logger logger;
final CosmosAsyncClient cosmosClient;
final CosmosAsyncContainer cosmosAsyncContainer;
final CosmosAsyncDa... | class AsyncBenchmark<T> {
private final MetricRegistry metricsRegistry = new MetricRegistry();
private final ScheduledReporter reporter;
private Meter successMeter;
private Meter failureMeter;
private boolean databaseCreated;
private boolean collectionCreated;
final Logger logger;
final CosmosAsyncClient cosmosClient;
... |
if the application deletes it should create too. when a user runs an application, the user expects to either 1. application handles the collection creation/deletion 2. the user provides the collection and the app doesn't create nor deletes. | private void createClients() {
String csvFile = "clientHostAndKey.txt";
String line = "";
String splitBy = ";";
try (BufferedReader br = new BufferedReader(new FileReader(csvFile))) {
while ((line = br.readLine()) != null) {
String[] hostAndKey = line.split(splitBy);
if (hostAndKey.length >= 2) {
String endpoint = host... | cosmosAsyncDatabase.createContainerIfNotExists(configuration.getCollectionId(), Configuration.PARTITION_KEY, configuration.getThroughput()).block().getContainer(); | private void createClients() {
String csvFile = "clientHostAndKey.txt";
String line = "";
String splitBy = ";";
try (BufferedReader br = new BufferedReader(new FileReader(csvFile))) {
while ((line = br.readLine()) != null) {
String[] hostAndKey = line.split(splitBy);
if (hostAndKey.length >= 2) {
String endpoint = host... | class AsynReadWithMultipleClients<T> {
private final static String ACCOUNT_ENDPOINT_TAG = "AccountEndpoint=";
private final static String ACCOUNT_KEY_TAG = "AccountKey=";
private final Semaphore concurrencyControlSemaphore;
private final Logger logger;
private final Configuration configuration;
private MetricRegistry m... | class AsynReadWithMultipleClients<T> {
private final static String ACCOUNT_ENDPOINT_TAG = "AccountEndpoint=";
private final static String ACCOUNT_KEY_TAG = "AccountKey=";
private final Semaphore concurrencyControlSemaphore;
private final Logger logger;
private final Configuration configuration;
private MetricRegistry m... |
Please check current design , it is more seem less in respect to customer expectation , code will only create resource if it is not present , and only delete newly created resource and not the existing | private void createClients() {
String csvFile = "clientHostAndKey.txt";
String line = "";
String splitBy = ";";
try (BufferedReader br = new BufferedReader(new FileReader(csvFile))) {
while ((line = br.readLine()) != null) {
String[] hostAndKey = line.split(splitBy);
if (hostAndKey.length >= 2) {
String endpoint = host... | cosmosAsyncDatabase.createContainerIfNotExists(configuration.getCollectionId(), Configuration.PARTITION_KEY, configuration.getThroughput()).block().getContainer(); | private void createClients() {
String csvFile = "clientHostAndKey.txt";
String line = "";
String splitBy = ";";
try (BufferedReader br = new BufferedReader(new FileReader(csvFile))) {
while ((line = br.readLine()) != null) {
String[] hostAndKey = line.split(splitBy);
if (hostAndKey.length >= 2) {
String endpoint = host... | class AsynReadWithMultipleClients<T> {
private final static String ACCOUNT_ENDPOINT_TAG = "AccountEndpoint=";
private final static String ACCOUNT_KEY_TAG = "AccountKey=";
private final Semaphore concurrencyControlSemaphore;
private final Logger logger;
private final Configuration configuration;
private MetricRegistry m... | class AsynReadWithMultipleClients<T> {
private final static String ACCOUNT_ENDPOINT_TAG = "AccountEndpoint=";
private final static String ACCOUNT_KEY_TAG = "AccountKey=";
private final Semaphore concurrencyControlSemaphore;
private final Logger logger;
private final Configuration configuration;
private MetricRegistry m... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.