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 |
|---|---|---|---|---|---|
https://netty.io/4.0/api/io/netty/handler/codec/http/HttpResponseStatus.html#OK | void deleteQueue() {
String queueName = testResourceNamer.randomName("test", 7);
QueueDescription description = new QueueDescription().setMaxDeliveryCount(15);
CreateQueueBody createEntity = new CreateQueueBody();
CreateQueueBodyContent content = new CreateQueueBodyContent()
.setType("application/xml")
.setQueueDescrip... | assertNotNull(response); | void deleteQueue() {
String queueName = testResourceNamer.randomName("test", 7);
QueueDescription description = new QueueDescription().setMaxDeliveryCount(15);
CreateQueueBody createEntity = new CreateQueueBody();
CreateQueueBodyContent content = new CreateQueueBodyContent()
.setType("application/xml")
.setQueueDescrip... | class ServiceBusManagementClientImplIntegrationTests extends TestBase {
private final ClientLogger logger = new ClientLogger(ServiceBusManagementClientImplIntegrationTests.class);
private final ServiceBusManagementSerializer serializer = new ServiceBusManagementSerializer();
private final Duration timeout = Duration.of... | class ServiceBusManagementClientImplIntegrationTests extends TestBase {
private final ClientLogger logger = new ClientLogger(ServiceBusManagementClientImplIntegrationTests.class);
private final ServiceBusManagementSerializer serializer = new ServiceBusManagementSerializer();
private final Duration timeout = Duration.of... |
Same comment as above. You can explicitly exclude dependencies and this would tie them to netty instead of another http client. | void deleteQueue() {
String queueName = testResourceNamer.randomName("test", 7);
QueueDescription description = new QueueDescription().setMaxDeliveryCount(15);
CreateQueueBody createEntity = new CreateQueueBody();
CreateQueueBodyContent content = new CreateQueueBodyContent()
.setType("application/xml")
.setQueueDescrip... | assertNotNull(response); | void deleteQueue() {
String queueName = testResourceNamer.randomName("test", 7);
QueueDescription description = new QueueDescription().setMaxDeliveryCount(15);
CreateQueueBody createEntity = new CreateQueueBody();
CreateQueueBodyContent content = new CreateQueueBodyContent()
.setType("application/xml")
.setQueueDescrip... | class ServiceBusManagementClientImplIntegrationTests extends TestBase {
private final ClientLogger logger = new ClientLogger(ServiceBusManagementClientImplIntegrationTests.class);
private final ServiceBusManagementSerializer serializer = new ServiceBusManagementSerializer();
private final Duration timeout = Duration.of... | class ServiceBusManagementClientImplIntegrationTests extends TestBase {
private final ClientLogger logger = new ClientLogger(ServiceBusManagementClientImplIntegrationTests.class);
private final ServiceBusManagementSerializer serializer = new ServiceBusManagementSerializer();
private final Duration timeout = Duration.of... |
`queueDescription` as arg name will be more appropriate ? | public QueueDescription createQueue(QueueDescription queue) {
return asyncClient.createQueue(queue).block();
} | return asyncClient.createQueue(queue).block(); | public QueueDescription createQueue(QueueDescription queue) {
return asyncClient.createQueue(queue).block();
} | class ServiceBusManagementClient {
private final ServiceBusManagementAsyncClient asyncClient;
/**
* Creates a new instance with the given client.
*
* @param asyncClient Asynchronous client to perform management calls through.
*/
ServiceBusManagementClient(ServiceBusManagementAsyncClient asyncClient) {
this.asyncClient ... | class ServiceBusManagementClient {
private final ServiceBusManagementAsyncClient asyncClient;
/**
* Creates a new instance with the given client.
*
* @param asyncClient Asynchronous client to perform management calls through.
*/
ServiceBusManagementClient(ServiceBusManagementAsyncClient asyncClient) {
this.asyncClient ... |
Went with .NET's parameter name. | public QueueDescription createQueue(QueueDescription queue) {
return asyncClient.createQueue(queue).block();
} | return asyncClient.createQueue(queue).block(); | public QueueDescription createQueue(QueueDescription queue) {
return asyncClient.createQueue(queue).block();
} | class ServiceBusManagementClient {
private final ServiceBusManagementAsyncClient asyncClient;
/**
* Creates a new instance with the given client.
*
* @param asyncClient Asynchronous client to perform management calls through.
*/
ServiceBusManagementClient(ServiceBusManagementAsyncClient asyncClient) {
this.asyncClient ... | class ServiceBusManagementClient {
private final ServiceBusManagementAsyncClient asyncClient;
/**
* Creates a new instance with the given client.
*
* @param asyncClient Asynchronous client to perform management calls through.
*/
ServiceBusManagementClient(ServiceBusManagementAsyncClient asyncClient) {
this.asyncClient ... |
blockSize is long now right? | public OutputStream newOutputStream(Path path, OpenOption... options) throws IOException {
if (options == null || options.length == 0) {
options = new OpenOption[] {
StandardOpenOption.CREATE,
StandardOpenOption.WRITE,
StandardOpenOption.TRUNCATE_EXISTING };
}
List<OpenOption> optionsList = Arrays.asList(options);
List... | Integer blockSize = fs.getBlockSize() == null ? null : fs.getBlockSize().intValue(); | public OutputStream newOutputStream(Path path, OpenOption... options) throws IOException {
if (options == null || options.length == 0) {
options = new OpenOption[] {
StandardOpenOption.CREATE,
StandardOpenOption.WRITE,
StandardOpenOption.TRUNCATE_EXISTING };
}
List<OpenOption> optionsList = Arrays.asList(options);
List... | class AzureFileSystemProvider extends FileSystemProvider {
private final ClientLogger logger = new ClientLogger(AzureFileSystemProvider.class);
public static final String CONTENT_TYPE = "Content-Type";
public static final String CONTENT_DISPOSITION = "Content-Disposition";
public static final String CONTENT_LANGUAGE = ... | class AzureFileSystemProvider extends FileSystemProvider {
private final ClientLogger logger = new ClientLogger(AzureFileSystemProvider.class);
public static final String CONTENT_TYPE = "Content-Type";
public static final String CONTENT_DISPOSITION = "Content-Disposition";
public static final String CONTENT_LANGUAGE = ... |
Or is this on purpose due to constraints below? | public OutputStream newOutputStream(Path path, OpenOption... options) throws IOException {
if (options == null || options.length == 0) {
options = new OpenOption[] {
StandardOpenOption.CREATE,
StandardOpenOption.WRITE,
StandardOpenOption.TRUNCATE_EXISTING };
}
List<OpenOption> optionsList = Arrays.asList(options);
List... | Integer blockSize = fs.getBlockSize() == null ? null : fs.getBlockSize().intValue(); | public OutputStream newOutputStream(Path path, OpenOption... options) throws IOException {
if (options == null || options.length == 0) {
options = new OpenOption[] {
StandardOpenOption.CREATE,
StandardOpenOption.WRITE,
StandardOpenOption.TRUNCATE_EXISTING };
}
List<OpenOption> optionsList = Arrays.asList(options);
List... | class AzureFileSystemProvider extends FileSystemProvider {
private final ClientLogger logger = new ClientLogger(AzureFileSystemProvider.class);
public static final String CONTENT_TYPE = "Content-Type";
public static final String CONTENT_DISPOSITION = "Content-Disposition";
public static final String CONTENT_LANGUAGE = ... | class AzureFileSystemProvider extends FileSystemProvider {
private final ClientLogger logger = new ClientLogger(AzureFileSystemProvider.class);
public static final String CONTENT_TYPE = "Content-Type";
public static final String CONTENT_DISPOSITION = "Content-Disposition";
public static final String CONTENT_LANGUAGE = ... |
It's long in 73, which is why I made the config value a long in anticipation of that, but this branch doesn't have those updates yet, so I'll strike these conversions to int once all that gets merged in. | public OutputStream newOutputStream(Path path, OpenOption... options) throws IOException {
if (options == null || options.length == 0) {
options = new OpenOption[] {
StandardOpenOption.CREATE,
StandardOpenOption.WRITE,
StandardOpenOption.TRUNCATE_EXISTING };
}
List<OpenOption> optionsList = Arrays.asList(options);
List... | Integer blockSize = fs.getBlockSize() == null ? null : fs.getBlockSize().intValue(); | public OutputStream newOutputStream(Path path, OpenOption... options) throws IOException {
if (options == null || options.length == 0) {
options = new OpenOption[] {
StandardOpenOption.CREATE,
StandardOpenOption.WRITE,
StandardOpenOption.TRUNCATE_EXISTING };
}
List<OpenOption> optionsList = Arrays.asList(options);
List... | class AzureFileSystemProvider extends FileSystemProvider {
private final ClientLogger logger = new ClientLogger(AzureFileSystemProvider.class);
public static final String CONTENT_TYPE = "Content-Type";
public static final String CONTENT_DISPOSITION = "Content-Disposition";
public static final String CONTENT_LANGUAGE = ... | class AzureFileSystemProvider extends FileSystemProvider {
private final ClientLogger logger = new ClientLogger(AzureFileSystemProvider.class);
public static final String CONTENT_TYPE = "Content-Type";
public static final String CONTENT_DISPOSITION = "Content-Disposition";
public static final String CONTENT_LANGUAGE = ... |
Add javadoc | public RecognizeCustomFormsOptions(final InputStream form, final long length, final String modelId) {
super(form, length);
this.modelId = Objects.requireNonNull(modelId, "'modelId' cannot be null");
} | } | public RecognizeCustomFormsOptions(final InputStream form, final long length, final String modelId) {
super(form, length);
this.modelId = modelId;
} | class RecognizeCustomFormsOptions extends RecognizeOptions {
private final String modelId;
public RecognizeCustomFormsOptions(final Flux<ByteBuffer> formData, final long length, final String modelId) {
super(formData, length);
this.modelId = Objects.requireNonNull(modelId, "'modelId' cannot be null");
}
public Recogniz... | class RecognizeCustomFormsOptions extends RecognizeOptions {
private final String modelId;
/**
* Create a {@code RecognizeCustomFormsOptions option} object
*
* @param form The {@code InputStream data} of the form to recognize form information from.
* @param length the exact length of the provided form data.
* @param mo... |
Support polling by user. | public void canDeployVirtualNetworkSyncPoll() throws Exception {
final String dp = "dpD" + testId;
Accepted<Deployment> acceptedDeployment = resourceClient.deployments()
.define(dp)
.withExistingResourceGroup(rgName)
.withTemplateLink(templateUri, contentVersion)
.withParametersLink(parametersUri, contentVersion)
.with... | } | public void canDeployVirtualNetworkSyncPoll() throws Exception {
final String dp = "dpD" + testId;
Accepted<Deployment> acceptedDeployment = resourceClient.deployments()
.define(dp)
.withExistingResourceGroup(rgName)
.withTemplateLink(templateUri, contentVersion)
.withParametersLink(parametersUri, contentVersion)
.with... | class DeploymentsTests extends ResourceManagerTestBase {
private ResourceGroups resourceGroups;
private ResourceGroup resourceGroup;
private String testId;
private String rgName;
private static String templateUri = "https:
private static String blankTemplateUri = "https:
private static String parametersUri = "https:
pr... | class DeploymentsTests extends ResourceManagerTestBase {
private ResourceGroups resourceGroups;
private ResourceGroup resourceGroup;
private String testId;
private String rgName;
private static String templateUri = "https:
private static String blankTemplateUri = "https:
private static String parametersUri = "https:
pr... |
In Reactor, void return types won't have `onNext()`. So, this message will have to be printed in `onComplete()` consumer. Update other samples too. ```java .subscribe(ignored -> {}, error -> logger.error("...", error), () -> logger.info("Delete Entity Successful.")); ``` | private void deleteEntity() {
TableServiceAsyncClient tableServiceAsyncClient = new TableServiceClientBuilder()
.connectionString("connectionString")
.buildAsyncClient();
TableAsyncClient tableAsyncClient = tableServiceAsyncClient.getTableAsyncClient("OfficeSupplies");
QueryOptions queryOptions = new QueryOptions();
qu... | logger.info("Delete Entity Successful."); | private void deleteEntity() {
TableServiceAsyncClient tableServiceAsyncClient = new TableServiceClientBuilder()
.connectionString("connectionString")
.buildAsyncClient();
TableAsyncClient tableAsyncClient = tableServiceAsyncClient.getTableAsyncClient("OfficeSupplies");
String rowKey = "crayolaMarkers";
String partition... | class TableServiceAsyncClientCodeSnippets {
final ClientLogger logger = new ClientLogger("TableServiceAsyncClientCodeSnippets");
/**
* create table code snippet
*/
public void createTable() {
TableServiceAsyncClient tableServiceAsyncClient = new TableServiceClientBuilder()
.connectionString("connectionString")
.buildAs... | class TableServiceAsyncClientCodeSnippets {
/**
* create table code snippet
*/
public void createTable() {
TableServiceAsyncClient tableServiceAsyncClient = new TableServiceClientBuilder()
.connectionString("connectionString")
.buildAsyncClient();
tableServiceAsyncClient.createTable("OfficeSupplies").subscribe(
Void ->... |
These methods should return `Mono<TableEntity>` - the updated/upserted entity. | public Mono<Void> updateEntity(UpdateMode updateMode, TableEntity tableEntity) {
return Mono.empty();
} | } | public Mono<Void> updateEntity(UpdateMode updateMode, TableEntity tableEntity) {
return Mono.empty();
} | class TableAsyncClient {
private final String tableName;
TableAsyncClient(String tableName) {
this.tableName = tableName;
}
/**
* Queries and returns entities in the given table using the select and filter strings
*
* @param queryOptions the odata query object
* @return a paged flux of all the entity which fit this cri... | class TableAsyncClient {
private final String tableName;
TableAsyncClient(String tableName) {
this.tableName = tableName;
}
/**
* Queries and returns entities in the given table using the select and filter strings
*
* @param queryOptions the odata query object
* @return a paged flux of all the entity which fit this cri... |
This returns a paged collection. So, you might have to check each `tableEntity` to find out if the one that you are testing for existence actually is in the returned collection. | private void existsEntity() {
TableServiceAsyncClient tableServiceAsyncClient = new TableServiceClientBuilder()
.connectionString("connectionString")
.buildAsyncClient();
TableAsyncClient tableAsyncClient = tableServiceAsyncClient.getTableAsyncClient("OfficeSupplies");
tableAsyncClient.queryEntitiesWithPartitionAndRowK... | logger.info("Table Entity exists: " + tableEntity); | private void existsEntity() {
TableServiceAsyncClient tableServiceAsyncClient = new TableServiceClientBuilder()
.connectionString("connectionString")
.buildAsyncClient();
TableAsyncClient tableAsyncClient = tableServiceAsyncClient.getTableAsyncClient("OfficeSupplies");
tableAsyncClient.get("crayolaMarkers", "markers")
... | class TableServiceAsyncClientCodeSnippets {
final ClientLogger logger = new ClientLogger("TableServiceAsyncClientCodeSnippets");
/**
* create table code snippet
*/
public void createTable() {
TableServiceAsyncClient tableServiceAsyncClient = new TableServiceClientBuilder()
.connectionString("connectionString")
.buildAs... | class TableServiceAsyncClientCodeSnippets {
/**
* create table code snippet
*/
public void createTable() {
TableServiceAsyncClient tableServiceAsyncClient = new TableServiceClientBuilder()
.connectionString("connectionString")
.buildAsyncClient();
tableServiceAsyncClient.createTable("OfficeSupplies").subscribe(
Void ->... |
I brought this up during our tables meeting and we decided we have to talk with the Tables service team since the Merge API call returns at 204 (no content) so we are still deciding how best to return something if that underlying functionality doesn't return an entity. So we are asking them about hero scenarios and wha... | public Mono<Void> updateEntity(UpdateMode updateMode, TableEntity tableEntity) {
return Mono.empty();
} | } | public Mono<Void> updateEntity(UpdateMode updateMode, TableEntity tableEntity) {
return Mono.empty();
} | class TableAsyncClient {
private final String tableName;
TableAsyncClient(String tableName) {
this.tableName = tableName;
}
/**
* Queries and returns entities in the given table using the select and filter strings
*
* @param queryOptions the odata query object
* @return a paged flux of all the entity which fit this cri... | class TableAsyncClient {
private final String tableName;
TableAsyncClient(String tableName) {
this.tableName = tableName;
}
/**
* Queries and returns entities in the given table using the select and filter strings
*
* @param queryOptions the odata query object
* @return a paged flux of all the entity which fit this cri... |
updated using get() method. | private void existsEntity() {
TableServiceAsyncClient tableServiceAsyncClient = new TableServiceClientBuilder()
.connectionString("connectionString")
.buildAsyncClient();
TableAsyncClient tableAsyncClient = tableServiceAsyncClient.getTableAsyncClient("OfficeSupplies");
tableAsyncClient.queryEntitiesWithPartitionAndRowK... | logger.info("Table Entity exists: " + tableEntity); | private void existsEntity() {
TableServiceAsyncClient tableServiceAsyncClient = new TableServiceClientBuilder()
.connectionString("connectionString")
.buildAsyncClient();
TableAsyncClient tableAsyncClient = tableServiceAsyncClient.getTableAsyncClient("OfficeSupplies");
tableAsyncClient.get("crayolaMarkers", "markers")
... | class TableServiceAsyncClientCodeSnippets {
final ClientLogger logger = new ClientLogger("TableServiceAsyncClientCodeSnippets");
/**
* create table code snippet
*/
public void createTable() {
TableServiceAsyncClient tableServiceAsyncClient = new TableServiceClientBuilder()
.connectionString("connectionString")
.buildAs... | class TableServiceAsyncClientCodeSnippets {
/**
* create table code snippet
*/
public void createTable() {
TableServiceAsyncClient tableServiceAsyncClient = new TableServiceClientBuilder()
.connectionString("connectionString")
.buildAsyncClient();
tableServiceAsyncClient.createTable("OfficeSupplies").subscribe(
Void ->... |
System.err.println` over ClientLogger | public void createTable() {
TableServiceAsyncClient tableServiceAsyncClient = new TableServiceClientBuilder()
.connectionString("connectionString")
.buildAsyncClient();
tableServiceAsyncClient.createTable("OfficeSupplies").subscribe(
Void -> {},
error -> logger.error("There was an error creating the table. Error: " + e... | error -> logger.error("There was an error creating the table. Error: " + error), | public void createTable() {
TableServiceAsyncClient tableServiceAsyncClient = new TableServiceClientBuilder()
.connectionString("connectionString")
.buildAsyncClient();
tableServiceAsyncClient.createTable("OfficeSupplies").subscribe(
Void -> { },
error -> System.err.println("There was an error creating the table. Error... | class TableServiceAsyncClientCodeSnippets {
final ClientLogger logger = new ClientLogger("TableServiceAsyncClientCodeSnippets");
/**
* create table code snippet
*/
/**
* delete table code snippet
*/
public void deleteTable() {
TableServiceAsyncClient tableServiceAsyncClient = new TableServiceClientBuilder()
.connection... | class TableServiceAsyncClientCodeSnippets {
/**
* create table code snippet
*/
/**
* delete table code snippet
*/
public void deleteTable() {
TableServiceAsyncClient tableServiceAsyncClient = new TableServiceClientBuilder()
.connectionString("connectionString")
.buildAsyncClient();
tableServiceAsyncClient.deleteTable("... |
Highlight usage of the fluent model. var queryOptions = new QueryOptions().setFilter("TableName eq OfficeSupplies"); | public void queryTable() {
TableServiceAsyncClient tableServiceAsyncClient = new TableServiceClientBuilder()
.connectionString("connectionString")
.buildAsyncClient();
QueryOptions queryOptions = new QueryOptions();
queryOptions.setFilter("TableName eq OfficeSupplies");
tableServiceAsyncClient.queryTables(queryOptions)... | QueryOptions queryOptions = new QueryOptions(); | public void queryTable() {
TableServiceAsyncClient tableServiceAsyncClient = new TableServiceClientBuilder()
.connectionString("connectionString")
.buildAsyncClient();
QueryOptions queryOptions = new QueryOptions().setFilter("TableName eq OfficeSupplies");
tableServiceAsyncClient.queryTables(queryOptions).subscribe(azu... | class TableServiceAsyncClientCodeSnippets {
final ClientLogger logger = new ClientLogger("TableServiceAsyncClientCodeSnippets");
/**
* create table code snippet
*/
public void createTable() {
TableServiceAsyncClient tableServiceAsyncClient = new TableServiceClientBuilder()
.connectionString("connectionString")
.buildAs... | class TableServiceAsyncClientCodeSnippets {
/**
* create table code snippet
*/
public void createTable() {
TableServiceAsyncClient tableServiceAsyncClient = new TableServiceClientBuilder()
.connectionString("connectionString")
.buildAsyncClient();
tableServiceAsyncClient.createTable("OfficeSupplies").subscribe(
Void ->... |
No need for the intermediate local variable `deleteEntityMono`. Just return tableAsyncClient.delete.... | private void deleteEntity() {
TableServiceAsyncClient tableServiceAsyncClient = new TableServiceClientBuilder()
.connectionString("connectionString")
.buildAsyncClient();
TableAsyncClient tableAsyncClient = tableServiceAsyncClient.getTableAsyncClient("OfficeSupplies");
String rowKey = "crayolaMarkers";
String partition... | return deleteEntityMono; | private void deleteEntity() {
TableServiceAsyncClient tableServiceAsyncClient = new TableServiceClientBuilder()
.connectionString("connectionString")
.buildAsyncClient();
TableAsyncClient tableAsyncClient = tableServiceAsyncClient.getTableAsyncClient("OfficeSupplies");
String rowKey = "crayolaMarkers";
String partition... | class TableServiceAsyncClientCodeSnippets {
final ClientLogger logger = new ClientLogger("TableServiceAsyncClientCodeSnippets");
/**
* create table code snippet
*/
public void createTable() {
TableServiceAsyncClient tableServiceAsyncClient = new TableServiceClientBuilder()
.connectionString("connectionString")
.buildAs... | class TableServiceAsyncClientCodeSnippets {
/**
* create table code snippet
*/
public void createTable() {
TableServiceAsyncClient tableServiceAsyncClient = new TableServiceClientBuilder()
.connectionString("connectionString")
.buildAsyncClient();
tableServiceAsyncClient.createTable("OfficeSupplies").subscribe(
Void ->... |
Should I be more explicit with source in the name? | public BlobDownloadHeaders() {
objectReplicationPolicies = null;
} | objectReplicationPolicies = null; | public BlobDownloadHeaders() {
objectReplicationSourcePolicies = null;
} | class BlobDownloadHeaders {
/**
* Instantiates an empty {@code BlobDownloadHeaders}.
*/
/**
* Instantiates a {@code BlobDownloadHeaders} object based on the generated, internal version of the type.
* @param headers The generated headers type from which to extract values.
*/
public BlobDownloadHeaders(com.azure.storage.... | class BlobDownloadHeaders {
/**
* Instantiates an empty {@code BlobDownloadHeaders}.
*/
/**
* Instantiates a {@code BlobDownloadHeaders} object based on the generated, internal version of the type.
* @param headers The generated headers type from which to extract values.
*/
public BlobDownloadHeaders(com.azure.storage.... |
Maybe `objectReplicationSourceProperties`? Since there's already another variable to hold the destination policy header if we get back the OR info of a destination blob. | public BlobDownloadHeaders() {
objectReplicationPolicies = null;
} | objectReplicationPolicies = null; | public BlobDownloadHeaders() {
objectReplicationSourcePolicies = null;
} | class BlobDownloadHeaders {
/**
* Instantiates an empty {@code BlobDownloadHeaders}.
*/
/**
* Instantiates a {@code BlobDownloadHeaders} object based on the generated, internal version of the type.
* @param headers The generated headers type from which to extract values.
*/
public BlobDownloadHeaders(com.azure.storage.... | class BlobDownloadHeaders {
/**
* Instantiates an empty {@code BlobDownloadHeaders}.
*/
/**
* Instantiates a {@code BlobDownloadHeaders} object based on the generated, internal version of the type.
* @param headers The generated headers type from which to extract values.
*/
public BlobDownloadHeaders(com.azure.storage.... |
changed to ORSourcePOlicies | public BlobDownloadHeaders() {
objectReplicationPolicies = null;
} | objectReplicationPolicies = null; | public BlobDownloadHeaders() {
objectReplicationSourcePolicies = null;
} | class BlobDownloadHeaders {
/**
* Instantiates an empty {@code BlobDownloadHeaders}.
*/
/**
* Instantiates a {@code BlobDownloadHeaders} object based on the generated, internal version of the type.
* @param headers The generated headers type from which to extract values.
*/
public BlobDownloadHeaders(com.azure.storage.... | class BlobDownloadHeaders {
/**
* Instantiates an empty {@code BlobDownloadHeaders}.
*/
/**
* Instantiates a {@code BlobDownloadHeaders} object based on the generated, internal version of the type.
* @param headers The generated headers type from which to extract values.
*/
public BlobDownloadHeaders(com.azure.storage.... |
Same comment here | public PolygonGeometry(List<LineGeometry> rings, GeometryBoundingBox boundingBox, Map<String, Object> properties) {
super(boundingBox, properties);
Objects.requireNonNull(rings, "'rings' cannot be null.");
this.rings = Collections.unmodifiableList(new ArrayList<>(rings));
} | this.rings = Collections.unmodifiableList(new ArrayList<>(rings)); | public PolygonGeometry(List<LineGeometry> rings, GeometryBoundingBox boundingBox, Map<String, Object> properties) {
super(boundingBox, properties);
Objects.requireNonNull(rings, "'rings' cannot be null.");
this.rings = Collections.unmodifiableList(new ArrayList<>(rings));
} | class PolygonGeometry extends Geometry {
private final List<LineGeometry> rings;
/**
* Constructs a geometric polygon.
*
* @param rings The lines that define the polygon.
* @throws NullPointerException If {@code rings} is {@code null}.
*/
public PolygonGeometry(List<LineGeometry> rings) {
this(rings, null, null);
}
/**... | class PolygonGeometry extends Geometry {
private final List<LineGeometry> rings;
/**
* Constructs a geometric polygon.
*
* @param rings The lines that define the polygon.
* @throws NullPointerException If {@code rings} is {@code null}.
*/
public PolygonGeometry(List<LineGeometry> rings) {
this(rings, null, null);
}
/**... |
Probably not going to have that for this PR, but we should consider this since the copy will be done for every message receive. | public Mono<Boolean> tryAdd(final T object) {
if (object == null) {
throw logger.logExceptionAsWarning(new IllegalArgumentException("object cannot be null"));
}
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
return objectSerializer.serialize(outputStream, object).map(s -> tryAdd(new EventData(s.toByt... | return objectSerializer.serialize(outputStream, object).map(s -> tryAdd(new EventData(s.toByteArray()))); | public Mono<Boolean> tryAdd(final T object) {
if (object == null) {
return monoError(logger, new IllegalArgumentException("object cannot be null"));
}
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
return serializer.serialize(outputStream, object).map(s -> tryAdd(new EventData(s.toByteArray())));
} | class ObjectBatch<T> extends EventDataBatchBase {
private final ClientLogger logger = new ClientLogger(ObjectBatch.class);
private final Class<T> batchType;
private final ObjectSerializer objectSerializer;
ObjectBatch(int maxMessageSize, String partitionId, String partitionKey, Class<T> batchType,
ErrorContextProvider ... | class ObjectBatch<T> extends EventDataBatchBase {
private final ClientLogger logger = new ClientLogger(ObjectBatch.class);
private final Class<T> batchType;
private final ObjectSerializer serializer;
ObjectBatch(int maxMessageSize, String partitionId, String partitionKey, Class<T> batchType,
ErrorContextProvider contex... |
Same response | public PolygonGeometry(List<LineGeometry> rings, GeometryBoundingBox boundingBox, Map<String, Object> properties) {
super(boundingBox, properties);
Objects.requireNonNull(rings, "'rings' cannot be null.");
this.rings = Collections.unmodifiableList(new ArrayList<>(rings));
} | this.rings = Collections.unmodifiableList(new ArrayList<>(rings)); | public PolygonGeometry(List<LineGeometry> rings, GeometryBoundingBox boundingBox, Map<String, Object> properties) {
super(boundingBox, properties);
Objects.requireNonNull(rings, "'rings' cannot be null.");
this.rings = Collections.unmodifiableList(new ArrayList<>(rings));
} | class PolygonGeometry extends Geometry {
private final List<LineGeometry> rings;
/**
* Constructs a geometric polygon.
*
* @param rings The lines that define the polygon.
* @throws NullPointerException If {@code rings} is {@code null}.
*/
public PolygonGeometry(List<LineGeometry> rings) {
this(rings, null, null);
}
/**... | class PolygonGeometry extends Geometry {
private final List<LineGeometry> rings;
/**
* Constructs a geometric polygon.
*
* @param rings The lines that define the polygon.
* @throws NullPointerException If {@code rings} is {@code null}.
*/
public PolygonGeometry(List<LineGeometry> rings) {
this(rings, null, null);
}
/**... |
Should this be using `monoError`? | public Mono<Boolean> tryAdd(final T object) {
if (object == null) {
throw logger.logExceptionAsWarning(new IllegalArgumentException("object cannot be null"));
}
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
return objectSerializer.serialize(outputStream, object).map(s -> tryAdd(new EventData(s.toByt... | throw logger.logExceptionAsWarning(new IllegalArgumentException("object cannot be null")); | public Mono<Boolean> tryAdd(final T object) {
if (object == null) {
return monoError(logger, new IllegalArgumentException("object cannot be null"));
}
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
return serializer.serialize(outputStream, object).map(s -> tryAdd(new EventData(s.toByteArray())));
} | class ObjectBatch<T> extends EventDataBatchBase {
private final ClientLogger logger = new ClientLogger(ObjectBatch.class);
private final Class<T> batchType;
private final ObjectSerializer objectSerializer;
ObjectBatch(int maxMessageSize, String partitionId, String partitionKey, Class<T> batchType,
ErrorContextProvider ... | class ObjectBatch<T> extends EventDataBatchBase {
private final ClientLogger logger = new ClientLogger(ObjectBatch.class);
private final Class<T> batchType;
private final ObjectSerializer serializer;
ObjectBatch(int maxMessageSize, String partitionId, String partitionKey, Class<T> batchType,
ErrorContextProvider contex... |
Given that this is internal a cool optimization would be creating a private extension of `ByteArrayOuputStream` to access its backing `byte[]` directly. `toByteArray` will make a clone of the `byte[]`. | public Mono<Boolean> tryAdd(final T object) {
if (object == null) {
throw logger.logExceptionAsWarning(new IllegalArgumentException("object cannot be null"));
}
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
return objectSerializer.serialize(outputStream, object).map(s -> tryAdd(new EventData(s.toByt... | return objectSerializer.serialize(outputStream, object).map(s -> tryAdd(new EventData(s.toByteArray()))); | public Mono<Boolean> tryAdd(final T object) {
if (object == null) {
return monoError(logger, new IllegalArgumentException("object cannot be null"));
}
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
return serializer.serialize(outputStream, object).map(s -> tryAdd(new EventData(s.toByteArray())));
} | class ObjectBatch<T> extends EventDataBatchBase {
private final ClientLogger logger = new ClientLogger(ObjectBatch.class);
private final Class<T> batchType;
private final ObjectSerializer objectSerializer;
ObjectBatch(int maxMessageSize, String partitionId, String partitionKey, Class<T> batchType,
ErrorContextProvider ... | class ObjectBatch<T> extends EventDataBatchBase {
private final ClientLogger logger = new ClientLogger(ObjectBatch.class);
private final Class<T> batchType;
private final ObjectSerializer serializer;
ObjectBatch(int maxMessageSize, String partitionId, String partitionKey, Class<T> batchType,
ErrorContextProvider contex... |
You should use `entityType` instead of topicName for your comparison | public ServiceBusSenderAsyncClient buildAsyncClient() {
final ServiceBusConnectionProcessor connectionProcessor = getOrCreateConnectionProcessor(messageSerializer);
final MessagingEntityType entityType = validateEntityPaths(logger, connectionStringEntityName, topicName,
queueName);
if (!CoreUtils.isNullOrEmpty(viaQueue... | if (!CoreUtils.isNullOrEmpty(viaQueueName) && !CoreUtils.isNullOrEmpty(topicName)) { | public ServiceBusSenderAsyncClient buildAsyncClient() {
final ServiceBusConnectionProcessor connectionProcessor = getOrCreateConnectionProcessor(messageSerializer);
final MessagingEntityType entityType = validateEntityPaths(logger, connectionStringEntityName, topicName,
queueName);
if (!CoreUtils.isNullOrEmpty(viaQueue... | class ServiceBusSenderClientBuilder {
private String queueName;
private String topicName;
private String viaQueueName;
private ServiceBusSenderClientBuilder() {
}
/**
* Sets the name of the Service Bus queue to publish messages to.
*
* @param queueName Name of the queue.
*
* @return The modified {@link ServiceBusSender... | class ServiceBusSenderClientBuilder {
private String queueName;
private String topicName;
private String viaQueueName;
private ServiceBusSenderClientBuilder() {
}
/**
* Sets the name of the Service Bus queue to publish messages to.
*
* @param queueName Name of the queue.
*
* @return The modified {@link ServiceBusSender... |
Also add documentation for this runtime error. It should be an IllegalStateException. | public ServiceBusSenderAsyncClient buildAsyncClient() {
final ServiceBusConnectionProcessor connectionProcessor = getOrCreateConnectionProcessor(messageSerializer);
final MessagingEntityType entityType = validateEntityPaths(logger, connectionStringEntityName, topicName,
queueName);
if (!CoreUtils.isNullOrEmpty(viaQueue... | if (!CoreUtils.isNullOrEmpty(viaQueueName) && !CoreUtils.isNullOrEmpty(topicName)) { | public ServiceBusSenderAsyncClient buildAsyncClient() {
final ServiceBusConnectionProcessor connectionProcessor = getOrCreateConnectionProcessor(messageSerializer);
final MessagingEntityType entityType = validateEntityPaths(logger, connectionStringEntityName, topicName,
queueName);
if (!CoreUtils.isNullOrEmpty(viaQueue... | class ServiceBusSenderClientBuilder {
private String queueName;
private String topicName;
private String viaQueueName;
private ServiceBusSenderClientBuilder() {
}
/**
* Sets the name of the Service Bus queue to publish messages to.
*
* @param queueName Name of the queue.
*
* @return The modified {@link ServiceBusSender... | class ServiceBusSenderClientBuilder {
private String queueName;
private String topicName;
private String viaQueueName;
private ServiceBusSenderClientBuilder() {
}
/**
* Sets the name of the Service Bus queue to publish messages to.
*
* @param queueName Name of the queue.
*
* @return The modified {@link ServiceBusSender... |
Do we need to do a string format? You can append it. | private Mono<AmqpSendLink> getSendLink() {
return connectionProcessor
.flatMap(connection -> {
String linkName = entityName;
if (!CoreUtils.isNullOrEmpty(viaEntityName)) {
linkName = String.format("VIA-%s", viaEntityName);
}
return connection.createSendLink(linkName, entityName, viaEntityName, retryOptions);
})
.doOnNe... | linkName = String.format("VIA-%s", viaEntityName); | private Mono<AmqpSendLink> getSendLink() {
return connectionProcessor
.flatMap(connection -> {
if (!CoreUtils.isNullOrEmpty(viaEntityName)) {
return connection.createSendLink("VIA-".concat(viaEntityName), viaEntityName, retryOptions,
entityName);
} else {
return connection.createSendLink(entityName, entityName, retryOp... | class ServiceBusSenderAsyncClient implements AutoCloseable {
/**
* The default maximum allowable size, in bytes, for a batch to be sent.
*/
static final int MAX_MESSAGE_LENGTH_BYTES = 256 * 1024;
private static final String TRANSACTION_LINK_NAME = "coordinator";
private static final CreateBatchOptions DEFAULT_BATCH_OPT... | class ServiceBusSenderAsyncClient implements AutoCloseable {
/**
* The default maximum allowable size, in bytes, for a batch to be sent.
*/
static final int MAX_MESSAGE_LENGTH_BYTES = 256 * 1024;
private static final String TRANSACTION_LINK_NAME = "coordinator";
private static final CreateBatchOptions DEFAULT_BATCH_OPT... |
This should be scoped to when the build method is actually invoked. | void viaQueueNameWithTopicNotAllowed() {
assertThrows(IllegalArgumentException.class, () -> {
final ServiceBusClientBuilder builder = new ServiceBusClientBuilder();
builder.connectionString(NAMESPACE_CONNECTION_STRING)
.sender()
.topicName(TOPIC_NAME)
.viaQueueName(VIA_QUEUE_NAME)
.buildAsyncClient();
});
} | builder.connectionString(NAMESPACE_CONNECTION_STRING) | void viaQueueNameWithTopicNotAllowed() {
ServiceBusSenderClientBuilder builder = new ServiceBusClientBuilder()
.connectionString(NAMESPACE_CONNECTION_STRING)
.sender()
.topicName(TOPIC_NAME)
.viaQueueName(VIA_QUEUE_NAME);
assertThrows(IllegalStateException.class, () -> builder.buildAsyncClient());
} | class ServiceBusClientBuilderTest {
private static final String NAMESPACE_NAME = "dummyNamespaceName";
private static final String DEFAULT_DOMAIN_NAME = "servicebus.windows.net/";
private static final String ENDPOINT_FORMAT = "sb:
private static final String QUEUE_NAME = "test-queue-name";
private static final String V... | class ServiceBusClientBuilderTest {
private static final String NAMESPACE_NAME = "dummyNamespaceName";
private static final String DEFAULT_DOMAIN_NAME = "servicebus.windows.net/";
private static final String ENDPOINT_FORMAT = "sb:
private static final String QUEUE_NAME = "test-queue-name";
private static final String V... |
This link name doesn't have to be declared. You only use the corresponding value within the if statement for each of them. | private Mono<AmqpSendLink> getSendLink() {
return connectionProcessor
.flatMap(connection -> {
String linkName = entityName;
if (!CoreUtils.isNullOrEmpty(viaEntityName)) {
linkName = "VIA-".concat(viaEntityName);
return connection.createSendLink(linkName, viaEntityName, retryOptions, entityName);
} else {
return connec... | String linkName = entityName; | private Mono<AmqpSendLink> getSendLink() {
return connectionProcessor
.flatMap(connection -> {
if (!CoreUtils.isNullOrEmpty(viaEntityName)) {
return connection.createSendLink("VIA-".concat(viaEntityName), viaEntityName, retryOptions,
entityName);
} else {
return connection.createSendLink(entityName, entityName, retryOp... | class ServiceBusSenderAsyncClient implements AutoCloseable {
/**
* The default maximum allowable size, in bytes, for a batch to be sent.
*/
static final int MAX_MESSAGE_LENGTH_BYTES = 256 * 1024;
private static final String TRANSACTION_LINK_NAME = "coordinator";
private static final CreateBatchOptions DEFAULT_BATCH_OPT... | class ServiceBusSenderAsyncClient implements AutoCloseable {
/**
* The default maximum allowable size, in bytes, for a batch to be sent.
*/
static final int MAX_MESSAGE_LENGTH_BYTES = 256 * 1024;
private static final String TRANSACTION_LINK_NAME = "coordinator";
private static final CreateBatchOptions DEFAULT_BATCH_OPT... |
Does the JVM check both environment and system properties when allowing these headers to be used? If not we should use whichever it uses directly as `Configuration` will lookup against both. | private Set<String> getAllowRestrictedHeaders() {
Properties properties = getNetworkProperties();
String[] allowRestrictedHeadersNetProperties =
properties.getProperty(JDK_HTTPCLIENT_ALLOW_RESTRICTED_HEADERS, "").split(",");
Configuration config = (this.configuration == null)
? Configuration.getGlobalConfiguration()
: ... | Configuration config = (this.configuration == null) | private Set<String> getAllowRestrictedHeaders() {
Properties properties = getNetworkProperties();
String[] allowRestrictedHeadersNetProperties =
properties.getProperty(JDK_HTTPCLIENT_ALLOW_RESTRICTED_HEADERS, "").split(",");
Configuration config = (this.configuration == null)
? Configuration.getGlobalConfiguration()
: ... | class JdkAsyncHttpClientBuilder {
private static final Duration DEFAULT_CONNECT_TIMEOUT = Duration.ofSeconds(60);
private static final String JAVA_HOME = System.getProperty("java.home");
private static final String JDK_HTTPCLIENT_ALLOW_RESTRICTED_HEADERS = "jdk.httpclient.allowRestrictedHeaders";
static final Set<Strin... | class JdkAsyncHttpClientBuilder {
private static final Duration DEFAULT_CONNECT_TIMEOUT = Duration.ofSeconds(60);
private static final String JAVA_HOME = System.getProperty("java.home");
private static final String JDK_HTTPCLIENT_ALLOW_RESTRICTED_HEADERS = "jdk.httpclient.allowRestrictedHeaders";
static final Set<Strin... |
What's the purpose of having Case_Insensitive_Order? | Set<String> getRestrictedHeaders() {
Set<String> allowRestrictedHeaders = getAllowRestrictedHeaders();
Set<String> restrictedHeaders = new TreeSet<>(String.CASE_INSENSITIVE_ORDER);
restrictedHeaders.addAll(DEFAULT_RESTRICTED_HEADERS);
restrictedHeaders.removeAll(allowRestrictedHeaders);
return restrictedHeaders;
} | Set<String> restrictedHeaders = new TreeSet<>(String.CASE_INSENSITIVE_ORDER); | Set<String> getRestrictedHeaders() {
Set<String> allowRestrictedHeaders = getAllowRestrictedHeaders();
Set<String> restrictedHeaders = new TreeSet<>(String.CASE_INSENSITIVE_ORDER);
restrictedHeaders.addAll(DEFAULT_RESTRICTED_HEADERS);
restrictedHeaders.removeAll(allowRestrictedHeaders);
return restrictedHeaders;
} | class JdkAsyncHttpClientBuilder {
private static final Duration DEFAULT_CONNECT_TIMEOUT = Duration.ofSeconds(60);
private static final String JAVA_HOME = System.getProperty("java.home");
private static final String JDK_HTTPCLIENT_ALLOW_RESTRICTED_HEADERS = "jdk.httpclient.allowRestrictedHeaders";
static final Set<Strin... | class JdkAsyncHttpClientBuilder {
private static final Duration DEFAULT_CONNECT_TIMEOUT = Duration.ofSeconds(60);
private static final String JAVA_HOME = System.getProperty("java.home");
private static final String JDK_HTTPCLIENT_ALLOW_RESTRICTED_HEADERS = "jdk.httpclient.allowRestrictedHeaders";
static final Set<Strin... |
Since most of our proxy and other configurations are checking both, users might want to use the same location (either env var or sys properties) for all their configurations. So, checking both as it makes it easier for the user. | private Set<String> getAllowRestrictedHeaders() {
Properties properties = getNetworkProperties();
String[] allowRestrictedHeadersNetProperties =
properties.getProperty(JDK_HTTPCLIENT_ALLOW_RESTRICTED_HEADERS, "").split(",");
Configuration config = (this.configuration == null)
? Configuration.getGlobalConfiguration()
: ... | Configuration config = (this.configuration == null) | private Set<String> getAllowRestrictedHeaders() {
Properties properties = getNetworkProperties();
String[] allowRestrictedHeadersNetProperties =
properties.getProperty(JDK_HTTPCLIENT_ALLOW_RESTRICTED_HEADERS, "").split(",");
Configuration config = (this.configuration == null)
? Configuration.getGlobalConfiguration()
: ... | class JdkAsyncHttpClientBuilder {
private static final Duration DEFAULT_CONNECT_TIMEOUT = Duration.ofSeconds(60);
private static final String JAVA_HOME = System.getProperty("java.home");
private static final String JDK_HTTPCLIENT_ALLOW_RESTRICTED_HEADERS = "jdk.httpclient.allowRestrictedHeaders";
static final Set<Strin... | class JdkAsyncHttpClientBuilder {
private static final Duration DEFAULT_CONNECT_TIMEOUT = Duration.ofSeconds(60);
private static final String JAVA_HOME = System.getProperty("java.home");
private static final String JDK_HTTPCLIENT_ALLOW_RESTRICTED_HEADERS = "jdk.httpclient.allowRestrictedHeaders";
static final Set<Strin... |
Case insensitive order will allow for `set.contains()` to ignore case and evaluate if the header is restricted or not. See unit tests. | Set<String> getRestrictedHeaders() {
Set<String> allowRestrictedHeaders = getAllowRestrictedHeaders();
Set<String> restrictedHeaders = new TreeSet<>(String.CASE_INSENSITIVE_ORDER);
restrictedHeaders.addAll(DEFAULT_RESTRICTED_HEADERS);
restrictedHeaders.removeAll(allowRestrictedHeaders);
return restrictedHeaders;
} | Set<String> restrictedHeaders = new TreeSet<>(String.CASE_INSENSITIVE_ORDER); | Set<String> getRestrictedHeaders() {
Set<String> allowRestrictedHeaders = getAllowRestrictedHeaders();
Set<String> restrictedHeaders = new TreeSet<>(String.CASE_INSENSITIVE_ORDER);
restrictedHeaders.addAll(DEFAULT_RESTRICTED_HEADERS);
restrictedHeaders.removeAll(allowRestrictedHeaders);
return restrictedHeaders;
} | class JdkAsyncHttpClientBuilder {
private static final Duration DEFAULT_CONNECT_TIMEOUT = Duration.ofSeconds(60);
private static final String JAVA_HOME = System.getProperty("java.home");
private static final String JDK_HTTPCLIENT_ALLOW_RESTRICTED_HEADERS = "jdk.httpclient.allowRestrictedHeaders";
static final Set<Strin... | class JdkAsyncHttpClientBuilder {
private static final Duration DEFAULT_CONNECT_TIMEOUT = Duration.ofSeconds(60);
private static final String JAVA_HOME = System.getProperty("java.home");
private static final String JDK_HTTPCLIENT_ALLOW_RESTRICTED_HEADERS = "jdk.httpclient.allowRestrictedHeaders";
static final Set<Strin... |
Will it be clear where the causes are? What identifies the causes if they want to find them quickly in the log? | public Mono<AccessToken> getToken(TokenRequestContext request) {
List<CredentialUnavailableException> exceptions = new ArrayList<>(4);
return Flux.fromIterable(credentials)
.flatMap(p -> p.getToken(request)
.doOnNext(t -> logger.info("Azure Identity => Attempted credential {} returns a token",
p.getClass().getSimpleNam... | + " and see more details in the causes below."); | public Mono<AccessToken> getToken(TokenRequestContext request) {
List<CredentialUnavailableException> exceptions = new ArrayList<>(4);
return Flux.fromIterable(credentials)
.flatMap(p -> p.getToken(request)
.doOnNext(t -> logger.info("Azure Identity => Attempted credential {} returns a token",
p.getClass().getSimpleNam... | class ChainedTokenCredential implements TokenCredential {
private final Deque<TokenCredential> credentials;
private final ClientLogger logger = new ClientLogger(getClass());
/**
* Create an instance of chained token credential that aggregates a list of token
* credentials.
*/
ChainedTokenCredential(Deque<TokenCredentia... | class ChainedTokenCredential implements TokenCredential {
private final ClientLogger logger = new ClientLogger(getClass());
private final List<TokenCredential> credentials;
private final String unavailableError = this.getClass().getSimpleName() + " authentication failed. ---> ";
/**
* Create an instance of chained toke... |
yes, that's a common Javadoc that signals the Java version info. | public static void main(String[] args) throws IOException {
FormRecognizerAsyncClient client = new FormRecognizerClientBuilder()
.credential(new AzureKeyCredential("{key}"))
.endpoint("https:
.buildAsyncClient();
File analyzeFile = new File("../formrecognizer/azure-ai-formrecognizer/src/samples/java/sample-forms/"
+ "f... | public static void main(String[] args) throws IOException {
FormRecognizerAsyncClient client = new FormRecognizerClientBuilder()
.credential(new AzureKeyCredential("{key}"))
.endpoint("https:
.buildAsyncClient();
File analyzeFile = new File("../formrecognizer/azure-ai-formrecognizer/src/samples/java/sample-forms/"
+ "f... | class AdvancedDiffLabeledUnlabeledDataAsync {
/**
* Main method to invoke this demo.
*
* @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 AdvancedDiffLabeledUnlabeledDataAsync {
/**
* Main method to invoke this demo.
*
* @param args Unused arguments to the program.
*
* @throws IOException Exception thrown when there is an error in reading all the bytes from the File.
*/
} | |
This error message has been improved through this PR: https://github.com/Azure/azure-sdk-for-java/pull/9022 | public Mono<AccessToken> getToken(TokenRequestContext request) {
List<CredentialUnavailableException> exceptions = new ArrayList<>(4);
return Flux.fromIterable(credentials)
.flatMap(p -> p.getToken(request)
.doOnNext(t -> logger.info("Azure Identity => Attempted credential {} returns a token",
p.getClass().getSimpleNam... | + " and see more details in the causes below."); | public Mono<AccessToken> getToken(TokenRequestContext request) {
List<CredentialUnavailableException> exceptions = new ArrayList<>(4);
return Flux.fromIterable(credentials)
.flatMap(p -> p.getToken(request)
.doOnNext(t -> logger.info("Azure Identity => Attempted credential {} returns a token",
p.getClass().getSimpleNam... | class ChainedTokenCredential implements TokenCredential {
private final Deque<TokenCredential> credentials;
private final ClientLogger logger = new ClientLogger(getClass());
/**
* Create an instance of chained token credential that aggregates a list of token
* credentials.
*/
ChainedTokenCredential(Deque<TokenCredentia... | class ChainedTokenCredential implements TokenCredential {
private final ClientLogger logger = new ClientLogger(getClass());
private final List<TokenCredential> credentials;
private final String unavailableError = this.getClass().getSimpleName() + " authentication failed. ---> ";
/**
* Create an instance of chained toke... |
Can use `if ( ! (t instanceof CredentialUnavailableException) )`? | public Mono<AccessToken> getToken(TokenRequestContext request) {
List<CredentialUnavailableException> exceptions = new ArrayList<>(4);
return Flux.fromIterable(credentials)
.flatMap(p -> p.getToken(request).onErrorResume(Exception.class, t -> {
if (!t.getClass().getSimpleName().equals("CredentialUnavailableException"))... | if (!t.getClass().getSimpleName().equals("CredentialUnavailableException")) { | public Mono<AccessToken> getToken(TokenRequestContext request) {
List<CredentialUnavailableException> exceptions = new ArrayList<>(4);
return Flux.fromIterable(credentials)
.flatMap(p -> p.getToken(request)
.doOnNext(t -> logger.info("Azure Identity => Attempted credential {} returns a token",
p.getClass().getSimpleNam... | class ChainedTokenCredential implements TokenCredential {
private final Deque<TokenCredential> credentials;
private final ClientLogger logger = new ClientLogger(getClass());
private final String unavailableError = this.getClass().getSimpleName() + " authentication failed. ---> ";
/**
* Create an instance of chained tok... | class ChainedTokenCredential implements TokenCredential {
private final ClientLogger logger = new ClientLogger(getClass());
private final List<TokenCredential> credentials;
private final String unavailableError = this.getClass().getSimpleName() + " authentication failed. ---> ";
/**
* Create an instance of chained toke... |
do we want to replace this with doOnSuccess ? and also add doOnRequest ? | public Mono<AccessToken> getToken(TokenRequestContext request) {
return Mono.defer(() -> {
if (cachedToken.get() != null) {
return identityClient.authenticateWithPublicClientCache(request, cachedToken.get())
.onErrorResume(t -> Mono.empty());
} else {
return Mono.empty();
}
}).switchIfEmpty(
Mono.defer(() -> identityCl... | .doOnNext(token -> LoggingUtil.logTokenSuccess(logger, request)) | public Mono<AccessToken> getToken(TokenRequestContext request) {
return Mono.defer(() -> {
if (cachedToken.get() != null) {
return identityClient.authenticateWithPublicClientCache(request, cachedToken.get())
.onErrorResume(t -> Mono.empty());
} else {
return Mono.empty();
}
}).switchIfEmpty(
Mono.defer(() -> identityCl... | class AuthorizationCodeCredential implements TokenCredential {
private final String authCode;
private final URI redirectUri;
private final IdentityClient identityClient;
private final AtomicReference<MsalAuthenticationAccount> cachedToken;
private final ClientLogger logger = new ClientLogger(AuthorizationCodeCredential... | class AuthorizationCodeCredential implements TokenCredential {
private final String authCode;
private final URI redirectUri;
private final IdentityClient identityClient;
private final AtomicReference<MsalAuthenticationAccount> cachedToken;
private final ClientLogger logger = new ClientLogger(AuthorizationCodeCredential... |
This can be misleading in cases when running on non-Azure hosted machines. As we default to VM credential if MSI endpoint is not set. Should we check if IMDS available before logging the environment ? | public Mono<AccessToken> getToken(TokenRequestContext request) {
Mono<AccessToken> accessTokenMono;
if (appServiceMSICredential != null) {
accessTokenMono = appServiceMSICredential.authenticate(request);
logger.info("Azure Identity => Managed Identity environment: MSI_ENDPOINT");
} else {
accessTokenMono = virtualMachi... | logger.info("Azure Identity => Managed Identity environment: IMDS"); | public Mono<AccessToken> getToken(TokenRequestContext request) {
Mono<AccessToken> accessTokenMono;
if (appServiceMSICredential != null) {
accessTokenMono = appServiceMSICredential.authenticate(request)
.doOnSuccess((t -> logger.info("Azure Identity => Managed Identity environment: MSI_ENDPOINT")));
} else {
accessToke... | class ManagedIdentityCredential implements TokenCredential {
private final AppServiceMsiCredential appServiceMSICredential;
private final VirtualMachineMsiCredential virtualMachineMSICredential;
private final ClientLogger logger = new ClientLogger(ManagedIdentityCredential.class);
/**
* Creates an instance of the Manag... | class ManagedIdentityCredential implements TokenCredential {
private final AppServiceMsiCredential appServiceMSICredential;
private final VirtualMachineMsiCredential virtualMachineMSICredential;
private final ClientLogger logger = new ClientLogger(ManagedIdentityCredential.class);
/**
* Creates an instance of the Manag... |
I've moved this log to be only printed in doOnSuccess(). | public Mono<AccessToken> getToken(TokenRequestContext request) {
Mono<AccessToken> accessTokenMono;
if (appServiceMSICredential != null) {
accessTokenMono = appServiceMSICredential.authenticate(request);
logger.info("Azure Identity => Managed Identity environment: MSI_ENDPOINT");
} else {
accessTokenMono = virtualMachi... | logger.info("Azure Identity => Managed Identity environment: IMDS"); | public Mono<AccessToken> getToken(TokenRequestContext request) {
Mono<AccessToken> accessTokenMono;
if (appServiceMSICredential != null) {
accessTokenMono = appServiceMSICredential.authenticate(request)
.doOnSuccess((t -> logger.info("Azure Identity => Managed Identity environment: MSI_ENDPOINT")));
} else {
accessToke... | class ManagedIdentityCredential implements TokenCredential {
private final AppServiceMsiCredential appServiceMSICredential;
private final VirtualMachineMsiCredential virtualMachineMSICredential;
private final ClientLogger logger = new ClientLogger(ManagedIdentityCredential.class);
/**
* Creates an instance of the Manag... | class ManagedIdentityCredential implements TokenCredential {
private final AppServiceMsiCredential appServiceMSICredential;
private final VirtualMachineMsiCredential virtualMachineMSICredential;
private final ClientLogger logger = new ClientLogger(ManagedIdentityCredential.class);
/**
* Creates an instance of the Manag... |
I modified everything to be doOnSuccess. We don't log anything on doOnRequest(). | public Mono<AccessToken> getToken(TokenRequestContext request) {
return Mono.defer(() -> {
if (cachedToken.get() != null) {
return identityClient.authenticateWithPublicClientCache(request, cachedToken.get())
.onErrorResume(t -> Mono.empty());
} else {
return Mono.empty();
}
}).switchIfEmpty(
Mono.defer(() -> identityCl... | .doOnNext(token -> LoggingUtil.logTokenSuccess(logger, request)) | public Mono<AccessToken> getToken(TokenRequestContext request) {
return Mono.defer(() -> {
if (cachedToken.get() != null) {
return identityClient.authenticateWithPublicClientCache(request, cachedToken.get())
.onErrorResume(t -> Mono.empty());
} else {
return Mono.empty();
}
}).switchIfEmpty(
Mono.defer(() -> identityCl... | class AuthorizationCodeCredential implements TokenCredential {
private final String authCode;
private final URI redirectUri;
private final IdentityClient identityClient;
private final AtomicReference<MsalAuthenticationAccount> cachedToken;
private final ClientLogger logger = new ClientLogger(AuthorizationCodeCredential... | class AuthorizationCodeCredential implements TokenCredential {
private final String authCode;
private final URI redirectUri;
private final IdentityClient identityClient;
private final AtomicReference<MsalAuthenticationAccount> cachedToken;
private final ClientLogger logger = new ClientLogger(AuthorizationCodeCredential... |
Same here, timeout should be an optional method param. You can still have a default in case it's not set. | public String getSchemaId(String schemaGroup, String schemaName, String schemaString, String schemaType) {
if (schemaStringCache.containsKey(schemaString)) {
logger.verbose("Cache hit schema string. Group: '{}', name: '{}'", schemaGroup, schemaName);
return schemaStringCache.get(schemaString).getSchemaId();
}
GetIdBySc... | .block(HTTP_REQUEST_TIMEOUT); | public String getSchemaId(String schemaGroup, String schemaName, String schemaString, String schemaType) {
if (schemaStringCache.containsKey(schemaString)) {
logger.verbose("Cache hit schema string. Group: '{}', name: '{}'", schemaGroup, schemaName);
return schemaStringCache.get(schemaString).getSchemaId();
}
GetIdBySc... | class implementation
* @throws IllegalArgumentException on bad schema type or if parser for schema type has already been registered
*/
public void addSchemaParser(Codec codec) {
if (CoreUtils.isNullOrEmpty(codec.schemaType())) {
throw logger.logExceptionAsError(
new IllegalArgumentException("Serialization type cannot b... | class implementation
* @throws IllegalArgumentException on bad schema type or if parser for schema type has already been registered
*/
public void addSchemaParser(Codec codec) {
if (CoreUtils.isNullOrEmpty(codec.schemaType())) {
throw logger.logExceptionAsError(
new IllegalArgumentException("Serialization type cannot b... |
Some say that mutating input parameters isn't good practice. https://softwareengineering.stackexchange.com/questions/245767/is-modifying-an-incoming-parameter-an-antipattern looks like we do a copy few lines below anyway. | public Mono<Response<BlockBlobItem>> uploadWithResponse(BlobParallelUploadOptions options) {
try {
Objects.requireNonNull(options);
final Map<String, String> metadataFinal = options.getMetadata() == null
? new HashMap<>() : options.getMetadata();
options.setMetadata(metadataFinal);
Flux<ByteBuffer> data = options.getDa... | options.setMetadata(metadataFinal); | new BlobParallelUploadOptions(df)
.setParallelTransferOptions(options.getParallelTransferOptions()).setHeaders(options.getHeaders())
.setMetadata(metadataFinal).setTags(options.getTags()).setTier(options.getTier())
.setRequestConditions(options.getRequestConditions())));
} catch (RuntimeException ex) {
return monoError... | class EncryptedBlobAsyncClient extends BlobAsyncClient {
static final int BLOB_DEFAULT_UPLOAD_BLOCK_SIZE = 4 * Constants.MB;
private static final long BLOB_MAX_UPLOAD_BLOCK_SIZE = 4000L * Constants.MB;
private final ClientLogger logger = new ClientLogger(EncryptedBlobAsyncClient.class);
/**
* An object of type {@link A... | class EncryptedBlobAsyncClient extends BlobAsyncClient {
static final int BLOB_DEFAULT_UPLOAD_BLOCK_SIZE = 4 * Constants.MB;
private static final long BLOB_MAX_UPLOAD_BLOCK_SIZE = 4000L * Constants.MB;
private final ClientLogger logger = new ClientLogger(EncryptedBlobAsyncClient.class);
/**
* An object of type {@link A... |
I don't have to set it on the options. I can use a local variable if that's better? | public Mono<Response<BlockBlobItem>> uploadWithResponse(BlobParallelUploadOptions options) {
try {
Objects.requireNonNull(options);
final Map<String, String> metadataFinal = options.getMetadata() == null
? new HashMap<>() : options.getMetadata();
options.setMetadata(metadataFinal);
Flux<ByteBuffer> data = options.getDa... | options.setMetadata(metadataFinal); | new BlobParallelUploadOptions(df)
.setParallelTransferOptions(options.getParallelTransferOptions()).setHeaders(options.getHeaders())
.setMetadata(metadataFinal).setTags(options.getTags()).setTier(options.getTier())
.setRequestConditions(options.getRequestConditions())));
} catch (RuntimeException ex) {
return monoError... | class EncryptedBlobAsyncClient extends BlobAsyncClient {
static final int BLOB_DEFAULT_UPLOAD_BLOCK_SIZE = 4 * Constants.MB;
private static final long BLOB_MAX_UPLOAD_BLOCK_SIZE = 4000L * Constants.MB;
private final ClientLogger logger = new ClientLogger(EncryptedBlobAsyncClient.class);
/**
* An object of type {@link A... | class EncryptedBlobAsyncClient extends BlobAsyncClient {
static final int BLOB_DEFAULT_UPLOAD_BLOCK_SIZE = 4 * Constants.MB;
private static final long BLOB_MAX_UPLOAD_BLOCK_SIZE = 4000L * Constants.MB;
private final ClientLogger logger = new ClientLogger(EncryptedBlobAsyncClient.class);
/**
* An object of type {@link A... |
Yes. I thought I went through and changed all these, but I guess I missed some. Nice catch! | public Mono<Response<BlockBlobItem>> uploadWithResponse(BlobParallelUploadOptions options) {
try {
Objects.requireNonNull(options);
final Map<String, String> metadataFinal = options.getMetadata() == null
? new HashMap<>() : options.getMetadata();
options.setMetadata(metadataFinal);
Flux<ByteBuffer> data = options.getDa... | Objects.requireNonNull(options); | new BlobParallelUploadOptions(df)
.setParallelTransferOptions(options.getParallelTransferOptions()).setHeaders(options.getHeaders())
.setMetadata(metadataFinal).setTags(options.getTags()).setTier(options.getTier())
.setRequestConditions(options.getRequestConditions())));
} catch (RuntimeException ex) {
return monoError... | class EncryptedBlobAsyncClient extends BlobAsyncClient {
static final int BLOB_DEFAULT_UPLOAD_BLOCK_SIZE = 4 * Constants.MB;
private static final long BLOB_MAX_UPLOAD_BLOCK_SIZE = 4000L * Constants.MB;
private final ClientLogger logger = new ClientLogger(EncryptedBlobAsyncClient.class);
/**
* An object of type {@link A... | class EncryptedBlobAsyncClient extends BlobAsyncClient {
static final int BLOB_DEFAULT_UPLOAD_BLOCK_SIZE = 4 * Constants.MB;
private static final long BLOB_MAX_UPLOAD_BLOCK_SIZE = 4000L * Constants.MB;
private final ClientLogger logger = new ClientLogger(EncryptedBlobAsyncClient.class);
/**
* An object of type {@link A... |
sounds good, | public Mono<Response<BlockBlobItem>> uploadWithResponse(BlobParallelUploadOptions options) {
try {
Objects.requireNonNull(options);
final Map<String, String> metadataFinal = options.getMetadata() == null
? new HashMap<>() : options.getMetadata();
options.setMetadata(metadataFinal);
Flux<ByteBuffer> data = options.getDa... | options.setMetadata(metadataFinal); | new BlobParallelUploadOptions(df)
.setParallelTransferOptions(options.getParallelTransferOptions()).setHeaders(options.getHeaders())
.setMetadata(metadataFinal).setTags(options.getTags()).setTier(options.getTier())
.setRequestConditions(options.getRequestConditions())));
} catch (RuntimeException ex) {
return monoError... | class EncryptedBlobAsyncClient extends BlobAsyncClient {
static final int BLOB_DEFAULT_UPLOAD_BLOCK_SIZE = 4 * Constants.MB;
private static final long BLOB_MAX_UPLOAD_BLOCK_SIZE = 4000L * Constants.MB;
private final ClientLogger logger = new ClientLogger(EncryptedBlobAsyncClient.class);
/**
* An object of type {@link A... | class EncryptedBlobAsyncClient extends BlobAsyncClient {
static final int BLOB_DEFAULT_UPLOAD_BLOCK_SIZE = 4 * Constants.MB;
private static final long BLOB_MAX_UPLOAD_BLOCK_SIZE = 4000L * Constants.MB;
private final ClientLogger logger = new ClientLogger(EncryptedBlobAsyncClient.class);
/**
* An object of type {@link A... |
btw. Collections.emtpyMap() might be more optimal. | public Mono<Response<BlockBlobItem>> uploadWithResponse(BlobParallelUploadOptions options) {
try {
Objects.requireNonNull(options);
final Map<String, String> metadataFinal = options.getMetadata() == null
? new HashMap<>() : options.getMetadata();
options.setMetadata(metadataFinal);
Flux<ByteBuffer> data = options.getDa... | options.setMetadata(metadataFinal); | new BlobParallelUploadOptions(df)
.setParallelTransferOptions(options.getParallelTransferOptions()).setHeaders(options.getHeaders())
.setMetadata(metadataFinal).setTags(options.getTags()).setTier(options.getTier())
.setRequestConditions(options.getRequestConditions())));
} catch (RuntimeException ex) {
return monoError... | class EncryptedBlobAsyncClient extends BlobAsyncClient {
static final int BLOB_DEFAULT_UPLOAD_BLOCK_SIZE = 4 * Constants.MB;
private static final long BLOB_MAX_UPLOAD_BLOCK_SIZE = 4000L * Constants.MB;
private final ClientLogger logger = new ClientLogger(EncryptedBlobAsyncClient.class);
/**
* An object of type {@link A... | class EncryptedBlobAsyncClient extends BlobAsyncClient {
static final int BLOB_DEFAULT_UPLOAD_BLOCK_SIZE = 4 * Constants.MB;
private static final long BLOB_MAX_UPLOAD_BLOCK_SIZE = 4000L * Constants.MB;
private final ClientLogger logger = new ClientLogger(EncryptedBlobAsyncClient.class);
/**
* An object of type {@link A... |
The amount of duplicated logic we're amassing is concerning. This is going to be painful from a maintenance standpoint. | public ServiceBusReceiverAsyncClient buildAsyncClient() {
final MessagingEntityType entityType = validateEntityPaths(logger, connectionStringEntityName, topicName,
queueName);
final String entityPath = getDeadLetterEntityPath(logger, entityType, queueName, topicName,
subscriptionName);
if (prefetchCount < 1) {
throw lo... | if (prefetchCount < 1) { | public ServiceBusReceiverAsyncClient buildAsyncClient() {
final MessagingEntityType entityType = validateEntityPaths(logger, connectionStringEntityName, topicName,
queueName);
final String entityPath = getEntityPath(logger, entityType, queueName, topicName, subscriptionName);
validateAndThrow(prefetchCount, maxAutoLock... | class ServiceBusSessionReceiverClientBuilder {
private Integer maxConcurrentSessions = null;
private int prefetchCount = DEFAULT_PREFETCH_COUNT;
private String queueName;
private ReceiveMode receiveMode = ReceiveMode.PEEK_LOCK;
private String sessionId;
private String subscriptionName;
private String topicName;
private... | class ServiceBusSessionReceiverClientBuilder {
private Integer maxConcurrentSessions = null;
private int prefetchCount = DEFAULT_PREFETCH_COUNT;
private String queueName;
private ReceiveMode receiveMode = ReceiveMode.PEEK_LOCK;
private String sessionId;
private String subscriptionName;
private String topicName;
private... |
Why returning an unmodifiable list here? I thought the intention of this API is return a copy of the current list for the user to modify before creating a CTC out of it. | public List<TokenCredential> getCredentials() {
return Collections.unmodifiableList(tokenCredentials);
} | return Collections.unmodifiableList(tokenCredentials); | public List<TokenCredential> getCredentials() {
return super.getCredentials();
} | class DefaultAzureCredential extends ChainedTokenCredential {
private final List<TokenCredential> tokenCredentials;
/**
* Creates default DefaultAzureCredential instance to use. This will use AZURE_CLIENT_ID,
* AZURE_CLIENT_SECRET, and AZURE_TENANT_ID environment variables to create a
* ClientSecretCredential.
*
* If t... | class DefaultAzureCredential extends ChainedTokenCredential {
/**
* Creates default DefaultAzureCredential instance to use. This will use AZURE_CLIENT_ID,
* AZURE_CLIENT_SECRET, and AZURE_TENANT_ID environment variables to create a
* ClientSecretCredential.
*
* If these environment variables are not available, then thi... |
I think @schaabs said, we either return immutable list or a copy of it. I think having it immutable prevents the use of indexes to replace/re-order items in place. and will require users to create their custom list whenever they want to modify it. We can return a copy too. | public List<TokenCredential> getCredentials() {
return Collections.unmodifiableList(tokenCredentials);
} | return Collections.unmodifiableList(tokenCredentials); | public List<TokenCredential> getCredentials() {
return super.getCredentials();
} | class DefaultAzureCredential extends ChainedTokenCredential {
private final List<TokenCredential> tokenCredentials;
/**
* Creates default DefaultAzureCredential instance to use. This will use AZURE_CLIENT_ID,
* AZURE_CLIENT_SECRET, and AZURE_TENANT_ID environment variables to create a
* ClientSecretCredential.
*
* If t... | class DefaultAzureCredential extends ChainedTokenCredential {
/**
* Creates default DefaultAzureCredential instance to use. This will use AZURE_CLIENT_ID,
* AZURE_CLIENT_SECRET, and AZURE_TENANT_ID environment variables to create a
* ClientSecretCredential.
*
* If these environment variables are not available, then thi... |
Discussed this offline, and since we're using `Colletions.unmodifiableList` to create this instance we can return it without worrying about users modifying it. | public List<TokenCredential> getCredentials() {
return credentials;
} | return credentials; | public List<TokenCredential> getCredentials() {
return credentials;
} | class ChainedTokenCredential implements TokenCredential {
private final List<TokenCredential> credentials;
private final String unavailableError = this.getClass().getSimpleName() + " authentication failed. ---> ";
/**
* Create an instance of chained token credential that aggregates a list of token
* credentials.
*/
Cha... | class ChainedTokenCredential implements TokenCredential {
private final List<TokenCredential> credentials;
private final String unavailableError = this.getClass().getSimpleName() + " authentication failed. ---> ";
/**
* Create an instance of chained token credential that aggregates a list of token
* credentials.
*/
Cha... |
This should return an unmodifiable list. Create the unmodifiable list in the ctor itself. | public List<TokenCredential> getCredentials() {
return tokenCredentials;
} | return tokenCredentials; | public List<TokenCredential> getCredentials() {
return super.getCredentials();
} | class DefaultAzureCredential extends ChainedTokenCredential {
private final List<TokenCredential> tokenCredentials;
/**
* Creates default DefaultAzureCredential instance to use. This will use AZURE_CLIENT_ID,
* AZURE_CLIENT_SECRET, and AZURE_TENANT_ID environment variables to create a
* ClientSecretCredential.
*
* If t... | class DefaultAzureCredential extends ChainedTokenCredential {
/**
* Creates default DefaultAzureCredential instance to use. This will use AZURE_CLIENT_ID,
* AZURE_CLIENT_SECRET, and AZURE_TENANT_ID environment variables to create a
* ClientSecretCredential.
*
* If these environment variables are not available, then thi... |
made it unmodifiable. If users want to modify it, they can create a modifiable list from it. @jianghaolu | public List<TokenCredential> getCredentials() {
return tokenCredentials;
} | return tokenCredentials; | public List<TokenCredential> getCredentials() {
return super.getCredentials();
} | class DefaultAzureCredential extends ChainedTokenCredential {
private final List<TokenCredential> tokenCredentials;
/**
* Creates default DefaultAzureCredential instance to use. This will use AZURE_CLIENT_ID,
* AZURE_CLIENT_SECRET, and AZURE_TENANT_ID environment variables to create a
* ClientSecretCredential.
*
* If t... | class DefaultAzureCredential extends ChainedTokenCredential {
/**
* Creates default DefaultAzureCredential instance to use. This will use AZURE_CLIENT_ID,
* AZURE_CLIENT_SECRET, and AZURE_TENANT_ID environment variables to create a
* ClientSecretCredential.
*
* If these environment variables are not available, then thi... |
The description here says that the list is read-only is this the case? It's returning the underlying instance of `credentials` as a `List<TokenCredential>`? We want to make sure we don't allow people to mutate the state of the already created credential. | public List<TokenCredential> getCredentials() {
return credentials;
} | return credentials; | public List<TokenCredential> getCredentials() {
return credentials;
} | class ChainedTokenCredential implements TokenCredential {
private final List<TokenCredential> credentials;
private final String unavailableError = this.getClass().getSimpleName() + " authentication failed. ---> ";
/**
* Create an instance of chained token credential that aggregates a list of token
* credentials.
*/
Cha... | class ChainedTokenCredential implements TokenCredential {
private final List<TokenCredential> credentials;
private final String unavailableError = this.getClass().getSimpleName() + " authentication failed. ---> ";
/**
* Create an instance of chained token credential that aggregates a list of token
* credentials.
*/
Cha... |
Since this is now `unmodifiableList` , we may want to document this in java doc for its getter @ https://github.com/Azure/azure-sdk-for-java/blob/44f6e0b52fe3203626036adcd48170b715cc0640/sdk/formrecognizer/azure-ai-formrecognizer/src/main/java/com/azure/ai/formrecognizer/models/BoundingBox.java#L41 | public BoundingBox(final List<Point> points) {
if (points == null) {
this.points = null;
} else {
this.points = Collections.unmodifiableList(new ArrayList<>(points));
}
} | } | public BoundingBox(final List<Point> points) {
if (points == null) {
this.points = null;
} else {
this.points = Collections.unmodifiableList(points);
}
} | class BoundingBox {
/**
* The list of coordinates of the Bounding box.
*/
private final List<Point> points;
/**
* Constructs a Bounding box object.
*
* @param points The list of coordinates of the Bounding box.
*/
/**
* Gets the list of all point coordinates of the bounding box.
*
* @return The list of all point coordi... | class BoundingBox {
/**
* The list of coordinates of the Bounding box.
*/
private final List<Point> points;
/**
* Constructs a Bounding box object.
*
* @param points The list of coordinates of the Bounding box.
*/
/**
* Gets the list of all point coordinates of the bounding box.
*
* @return The unmodifiable list of all... |
Would it make sense to use `!CoreUtils.isNullOrEmpty(errorInformationList)` , that will also check for null ? | public FormRecognizerException(final String message, final List<ErrorInformation> errorInformationList) {
super(message);
StringBuilder errorInformationStringBuilder = new StringBuilder().append(message);
if (!errorInformationList.isEmpty()) {
for (ErrorInformation errorInformation : errorInformationList) {
errorInform... | if (!errorInformationList.isEmpty()) { | public FormRecognizerException(final String message, final List<ErrorInformation> errorInformationList) {
super(message);
StringBuilder errorInformationStringBuilder = new StringBuilder().append(message);
if (!CoreUtils.isNullOrEmpty(errorInformationList)) {
for (ErrorInformation errorInformation : errorInformationList... | class FormRecognizerException extends AzureException {
private final List<ErrorInformation> errorInformationList;
private final String errorInformationMessage;
/**
* Initializes a new instance of {@link FormRecognizerException} class
*
* @param message Text containing the details of the exception.
* @param errorInforma... | class FormRecognizerException extends AzureException {
private final List<ErrorInformation> errorInformationList;
private final String errorInformationMessage;
/**
* Initializes a new instance of {@link FormRecognizerException} class
*
* @param message Text containing the details of the exception.
* @param errorInforma... |
Don't need to create a new ArrayList here. | public BoundingBox(final List<Point> points) {
if (points == null) {
this.points = null;
} else {
this.points = Collections.unmodifiableList(new ArrayList<>(points));
}
} | this.points = Collections.unmodifiableList(new ArrayList<>(points)); | public BoundingBox(final List<Point> points) {
if (points == null) {
this.points = null;
} else {
this.points = Collections.unmodifiableList(points);
}
} | class BoundingBox {
/**
* The list of coordinates of the Bounding box.
*/
private final List<Point> points;
/**
* Constructs a Bounding box object.
*
* @param points The list of coordinates of the Bounding box.
*/
/**
* Gets the list of all point coordinates of the bounding box.
*
* @return The unmodifiable list of all... | class BoundingBox {
/**
* The list of coordinates of the Bounding box.
*/
private final List<Point> points;
/**
* Constructs a Bounding box object.
*
* @param points The list of coordinates of the Bounding box.
*/
/**
* Gets the list of all point coordinates of the bounding box.
*
* @return The unmodifiable list of all... |
Not sure whether it may be `http` or not. I think it better to extract `host` from `url` first. | private String constructStorageAccountId(String vhdUrl) {
try {
return ResourceUtils.constructResourceId(this.manager().subscriptionId(),
resourceGroupName(),
"Microsoft.Storage",
"storageAccounts",
vhdUrl.split("\\.")[0].replace("https:
"");
} catch (RuntimeException ex) {
throw logger.logExceptionAsError(
new Invalid... | vhdUrl.split("\\.")[0].replace("https: | private String constructStorageAccountId(String vhdUrl) {
try {
return ResourceUtils.constructResourceId(this.manager().subscriptionId(),
resourceGroupName(),
"Microsoft.Storage",
"storageAccounts",
vhdUrl.split("\\.")[0].replace("https:
"");
} catch (RuntimeException ex) {
throw logger.logExceptionAsError(
new Invalid... | class SnapshotImpl extends GroupableResourceImpl<Snapshot, SnapshotInner, SnapshotImpl, ComputeManager>
implements Snapshot, Snapshot.Definition, Snapshot.Update {
private final ClientLogger logger = new ClientLogger(SnapshotImpl.class);
SnapshotImpl(String name, SnapshotInner innerModel, final ComputeManager computeMa... | class SnapshotImpl extends GroupableResourceImpl<Snapshot, SnapshotInner, SnapshotImpl, ComputeManager>
implements Snapshot, Snapshot.Definition, Snapshot.Update {
private final ClientLogger logger = new ClientLogger(SnapshotImpl.class);
SnapshotImpl(String name, SnapshotInner innerModel, final ComputeManager computeMa... |
Check whether to use `File.deleteOnExit` ? | private File compressSource(File sourceFolder) throws IOException {
File compressFile = File.createTempFile("java_package", "tar.gz");
try (TarArchiveOutputStream tarArchiveOutputStream = new TarArchiveOutputStream(
new GZIPOutputStream(new FileOutputStream(compressFile)))) {
tarArchiveOutputStream.setLongFileMode(TarA... | File compressFile = File.createTempFile("java_package", "tar.gz"); | private File compressSource(File sourceFolder) throws IOException {
File compressFile = File.createTempFile("java_package", "tar.gz");
compressFile.deleteOnExit();
try (TarArchiveOutputStream tarArchiveOutputStream = new TarArchiveOutputStream(
new GZIPOutputStream(new FileOutputStream(compressFile)))) {
tarArchiveOutp... | class SpringAppDeploymentImpl
extends ExternalChildResourceImpl<SpringAppDeployment, DeploymentResourceInner, SpringAppImpl, SpringApp>
implements SpringAppDeployment, SpringAppDeployment.Definition, SpringAppDeployment.Update {
private static final int BLOCK_SIZE = 4 * 1024 * 1024;
private final SpringAppDeploymentsIm... | class SpringAppDeploymentImpl
extends ExternalChildResourceImpl<SpringAppDeployment, DeploymentResourceInner, SpringAppImpl, SpringApp>
implements SpringAppDeployment, SpringAppDeployment.Definition, SpringAppDeployment.Update {
private static final int BLOCK_SIZE = 4 * 1024 * 1024;
private final SpringAppDeploymentsIm... |
This method is only used once. Why don't we roll in the functionality. | void singleUnnamedSession(MessagingEntityType entityType) {
final int entityIndex = 0;
final String messageId = "singleUnnamedSession";
final String sessionId = "singleUnnamedSession-" + Instant.now().toString();
final String contents = "Some-contents";
final int numberToSend = 5;
final List<String> lockTokens = new Ar... | completeMessages(receiver, lockTokens, sessionId); | void singleUnnamedSession(MessagingEntityType entityType) {
final int entityIndex = TestUtils.USE_CASE_SINGLE_SESSION;
final String messageId = "singleUnnamedSession";
final String sessionId = "singleUnnamedSession-" + Instant.now().toString();
final String contents = "Some-contents";
final int numberToSend = 5;
final ... | class UnnamedSessionManagerIntegrationTest extends IntegrationTestBase {
private final AtomicInteger messagesPending = new AtomicInteger();
private ServiceBusReceiverAsyncClient receiver;
private ServiceBusSenderAsyncClient sender;
UnnamedSessionManagerIntegrationTest() {
super(new ClientLogger(UnnamedSessionManagerInt... | class UnnamedSessionManagerIntegrationTest extends IntegrationTestBase {
private final AtomicInteger messagesPending = new AtomicInteger();
private ServiceBusReceiverAsyncClient receiver;
private ServiceBusSenderAsyncClient sender;
UnnamedSessionManagerIntegrationTest() {
super(new ClientLogger(UnnamedSessionManagerInt... |
I think, it is cleaner and improve readability. | void singleUnnamedSession(MessagingEntityType entityType) {
final int entityIndex = 0;
final String messageId = "singleUnnamedSession";
final String sessionId = "singleUnnamedSession-" + Instant.now().toString();
final String contents = "Some-contents";
final int numberToSend = 5;
final List<String> lockTokens = new Ar... | completeMessages(receiver, lockTokens, sessionId); | void singleUnnamedSession(MessagingEntityType entityType) {
final int entityIndex = TestUtils.USE_CASE_SINGLE_SESSION;
final String messageId = "singleUnnamedSession";
final String sessionId = "singleUnnamedSession-" + Instant.now().toString();
final String contents = "Some-contents";
final int numberToSend = 5;
final ... | class UnnamedSessionManagerIntegrationTest extends IntegrationTestBase {
private final AtomicInteger messagesPending = new AtomicInteger();
private ServiceBusReceiverAsyncClient receiver;
private ServiceBusSenderAsyncClient sender;
UnnamedSessionManagerIntegrationTest() {
super(new ClientLogger(UnnamedSessionManagerInt... | class UnnamedSessionManagerIntegrationTest extends IntegrationTestBase {
private final AtomicInteger messagesPending = new AtomicInteger();
private ServiceBusReceiverAsyncClient receiver;
private ServiceBusSenderAsyncClient sender;
UnnamedSessionManagerIntegrationTest() {
super(new ClientLogger(UnnamedSessionManagerInt... |
I don't think so. Methods are reusable pieces of code. | void singleUnnamedSession(MessagingEntityType entityType) {
final int entityIndex = 0;
final String messageId = "singleUnnamedSession";
final String sessionId = "singleUnnamedSession-" + Instant.now().toString();
final String contents = "Some-contents";
final int numberToSend = 5;
final List<String> lockTokens = new Ar... | completeMessages(receiver, lockTokens, sessionId); | void singleUnnamedSession(MessagingEntityType entityType) {
final int entityIndex = TestUtils.USE_CASE_SINGLE_SESSION;
final String messageId = "singleUnnamedSession";
final String sessionId = "singleUnnamedSession-" + Instant.now().toString();
final String contents = "Some-contents";
final int numberToSend = 5;
final ... | class UnnamedSessionManagerIntegrationTest extends IntegrationTestBase {
private final AtomicInteger messagesPending = new AtomicInteger();
private ServiceBusReceiverAsyncClient receiver;
private ServiceBusSenderAsyncClient sender;
UnnamedSessionManagerIntegrationTest() {
super(new ClientLogger(UnnamedSessionManagerInt... | class UnnamedSessionManagerIntegrationTest extends IntegrationTestBase {
private final AtomicInteger messagesPending = new AtomicInteger();
private ServiceBusReceiverAsyncClient receiver;
private ServiceBusSenderAsyncClient sender;
UnnamedSessionManagerIntegrationTest() {
super(new ClientLogger(UnnamedSessionManagerInt... |
This is an extra 3 lines. or one statement. You don't even use the return value. | void singleUnnamedSession(MessagingEntityType entityType) {
final int entityIndex = 0;
final String messageId = "singleUnnamedSession";
final String sessionId = "singleUnnamedSession-" + Instant.now().toString();
final String contents = "Some-contents";
final int numberToSend = 5;
final List<String> lockTokens = new Ar... | completeMessages(receiver, lockTokens, sessionId); | void singleUnnamedSession(MessagingEntityType entityType) {
final int entityIndex = TestUtils.USE_CASE_SINGLE_SESSION;
final String messageId = "singleUnnamedSession";
final String sessionId = "singleUnnamedSession-" + Instant.now().toString();
final String contents = "Some-contents";
final int numberToSend = 5;
final ... | class UnnamedSessionManagerIntegrationTest extends IntegrationTestBase {
private final AtomicInteger messagesPending = new AtomicInteger();
private ServiceBusReceiverAsyncClient receiver;
private ServiceBusSenderAsyncClient sender;
UnnamedSessionManagerIntegrationTest() {
super(new ClientLogger(UnnamedSessionManagerInt... | class UnnamedSessionManagerIntegrationTest extends IntegrationTestBase {
private final AtomicInteger messagesPending = new AtomicInteger();
private ServiceBusReceiverAsyncClient receiver;
private ServiceBusSenderAsyncClient sender;
UnnamedSessionManagerIntegrationTest() {
super(new ClientLogger(UnnamedSessionManagerInt... |
Since you are checking `instanceof` here, it's better to show that you are converting it into `Integer` type by casting it: `Integer quantity = (Integer) formField.getFieldValue()`. The `printf` statement with `%d` is too subtle to understand why you checked if this was an `instanceof` an Integer. Make the same chang... | private static void getAccountProperties(FormTrainingClient formTrainingClient) {
AccountProperties accountProperties = formTrainingClient.getAccountProperties();
System.out.printf("Max number of models that can be trained for this account: %s%n",
accountProperties.getCustomModelLimit());
System.out.printf("Current cou... | AccountProperties accountProperties = formTrainingClient.getAccountProperties(); | private static void getAccountProperties(FormTrainingClient formTrainingClient) {
AccountProperties accountProperties = formTrainingClient.getAccountProperties();
System.out.printf("Max number of models that can be trained for this account: %s%n",
accountProperties.getCustomModelLimit());
System.out.printf("Current cou... | class Authentication {
/**
* Main method to invoke this demo.
*
* @param args Unused arguments to the program.
*
* @throws IOException Exception thrown when there is an error in reading all the bytes from the File.
*/
public static void main(String[] args) {
/**
* Set the environment variables with your own values befo... | class Authentication {
/**
* Main method to invoke this demo.
*
* @param args Unused arguments to the program.
*
*/
public static void main(String[] args) {
/**
* Set the environment variables with your own values before running the sample:
* AZURE_CLIENT_ID - the client ID of your active directory application.
* AZURE... |
I feel like we need to either link to the API ref or somehow communicate the expected types for each receipt field. Sorry if you did this and I missed it | public static void main(final String[] args) {
FormRecognizerClient client = new FormRecognizerClientBuilder()
.credential(new AzureKeyCredential("{key}"))
.endpoint("https:
.buildClient();
String receiptUrl = "https:
+ "/azure-ai-formrecognizer/src/samples/java/sample-forms/receipts/contoso-allinone.jpg";
SyncPoller<O... | if (merchantNameFieldValue instanceof String) { | public static void main(final String[] args) {
FormRecognizerClient client = new FormRecognizerClientBuilder()
.credential(new AzureKeyCredential("{key}"))
.endpoint("https:
.buildClient();
String receiptUrl = "https:
+ "/azure-ai-formrecognizer/src/samples/java/sample-forms/receipts/contoso-allinone.jpg";
SyncPoller<O... | class RecognizeReceiptsFromUrl {
/**
* Main method to invoke this demo.
*
* @param args Unused. Arguments to the program.
*/
@SuppressWarnings("unchecked")
} | class RecognizeReceiptsFromUrl {
/**
* Main method to invoke this demo.
*
* @param args Unused. Arguments to the program.
*/
} |
added :) | public static void main(final String[] args) {
FormRecognizerClient client = new FormRecognizerClientBuilder()
.credential(new AzureKeyCredential("{key}"))
.endpoint("https:
.buildClient();
String receiptUrl = "https:
+ "/azure-ai-formrecognizer/src/samples/java/sample-forms/receipts/contoso-allinone.jpg";
SyncPoller<O... | if (merchantNameFieldValue instanceof String) { | public static void main(final String[] args) {
FormRecognizerClient client = new FormRecognizerClientBuilder()
.credential(new AzureKeyCredential("{key}"))
.endpoint("https:
.buildClient();
String receiptUrl = "https:
+ "/azure-ai-formrecognizer/src/samples/java/sample-forms/receipts/contoso-allinone.jpg";
SyncPoller<O... | class RecognizeReceiptsFromUrl {
/**
* Main method to invoke this demo.
*
* @param args Unused. Arguments to the program.
*/
@SuppressWarnings("unchecked")
} | class RecognizeReceiptsFromUrl {
/**
* Main method to invoke this demo.
*
* @param args Unused. Arguments to the program.
*/
} |
Update this to using the public beginRecognizeContent API | public void recognizeContentResultWithBlankPdf(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
SyncPoller<OperationResult, List<FormPage>> syncPoller =
client.beginRecognizeContent(getReplayableBufferData(BLANK_FORM_LOCAL_URL), BLA... | client.beginRecognizeContent(getReplayableBufferData(BLANK_FORM_LOCAL_URL), BLANK_FORM_FILE_LENGTH, | public void recognizeContentResultWithBlankPdf(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
blankPdfDataRunner((data, dataLength) -> {
SyncPoller<OperationResult, List<FormPage>> syncPoller = client.beginRecognizeContent(
new R... | class FormRecognizerAsyncClientTest extends FormRecognizerClientTestBase {
private FormRecognizerAsyncClient client;
@BeforeAll
static void beforeAll() {
StepVerifier.setDefaultTimeout(Duration.ofSeconds(30));
}
@AfterAll
static void afterAll() {
StepVerifier.resetDefaultTimeout();
}
private FormRecognizerAsyncClient g... | class FormRecognizerAsyncClientTest extends FormRecognizerClientTestBase {
private FormRecognizerAsyncClient client;
@BeforeAll
static void beforeAll() {
StepVerifier.setDefaultTimeout(Duration.ofSeconds(30));
}
@AfterAll
static void afterAll() {
StepVerifier.resetDefaultTimeout();
}
private FormRecognizerAsyncClient g... |
not sure what it means. ``` client.beginRecognizeContent() ``` is already a public API | public void recognizeContentResultWithBlankPdf(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
SyncPoller<OperationResult, List<FormPage>> syncPoller =
client.beginRecognizeContent(getReplayableBufferData(BLANK_FORM_LOCAL_URL), BLA... | client.beginRecognizeContent(getReplayableBufferData(BLANK_FORM_LOCAL_URL), BLANK_FORM_FILE_LENGTH, | public void recognizeContentResultWithBlankPdf(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
blankPdfDataRunner((data, dataLength) -> {
SyncPoller<OperationResult, List<FormPage>> syncPoller = client.beginRecognizeContent(
new R... | class FormRecognizerAsyncClientTest extends FormRecognizerClientTestBase {
private FormRecognizerAsyncClient client;
@BeforeAll
static void beforeAll() {
StepVerifier.setDefaultTimeout(Duration.ofSeconds(30));
}
@AfterAll
static void afterAll() {
StepVerifier.resetDefaultTimeout();
}
private FormRecognizerAsyncClient g... | class FormRecognizerAsyncClientTest extends FormRecognizerClientTestBase {
private FormRecognizerAsyncClient client;
@BeforeAll
static void beforeAll() {
StepVerifier.setDefaultTimeout(Duration.ofSeconds(30));
}
@AfterAll
static void afterAll() {
StepVerifier.resetDefaultTimeout();
}
private FormRecognizerAsyncClient g... |
Should this print 'null/null' or just be empty strings? | void testUserAgentStringFormat() {
String javaVersion = System.getProperty("java.version");
String osName = System.getProperty("os.name");
String osVersion = System.getProperty("os.version");
String plaform = new StringBuilder().append("(")
.append(javaVersion).append("; ")
.append(osName).append("; ")
.append(osVersio... | assertEquals("myapp azsdk-java-null/null " + plaform, | void testUserAgentStringFormat() {
String javaVersion = System.getProperty("java.version");
String osName = System.getProperty("os.name");
String osVersion = System.getProperty("os.version");
String plaform = new StringBuilder().append("(")
.append(javaVersion).append("; ")
.append(osName).append("; ")
.append(osVersio... | class UserAgentUtilTest {
@Test
} | class UserAgentUtilTest {
@Test
} |
This is the existing format and it might be useful in doing a regex match to extract fields from the user agent string. | void testUserAgentStringFormat() {
String javaVersion = System.getProperty("java.version");
String osName = System.getProperty("os.name");
String osVersion = System.getProperty("os.version");
String plaform = new StringBuilder().append("(")
.append(javaVersion).append("; ")
.append(osName).append("; ")
.append(osVersio... | assertEquals("myapp azsdk-java-null/null " + plaform, | void testUserAgentStringFormat() {
String javaVersion = System.getProperty("java.version");
String osName = System.getProperty("os.name");
String osVersion = System.getProperty("os.version");
String plaform = new StringBuilder().append("(")
.append(javaVersion).append("; ")
.append(osName).append("; ")
.append(osVersio... | class UserAgentUtilTest {
@Test
} | class UserAgentUtilTest {
@Test
} |
sourceUrl -> invalidSourceUrl | public void recognizeReceiptInvalidSourceUrl(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
invalidSourceUrlRunner((sourceUrl) -> {
ErrorResponseException errorResponseException = assertThrows(ErrorResponseException.class,
() -> c... | invalidSourceUrlRunner((sourceUrl) -> { | public void recognizeReceiptInvalidSourceUrl(HttpClient httpClient, FormRecognizerServiceVersion serviceVersion) {
client = getFormRecognizerAsyncClient(httpClient, serviceVersion);
invalidSourceUrlRunner((invalidSourceUrl) -> {
HttpResponseException errorResponseException = assertThrows(HttpResponseException.class,
()... | class FormRecognizerAsyncClientTest extends FormRecognizerClientTestBase {
private FormRecognizerAsyncClient client;
@BeforeAll
static void beforeAll() {
StepVerifier.setDefaultTimeout(Duration.ofSeconds(30));
}
@AfterAll
static void afterAll() {
StepVerifier.resetDefaultTimeout();
}
private FormRecognizerAsyncClient g... | class FormRecognizerAsyncClientTest extends FormRecognizerClientTestBase {
private FormRecognizerAsyncClient client;
@BeforeAll
static void beforeAll() {
StepVerifier.setDefaultTimeout(Duration.ofSeconds(30));
}
@AfterAll
static void afterAll() {
StepVerifier.resetDefaultTimeout();
}
private FormRecognizerAsyncClient g... |
Here last `AsyncPollResponse` will be in `FAILED` state with error in `PollResult`. Unlike track1 client-runtime, it will not throw CloudException during the polling. | public void lroBasedOnAsyncOperationFailed() {
ServerConfigure serverConfigure = new ServerConfigure();
final String resourceEndpoint = "/resource/1";
final String operationEndpoint = "/operations/1";
ResponseTransformer provisioningStateLroService = new ResponseTransformer() {
private final int[] getCallCount = new in... | Assertions.assertEquals(LongRunningOperationStatus.FAILED, pollResponse.getStatus()); | public void lroBasedOnAsyncOperationFailed() {
ServerConfigure serverConfigure = new ServerConfigure();
final String resourceEndpoint = "/resource/1";
final String operationEndpoint = "/operations/1";
ResponseTransformer provisioningStateLroService = new ResponseTransformer() {
private final int[] getCallCount = new in... | class LROPollerTests {
private static final SerializerAdapter SERIALIZER = new AzureJacksonAdapter();
private static final Duration POLLING_DURATION = Duration.ofMillis(100);
@BeforeEach
public void beforeTest() {
MockitoAnnotations.initMocks(this);
}
@AfterEach
public void afterTest() {
Mockito.framework().clearInline... | class LROPollerTests {
private static final SerializerAdapter SERIALIZER = new AzureJacksonAdapter();
private static final Duration POLLING_DURATION = Duration.ofMillis(100);
@BeforeEach
public void beforeTest() {
MockitoAnnotations.initMocks(this);
}
@AfterEach
public void afterTest() {
Mockito.framework().clearInline... |
Why is this logger.warn() and not logger.info(), is this intentional? | public Mono<ShouldRetryResult> shouldRetry(Exception exception) {
CosmosException exceptionToThrow = null;
Duration backoffTime = Duration.ofSeconds(0);
Duration timeout = Duration.ofSeconds(0);
boolean forceRefreshAddressCache = false;
if (!(exception instanceof GoneException) &&
!(exception instanceof RetryWithExcept... | logger.warn("Received gone exception after backoff/retry. Will fail the request. {}, short stackTrace = [{}]", | public Mono<ShouldRetryResult> shouldRetry(Exception exception) {
CosmosException exceptionToThrow = null;
Duration backoffTime = Duration.ofSeconds(0);
Duration timeout = Duration.ofSeconds(0);
boolean forceRefreshAddressCache = false;
if (!(exception instanceof GoneException) &&
!(exception instanceof RetryWithExcept... | class GoneAndRetryWithRetryPolicy extends RetryPolicyWithDiagnostics {
private final static Logger logger = LoggerFactory.getLogger(GoneAndRetryWithRetryPolicy.class);
private final static int LIMITED_STACK_TRACE_FAILURE_DEPTH = 3;
private final static int DEFAULT_WAIT_TIME_IN_SECONDS = 30;
private final static int MAX... | class GoneAndRetryWithRetryPolicy extends RetryPolicyWithDiagnostics {
private final static Logger logger = LoggerFactory.getLogger(GoneAndRetryWithRetryPolicy.class);
private final static int DEFAULT_WAIT_TIME_IN_SECONDS = 30;
private final static int MAXIMUM_BACKOFF_TIME_IN_SECONDS = 15;
private final static int INIT... |
after all the retries are exhausted we want to print a warn message indicating failure. however when there are more retry attempt are left we want to print a info message. | public Mono<ShouldRetryResult> shouldRetry(Exception exception) {
CosmosException exceptionToThrow = null;
Duration backoffTime = Duration.ofSeconds(0);
Duration timeout = Duration.ofSeconds(0);
boolean forceRefreshAddressCache = false;
if (!(exception instanceof GoneException) &&
!(exception instanceof RetryWithExcept... | logger.warn("Received gone exception after backoff/retry. Will fail the request. {}, short stackTrace = [{}]", | public Mono<ShouldRetryResult> shouldRetry(Exception exception) {
CosmosException exceptionToThrow = null;
Duration backoffTime = Duration.ofSeconds(0);
Duration timeout = Duration.ofSeconds(0);
boolean forceRefreshAddressCache = false;
if (!(exception instanceof GoneException) &&
!(exception instanceof RetryWithExcept... | class GoneAndRetryWithRetryPolicy extends RetryPolicyWithDiagnostics {
private final static Logger logger = LoggerFactory.getLogger(GoneAndRetryWithRetryPolicy.class);
private final static int LIMITED_STACK_TRACE_FAILURE_DEPTH = 3;
private final static int DEFAULT_WAIT_TIME_IN_SECONDS = 30;
private final static int MAX... | class GoneAndRetryWithRetryPolicy extends RetryPolicyWithDiagnostics {
private final static Logger logger = LoggerFactory.getLogger(GoneAndRetryWithRetryPolicy.class);
private final static int DEFAULT_WAIT_TIME_IN_SECONDS = 30;
private final static int MAXIMUM_BACKOFF_TIME_IN_SECONDS = 15;
private final static int INIT... |
`super.beforeTest()` is an empty method, you can remove this. | protected void beforeTest() {
super.beforeTest();
String connectionString = interceptorManager.isPlaybackMode()
? "DefaultEndpointsProtocol=https;AccountName=dummyAccount;AccountKey=xyzDummy;EndpointSuffix=core.windows.net"
: System.getenv("AZURE_TABLES_CONNECTION_STRING");
StorageConnectionString storageConnectionStri... | super.beforeTest(); | protected void beforeTest() {
String connectionString = interceptorManager.isPlaybackMode()
? "DefaultEndpointsProtocol=https;AccountName=dummyAccount;AccountKey=xyzDummy;EndpointSuffix=core.windows.net"
: System.getenv("AZURE_TABLES_CONNECTION_STRING");
StorageConnectionString storageConnectionString
= StorageConnecti... | class AzureTableImplTest extends TestBase {
private static final String PARTITION_KEY = "PartitionKey";
private static final String ROW_KEY = "RowKey";
private static final int TIMEOUT = 5000;
private AzureTableImpl azureTable;
@Override
@Override
protected void afterTest() {
QueryOptions queryOptions = new QueryOption... | class AzureTableImplTest extends TestBase {
private static final String PARTITION_KEY = "PartitionKey";
private static final String ROW_KEY = "RowKey";
private static final int TIMEOUT = 5000;
private AzureTableImpl azureTable;
@Override
@Override
protected void afterTest() {
QueryOptions queryOptions = new QueryOption... |
Remove `this.` | public Mono<HttpResponse> process(HttpPipelineCallContext context, HttpPipelineNextPolicy next) {
String authorizationValue = this.credential.generateAuthorizationHeader(context.getHttpRequest().getUrl(),
context.getHttpRequest().getHeaders().toMap());
context.getHttpRequest().setHeader("Authorization", authorizationVa... | String authorizationValue = this.credential.generateAuthorizationHeader(context.getHttpRequest().getUrl(), | public Mono<HttpResponse> process(HttpPipelineCallContext context, HttpPipelineNextPolicy next) {
String authorizationValue = credential.generateAuthorizationHeader(context.getHttpRequest().getUrl(),
context.getHttpRequest().getHeaders().toMap());
context.getHttpRequest().setHeader("Authorization", authorizationValue);... | class TablesSharedKeyCredentialPolicy implements HttpPipelinePolicy {
private final TablesSharedKeyCredential credential;
/**
* constructor for the TablesSharedKeyCredentialPolicy class
*
* @param credential the credentials of the account
*/
public TablesSharedKeyCredentialPolicy(TablesSharedKeyCredential credential) {... | class TablesSharedKeyCredentialPolicy implements HttpPipelinePolicy {
private final TablesSharedKeyCredential credential;
/**
* constructor for the TablesSharedKeyCredentialPolicy class
*
* @param credential the credentials of the account
*/
public TablesSharedKeyCredentialPolicy(TablesSharedKeyCredential credential) {... |
This can be simplified to. Same with the line below. ```java this.accountName = Objects.requireNonNull(accountName, "'accountName' cannot be null."); ``` | public TablesSharedKeyCredential(String accountName, String accountKey) {
Objects.requireNonNull(accountName, "'accountName' cannot be null.");
Objects.requireNonNull(accountKey, "'accountKey' cannot be null.");
this.accountName = accountName;
this.accountKey = accountKey;
} | Objects.requireNonNull(accountName, "'accountName' cannot be null."); | public TablesSharedKeyCredential(String accountName, String accountKey) {
this.accountName = Objects.requireNonNull(accountName, "'accountName' cannot be null.");
this.accountKey = Objects.requireNonNull(accountKey, "'accountKey' cannot be null.");
} | class TablesSharedKeyCredential {
private static final String AUTHORIZATION_HEADER_FORMAT = "SharedKeyLite %s:%s";
private final String accountName;
private final String accountKey;
/**
* Constructor for TableSharedKeyCredential Class
*
* @param accountName name of the storage account
* @param accountKey key to the sto... | class TablesSharedKeyCredential {
private static final String AUTHORIZATION_HEADER_FORMAT = "SharedKeyLite %s:%s";
private final String accountName;
private final String accountKey;
/**
* Constructor for TableSharedKeyCredential Class
*
* @param accountName name of the storage account
* @param accountKey key to the sto... |
same here ... not sure | public static void main(String[] args) throws IOException {
FormRecognizerClient client = new FormRecognizerClientBuilder()
.credential(new AzureKeyCredential("{key}"))
.endpoint("https:
.buildClient();
File analyzeFile = new File("../formrecognizer/azure-ai-formrecognizer/src/samples/java/sample-forms/"
+ "forms/Form_... | public static void main(String[] args) throws IOException {
FormRecognizerClient client = new FormRecognizerClientBuilder()
.credential(new AzureKeyCredential("{key}"))
.endpoint("https:
.buildClient();
File analyzeFile = new File("../formrecognizer/azure-ai-formrecognizer/src/samples/java/sample-forms/"
+ "forms/Form_... | class AdvancedDiffLabeledUnlabeledData {
/**
* Main method to invoke this demo.
*
* @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 AdvancedDiffLabeledUnlabeledData {
/**
* Main method to invoke this demo.
*
* @param args Unused arguments to the program.
*
* @throws IOException Exception thrown when there is an error in reading all the bytes from the File.
*/
} | |
I'd be consistent about using `final`. If you use final here. I'd expect you to use it in all other cases in your code where you don't expect variables to be reassigned. | protected void beforeTest() {
super.beforeTest();
String connectionString = interceptorManager.isPlaybackMode()
? "DefaultEndpointsProtocol=https;AccountName=dummyAccount;AccountKey=xyzDummy;EndpointSuffix=core.windows.net"
: System.getenv("AZURE_TABLES_CONNECTION_STRING");
StorageConnectionString storageConnectionStri... | final List<HttpPipelinePolicy> policies = new ArrayList<>(); | protected void beforeTest() {
String connectionString = interceptorManager.isPlaybackMode()
? "DefaultEndpointsProtocol=https;AccountName=dummyAccount;AccountKey=xyzDummy;EndpointSuffix=core.windows.net"
: System.getenv("AZURE_TABLES_CONNECTION_STRING");
StorageConnectionString storageConnectionString
= StorageConnecti... | class AzureTableImplTest extends TestBase {
private static final String PARTITION_KEY = "PartitionKey";
private static final String ROW_KEY = "RowKey";
private static final int TIMEOUT = 5000;
private AzureTableImpl azureTable;
@Override
@Override
protected void afterTest() {
QueryOptions queryOptions = new QueryOption... | class AzureTableImplTest extends TestBase {
private static final String PARTITION_KEY = "PartitionKey";
private static final String ROW_KEY = "RowKey";
private static final int TIMEOUT = 5000;
private AzureTableImpl azureTable;
@Override
@Override
protected void afterTest() {
QueryOptions queryOptions = new QueryOption... |
If you import this, it won't need to be fully qualified. | void createTableDuplicateName() {
String tableName = testResourceNamer.randomName("test", 20);
TableProperties tableProperties = new TableProperties().setTableName(tableName);
createTable(tableName);
String requestId = testResourceNamer.randomUuid();
StepVerifier.create(azureTable.getTables().createWithResponseAsync(ta... | .expectError(com.azure.data.tables.implementation.models.TableServiceErrorException.class) | void createTableDuplicateName() {
String tableName = testResourceNamer.randomName("test", 20);
TableProperties tableProperties = new TableProperties().setTableName(tableName);
createTable(tableName);
String requestId = testResourceNamer.randomUuid();
StepVerifier.create(azureTable.getTables().createWithResponseAsync(ta... | class AzureTableImplTest extends TestBase {
private static final String PARTITION_KEY = "PartitionKey";
private static final String ROW_KEY = "RowKey";
private static final int TIMEOUT = 5000;
private AzureTableImpl azureTable;
@Override
protected void beforeTest() {
String connectionString = interceptorManager.isPlayb... | class AzureTableImplTest extends TestBase {
private static final String PARTITION_KEY = "PartitionKey";
private static final String ROW_KEY = "RowKey";
private static final int TIMEOUT = 5000;
private AzureTableImpl azureTable;
@Override
protected void beforeTest() {
String connectionString = interceptorManager.isPlayb... |
This should be removed. | public Mono<Void> complete(String lockToken) {
/*if (lockToken instanceof ServiceBusReceivedMessage) {
return complete(lockToken, ((ServiceBusReceivedMessage) lockToken).getSessionId());
} else {
return updateDisposition(lockToken, DispositionStatus.COMPLETED, null, null,
null, null, null);
}*/
return updateDisposition... | /*if (lockToken instanceof ServiceBusReceivedMessage) { | public Mono<Void> complete(String lockToken) {
return updateDisposition(lockToken, DispositionStatus.COMPLETED, null, null,
null, receiverOptions.getSessionId(), null);
} | class ServiceBusReceiverAsyncClient implements AutoCloseable {
private static final DeadLetterOptions DEFAULT_DEAD_LETTER_OPTIONS = new DeadLetterOptions();
private static final String TRANSACTION_LINK_NAME = "coordinator";
private final AtomicBoolean isDisposed = new AtomicBoolean();
private final MessageLockContainer... | class ServiceBusReceiverAsyncClient implements AutoCloseable {
private static final DeadLetterOptions DEFAULT_DEAD_LETTER_OPTIONS = new DeadLetterOptions();
private static final String TRANSACTION_LINK_NAME = "coordinator";
private final AtomicBoolean isDisposed = new AtomicBoolean();
private final MessageLockContainer... |
Any reason `Class.forName(String)` needs to be used instead of `ByteBufferReceiveTest.class`? | public static void main(String[] args) {
Class<?>[] testClasses;
try {
testClasses = new Class<?>[]{
Class.forName("com.azure.core.perf.ByteBufferReceiveTest"),
Class.forName("com.azure.core.perf.JsonReceiveTest"),
Class.forName("com.azure.core.perf.JsonSendTest"),
Class.forName("com.azure.core.perf.XmlReceiveTest"),
C... | Class.forName("com.azure.core.perf.ByteBufferReceiveTest"), | public static void main(String[] args) {
PerfStressProgram.run(new Class<?>[]{
ByteBufferReceiveTest.class,
JsonReceiveTest.class,
JsonSendTest.class,
XmlReceiveTest.class,
XmlSendTest.class,
ByteBufferSendTest.class
}, args);
} | class App {
} | class App {
} |
Is the same seed used to ensure runs are consistent across each other? | public ByteBufferReceiveTest(PerfStressOptions options) throws IOException, URISyntaxException {
super(options);
bodyBytes = new byte[(int) options.getSize()];
new Random(0).nextBytes(bodyBytes);
mockHTTPClient = new MockHttpClient(httpRequest -> createMockResponse(httpRequest,
"application/octet-stream", bodyBytes));
... | new Random(0).nextBytes(bodyBytes); | public ByteBufferReceiveTest(PerfStressOptions options) throws IOException, URISyntaxException {
super(options);
bodyBytes = new byte[(int) options.getSize()];
new Random(0).nextBytes(bodyBytes);
mockHTTPClient = new MockHttpClient(httpRequest -> createMockResponse(httpRequest,
"application/octet-stream", bodyBytes));
... | class ByteBufferReceiveTest extends RestProxyTestBase<PerfStressOptions> {
private final MockHttpClient mockHTTPClient;
private final MyRestProxyService service;
private final byte[] bodyBytes;
@Override
public void run() {
throw new UnsupportedOperationException();
}
@Override
public Mono<Void> runAsync() {
return ser... | class ByteBufferReceiveTest extends RestProxyTestBase<PerfStressOptions> {
private final MockHttpClient mockHTTPClient;
private final MyRestProxyService service;
private final byte[] bodyBytes;
@Override
public void run() {
throw new UnsupportedOperationException();
}
@Override
public Mono<Void> runAsync() {
return ser... |
This is to simulate consumption of the response stream, correct? | public Mono<Void> runAsync() {
return service.getRawDataAsync()
.flatMapMany(response -> response.getValue())
.map(byteBuffer -> {
for (int i = 0; i < byteBuffer.remaining(); i++) {
byteBuffer.get();
}
return 1;
}).then();
} | } | public Mono<Void> runAsync() {
return service.getRawDataAsync()
.flatMapMany(response -> response.getValue())
.map(byteBuffer -> {
for (int i = 0; i < byteBuffer.remaining(); i++) {
byteBuffer.get();
}
return 1;
}).then();
} | class ByteBufferReceiveTest extends RestProxyTestBase<PerfStressOptions> {
private final MockHttpClient mockHTTPClient;
private final MyRestProxyService service;
private final byte[] bodyBytes;
public ByteBufferReceiveTest(PerfStressOptions options) throws IOException, URISyntaxException {
super(options);
bodyBytes = n... | class ByteBufferReceiveTest extends RestProxyTestBase<PerfStressOptions> {
private final MockHttpClient mockHTTPClient;
private final MyRestProxyService service;
private final byte[] bodyBytes;
public ByteBufferReceiveTest(PerfStressOptions options) throws IOException, URISyntaxException {
super(options);
bodyBytes = n... |
Yes, this would be interesting. For example having a block size equivalent to the TCP packet size, etc. | public ByteBufferSendTest(PerfStressOptions options) {
super(options);
dataToSend = TestDataCreationHelper.createRandomByteBufferFlux(options.getSize());
mockHttpReceiveClient = new MockHttpReceiveClient();
final HttpPipeline pipeline = new HttpPipelineBuilder()
.httpClient(mockHttpReceiveClient)
.build();
service = Re... | public ByteBufferSendTest(PerfStressOptions options) {
super(options);
dataToSend = TestDataCreationHelper.createRandomByteBufferFlux(options.getSize());
mockHttpReceiveClient = new MockHttpReceiveClient();
final HttpPipeline pipeline = new HttpPipelineBuilder()
.httpClient(mockHttpReceiveClient)
.build();
service = Re... | class ByteBufferSendTest extends RestProxyTestBase<PerfStressOptions> {
private final MockHttpReceiveClient mockHttpReceiveClient;
private final MyRestProxyService service;
private final Flux<ByteBuffer> dataToSend;
@Override
public void run() {
throw new UnsupportedOperationException();
}
@Override
public Mono<Void> r... | class ByteBufferSendTest extends RestProxyTestBase<PerfStressOptions> {
private final MockHttpReceiveClient mockHttpReceiveClient;
private final MyRestProxyService service;
private final Flux<ByteBuffer> dataToSend;
@Override
public void run() {
throw new UnsupportedOperationException();
}
@Override
public Mono<Void> r... | |
with this you will be loosing the cause exception stacktrace. You probably want to keep the root cause exception stacktrace. | public int compare(Object obj1, Object obj2) {
ItemType type1 = ItemTypeHelper.getOrderByItemType(obj1);
ItemType type2 = ItemTypeHelper.getOrderByItemType(obj2);
int cmp = Integer.compare(type1.getVal(), type2.getVal());
if (cmp != 0) {
return cmp;
}
switch (type1) {
case NoValue:
case Null:
return 0;
case Boolean:
re... | throw new IllegalStateException(String.format("Exception for getting hash for type %s: %s ", type1.toString(), e.getMessage())); | public int compare(Object obj1, Object obj2) {
ItemType type1 = ItemTypeHelper.getOrderByItemType(obj1);
ItemType type2 = ItemTypeHelper.getOrderByItemType(obj2);
int cmp = Integer.compare(type1.getVal(), type2.getVal());
if (cmp != 0) {
return cmp;
}
switch (type1) {
case NoValue:
case Null:
return 0;
case Boolean:
re... | class SingletonHelper {
private static final ItemComparator INSTANCE = new ItemComparator();
} | class SingletonHelper {
private static final ItemComparator INSTANCE = new ItemComparator();
} |
You don't need to mock this anymore you can set the string and return it. | void setup() {
MockitoAnnotations.initMocks(this);
when(asyncClient.getEntityPath()).thenReturn(ENTITY_PATH);
when(asyncClient.getFullyQualifiedNamespace()).thenReturn(NAMESPACE);
when(asyncClient.getReceiverOptions()).thenReturn(new ReceiverOptions(ReceiveMode.PEEK_LOCK, 1,
maxAutoLockRenewalDuration));
when(messageLo... | when(messageLockToken).thenReturn(LOCK_TOKEN); | void setup() {
MockitoAnnotations.initMocks(this);
when(asyncClient.getEntityPath()).thenReturn(ENTITY_PATH);
when(asyncClient.getFullyQualifiedNamespace()).thenReturn(NAMESPACE);
when(asyncClient.getReceiverOptions()).thenReturn(new ReceiverOptions(ReceiveMode.PEEK_LOCK, 1,
maxAutoLockRenewalDuration));
client = new S... | class ServiceBusReceiverClientTest {
private static final String NAMESPACE = "test-namespace";
private static final String ENTITY_PATH = "test-entity-path";
private static final String LOCK_TOKEN = UUID.randomUUID().toString();
private static final Duration OPERATION_TIMEOUT = Duration.ofSeconds(5);
private final Clien... | class ServiceBusReceiverClientTest {
private static final String NAMESPACE = "test-namespace";
private static final String ENTITY_PATH = "test-entity-path";
private static final String LOCK_TOKEN = UUID.randomUUID().toString();
private static final Duration OPERATION_TIMEOUT = Duration.ofSeconds(5);
private final Clien... |
I see, good point, changed to following: new IllegalStateException(String.format("Getting hash exception for type %s ", type1.toString()), e) | public int compare(Object obj1, Object obj2) {
ItemType type1 = ItemTypeHelper.getOrderByItemType(obj1);
ItemType type2 = ItemTypeHelper.getOrderByItemType(obj2);
int cmp = Integer.compare(type1.getVal(), type2.getVal());
if (cmp != 0) {
return cmp;
}
switch (type1) {
case NoValue:
case Null:
return 0;
case Boolean:
re... | throw new IllegalStateException(String.format("Exception for getting hash for type %s: %s ", type1.toString(), e.getMessage())); | public int compare(Object obj1, Object obj2) {
ItemType type1 = ItemTypeHelper.getOrderByItemType(obj1);
ItemType type2 = ItemTypeHelper.getOrderByItemType(obj2);
int cmp = Integer.compare(type1.getVal(), type2.getVal());
if (cmp != 0) {
return cmp;
}
switch (type1) {
case NoValue:
case Null:
return 0;
case Boolean:
re... | class SingletonHelper {
private static final ItemComparator INSTANCE = new ItemComparator();
} | class SingletonHelper {
private static final ItemComparator INSTANCE = new ItemComparator();
} |
I don't think this exception message makes sense, since there is no `type1` in this try catch block. | public int compare(Object obj1, Object obj2) {
ItemType type1 = ItemTypeHelper.getOrderByItemType(obj1);
ItemType type2 = ItemTypeHelper.getOrderByItemType(obj2);
int cmp = Integer.compare(type1.getVal(), type2.getVal());
if (cmp != 0) {
return cmp;
}
switch (type1) {
case NoValue:
case Null:
return 0;
case Boolean:
re... | throw new IllegalStateException(String.format("Getting hash exception for type %s ", type1.toString()), e); | public int compare(Object obj1, Object obj2) {
ItemType type1 = ItemTypeHelper.getOrderByItemType(obj1);
ItemType type2 = ItemTypeHelper.getOrderByItemType(obj2);
int cmp = Integer.compare(type1.getVal(), type2.getVal());
if (cmp != 0) {
return cmp;
}
switch (type1) {
case NoValue:
case Null:
return 0;
case Boolean:
re... | class SingletonHelper {
private static final ItemComparator INSTANCE = new ItemComparator();
} | class SingletonHelper {
private static final ItemComparator INSTANCE = new ItemComparator();
} |
hmmm, we could remove the type from the exception message, but thought it might give some hint which type is having hash issue? | public int compare(Object obj1, Object obj2) {
ItemType type1 = ItemTypeHelper.getOrderByItemType(obj1);
ItemType type2 = ItemTypeHelper.getOrderByItemType(obj2);
int cmp = Integer.compare(type1.getVal(), type2.getVal());
if (cmp != 0) {
return cmp;
}
switch (type1) {
case NoValue:
case Null:
return 0;
case Boolean:
re... | throw new IllegalStateException(String.format("Getting hash exception for type %s ", type1.toString()), e); | public int compare(Object obj1, Object obj2) {
ItemType type1 = ItemTypeHelper.getOrderByItemType(obj1);
ItemType type2 = ItemTypeHelper.getOrderByItemType(obj2);
int cmp = Integer.compare(type1.getVal(), type2.getVal());
if (cmp != 0) {
return cmp;
}
switch (type1) {
case NoValue:
case Null:
return 0;
case Boolean:
re... | class SingletonHelper {
private static final ItemComparator INSTANCE = new ItemComparator();
} | class SingletonHelper {
private static final ItemComparator INSTANCE = new ItemComparator();
} |
why only type1 and not type2 ? Also, what does type1.toString() represents ? | public int compare(Object obj1, Object obj2) {
ItemType type1 = ItemTypeHelper.getOrderByItemType(obj1);
ItemType type2 = ItemTypeHelper.getOrderByItemType(obj2);
int cmp = Integer.compare(type1.getVal(), type2.getVal());
if (cmp != 0) {
return cmp;
}
switch (type1) {
case NoValue:
case Null:
return 0;
case Boolean:
re... | throw new IllegalStateException(String.format("Getting hash exception for type %s ", type1.toString()), e); | public int compare(Object obj1, Object obj2) {
ItemType type1 = ItemTypeHelper.getOrderByItemType(obj1);
ItemType type2 = ItemTypeHelper.getOrderByItemType(obj2);
int cmp = Integer.compare(type1.getVal(), type2.getVal());
if (cmp != 0) {
return cmp;
}
switch (type1) {
case NoValue:
case Null:
return 0;
case Boolean:
re... | class SingletonHelper {
private static final ItemComparator INSTANCE = new ItemComparator();
} | class SingletonHelper {
private static final ItemComparator INSTANCE = new ItemComparator();
} |
I think with Java samples we want to start showing the easier way of doing things which are usually with higher versions of the Java language. But since our support needs to be catered to atleast Java 8 we show the Java 8 way and the other way is commented. | public static void main(String[] args) throws IOException {
FormRecognizerAsyncClient client = new FormRecognizerClientBuilder()
.credential(new AzureKeyCredential("{key}"))
.endpoint("https:
.buildAsyncClient();
File analyzeFile = new File("../formrecognizer/azure-ai-formrecognizer/src/samples/java/sample-forms/"
+ "f... | public static void main(String[] args) throws IOException {
FormRecognizerAsyncClient client = new FormRecognizerClientBuilder()
.credential(new AzureKeyCredential("{key}"))
.endpoint("https:
.buildAsyncClient();
File analyzeFile = new File("../formrecognizer/azure-ai-formrecognizer/src/samples/java/sample-forms/"
+ "f... | class AdvancedDiffLabeledUnlabeledDataAsync {
/**
* Main method to invoke this demo.
*
* @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 AdvancedDiffLabeledUnlabeledDataAsync {
/**
* Main method to invoke this demo.
*
* @param args Unused arguments to the program.
*
* @throws IOException Exception thrown when there is an error in reading all the bytes from the File.
*/
} | |
since we can only reach to this step when type1 equals type2, so I think either should work. it will tell us whether it is objectNode or arrayNode. (The name of the ItemType enum) | public int compare(Object obj1, Object obj2) {
ItemType type1 = ItemTypeHelper.getOrderByItemType(obj1);
ItemType type2 = ItemTypeHelper.getOrderByItemType(obj2);
int cmp = Integer.compare(type1.getVal(), type2.getVal());
if (cmp != 0) {
return cmp;
}
switch (type1) {
case NoValue:
case Null:
return 0;
case Boolean:
re... | throw new IllegalStateException(String.format("Getting hash exception for type %s ", type1.toString()), e); | public int compare(Object obj1, Object obj2) {
ItemType type1 = ItemTypeHelper.getOrderByItemType(obj1);
ItemType type2 = ItemTypeHelper.getOrderByItemType(obj2);
int cmp = Integer.compare(type1.getVal(), type2.getVal());
if (cmp != 0) {
return cmp;
}
switch (type1) {
case NoValue:
case Null:
return 0;
case Boolean:
re... | class SingletonHelper {
private static final ItemComparator INSTANCE = new ItemComparator();
} | class SingletonHelper {
private static final ItemComparator INSTANCE = new ItemComparator();
} |
nit: weird formatting here | public static void main(String[] args) throws IOException {
FormRecognizerAsyncClient client = new FormRecognizerClientBuilder()
.credential(new AzureKeyCredential("{key}"))
.endpoint("https:
.buildAsyncClient();
File analyzeFile = new File("../formrecognizer/azure-ai-formrecognizer/src/samples/java/sample-forms/"
+ "f... | public static void main(String[] args) throws IOException {
FormRecognizerAsyncClient client = new FormRecognizerClientBuilder()
.credential(new AzureKeyCredential("{key}"))
.endpoint("https:
.buildAsyncClient();
File analyzeFile = new File("../formrecognizer/azure-ai-formrecognizer/src/samples/java/sample-forms/"
+ "f... | class AdvancedDiffLabeledUnlabeledDataAsync {
/**
* Main method to invoke this demo.
*
* @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 AdvancedDiffLabeledUnlabeledDataAsync {
/**
* Main method to invoke this demo.
*
* @param args Unused arguments to the program.
*
* @throws IOException Exception thrown when there is an error in reading all the bytes from the File.
*/
} | |
same here | public static void main(String[] args) throws IOException {
FormRecognizerAsyncClient client = new FormRecognizerClientBuilder()
.credential(new AzureKeyCredential("{key}"))
.endpoint("https:
.buildAsyncClient();
File analyzeFile = new File("../formrecognizer/azure-ai-formrecognizer/src/samples/java/sample-forms/"
+ "f... | public static void main(String[] args) throws IOException {
FormRecognizerAsyncClient client = new FormRecognizerClientBuilder()
.credential(new AzureKeyCredential("{key}"))
.endpoint("https:
.buildAsyncClient();
File analyzeFile = new File("../formrecognizer/azure-ai-formrecognizer/src/samples/java/sample-forms/"
+ "f... | class AdvancedDiffLabeledUnlabeledDataAsync {
/**
* Main method to invoke this demo.
*
* @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 AdvancedDiffLabeledUnlabeledDataAsync {
/**
* Main method to invoke this demo.
*
* @param args Unused arguments to the program.
*
* @throws IOException Exception thrown when there is an error in reading all the bytes from the File.
*/
} | |
Could be the diff mode, https://github.com/Azure/azure-sdk-for-java/blob/4364c78509af8849ca38fed9c030d9608ad5e13b/sdk/formrecognizer/azure-ai-formrecognizer/src/samples/java/com/azure/ai/formrecognizer/AdvancedDiffLabeledUnlabeledDataAsync.java#L94 | public static void main(String[] args) throws IOException {
FormRecognizerAsyncClient client = new FormRecognizerClientBuilder()
.credential(new AzureKeyCredential("{key}"))
.endpoint("https:
.buildAsyncClient();
File analyzeFile = new File("../formrecognizer/azure-ai-formrecognizer/src/samples/java/sample-forms/"
+ "f... | public static void main(String[] args) throws IOException {
FormRecognizerAsyncClient client = new FormRecognizerClientBuilder()
.credential(new AzureKeyCredential("{key}"))
.endpoint("https:
.buildAsyncClient();
File analyzeFile = new File("../formrecognizer/azure-ai-formrecognizer/src/samples/java/sample-forms/"
+ "f... | class AdvancedDiffLabeledUnlabeledDataAsync {
/**
* Main method to invoke this demo.
*
* @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 AdvancedDiffLabeledUnlabeledDataAsync {
/**
* Main method to invoke this demo.
*
* @param args Unused arguments to the program.
*
* @throws IOException Exception thrown when there is an error in reading all the bytes from the File.
*/
} | |
Weird! Okay ignore me :) | public static void main(String[] args) throws IOException {
FormRecognizerAsyncClient client = new FormRecognizerClientBuilder()
.credential(new AzureKeyCredential("{key}"))
.endpoint("https:
.buildAsyncClient();
File analyzeFile = new File("../formrecognizer/azure-ai-formrecognizer/src/samples/java/sample-forms/"
+ "f... | public static void main(String[] args) throws IOException {
FormRecognizerAsyncClient client = new FormRecognizerClientBuilder()
.credential(new AzureKeyCredential("{key}"))
.endpoint("https:
.buildAsyncClient();
File analyzeFile = new File("../formrecognizer/azure-ai-formrecognizer/src/samples/java/sample-forms/"
+ "f... | class AdvancedDiffLabeledUnlabeledDataAsync {
/**
* Main method to invoke this demo.
*
* @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 AdvancedDiffLabeledUnlabeledDataAsync {
/**
* Main method to invoke this demo.
*
* @param args Unused arguments to the program.
*
* @throws IOException Exception thrown when there is an error in reading all the bytes from the File.
*/
} | |
remove? | public static void main(String[] args) throws IOException {
FormRecognizerAsyncClient client = new FormRecognizerClientBuilder()
.credential(new AzureKeyCredential("{key}"))
.endpoint("https:
.buildAsyncClient();
File analyzeFile = new File("../formrecognizer/azure-ai-formrecognizer/src/samples/java/sample-forms/"
+ "f... | public static void main(String[] args) throws IOException {
FormRecognizerAsyncClient client = new FormRecognizerClientBuilder()
.credential(new AzureKeyCredential("{key}"))
.endpoint("https:
.buildAsyncClient();
File analyzeFile = new File("../formrecognizer/azure-ai-formrecognizer/src/samples/java/sample-forms/"
+ "f... | class AdvancedDiffLabeledUnlabeledDataAsync {
/**
* Main method to invoke this demo.
*
* @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 AdvancedDiffLabeledUnlabeledDataAsync {
/**
* Main method to invoke this demo.
*
* @param args Unused arguments to the program.
*
* @throws IOException Exception thrown when there is an error in reading all the bytes from the File.
*/
} | |
Could you show the example of how to set request id? | private static void autoCompleteWithOneTermContext(SearchClient searchClient) {
AutocompleteOptions params = new AutocompleteOptions().setAutocompleteMode(
AutocompleteMode.ONE_TERM_WITH_CONTEXT);
PagedIterableBase<AutocompleteItem, AutocompletePagedResponse> results = searchClient.autocomplete("coffee m",
"sg", params... | PagedIterableBase<AutocompleteItem, AutocompletePagedResponse> results = searchClient.autocomplete("coffee m", | private static void autoCompleteWithOneTermContext(SearchClient searchClient) {
AutocompleteOptions params = new AutocompleteOptions().setAutocompleteMode(
AutocompleteMode.ONE_TERM_WITH_CONTEXT);
PagedIterableBase<AutocompleteItem, AutocompletePagedResponse> results = searchClient.autocomplete("coffee m",
"sg", params... | class AutoCompleteExample {
/**
* From the Azure portal, get your Azure Cognitive Search service URL and API key,
* and set the values of these environment variables:
*/
private static final String ENDPOINT = Configuration.getGlobalConfiguration().get("AZURE_COGNITIVE_SEARCH_ENDPOINT");
private static final String API_... | class AutoCompleteExample {
/**
* From the Azure portal, get your Azure Cognitive Search service URL and API key,
* and set the values of these environment variables:
*/
private static final String ENDPOINT = Configuration.getGlobalConfiguration().get("AZURE_COGNITIVE_SEARCH_ENDPOINT");
private static final String API_... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.