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
This would be more readable with a `switch` statement
private void initializeCryptoClients() { if (localKeyCryptographyClient != null) { return; } if (key.get().getKeyType().equals(RSA) || key.get().getKeyType().equals(RSA_HSM)) { localKeyCryptographyClient = new RsaKeyCryptographyClient(key.get(), cryptographyServiceClient); } else if (key.get().getKeyType().equals(EC) |...
"The Json Web Key Type: %s is not supported.", key.get().getKeyType().toString())));
private void initializeCryptoClients() { if (localKeyCryptographyClient != null) { return; } if (key.getKeyType().equals(RSA) || key.getKeyType().equals(RSA_HSM)) { localKeyCryptographyClient = new RsaKeyCryptographyClient(key, cryptographyServiceClient); } else if (key.getKeyType().equals(EC) || key.getKeyType().equal...
class CryptographyAsyncClient { static final String KEY_VAULT_SCOPE = "https: static final String SECRETS_COLLECTION = "secrets"; AtomicReference<JsonWebKey> key; private final CryptographyService service; private CryptographyServiceClient cryptographyServiceClient; private LocalKeyCryptographyClient localKeyCryptograp...
class CryptographyAsyncClient { static final String KEY_VAULT_SCOPE = "https: static final String SECRETS_COLLECTION = "secrets"; JsonWebKey key; private final CryptographyService service; private CryptographyServiceClient cryptographyServiceClient; private LocalKeyCryptographyClient localKeyCryptographyClient; private...
yup, thanks for the catch. Updated.
Mono<UnwrapResult> unwrapKey(KeyWrapAlgorithm algorithm, byte[] encryptedKey, Context context) { Objects.requireNonNull(algorithm, "Key Wrap algorithm cannot be null."); Objects.requireNonNull(encryptedKey, "Encrypted key content to be unwrapped cannot be null."); return ensureValidKeyAvailable().flatMap(available -> {...
if (!checkKeyPermissions(this.key.get().getKeyOps(), KeyOperation.WRAP_KEY)) {
Mono<UnwrapResult> unwrapKey(KeyWrapAlgorithm algorithm, byte[] encryptedKey, Context context) { Objects.requireNonNull(algorithm, "Key Wrap algorithm cannot be null."); Objects.requireNonNull(encryptedKey, "Encrypted key content to be unwrapped cannot be null."); return ensureValidKeyAvailable().flatMap(available -> {...
class CryptographyAsyncClient { static final String KEY_VAULT_SCOPE = "https: static final String SECRETS_COLLECTION = "secrets"; AtomicReference<JsonWebKey> key; private final CryptographyService service; private CryptographyServiceClient cryptographyServiceClient; private LocalKeyCryptographyClient localKeyCryptograp...
class CryptographyAsyncClient { static final String KEY_VAULT_SCOPE = "https: static final String SECRETS_COLLECTION = "secrets"; JsonWebKey key; private final CryptographyService service; private CryptographyServiceClient cryptographyServiceClient; private LocalKeyCryptographyClient localKeyCryptographyClient; private...
Updated.
private Mono<Boolean> ensureValidKeyAvailable() { boolean keyAvailable = !(this.key == null && keyCollection != null); if (!keyAvailable) { if (keyCollection.equals(SECRETS_COLLECTION)) { return getSecretKey().flatMap(jwk -> { this.key = new AtomicReference<>(jwk); initializeCryptoClients(); return Mono.just(this.key.g...
boolean keyAvailable = !(this.key == null && keyCollection != null);
private Mono<Boolean> ensureValidKeyAvailable() { boolean keyNotAvailable = (this.key == null && keyCollection != null); if (keyNotAvailable) { if (keyCollection.equals(SECRETS_COLLECTION)) { return getSecretKey().map(jwk -> { this.key = (jwk); initializeCryptoClients(); return this.key.isValid(); }); } else { return g...
class CryptographyAsyncClient { static final String KEY_VAULT_SCOPE = "https: static final String SECRETS_COLLECTION = "secrets"; AtomicReference<JsonWebKey> key; private final CryptographyService service; private CryptographyServiceClient cryptographyServiceClient; private LocalKeyCryptographyClient localKeyCryptograp...
class CryptographyAsyncClient { static final String KEY_VAULT_SCOPE = "https: static final String SECRETS_COLLECTION = "secrets"; JsonWebKey key; private final CryptographyService service; private CryptographyServiceClient cryptographyServiceClient; private LocalKeyCryptographyClient localKeyCryptographyClient; private...
Expandable String enum, cannot do that, as discussed.
private void initializeCryptoClients() { if (localKeyCryptographyClient != null) { return; } if (key.get().getKeyType().equals(RSA) || key.get().getKeyType().equals(RSA_HSM)) { localKeyCryptographyClient = new RsaKeyCryptographyClient(key.get(), cryptographyServiceClient); } else if (key.get().getKeyType().equals(EC) |...
"The Json Web Key Type: %s is not supported.", key.get().getKeyType().toString())));
private void initializeCryptoClients() { if (localKeyCryptographyClient != null) { return; } if (key.getKeyType().equals(RSA) || key.getKeyType().equals(RSA_HSM)) { localKeyCryptographyClient = new RsaKeyCryptographyClient(key, cryptographyServiceClient); } else if (key.getKeyType().equals(EC) || key.getKeyType().equal...
class CryptographyAsyncClient { static final String KEY_VAULT_SCOPE = "https: static final String SECRETS_COLLECTION = "secrets"; AtomicReference<JsonWebKey> key; private final CryptographyService service; private CryptographyServiceClient cryptographyServiceClient; private LocalKeyCryptographyClient localKeyCryptograp...
class CryptographyAsyncClient { static final String KEY_VAULT_SCOPE = "https: static final String SECRETS_COLLECTION = "secrets"; JsonWebKey key; private final CryptographyService service; private CryptographyServiceClient cryptographyServiceClient; private LocalKeyCryptographyClient localKeyCryptographyClient; private...
Would be great to have tests that validate all the properties that are in CBS channel.
public Mono<OffsetDateTime> authorize(String tokenAudience, String scopes) { return cbsChannelMono.flatMap(channel -> credential.getToken(new TokenRequestContext().addScopes(scopes)) .flatMap(accessToken -> { final Message request = Proton.message(); final Map<String, Object> properties = new HashMap<>(); properties.pu...
properties.put(PUT_TOKEN_EXPIRY, Date.from(accessToken.getExpiresAt().toInstant()));
public Mono<OffsetDateTime> authorize(String tokenAudience, String scopes) { return cbsChannelMono.flatMap(channel -> credential.getToken(new TokenRequestContext().addScopes(scopes)) .flatMap(accessToken -> { final Message request = Proton.message(); final Map<String, Object> properties = new HashMap<>(); properties.pu...
class ClaimsBasedSecurityChannel implements ClaimsBasedSecurityNode { static final String PUT_TOKEN_TYPE = "type"; static final String PUT_TOKEN_AUDIENCE = "name"; static final String PUT_TOKEN_EXPIRY = "expiration"; private static final String PUT_TOKEN_OPERATION = "operation"; private static final String PUT_TOKEN_OP...
class ClaimsBasedSecurityChannel implements ClaimsBasedSecurityNode { static final String PUT_TOKEN_TYPE = "type"; static final String PUT_TOKEN_AUDIENCE = "name"; static final String PUT_TOKEN_EXPIRY = "expiration"; private static final String PUT_TOKEN_OPERATION = "operation"; private static final String PUT_TOKEN_OP...
I'll add one.
public Mono<OffsetDateTime> authorize(String tokenAudience, String scopes) { return cbsChannelMono.flatMap(channel -> credential.getToken(new TokenRequestContext().addScopes(scopes)) .flatMap(accessToken -> { final Message request = Proton.message(); final Map<String, Object> properties = new HashMap<>(); properties.pu...
properties.put(PUT_TOKEN_EXPIRY, Date.from(accessToken.getExpiresAt().toInstant()));
public Mono<OffsetDateTime> authorize(String tokenAudience, String scopes) { return cbsChannelMono.flatMap(channel -> credential.getToken(new TokenRequestContext().addScopes(scopes)) .flatMap(accessToken -> { final Message request = Proton.message(); final Map<String, Object> properties = new HashMap<>(); properties.pu...
class ClaimsBasedSecurityChannel implements ClaimsBasedSecurityNode { static final String PUT_TOKEN_TYPE = "type"; static final String PUT_TOKEN_AUDIENCE = "name"; static final String PUT_TOKEN_EXPIRY = "expiration"; private static final String PUT_TOKEN_OPERATION = "operation"; private static final String PUT_TOKEN_OP...
class ClaimsBasedSecurityChannel implements ClaimsBasedSecurityNode { static final String PUT_TOKEN_TYPE = "type"; static final String PUT_TOKEN_AUDIENCE = "name"; static final String PUT_TOKEN_EXPIRY = "expiration"; private static final String PUT_TOKEN_OPERATION = "operation"; private static final String PUT_TOKEN_OP...
`configuredLogLevel` is only ever set here in the constructor. I wonder if it is worth doing a micro-optimisation here to determine which log levels are valid and pre-compute the boolean conditions here, to simplify the `isTraceEnabled`, etc methods?
public DefaultLogger(String className) { String classPath; try { classPath = Class.forName(className).getCanonicalName(); } catch (ClassNotFoundException e) { classPath = className; } this.classPath = classPath; this.configuredLogLevel = LogLevel.fromString(Configuration.getGlobalConfiguration().get(Configuration.PROPE...
.getLogLevel();
public DefaultLogger(String className) { String classPath; try { classPath = Class.forName(className).getCanonicalName(); } catch (ClassNotFoundException e) { classPath = className; } this.classPath = classPath; int configuredLogLevel = LogLevel.fromString(Configuration.getGlobalConfiguration().get(Configuration.PROPER...
class name passes in. */
class name passes in. */
Yeah, I had initially done it that way to have booleans for each of the log levels but the performance improvements were not noticeable by doing that way vs the current approach. Moreover, `is*Enabled` methods in DefaultLogger are much faster than their logback counterparts (557664530 ops/sec vs 501866764 ops/sec). S...
public DefaultLogger(String className) { String classPath; try { classPath = Class.forName(className).getCanonicalName(); } catch (ClassNotFoundException e) { classPath = className; } this.classPath = classPath; this.configuredLogLevel = LogLevel.fromString(Configuration.getGlobalConfiguration().get(Configuration.PROPE...
.getLogLevel();
public DefaultLogger(String className) { String classPath; try { classPath = Class.forName(className).getCanonicalName(); } catch (ClassNotFoundException e) { classPath = className; } this.classPath = classPath; int configuredLogLevel = LogLevel.fromString(Configuration.getGlobalConfiguration().get(Configuration.PROPER...
class name passes in. */
class name passes in. */
does it mean we'll send one span for the first try only? It should be one span per Send call. If there is more than one try - it should wrap all of them: - duration should be duration of send() call - result is the result of all tries (i.e. eventually sent or failed)
public Mono<Void> send(EventDataBatch batch) { if (batch == null) { return monoError(logger, new NullPointerException("'batch' cannot be null.")); } else if (batch.getEvents().isEmpty()) { logger.warning(Messages.CANNOT_SEND_EVENT_BATCH_EMPTY); return Mono.empty(); } if (!CoreUtils.isNullOrEmpty(batch.getPartitionId())...
if (isTracingEnabled && !parentContext.get().getData(HOST_NAME_KEY).isPresent()) {
public Mono<Void> send(EventDataBatch batch) { if (batch == null) { return monoError(logger, new NullPointerException("'batch' cannot be null.")); } else if (batch.getEvents().isEmpty()) { logger.warning(Messages.CANNOT_SEND_EVENT_BATCH_EMPTY); return Mono.empty(); } if (!CoreUtils.isNullOrEmpty(batch.getPartitionId())...
class EventHubProducerAsyncClient implements Closeable { private static final int MAX_PARTITION_KEY_LENGTH = 128; private static final String SENDER_ENTITY_PATH_FORMAT = "%s/Partitions/%s"; private static final SendOptions DEFAULT_SEND_OPTIONS = new SendOptions(); private static final CreateBatchOptions DEFAULT_BATCH_O...
class EventHubProducerAsyncClient implements Closeable { private static final int MAX_PARTITION_KEY_LENGTH = 128; private static final String SENDER_ENTITY_PATH_FORMAT = "%s/Partitions/%s"; private static final SendOptions DEFAULT_SEND_OPTIONS = new SendOptions(); private static final CreateBatchOptions DEFAULT_BATCH_O...
>does it mean we'll send one span for the first try only? yes, it will only start the first send span. > it should wrap all of them does this mean we want to add links between all the send spans but start only a single span?
public Mono<Void> send(EventDataBatch batch) { if (batch == null) { return monoError(logger, new NullPointerException("'batch' cannot be null.")); } else if (batch.getEvents().isEmpty()) { logger.warning(Messages.CANNOT_SEND_EVENT_BATCH_EMPTY); return Mono.empty(); } if (!CoreUtils.isNullOrEmpty(batch.getPartitionId())...
if (isTracingEnabled && !parentContext.get().getData(HOST_NAME_KEY).isPresent()) {
public Mono<Void> send(EventDataBatch batch) { if (batch == null) { return monoError(logger, new NullPointerException("'batch' cannot be null.")); } else if (batch.getEvents().isEmpty()) { logger.warning(Messages.CANNOT_SEND_EVENT_BATCH_EMPTY); return Mono.empty(); } if (!CoreUtils.isNullOrEmpty(batch.getPartitionId())...
class EventHubProducerAsyncClient implements Closeable { private static final int MAX_PARTITION_KEY_LENGTH = 128; private static final String SENDER_ENTITY_PATH_FORMAT = "%s/Partitions/%s"; private static final SendOptions DEFAULT_SEND_OPTIONS = new SendOptions(); private static final CreateBatchOptions DEFAULT_BATCH_O...
class EventHubProducerAsyncClient implements Closeable { private static final int MAX_PARTITION_KEY_LENGTH = 128; private static final String SENDER_ENTITY_PATH_FORMAT = "%s/Partitions/%s"; private static final SendOptions DEFAULT_SEND_OPTIONS = new SendOptions(); private static final CreateBatchOptions DEFAULT_BATCH_O...
We still create span per message and link all of these spans to the single 'send' span
public Mono<Void> send(EventDataBatch batch) { if (batch == null) { return monoError(logger, new NullPointerException("'batch' cannot be null.")); } else if (batch.getEvents().isEmpty()) { logger.warning(Messages.CANNOT_SEND_EVENT_BATCH_EMPTY); return Mono.empty(); } if (!CoreUtils.isNullOrEmpty(batch.getPartitionId())...
if (isTracingEnabled && !parentContext.get().getData(HOST_NAME_KEY).isPresent()) {
public Mono<Void> send(EventDataBatch batch) { if (batch == null) { return monoError(logger, new NullPointerException("'batch' cannot be null.")); } else if (batch.getEvents().isEmpty()) { logger.warning(Messages.CANNOT_SEND_EVENT_BATCH_EMPTY); return Mono.empty(); } if (!CoreUtils.isNullOrEmpty(batch.getPartitionId())...
class EventHubProducerAsyncClient implements Closeable { private static final int MAX_PARTITION_KEY_LENGTH = 128; private static final String SENDER_ENTITY_PATH_FORMAT = "%s/Partitions/%s"; private static final SendOptions DEFAULT_SEND_OPTIONS = new SendOptions(); private static final CreateBatchOptions DEFAULT_BATCH_O...
class EventHubProducerAsyncClient implements Closeable { private static final int MAX_PARTITION_KEY_LENGTH = 128; private static final String SENDER_ENTITY_PATH_FORMAT = "%s/Partitions/%s"; private static final SendOptions DEFAULT_SEND_OPTIONS = new SendOptions(); private static final CreateBatchOptions DEFAULT_BATCH_O...
is it called on each try? will it end the span after first retry?
public Mono<Void> send(EventDataBatch batch) { if (batch == null) { return monoError(logger, new NullPointerException("'batch' cannot be null.")); } else if (batch.getEvents().isEmpty()) { logger.warning(Messages.CANNOT_SEND_EVENT_BATCH_EMPTY); return Mono.empty(); } if (!CoreUtils.isNullOrEmpty(batch.getPartitionId())...
.doOnEach(signal -> {
public Mono<Void> send(EventDataBatch batch) { if (batch == null) { return monoError(logger, new NullPointerException("'batch' cannot be null.")); } else if (batch.getEvents().isEmpty()) { logger.warning(Messages.CANNOT_SEND_EVENT_BATCH_EMPTY); return Mono.empty(); } if (!CoreUtils.isNullOrEmpty(batch.getPartitionId())...
class EventHubProducerAsyncClient implements Closeable { private static final int MAX_PARTITION_KEY_LENGTH = 128; private static final String SENDER_ENTITY_PATH_FORMAT = "%s/Partitions/%s"; private static final SendOptions DEFAULT_SEND_OPTIONS = new SendOptions(); private static final CreateBatchOptions DEFAULT_BATCH_O...
class EventHubProducerAsyncClient implements Closeable { private static final int MAX_PARTITION_KEY_LENGTH = 128; private static final String SENDER_ENTITY_PATH_FORMAT = "%s/Partitions/%s"; private static final SendOptions DEFAULT_SEND_OPTIONS = new SendOptions(); private static final CreateBatchOptions DEFAULT_BATCH_O...
does it mean we no longer set error if all retries has failed?
private Mono<Void> sendInternal(Flux<EventData> events, SendOptions options) { final String partitionKey = options.getPartitionKey(); final String partitionId = options.getPartitionId(); if (!CoreUtils.isNullOrEmpty(partitionKey) && !CoreUtils.isNullOrEmpty(partitionId)) { return monoError(logger, new IllegalArgumentEx...
final String partitionKey = options.getPartitionKey();
private Mono<Void> sendInternal(Flux<EventData> events, SendOptions options) { final String partitionKey = options.getPartitionKey(); final String partitionId = options.getPartitionId(); if (!CoreUtils.isNullOrEmpty(partitionKey) && !CoreUtils.isNullOrEmpty(partitionId)) { return monoError(logger, new IllegalArgumentEx...
class EventHubProducerAsyncClient implements Closeable { private static final int MAX_PARTITION_KEY_LENGTH = 128; private static final String SENDER_ENTITY_PATH_FORMAT = "%s/Partitions/%s"; private static final SendOptions DEFAULT_SEND_OPTIONS = new SendOptions(); private static final CreateBatchOptions DEFAULT_BATCH_O...
class EventHubProducerAsyncClient implements Closeable { private static final int MAX_PARTITION_KEY_LENGTH = 128; private static final String SENDER_ENTITY_PATH_FORMAT = "%s/Partitions/%s"; private static final SendOptions DEFAULT_SEND_OPTIONS = new SendOptions(); private static final CreateBatchOptions DEFAULT_BATCH_O...
No, so with the updated code, it nows does `doOnEach` after the `withRetry` has completed. So, once withRetry completes either with `error` or `success` , it will send a signal and the `endSpan` uses the signal type to set error or success.
public Mono<Void> send(EventDataBatch batch) { if (batch == null) { return monoError(logger, new NullPointerException("'batch' cannot be null.")); } else if (batch.getEvents().isEmpty()) { logger.warning(Messages.CANNOT_SEND_EVENT_BATCH_EMPTY); return Mono.empty(); } if (!CoreUtils.isNullOrEmpty(batch.getPartitionId())...
.doOnEach(signal -> {
public Mono<Void> send(EventDataBatch batch) { if (batch == null) { return monoError(logger, new NullPointerException("'batch' cannot be null.")); } else if (batch.getEvents().isEmpty()) { logger.warning(Messages.CANNOT_SEND_EVENT_BATCH_EMPTY); return Mono.empty(); } if (!CoreUtils.isNullOrEmpty(batch.getPartitionId())...
class EventHubProducerAsyncClient implements Closeable { private static final int MAX_PARTITION_KEY_LENGTH = 128; private static final String SENDER_ENTITY_PATH_FORMAT = "%s/Partitions/%s"; private static final SendOptions DEFAULT_SEND_OPTIONS = new SendOptions(); private static final CreateBatchOptions DEFAULT_BATCH_O...
class EventHubProducerAsyncClient implements Closeable { private static final int MAX_PARTITION_KEY_LENGTH = 128; private static final String SENDER_ENTITY_PATH_FORMAT = "%s/Partitions/%s"; private static final SendOptions DEFAULT_SEND_OPTIONS = new SendOptions(); private static final CreateBatchOptions DEFAULT_BATCH_O...
same as [above](https://github.com/Azure/azure-sdk-for-java/pull/7704/files#r376009331)
private Mono<Void> sendInternal(Flux<EventData> events, SendOptions options) { final String partitionKey = options.getPartitionKey(); final String partitionId = options.getPartitionId(); if (!CoreUtils.isNullOrEmpty(partitionKey) && !CoreUtils.isNullOrEmpty(partitionId)) { return monoError(logger, new IllegalArgumentEx...
final String partitionKey = options.getPartitionKey();
private Mono<Void> sendInternal(Flux<EventData> events, SendOptions options) { final String partitionKey = options.getPartitionKey(); final String partitionId = options.getPartitionId(); if (!CoreUtils.isNullOrEmpty(partitionKey) && !CoreUtils.isNullOrEmpty(partitionId)) { return monoError(logger, new IllegalArgumentEx...
class EventHubProducerAsyncClient implements Closeable { private static final int MAX_PARTITION_KEY_LENGTH = 128; private static final String SENDER_ENTITY_PATH_FORMAT = "%s/Partitions/%s"; private static final SendOptions DEFAULT_SEND_OPTIONS = new SendOptions(); private static final CreateBatchOptions DEFAULT_BATCH_O...
class EventHubProducerAsyncClient implements Closeable { private static final int MAX_PARTITION_KEY_LENGTH = 128; private static final String SENDER_ENTITY_PATH_FORMAT = "%s/Partitions/%s"; private static final SendOptions DEFAULT_SEND_OPTIONS = new SendOptions(); private static final CreateBatchOptions DEFAULT_BATCH_O...
Can you add a comment that this is to accommodate the root?
public ShareFileAsyncClient getFileClient(String fileName) { String filePath = directoryPath + "/" + fileName; if (directoryPath.isEmpty()) { filePath = fileName; } return new ShareFileAsyncClient(azureFileStorageClient, shareName, filePath, null, accountName, serviceVersion); }
filePath = fileName;
public ShareFileAsyncClient getFileClient(String fileName) { String filePath = directoryPath + "/" + fileName; if (directoryPath.isEmpty()) { filePath = fileName; } return new ShareFileAsyncClient(azureFileStorageClient, shareName, filePath, null, accountName, serviceVersion); }
class ShareDirectoryAsyncClient { private final ClientLogger logger = new ClientLogger(ShareDirectoryAsyncClient.class); private final AzureFileStorageImpl azureFileStorageClient; private final String shareName; private final String directoryPath; private final String snapshot; private final String accountName; private...
class ShareDirectoryAsyncClient { private final ClientLogger logger = new ClientLogger(ShareDirectoryAsyncClient.class); private final AzureFileStorageImpl azureFileStorageClient; private final String shareName; private final String directoryPath; private final String snapshot; private final String accountName; private...
done
public ShareFileAsyncClient getFileClient(String fileName) { String filePath = directoryPath + "/" + fileName; if (directoryPath.isEmpty()) { filePath = fileName; } return new ShareFileAsyncClient(azureFileStorageClient, shareName, filePath, null, accountName, serviceVersion); }
filePath = fileName;
public ShareFileAsyncClient getFileClient(String fileName) { String filePath = directoryPath + "/" + fileName; if (directoryPath.isEmpty()) { filePath = fileName; } return new ShareFileAsyncClient(azureFileStorageClient, shareName, filePath, null, accountName, serviceVersion); }
class ShareDirectoryAsyncClient { private final ClientLogger logger = new ClientLogger(ShareDirectoryAsyncClient.class); private final AzureFileStorageImpl azureFileStorageClient; private final String shareName; private final String directoryPath; private final String snapshot; private final String accountName; private...
class ShareDirectoryAsyncClient { private final ClientLogger logger = new ClientLogger(ShareDirectoryAsyncClient.class); private final AzureFileStorageImpl azureFileStorageClient; private final String shareName; private final String directoryPath; private final String snapshot; private final String accountName; private...
Should log these and others
public Path getName(int i) { if (i < 0 || i >= this.getNameCount()) { throw new IllegalArgumentException(); } return this.parentFileSystem.getPath(this.splitToElements(this.withoutRoot())[i]); }
throw new IllegalArgumentException();
public Path getName(int i) { if (i < 0 || i >= this.getNameCount()) { throw Utility.logError(logger, new IllegalArgumentException(String.format("Index %d is out of bounds", i))); } return this.parentFileSystem.getPath(this.splitToElements(this.withoutRoot())[i]); }
class AzurePath implements Path { private final ClientLogger logger = new ClientLogger(AzurePath.class); private static final String ROOT_DIR_SUFFIX = ":"; private final AzureFileSystem parentFileSystem; private final String pathString; AzurePath(AzureFileSystem parentFileSystem, String s, String... strings) { if (stri...
class AzurePath implements Path { private final ClientLogger logger = new ClientLogger(AzurePath.class); private static final String ROOT_DIR_SUFFIX = ":"; private final AzureFileSystem parentFileSystem; private final String pathString; AzurePath(AzureFileSystem parentFileSystem, String first, String... more) { this.pa...
Should use splitToElements
public Path getRoot() { String firstElement = pathString.split(parentFileSystem.getSeparator())[0]; if (firstElement.endsWith(ROOT_DIR_SUFFIX)) { return this.parentFileSystem.getPath(firstElement); } return null; }
String firstElement = pathString.split(parentFileSystem.getSeparator())[0];
public Path getRoot() { String firstElement = this.splitToElements()[0]; if (firstElement.endsWith(ROOT_DIR_SUFFIX)) { return this.parentFileSystem.getPath(firstElement); } return null; }
class AzurePath implements Path { private final ClientLogger logger = new ClientLogger(AzurePath.class); private static final String ROOT_DIR_SUFFIX = ":"; private final AzureFileSystem parentFileSystem; private final String pathString; AzurePath(AzureFileSystem parentFileSystem, String s, String... strings) { if (stri...
class AzurePath implements Path { private final ClientLogger logger = new ClientLogger(AzurePath.class); private static final String ROOT_DIR_SUFFIX = ":"; private final AzureFileSystem parentFileSystem; private final String pathString; AzurePath(AzureFileSystem parentFileSystem, String first, String... more) { this.pa...
Just use .equals. It's clear and safer and evidently equivalent.
public boolean startsWith(Path path) { /* There can only be one instance of a file system with a given id, so comparing object identity is equivalent to checking ids here. */ if (path.getFileSystem() != this.parentFileSystem) { return false; } String[] thisPathElements = this.splitToElements(); String[] otherPathElemen...
if (path.getFileSystem() != this.parentFileSystem) {
public boolean startsWith(Path path) { if (!path.getFileSystem().equals(this.parentFileSystem)) { return false; } String[] thisPathElements = this.splitToElements(); String[] otherPathElements = ((AzurePath) path).splitToElements(); if (otherPathElements.length > thisPathElements.length) { return false; } for (int i = ...
class AzurePath implements Path { private final ClientLogger logger = new ClientLogger(AzurePath.class); private static final String ROOT_DIR_SUFFIX = ":"; private final AzureFileSystem parentFileSystem; private final String pathString; AzurePath(AzureFileSystem parentFileSystem, String s, String... strings) { if (stri...
class AzurePath implements Path { private final ClientLogger logger = new ClientLogger(AzurePath.class); private static final String ROOT_DIR_SUFFIX = ":"; private final AzureFileSystem parentFileSystem; private final String pathString; AzurePath(AzureFileSystem parentFileSystem, String first, String... more) { this.pa...
What about a path with ".."? In other words, should we normalize first?
public boolean startsWith(Path path) { /* There can only be one instance of a file system with a given id, so comparing object identity is equivalent to checking ids here. */ if (path.getFileSystem() != this.parentFileSystem) { return false; } String[] thisPathElements = this.splitToElements(); String[] otherPathElemen...
if (!otherPathElements[i].equals(thisPathElements[i])) {
public boolean startsWith(Path path) { if (!path.getFileSystem().equals(this.parentFileSystem)) { return false; } String[] thisPathElements = this.splitToElements(); String[] otherPathElements = ((AzurePath) path).splitToElements(); if (otherPathElements.length > thisPathElements.length) { return false; } for (int i = ...
class AzurePath implements Path { private final ClientLogger logger = new ClientLogger(AzurePath.class); private static final String ROOT_DIR_SUFFIX = ":"; private final AzureFileSystem parentFileSystem; private final String pathString; AzurePath(AzureFileSystem parentFileSystem, String s, String... strings) { if (stri...
class AzurePath implements Path { private final ClientLogger logger = new ClientLogger(AzurePath.class); private static final String ROOT_DIR_SUFFIX = ":"; private final AzureFileSystem parentFileSystem; private final String pathString; AzurePath(AzureFileSystem parentFileSystem, String first, String... more) { this.pa...
Can remove the todo as the root validity check is gone.
public Path normalize() { Deque<String> stack = new ArrayDeque<>(); String[] pathElements = this.splitToElements(); Path root = this.getRoot(); String rootStr = root == null ? null : root.toString(); for (String element : pathElements) { if (element.equals(".")) { continue; } else if (element.equals("..")) { if (rootSt...
Path root = this.getRoot();
public Path normalize() { Deque<String> stack = new ArrayDeque<>(); String[] pathElements = this.splitToElements(); Path root = this.getRoot(); String rootStr = root == null ? null : root.toString(); for (String element : pathElements) { if (element.equals(".")) { continue; } else if (element.equals("..")) { if (rootSt...
class AzurePath implements Path { private final ClientLogger logger = new ClientLogger(AzurePath.class); private static final String ROOT_DIR_SUFFIX = ":"; private final AzureFileSystem parentFileSystem; private final String pathString; AzurePath(AzureFileSystem parentFileSystem, String s, String... strings) { if (stri...
class AzurePath implements Path { private final ClientLogger logger = new ClientLogger(AzurePath.class); private static final String ROOT_DIR_SUFFIX = ":"; private final AzureFileSystem parentFileSystem; private final String pathString; AzurePath(AzureFileSystem parentFileSystem, String first, String... more) { this.pa...
Add a comment here to explain that this is the special case where we split after removing the root of a path that is just the root.
private String[] splitToElements(String str) { String[] arr = str.split(this.parentFileSystem.getSeparator()); if (arr.length == 1 && arr[0].isEmpty()) { return new String[0]; } return arr; }
if (arr.length == 1 && arr[0].isEmpty()) {
private String[] splitToElements(String str) { String[] arr = str.split(this.parentFileSystem.getSeparator()); /* This is a special case where we split after removing the root from a path that is just the root. Or otherwise have an empty path. */ if (arr.length == 1 && arr[0].isEmpty()) { return new String[0]; } return...
class AzurePath implements Path { private final ClientLogger logger = new ClientLogger(AzurePath.class); private static final String ROOT_DIR_SUFFIX = ":"; private final AzureFileSystem parentFileSystem; private final String pathString; AzurePath(AzureFileSystem parentFileSystem, String s, String... strings) { if (stri...
class AzurePath implements Path { private final ClientLogger logger = new ClientLogger(AzurePath.class); private static final String ROOT_DIR_SUFFIX = ":"; private final AzureFileSystem parentFileSystem; private final String pathString; AzurePath(AzureFileSystem parentFileSystem, String first, String... more) { this.pa...
I think it makes sense to normalize before comparing
public boolean startsWith(Path path) { /* There can only be one instance of a file system with a given id, so comparing object identity is equivalent to checking ids here. */ if (path.getFileSystem() != this.parentFileSystem) { return false; } String[] thisPathElements = this.splitToElements(); String[] otherPathElemen...
if (!otherPathElements[i].equals(thisPathElements[i])) {
public boolean startsWith(Path path) { if (!path.getFileSystem().equals(this.parentFileSystem)) { return false; } String[] thisPathElements = this.splitToElements(); String[] otherPathElements = ((AzurePath) path).splitToElements(); if (otherPathElements.length > thisPathElements.length) { return false; } for (int i = ...
class AzurePath implements Path { private final ClientLogger logger = new ClientLogger(AzurePath.class); private static final String ROOT_DIR_SUFFIX = ":"; private final AzureFileSystem parentFileSystem; private final String pathString; AzurePath(AzureFileSystem parentFileSystem, String s, String... strings) { if (stri...
class AzurePath implements Path { private final ClientLogger logger = new ClientLogger(AzurePath.class); private static final String ROOT_DIR_SUFFIX = ":"; private final AzureFileSystem parentFileSystem; private final String pathString; AzurePath(AzureFileSystem parentFileSystem, String first, String... more) { this.pa...
It looks like the default system (which I'm generally trying to follow) doesn't normalize and will return false for "foo/bar" starts with "foo/.", so I'll leave this as is.
public boolean startsWith(Path path) { /* There can only be one instance of a file system with a given id, so comparing object identity is equivalent to checking ids here. */ if (path.getFileSystem() != this.parentFileSystem) { return false; } String[] thisPathElements = this.splitToElements(); String[] otherPathElemen...
if (!otherPathElements[i].equals(thisPathElements[i])) {
public boolean startsWith(Path path) { if (!path.getFileSystem().equals(this.parentFileSystem)) { return false; } String[] thisPathElements = this.splitToElements(); String[] otherPathElements = ((AzurePath) path).splitToElements(); if (otherPathElements.length > thisPathElements.length) { return false; } for (int i = ...
class AzurePath implements Path { private final ClientLogger logger = new ClientLogger(AzurePath.class); private static final String ROOT_DIR_SUFFIX = ":"; private final AzureFileSystem parentFileSystem; private final String pathString; AzurePath(AzureFileSystem parentFileSystem, String s, String... strings) { if (stri...
class AzurePath implements Path { private final ClientLogger logger = new ClientLogger(AzurePath.class); private static final String ROOT_DIR_SUFFIX = ":"; private final AzureFileSystem parentFileSystem; private final String pathString; AzurePath(AzureFileSystem parentFileSystem, String first, String... more) { this.pa...
Any reason to use a reactive stream here only to block it? Instead could a `Stream` be used? Another option, based on the logic here, we could have a local instance of the `String[]` and just access and return the last element in the list.
public Path getFileName() { if (this.withoutRoot().isEmpty()) { return null; } else { return this.parentFileSystem.getPath(Flux.fromArray(this.splitToElements()).last().block()); } }
return this.parentFileSystem.getPath(Flux.fromArray(this.splitToElements()).last().block());
public Path getFileName() { if (this.withoutRoot().isEmpty()) { return null; } else { List<String> elements = Arrays.asList(this.splitToElements()); return this.parentFileSystem.getPath(elements.get(elements.size() - 1)); } }
class AzurePath implements Path { private final ClientLogger logger = new ClientLogger(AzurePath.class); private static final String ROOT_DIR_SUFFIX = ":"; private final AzureFileSystem parentFileSystem; private final String pathString; AzurePath(AzureFileSystem parentFileSystem, String first, String... more) { if (mor...
class AzurePath implements Path { private final ClientLogger logger = new ClientLogger(AzurePath.class); private static final String ROOT_DIR_SUFFIX = ":"; private final AzureFileSystem parentFileSystem; private final String pathString; AzurePath(AzureFileSystem parentFileSystem, String first, String... more) { this.pa...
Given there is numerous calls to this method should the split pathString be stored as a field on the instance?
private String[] splitToElements() { return this.splitToElements(this.pathString); }
return this.splitToElements(this.pathString);
private String[] splitToElements() { return this.splitToElements(this.pathString); }
class AzurePath implements Path { private final ClientLogger logger = new ClientLogger(AzurePath.class); private static final String ROOT_DIR_SUFFIX = ":"; private final AzureFileSystem parentFileSystem; private final String pathString; AzurePath(AzureFileSystem parentFileSystem, String first, String... more) { if (mor...
class AzurePath implements Path { private final ClientLogger logger = new ClientLogger(AzurePath.class); private static final String ROOT_DIR_SUFFIX = ":"; private final AzureFileSystem parentFileSystem; private final String pathString; AzurePath(AzureFileSystem parentFileSystem, String first, String... more) { this.pa...
I was wondering that as I wrote it. The consequence is that these objects basically double their memory usage, right? Since we would then store the pathString as one object and then all of its components again separately. I didn't feel like I had enough knowledge of customer scenarios to know if they were cpu or memory...
private String[] splitToElements() { return this.splitToElements(this.pathString); }
return this.splitToElements(this.pathString);
private String[] splitToElements() { return this.splitToElements(this.pathString); }
class AzurePath implements Path { private final ClientLogger logger = new ClientLogger(AzurePath.class); private static final String ROOT_DIR_SUFFIX = ":"; private final AzureFileSystem parentFileSystem; private final String pathString; AzurePath(AzureFileSystem parentFileSystem, String first, String... more) { if (mor...
class AzurePath implements Path { private final ClientLogger logger = new ClientLogger(AzurePath.class); private static final String ROOT_DIR_SUFFIX = ":"; private final AzureFileSystem parentFileSystem; private final String pathString; AzurePath(AzureFileSystem parentFileSystem, String first, String... more) { this.pa...
I think I addressed the Stream concern above and the String[] concern below :)
public Path getFileName() { if (this.withoutRoot().isEmpty()) { return null; } else { return this.parentFileSystem.getPath(Flux.fromArray(this.splitToElements()).last().block()); } }
return this.parentFileSystem.getPath(Flux.fromArray(this.splitToElements()).last().block());
public Path getFileName() { if (this.withoutRoot().isEmpty()) { return null; } else { List<String> elements = Arrays.asList(this.splitToElements()); return this.parentFileSystem.getPath(elements.get(elements.size() - 1)); } }
class AzurePath implements Path { private final ClientLogger logger = new ClientLogger(AzurePath.class); private static final String ROOT_DIR_SUFFIX = ":"; private final AzureFileSystem parentFileSystem; private final String pathString; AzurePath(AzureFileSystem parentFileSystem, String first, String... more) { if (mor...
class AzurePath implements Path { private final ClientLogger logger = new ClientLogger(AzurePath.class); private static final String ROOT_DIR_SUFFIX = ":"; private final AzureFileSystem parentFileSystem; private final String pathString; AzurePath(AzureFileSystem parentFileSystem, String first, String... more) { this.pa...
That makes sense to me
private String[] splitToElements() { return this.splitToElements(this.pathString); }
return this.splitToElements(this.pathString);
private String[] splitToElements() { return this.splitToElements(this.pathString); }
class AzurePath implements Path { private final ClientLogger logger = new ClientLogger(AzurePath.class); private static final String ROOT_DIR_SUFFIX = ":"; private final AzureFileSystem parentFileSystem; private final String pathString; AzurePath(AzureFileSystem parentFileSystem, String first, String... more) { if (mor...
class AzurePath implements Path { private final ClientLogger logger = new ClientLogger(AzurePath.class); private static final String ROOT_DIR_SUFFIX = ":"; private final AzureFileSystem parentFileSystem; private final String pathString; AzurePath(AzureFileSystem parentFileSystem, String first, String... more) { this.pa...
```suggestion .map(ByteBuffer::wrap) ```
public BufferedHttpResponse(HttpResponse innerHttpResponse) { super(innerHttpResponse.getRequest()); this.innerHttpResponse = innerHttpResponse; this.cachedBody = FluxUtil.collectBytesInByteBufferStream(innerHttpResponse.getBody()) .map(bytes -> ByteBuffer.wrap(bytes)) .flux() .cache(); }
.map(bytes -> ByteBuffer.wrap(bytes))
public BufferedHttpResponse(HttpResponse innerHttpResponse) { super(innerHttpResponse.getRequest()); this.innerHttpResponse = innerHttpResponse; this.cachedBody = FluxUtil.collectBytesInByteBufferStream(innerHttpResponse.getBody()) .map(ByteBuffer::wrap) .flux() .cache(); }
class BufferedHttpResponse extends HttpResponse { private final HttpResponse innerHttpResponse; private final Flux<ByteBuffer> cachedBody; /** * Creates a buffered HTTP response. * * @param innerHttpResponse The HTTP response to buffer */ @Override public int getStatusCode() { return innerHttpResponse.getStatusCode(); ...
class BufferedHttpResponse extends HttpResponse { private final HttpResponse innerHttpResponse; private final Flux<ByteBuffer> cachedBody; /** * Creates a buffered HTTP response. * * @param innerHttpResponse The HTTP response to buffer */ @Override public int getStatusCode() { return innerHttpResponse.getStatusCode(); ...
```suggestion return cachedBody.next().map(ByteBuffer::array); ```
public Mono<byte[]> getBodyAsByteArray() { return cachedBody.next().map(byteBuffer -> byteBuffer.array()); }
return cachedBody.next().map(byteBuffer -> byteBuffer.array());
public Mono<byte[]> getBodyAsByteArray() { return cachedBody.next().map(ByteBuffer::array); }
class BufferedHttpResponse extends HttpResponse { private final HttpResponse innerHttpResponse; private final Flux<ByteBuffer> cachedBody; /** * Creates a buffered HTTP response. * * @param innerHttpResponse The HTTP response to buffer */ public BufferedHttpResponse(HttpResponse innerHttpResponse) { super(innerHttpResp...
class BufferedHttpResponse extends HttpResponse { private final HttpResponse innerHttpResponse; private final Flux<ByteBuffer> cachedBody; /** * Creates a buffered HTTP response. * * @param innerHttpResponse The HTTP response to buffer */ public BufferedHttpResponse(HttpResponse innerHttpResponse) { super(innerHttpResp...
Do we need to handle Flux still?
private static Type extractEntityTypeFromReturnType(HttpResponseDecodeData decodeData) { Type token = decodeData.getReturnType(); if (token != null) { if (TypeUtil.isTypeOrSubTypeOf(token, Mono.class)) { token = TypeUtil.getTypeArgument(token); } if (TypeUtil.isTypeOrSubTypeOf(token, Response.class)) { token = TypeUtil...
token = TypeUtil.getRestResponseBodyType(token);
private static Type extractEntityTypeFromReturnType(HttpResponseDecodeData decodeData) { Type token = decodeData.getReturnType(); if (token != null) { if (TypeUtil.isTypeOrSubTypeOf(token, Mono.class)) { token = TypeUtil.getTypeArgument(token); } if (TypeUtil.isTypeOrSubTypeOf(token, Response.class)) { token = TypeUtil...
class instead. wireResponseType = TypeUtil.createParameterizedType(ItemPage.class, resultType); } else { wireResponseType = wireType; }
class instead. wireResponseType = TypeUtil.createParameterizedType(ItemPage.class, resultType); } else { wireResponseType = wireType; }
Not in this path. We handle "Flux<ByteBuffer>" in different code path.
private static Type extractEntityTypeFromReturnType(HttpResponseDecodeData decodeData) { Type token = decodeData.getReturnType(); if (token != null) { if (TypeUtil.isTypeOrSubTypeOf(token, Mono.class)) { token = TypeUtil.getTypeArgument(token); } if (TypeUtil.isTypeOrSubTypeOf(token, Response.class)) { token = TypeUtil...
token = TypeUtil.getRestResponseBodyType(token);
private static Type extractEntityTypeFromReturnType(HttpResponseDecodeData decodeData) { Type token = decodeData.getReturnType(); if (token != null) { if (TypeUtil.isTypeOrSubTypeOf(token, Mono.class)) { token = TypeUtil.getTypeArgument(token); } if (TypeUtil.isTypeOrSubTypeOf(token, Response.class)) { token = TypeUtil...
class instead. wireResponseType = TypeUtil.createParameterizedType(ItemPage.class, resultType); } else { wireResponseType = wireType; }
class instead. wireResponseType = TypeUtil.createParameterizedType(ItemPage.class, resultType); } else { wireResponseType = wireType; }
Ah, perfect!
private static Type extractEntityTypeFromReturnType(HttpResponseDecodeData decodeData) { Type token = decodeData.getReturnType(); if (token != null) { if (TypeUtil.isTypeOrSubTypeOf(token, Mono.class)) { token = TypeUtil.getTypeArgument(token); } if (TypeUtil.isTypeOrSubTypeOf(token, Response.class)) { token = TypeUtil...
token = TypeUtil.getRestResponseBodyType(token);
private static Type extractEntityTypeFromReturnType(HttpResponseDecodeData decodeData) { Type token = decodeData.getReturnType(); if (token != null) { if (TypeUtil.isTypeOrSubTypeOf(token, Mono.class)) { token = TypeUtil.getTypeArgument(token); } if (TypeUtil.isTypeOrSubTypeOf(token, Response.class)) { token = TypeUtil...
class instead. wireResponseType = TypeUtil.createParameterizedType(ItemPage.class, resultType); } else { wireResponseType = wireType; }
class instead. wireResponseType = TypeUtil.createParameterizedType(ItemPage.class, resultType); } else { wireResponseType = wireType; }
We don't need this `.single()` anymore, right ? Here and every other method in this class.
static public Mono<Database> createDatabaseIfNotExists(AsyncDocumentClient client, String databaseName) { return client.readDatabase("/dbs/" + databaseName, null) .onErrorResume( e -> { if (e instanceof CosmosClientException) { CosmosClientException dce = (CosmosClientException) e; if (dce.getStatusCode() == 404) { Da...
).map(ResourceResponse::getResource).single();
static public Mono<Database> createDatabaseIfNotExists(AsyncDocumentClient client, String databaseName) { return client.readDatabase("/dbs/" + databaseName, null) .onErrorResume( e -> { if (e instanceof CosmosClientException) { CosmosClientException dce = (CosmosClientException) e; if (dce.getStatusCode() == 404) { Da...
class Helpers { static public String createDocumentCollectionUri(String databaseName, String collectionName) { return String.format("/dbs/%s/colls/%s", databaseName, collectionName); } static public String createDatabaseUri(String databaseName) { return String.format("/dbs/%s", databaseName); } static public Mono<Docum...
class Helpers { static public String createDocumentCollectionUri(String databaseName, String collectionName) { return String.format("/dbs/%s/colls/%s", databaseName, collectionName); } static public String createDatabaseUri(String databaseName) { return String.format("/dbs/%s", databaseName); } static public Mono<Docum...
Same here, unnecessary conversion to `.single()`
public void transformObservableToCompletableFuture() throws Exception { Mono<ResourceResponse<DocumentCollection>> createCollectionObservable = client .createCollection(getDatabaseLink(), collectionDefinition, null); CompletableFuture<ResourceResponse<DocumentCollection>> future = createCollectionObservable.single().to...
CompletableFuture<ResourceResponse<DocumentCollection>> future = createCollectionObservable.single().toFuture();
public void transformObservableToCompletableFuture() throws Exception { Mono<ResourceResponse<DocumentCollection>> createCollectionObservable = client .createCollection(getDatabaseLink(), collectionDefinition, null); CompletableFuture<ResourceResponse<DocumentCollection>> future = createCollectionObservable.single().to...
class CollectionCRUDAsyncAPITest extends DocumentClientTest { private final static int TIMEOUT = 120000; private Database createdDatabase; private AsyncDocumentClient client; private DocumentCollection collectionDefinition; @BeforeClass(groups = "samples", timeOut = TIMEOUT) public void before_CollectionCRUDAsyncAPITes...
class CollectionCRUDAsyncAPITest extends DocumentClientTest { private final static int TIMEOUT = 120000; private Database createdDatabase; private AsyncDocumentClient client; private DocumentCollection collectionDefinition; @BeforeClass(groups = "samples", timeOut = TIMEOUT) public void before_CollectionCRUDAsyncAPITes...
Please remove unnecessary `.single()`
private Mono<DocumentCollection> readCollectionAsync(String collectionLink, DocumentClientRetryPolicy retryPolicyInstance, Map<String, Object> properties) { String path = Utils.joinPath(collectionLink, null); RxDocumentServiceRequest request = RxDocumentServiceRequest.create( OperationType.Read, ResourceType.DocumentCo...
.getResource()).single();
private Mono<DocumentCollection> readCollectionAsync(String collectionLink, DocumentClientRetryPolicy retryPolicyInstance, Map<String, Object> properties) { String path = Utils.joinPath(collectionLink, null); RxDocumentServiceRequest request = RxDocumentServiceRequest.create( OperationType.Read, ResourceType.DocumentCo...
class RxClientCollectionCache extends RxCollectionCache { private RxStoreModel storeModel; private final IAuthorizationTokenProvider tokenProvider; private final IRetryPolicyFactory retryPolicy; private final ISessionContainer sessionContainer; public RxClientCollectionCache(ISessionContainer sessionContainer, RxStoreM...
class RxClientCollectionCache extends RxCollectionCache { private RxStoreModel storeModel; private final IAuthorizationTokenProvider tokenProvider; private final IRetryPolicyFactory retryPolicy; private final ISessionContainer sessionContainer; public RxClientCollectionCache(ISessionContainer sessionContainer, RxStoreM...
as discussed offline. they are intentionally kept as they will do correctness validation to ensure Mono is not empty.
static public Mono<Database> createDatabaseIfNotExists(AsyncDocumentClient client, String databaseName) { return client.readDatabase("/dbs/" + databaseName, null) .onErrorResume( e -> { if (e instanceof CosmosClientException) { CosmosClientException dce = (CosmosClientException) e; if (dce.getStatusCode() == 404) { Da...
).map(ResourceResponse::getResource).single();
static public Mono<Database> createDatabaseIfNotExists(AsyncDocumentClient client, String databaseName) { return client.readDatabase("/dbs/" + databaseName, null) .onErrorResume( e -> { if (e instanceof CosmosClientException) { CosmosClientException dce = (CosmosClientException) e; if (dce.getStatusCode() == 404) { Da...
class Helpers { static public String createDocumentCollectionUri(String databaseName, String collectionName) { return String.format("/dbs/%s/colls/%s", databaseName, collectionName); } static public String createDatabaseUri(String databaseName) { return String.format("/dbs/%s", databaseName); } static public Mono<Docum...
class Helpers { static public String createDocumentCollectionUri(String databaseName, String collectionName) { return String.format("/dbs/%s/colls/%s", databaseName, collectionName); } static public String createDatabaseUri(String databaseName) { return String.format("/dbs/%s", databaseName); } static public Mono<Docum...
as discussed offline. they are intentionally kept as they will do correctness validation to ensure Mono is not empty.
private Mono<DocumentCollection> readCollectionAsync(String collectionLink, DocumentClientRetryPolicy retryPolicyInstance, Map<String, Object> properties) { String path = Utils.joinPath(collectionLink, null); RxDocumentServiceRequest request = RxDocumentServiceRequest.create( OperationType.Read, ResourceType.DocumentCo...
.getResource()).single();
private Mono<DocumentCollection> readCollectionAsync(String collectionLink, DocumentClientRetryPolicy retryPolicyInstance, Map<String, Object> properties) { String path = Utils.joinPath(collectionLink, null); RxDocumentServiceRequest request = RxDocumentServiceRequest.create( OperationType.Read, ResourceType.DocumentCo...
class RxClientCollectionCache extends RxCollectionCache { private RxStoreModel storeModel; private final IAuthorizationTokenProvider tokenProvider; private final IRetryPolicyFactory retryPolicy; private final ISessionContainer sessionContainer; public RxClientCollectionCache(ISessionContainer sessionContainer, RxStoreM...
class RxClientCollectionCache extends RxCollectionCache { private RxStoreModel storeModel; private final IAuthorizationTokenProvider tokenProvider; private final IRetryPolicyFactory retryPolicy; private final ISessionContainer sessionContainer; public RxClientCollectionCache(ISessionContainer sessionContainer, RxStoreM...
please also change Send span (line 81 to have Client kind)
public Context start(String spanName, Context context, ProcessKind processKind) { Objects.requireNonNull(spanName, "'spanName' cannot be null."); Objects.requireNonNull(context, "'context' cannot be null."); Objects.requireNonNull(processKind, "'processKind' cannot be null."); Span span; Builder spanBuilder; switch (pr...
span = spanBuilder.setSpanKind(Span.Kind.PRODUCER).startSpan();
public Context start(String spanName, Context context, ProcessKind processKind) { Objects.requireNonNull(spanName, "'spanName' cannot be null."); Objects.requireNonNull(context, "'context' cannot be null."); Objects.requireNonNull(processKind, "'processKind' cannot be null."); Span span; Builder spanBuilder; switch (pr...
class OpenTelemetryTracer implements com.azure.core.util.tracing.Tracer { private static final Tracer TRACER = OpenTelemetry.getTracerFactory().get("Azure-OpenTelemetry"); static final String AZ_NAMESPACE_KEY = "az.namespace"; static final String COMPONENT = "component"; static final String MESSAGE_BUS_DESTINATION = "m...
class OpenTelemetryTracer implements com.azure.core.util.tracing.Tracer { private static final Tracer TRACER = OpenTelemetry.getTracerFactory().get("Azure-OpenTelemetry"); static final String AZ_NAMESPACE_KEY = "az.namespace"; static final String COMPONENT = "component"; static final String MESSAGE_BUS_DESTINATION = "m...
If `options.getHttpPipeline()` is not null, the client provided in `TokenRequestContext` is overwritten. Can you please add comments on why this is done? Also, it would be better to check if `options.getHttpPipeline()` is not null first instead of setting up the pipeline which might get overwritten immediately after.
public Mono<AccessToken> authenticateWithClientSecret(String clientSecret, TokenRequestContext request) { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; try { ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(clientId, ClientCreden...
return Mono.error(e);
public Mono<AccessToken> authenticateWithClientSecret(String clientSecret, TokenRequestContext request) { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; try { ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(clientId, ClientCreden...
class IdentityClient { private static final SerializerAdapter SERIALIZER_ADAPTER = JacksonAdapter.createDefaultSerializerAdapter(); private static final Random RANDOM = new Random(); private final ClientLogger logger = new ClientLogger(IdentityClient.class); private final IdentityClientOptions options; private final Pu...
class IdentityClient { private static final SerializerAdapter SERIALIZER_ADAPTER = JacksonAdapter.createDefaultSerializerAdapter(); private static final Random RANDOM = new Random(); private final ClientLogger logger = new ClientLogger(IdentityClient.class); private final IdentityClientOptions options; private final Pu...
This line can be removed if you pass the default client as suggested above.
private HttpPipeline setupPipeline(HttpClient httpClient) { List<HttpPipelinePolicy> policies = new ArrayList<>(); HttpLogOptions httpLogOptions = new HttpLogOptions(); HttpPolicyProviders.addBeforeRetryPolicies(policies); policies.add(new RetryPolicy()); HttpPolicyProviders.addAfterRetryPolicies(policies); policies.ad...
HttpClient client = httpClient != null ? httpClient : HttpClient.createDefault();
private HttpPipeline setupPipeline(HttpClient httpClient) { List<HttpPipelinePolicy> policies = new ArrayList<>(); HttpLogOptions httpLogOptions = new HttpLogOptions(); HttpPolicyProviders.addBeforeRetryPolicies(policies); policies.add(new RetryPolicy()); HttpPolicyProviders.addAfterRetryPolicies(policies); policies.ad...
class IdentityClient { private static final SerializerAdapter SERIALIZER_ADAPTER = JacksonAdapter.createDefaultSerializerAdapter(); private static final Random RANDOM = new Random(); private final ClientLogger logger = new ClientLogger(IdentityClient.class); private final IdentityClientOptions options; private final Pu...
class IdentityClient { private static final SerializerAdapter SERIALIZER_ADAPTER = JacksonAdapter.createDefaultSerializerAdapter(); private static final Random RANDOM = new Random(); private final ClientLogger logger = new ClientLogger(IdentityClient.class); private final IdentityClientOptions options; private final Pu...
should we use the same pipeline that we create for the publicApplicationClient in the constructor so we don't have to create a new pipeline for every call to authenticate through the confidential client?
public Mono<AccessToken> authenticateWithClientSecret(String clientSecret, TokenRequestContext request) { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; try { ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(clientId, ClientCreden...
}
public Mono<AccessToken> authenticateWithClientSecret(String clientSecret, TokenRequestContext request) { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; try { ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(clientId, ClientCreden...
class IdentityClient { private static final SerializerAdapter SERIALIZER_ADAPTER = JacksonAdapter.createDefaultSerializerAdapter(); private static final Random RANDOM = new Random(); private final ClientLogger logger = new ClientLogger(IdentityClient.class); private final IdentityClientOptions options; private final Pu...
class IdentityClient { private static final SerializerAdapter SERIALIZER_ADAPTER = JacksonAdapter.createDefaultSerializerAdapter(); private static final Random RANDOM = new Random(); private final ClientLogger logger = new ClientLogger(IdentityClient.class); private final IdentityClientOptions options; private final Pu...
yeah, pipeline construction is now moved to the constructor.
public Mono<AccessToken> authenticateWithClientSecret(String clientSecret, TokenRequestContext request) { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; try { ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(clientId, ClientCreden...
}
public Mono<AccessToken> authenticateWithClientSecret(String clientSecret, TokenRequestContext request) { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; try { ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(clientId, ClientCreden...
class IdentityClient { private static final SerializerAdapter SERIALIZER_ADAPTER = JacksonAdapter.createDefaultSerializerAdapter(); private static final Random RANDOM = new Random(); private final ClientLogger logger = new ClientLogger(IdentityClient.class); private final IdentityClientOptions options; private final Pu...
class IdentityClient { private static final SerializerAdapter SERIALIZER_ADAPTER = JacksonAdapter.createDefaultSerializerAdapter(); private static final Random RANDOM = new Random(); private final ClientLogger logger = new ClientLogger(IdentityClient.class); private final IdentityClientOptions options; private final Pu...
I believe this should be `applicationBuilder.httpClient(new HttpPipelineAdapter(httpPipeline));` rather than `applicationBuilder.httpClient(new HttpPipelineAdapter(options.getHttpPipeline()));` because `httpPipeline` could have been set directly from the options or constructed in the ctor, so I think it's possible that...
public Mono<AccessToken> authenticateWithClientSecret(String clientSecret, TokenRequestContext request) { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; try { ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(clientId, ClientCreden...
applicationBuilder.httpClient(new HttpPipelineAdapter(options.getHttpPipeline()));
public Mono<AccessToken> authenticateWithClientSecret(String clientSecret, TokenRequestContext request) { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; try { ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(clientId, ClientCreden...
class IdentityClient { private static final SerializerAdapter SERIALIZER_ADAPTER = JacksonAdapter.createDefaultSerializerAdapter(); private static final Random RANDOM = new Random(); private final ClientLogger logger = new ClientLogger(IdentityClient.class); private final IdentityClientOptions options; private final Pu...
class IdentityClient { private static final SerializerAdapter SERIALIZER_ADAPTER = JacksonAdapter.createDefaultSerializerAdapter(); private static final Random RANDOM = new Random(); private final ClientLogger logger = new ClientLogger(IdentityClient.class); private final IdentityClientOptions options; private final Pu...
added the logic to cache the pipeline adapter. Thanks for the catch on http pipeline, it was an oversight by me.
public Mono<AccessToken> authenticateWithClientSecret(String clientSecret, TokenRequestContext request) { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; try { ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(clientId, ClientCreden...
applicationBuilder.httpClient(new HttpPipelineAdapter(options.getHttpPipeline()));
public Mono<AccessToken> authenticateWithClientSecret(String clientSecret, TokenRequestContext request) { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; try { ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(clientId, ClientCreden...
class IdentityClient { private static final SerializerAdapter SERIALIZER_ADAPTER = JacksonAdapter.createDefaultSerializerAdapter(); private static final Random RANDOM = new Random(); private final ClientLogger logger = new ClientLogger(IdentityClient.class); private final IdentityClientOptions options; private final Pu...
class IdentityClient { private static final SerializerAdapter SERIALIZER_ADAPTER = JacksonAdapter.createDefaultSerializerAdapter(); private static final Random RANDOM = new Random(); private final ClientLogger logger = new ClientLogger(IdentityClient.class); private final IdentityClientOptions options; private final Pu...
Consider using the `validatePrimaryLanguage` for testing the results, rather than converting them to lists and then doing the comparison.
public void detectSingleTextLanguage() { DetectedLanguage primaryLanguage = new DetectedLanguage("English", "en", 1.0); StepVerifier.create(client.detectLanguage("This is a test English Text")) .assertNext(response -> validateDetectedLanguages(Collections.singletonList(primaryLanguage), Collections.singletonList(respon...
.assertNext(response -> validateDetectedLanguages(Collections.singletonList(primaryLanguage),
public void detectSingleTextLanguage() { DetectedLanguage primaryLanguage = new DetectedLanguage("English", "en", 1.0); StepVerifier.create(client.detectLanguage("This is a test English Text")) .assertNext(response -> validatePrimaryLanguage(primaryLanguage, response)) .verifyComplete(); }
class TextAnalyticsAsyncClientTest extends TextAnalyticsClientTestBase { private TextAnalyticsAsyncClient client; @BeforeAll static void beforeAll() { StepVerifier.setDefaultTimeout(Duration.ofSeconds(30)); } @AfterAll static void afterAll() { StepVerifier.resetDefaultTimeout(); } @Override protected void beforeTest() ...
class TextAnalyticsAsyncClientTest extends TextAnalyticsClientTestBase { private TextAnalyticsAsyncClient client; @BeforeAll static void beforeAll() { StepVerifier.setDefaultTimeout(Duration.ofSeconds(30)); } @AfterAll static void afterAll() { StepVerifier.resetDefaultTimeout(); } @Override protected void beforeTest() ...
no assert ?
public void recognizeEntitiesForFaultyText() { StepVerifier.create(client.recognizeEntities("!@ .verifyComplete(); }
.verifyComplete();
public void recognizeEntitiesForFaultyText() { StepVerifier.create(client.recognizeEntities("!@ .expectNextCount(0) .verifyComplete(); }
class TextAnalyticsAsyncClientTest extends TextAnalyticsClientTestBase { private TextAnalyticsAsyncClient client; @BeforeAll static void beforeAll() { StepVerifier.setDefaultTimeout(Duration.ofSeconds(30)); } @AfterAll static void afterAll() { StepVerifier.resetDefaultTimeout(); } @Override protected void beforeTest() ...
class TextAnalyticsAsyncClientTest extends TextAnalyticsClientTestBase { private TextAnalyticsAsyncClient client; @BeforeAll static void beforeAll() { StepVerifier.setDefaultTimeout(Duration.ofSeconds(30)); } @AfterAll static void afterAll() { StepVerifier.resetDefaultTimeout(); } @Override protected void beforeTest() ...
updated
public void recognizeEntitiesForFaultyText() { StepVerifier.create(client.recognizeEntities("!@ .verifyComplete(); }
.verifyComplete();
public void recognizeEntitiesForFaultyText() { StepVerifier.create(client.recognizeEntities("!@ .expectNextCount(0) .verifyComplete(); }
class TextAnalyticsAsyncClientTest extends TextAnalyticsClientTestBase { private TextAnalyticsAsyncClient client; @BeforeAll static void beforeAll() { StepVerifier.setDefaultTimeout(Duration.ofSeconds(30)); } @AfterAll static void afterAll() { StepVerifier.resetDefaultTimeout(); } @Override protected void beforeTest() ...
class TextAnalyticsAsyncClientTest extends TextAnalyticsClientTestBase { private TextAnalyticsAsyncClient client; @BeforeAll static void beforeAll() { StepVerifier.setDefaultTimeout(Duration.ofSeconds(30)); } @AfterAll static void afterAll() { StepVerifier.resetDefaultTimeout(); } @Override protected void beforeTest() ...
Can use `validatePrimaryLanguage` here and below.
public void detectSingleTextLanguage() { DetectedLanguage primaryLanguage = new DetectedLanguage("English", "en", 0.0); List<DetectedLanguage> expectedLanguageList = Collections.singletonList(primaryLanguage); validateDetectedLanguages( Collections.singletonList(client.detectLanguage("This is a test English Text")), ex...
validateDetectedLanguages(
public void detectSingleTextLanguage() { validatePrimaryLanguage(new DetectedLanguage("English", "en", 0.0), client.detectLanguage("This is a test English Text")); }
class TextAnalyticsClientTest extends TextAnalyticsClientTestBase { private TextAnalyticsClient client; @Override protected void beforeTest() { client = clientSetup(httpPipeline -> new TextAnalyticsClientBuilder() .endpoint(getEndpoint()) .pipeline(httpPipeline) .buildClient()); } /** * Verify that we can get statistic...
class TextAnalyticsClientTest extends TextAnalyticsClientTestBase { private TextAnalyticsClient client; @Override protected void beforeTest() { client = clientSetup(httpPipeline -> new TextAnalyticsClientBuilder() .endpoint(getEndpoint()) .pipeline(httpPipeline) .buildClient()); } /** * Verify that we can get statistic...
use `validatePrimaryLanguage` instead.
public void updateToValidKey() { final TextAnalyticsApiKeyCredential credential = new TextAnalyticsApiKeyCredential(INVALID_KEY); final TextAnalyticsClient client = createClientBuilder(getEndpoint(), credential).buildClient(); credential.updateCredential(getApiKey()); validateDetectedLanguages( Collections.singletonLis...
validateDetectedLanguages(
public void updateToValidKey() { final TextAnalyticsApiKeyCredential credential = new TextAnalyticsApiKeyCredential(INVALID_KEY); final TextAnalyticsClient client = createClientBuilder(getEndpoint(), credential).buildClient(); credential.updateCredential(getApiKey()); validatePrimaryLanguage(new DetectedLanguage("Engli...
class TextAnalyticsClientTest extends TextAnalyticsClientTestBase { private TextAnalyticsClient client; @Override protected void beforeTest() { client = clientSetup(httpPipeline -> new TextAnalyticsClientBuilder() .endpoint(getEndpoint()) .pipeline(httpPipeline) .buildClient()); } /** * Verify that we can get statistic...
class TextAnalyticsClientTest extends TextAnalyticsClientTestBase { private TextAnalyticsClient client; @Override protected void beforeTest() { client = clientSetup(httpPipeline -> new TextAnalyticsClientBuilder() .endpoint(getEndpoint()) .pipeline(httpPipeline) .buildClient()); } /** * Verify that we can get statistic...
consider renaming this to `detectLanguageBatchWithResponse` to be consistent
Mono<Response<DetectLanguageResult>> detectLanguageWithResponse(String text, String countryHint, Context context) { Objects.requireNonNull(text, "'text' cannot be null."); List<DetectLanguageInput> languageInputs = Collections.singletonList(new DetectLanguageInput("0", text, countryHint)); return detectBatchLanguageWit...
return detectBatchLanguageWithResponse(languageInputs, null, context)
new DetectLanguageInput("0", text, countryHint)); return detectLanguageBatchWithResponse(languageInputs, null, context) .map(response -> new SimpleResponse<>(response, Transforms.processSingleResponseErrorResult(response).getValue().getPrimaryLanguage())); } Mono<Response<DocumentResultCollection<DetectLanguageResult>>...
class DetectLanguageAsyncClient { private final ClientLogger logger = new ClientLogger(DetectLanguageAsyncClient.class); private final TextAnalyticsClientImpl service; /** * Create a {@code DetectLanguageAsyncClient} that sends requests to the Text Analytics services's detect language * endpoint. * * @param service The...
class DetectLanguageAsyncClient { private final ClientLogger logger = new ClientLogger(DetectLanguageAsyncClient.class); private final TextAnalyticsClientImpl service; /** * Create a {@code DetectLanguageAsyncClient} that sends requests to the Text Analytics services's detect language * endpoint. * * @param service The...
ditto
public void createDocumentWithErrorClient() throws Exception { final StringWriter consoleWriter = new StringWriter(); addAppenderAndLogger(NETWORK_LOGGING_CATEGORY, Level.ERROR, APPENDER_NAME, consoleWriter); Logger logger = LoggerFactory.getLogger(NETWORK_LOGGING_CATEGORY); Assert.assertTrue(logger.isErrorEnabled()); ...
Assert.assertTrue(logger.isErrorEnabled());
public void createDocumentWithErrorClient() throws Exception { final StringWriter consoleWriter = new StringWriter(); addAppenderAndLogger(NETWORK_LOGGING_CATEGORY, Level.ERROR, APPENDER_NAME, consoleWriter); Logger logger = LoggerFactory.getLogger(NETWORK_LOGGING_CATEGORY); assertThat(logger.isErrorEnabled()).isTrue()...
class LogLevelTest extends TestSuiteBase { public final static String COSMOS_DB_LOGGING_CATEGORY = "com.azure.data.cosmos"; public final static String NETWORK_LOGGING_CATEGORY = "com.azure.data.cosmos.netty-network"; public final static String LOG_PATTERN_1 = "HTTP/1.1 200 Ok."; public final static String LOG_PATTERN_2...
class LogLevelTest extends TestSuiteBase { public final static String COSMOS_DB_LOGGING_CATEGORY = "com.azure.data.cosmos"; public final static String NETWORK_LOGGING_CATEGORY = "com.azure.data.cosmos.netty-network"; public final static String LOG_PATTERN_1 = "HTTP/1.1 200 Ok."; public final static String LOG_PATTERN_2...
here and everywhere else please, ditto
public void createDocumentWithDebugLevel() throws Exception { final StringWriter consoleWriter = new StringWriter(); addAppenderAndLogger(NETWORK_LOGGING_CATEGORY, Level.DEBUG, APPENDER_NAME, consoleWriter); Logger logger = LoggerFactory.getLogger(NETWORK_LOGGING_CATEGORY); Assert.assertTrue(logger.isDebugEnabled()); C...
Assert.assertTrue(logger.isDebugEnabled());
public void createDocumentWithDebugLevel() throws Exception { final StringWriter consoleWriter = new StringWriter(); addAppenderAndLogger(NETWORK_LOGGING_CATEGORY, Level.DEBUG, APPENDER_NAME, consoleWriter); final Logger logger = LoggerFactory.getLogger(NETWORK_LOGGING_CATEGORY); assertThat(logger.isDebugEnabled()).isT...
class LogLevelTest extends TestSuiteBase { public final static String COSMOS_DB_LOGGING_CATEGORY = "com.azure.data.cosmos"; public final static String NETWORK_LOGGING_CATEGORY = "com.azure.data.cosmos.netty-network"; public final static String LOG_PATTERN_1 = "HTTP/1.1 200 Ok."; public final static String LOG_PATTERN_2...
class LogLevelTest extends TestSuiteBase { public final static String COSMOS_DB_LOGGING_CATEGORY = "com.azure.data.cosmos"; public final static String NETWORK_LOGGING_CATEGORY = "com.azure.data.cosmos.netty-network"; public final static String LOG_PATTERN_1 = "HTTP/1.1 200 Ok."; public final static String LOG_PATTERN_2...
Should this be in the bodyIntern method instead?
public Flux<ByteBuffer> getBody() { return bodyIntern().doFinally(s -> { if (!reactorNettyConnection.isDisposed()) { reactorNettyConnection.channel().eventLoop().execute(reactorNettyConnection::dispose); } }).map(byteBuf -> { if (this.disableBufferCopy) { return byteBuf.nioBuffer(); } return deepCopyBuffer(byteBuf); })...
}).map(byteBuf -> {
public Flux<ByteBuffer> getBody() { return bodyIntern().doFinally(s -> { if (!reactorNettyConnection.isDisposed()) { reactorNettyConnection.channel().eventLoop().execute(reactorNettyConnection::dispose); } }).map(byteBuf -> this.disableBufferCopy ? byteBuf.nioBuffer() : deepCopyBuffer(byteBuf)); }
class ReactorNettyHttpResponse extends HttpResponse { private final HttpClientResponse reactorNettyResponse; private final Connection reactorNettyConnection; private final boolean disableBufferCopy; ReactorNettyHttpResponse(HttpClientResponse reactorNettyResponse, Connection reactorNettyConnection, HttpRequest httpRequ...
class ReactorNettyHttpResponse extends HttpResponse { private static final ByteBuffer EMPTY_BYTE_BUFFER = ByteBuffer.wrap(new byte[0]); private final HttpClientResponse reactorNettyResponse; private final Connection reactorNettyConnection; private final boolean disableBufferCopy; ReactorNettyHttpResponse(HttpClientResp...
As discussed, changing bodyIntern will result in double copy for other `getBody*` methods that don't return `Flux<ByteBuffer>`
public Flux<ByteBuffer> getBody() { return bodyIntern().doFinally(s -> { if (!reactorNettyConnection.isDisposed()) { reactorNettyConnection.channel().eventLoop().execute(reactorNettyConnection::dispose); } }).map(byteBuf -> { if (this.disableBufferCopy) { return byteBuf.nioBuffer(); } return deepCopyBuffer(byteBuf); })...
}).map(byteBuf -> {
public Flux<ByteBuffer> getBody() { return bodyIntern().doFinally(s -> { if (!reactorNettyConnection.isDisposed()) { reactorNettyConnection.channel().eventLoop().execute(reactorNettyConnection::dispose); } }).map(byteBuf -> this.disableBufferCopy ? byteBuf.nioBuffer() : deepCopyBuffer(byteBuf)); }
class ReactorNettyHttpResponse extends HttpResponse { private final HttpClientResponse reactorNettyResponse; private final Connection reactorNettyConnection; private final boolean disableBufferCopy; ReactorNettyHttpResponse(HttpClientResponse reactorNettyResponse, Connection reactorNettyConnection, HttpRequest httpRequ...
class ReactorNettyHttpResponse extends HttpResponse { private static final ByteBuffer EMPTY_BYTE_BUFFER = ByteBuffer.wrap(new byte[0]); private final HttpClientResponse reactorNettyResponse; private final Connection reactorNettyConnection; private final boolean disableBufferCopy; ReactorNettyHttpResponse(HttpClientResp...
minor; maybe not now, but we could have a static empty ByteBuffer in class level and if size == 0, we can just return that, instead of creating a new empty `duplicate` reference every time.
private static ByteBuffer deepCopyBuffer(ByteBuf byteBuf) { ByteBuffer buffer = byteBuf.nioBuffer(); int offset = buffer.position(); int size = buffer.remaining(); byte[] duplicate = new byte[size]; for (int i = 0; i < size; i++) { duplicate[i] = buffer.get(i + offset); } return ByteBuffer.wrap(duplicate); }
int size = buffer.remaining();
private static ByteBuffer deepCopyBuffer(ByteBuf byteBuf) { ByteBuffer buffer = ByteBuffer.allocate(byteBuf.readableBytes()); byteBuf.readBytes(buffer); buffer.rewind(); return buffer; }
class ReactorNettyHttpResponse extends HttpResponse { private final HttpClientResponse reactorNettyResponse; private final Connection reactorNettyConnection; private final boolean disableBufferCopy; ReactorNettyHttpResponse(HttpClientResponse reactorNettyResponse, Connection reactorNettyConnection, HttpRequest httpRequ...
class ReactorNettyHttpResponse extends HttpResponse { private static final ByteBuffer EMPTY_BYTE_BUFFER = ByteBuffer.wrap(new byte[0]); private final HttpClientResponse reactorNettyResponse; private final Connection reactorNettyConnection; private final boolean disableBufferCopy; ReactorNettyHttpResponse(HttpClientResp...
Reduce this to a one-liner: `return disableBufferCopy ? byteBuf.nioBuffer() : deepCopyBuffer(byteBuf);`
public Flux<ByteBuffer> getBody() { return bodyIntern().doFinally(s -> { if (!reactorNettyConnection.isDisposed()) { reactorNettyConnection.channel().eventLoop().execute(reactorNettyConnection::dispose); } }).map(byteBuf -> { if (this.disableBufferCopy) { return byteBuf.nioBuffer(); } return deepCopyBuffer(byteBuf); })...
return deepCopyBuffer(byteBuf);
public Flux<ByteBuffer> getBody() { return bodyIntern().doFinally(s -> { if (!reactorNettyConnection.isDisposed()) { reactorNettyConnection.channel().eventLoop().execute(reactorNettyConnection::dispose); } }).map(byteBuf -> this.disableBufferCopy ? byteBuf.nioBuffer() : deepCopyBuffer(byteBuf)); }
class ReactorNettyHttpResponse extends HttpResponse { private final HttpClientResponse reactorNettyResponse; private final Connection reactorNettyConnection; private final boolean disableBufferCopy; ReactorNettyHttpResponse(HttpClientResponse reactorNettyResponse, Connection reactorNettyConnection, HttpRequest httpRequ...
class ReactorNettyHttpResponse extends HttpResponse { private static final ByteBuffer EMPTY_BYTE_BUFFER = ByteBuffer.wrap(new byte[0]); private final HttpClientResponse reactorNettyResponse; private final Connection reactorNettyConnection; private final boolean disableBufferCopy; ReactorNettyHttpResponse(HttpClientResp...
nit: Random newline change
public static HttpClient createInstance() { if (defaultProvider == null) { throw new IllegalStateException(CANNOT_FIND_HTTP_CLIENT); } return defaultProvider.createInstance(); }
return defaultProvider.createInstance();
public static HttpClient createInstance() { if (defaultProvider == null) { throw new IllegalStateException(CANNOT_FIND_HTTP_CLIENT); } return defaultProvider.createInstance(); }
class HttpClientProviders { private static HttpClientProvider defaultProvider; private static final String CANNOT_FIND_HTTP_CLIENT = "Cannot find any HttpClient provider on the classpath - unable to create a default HttpClient instance"; static { ServiceLoader<HttpClientProvider> serviceLoader = ServiceLoader.load(Http...
class HttpClientProviders { private static HttpClientProvider defaultProvider; private static final String CANNOT_FIND_HTTP_CLIENT = "Cannot find any HttpClient provider on the classpath - unable to create a default HttpClient instance"; static { ServiceLoader<HttpClientProvider> serviceLoader = ServiceLoader.load(Http...
Recursion should be avoided as much as we can because of obvious reasons. I believe this can easily be converted to a while loop.
private CosmosClientException extractCosmosClientExceptionIfAny(Throwable t) { if (t == null) { return null; } if (t instanceof CosmosClientException) { return (CosmosClientException) t; } return extractCosmosClientExceptionIfAny(t.getCause()); }
return extractCosmosClientExceptionIfAny(t.getCause());
private CosmosClientException extractCosmosClientExceptionIfAny(Throwable t) { if (t == null) { return null; } while(!(t instanceof CosmosClientException)) { t = t.getCause(); } return (CosmosClientException) t; }
class RetryAnalyzer extends RetryAnalyzerCount { private final Logger logger = LoggerFactory.getLogger(RetryAnalyzer.class); private final int waitBetweenRetriesInSeconds = 120; public RetryAnalyzer() { this.setCount(Integer.parseInt(TestConfigurations.MAX_RETRY_LIMIT)); } @Override public boolean retryMethod(ITestResu...
class RetryAnalyzer extends RetryAnalyzerCount { private final Logger logger = LoggerFactory.getLogger(RetryAnalyzer.class); private final int waitBetweenRetriesInSeconds = 120; public RetryAnalyzer() { this.setCount(Integer.parseInt(TestConfigurations.MAX_RETRY_LIMIT)); } @Override public boolean retryMethod(ITestResu...
why?
private CosmosClientException extractCosmosClientExceptionIfAny(Throwable t) { if (t == null) { return null; } if (t instanceof CosmosClientException) { return (CosmosClientException) t; } return extractCosmosClientExceptionIfAny(t.getCause()); }
return extractCosmosClientExceptionIfAny(t.getCause());
private CosmosClientException extractCosmosClientExceptionIfAny(Throwable t) { if (t == null) { return null; } while(!(t instanceof CosmosClientException)) { t = t.getCause(); } return (CosmosClientException) t; }
class RetryAnalyzer extends RetryAnalyzerCount { private final Logger logger = LoggerFactory.getLogger(RetryAnalyzer.class); private final int waitBetweenRetriesInSeconds = 120; public RetryAnalyzer() { this.setCount(Integer.parseInt(TestConfigurations.MAX_RETRY_LIMIT)); } @Override public boolean retryMethod(ITestResu...
class RetryAnalyzer extends RetryAnalyzerCount { private final Logger logger = LoggerFactory.getLogger(RetryAnalyzer.class); private final int waitBetweenRetriesInSeconds = 120; public RetryAnalyzer() { this.setCount(Integer.parseInt(TestConfigurations.MAX_RETRY_LIMIT)); } @Override public boolean retryMethod(ITestResu...
The text that needs to be analyzed.
public static void main(String[] args) { TextAnalyticsAsyncClient client = new TextAnalyticsClientBuilder() .apiKey(new TextAnalyticsApiKeyCredential("{api_key}")) .endpoint("{endpoint}") .buildAsyncClient(); String text = "My SSN is 555-55-5555"; client.recognizePiiEntities(text).subscribe( entity -> System.out.printf...
public static void main(String[] args) { TextAnalyticsAsyncClient client = new TextAnalyticsClientBuilder() .apiKey(new TextAnalyticsApiKeyCredential("{api_key}")) .endpoint("{endpoint}") .buildAsyncClient(); String text = "My SSN is 555-55-5555"; client.recognizePiiEntities(text).subscribe( entity -> System.out.printf...
class RecognizePiiAsync { /** * Main method to invoke this demo about how to recognize the PII entities of an input text. * * @param args Unused arguments to the program. */ }
class RecognizePiiAsync { /** * Main method to invoke this demo about how to recognize the PII entities of an input text. * * @param args Unused arguments to the program. */ }
Revert the keys and endpoint information from here
public static void main(String[] args) { TextAnalyticsClient client = new TextAnalyticsClientBuilder() .apiKey(new TextAnalyticsApiKeyCredential("b2f8b7b697c348dcb0e30055d49f3d0f")) .endpoint("https: .buildClient(); List<TextDocumentInput> inputs = Arrays.asList( new TextDocumentInput("1", "The hotel was dark and uncle...
.apiKey(new TextAnalyticsApiKeyCredential("b2f8b7b697c348dcb0e30055d49f3d0f"))
public static void main(String[] args) { TextAnalyticsClient client = new TextAnalyticsClientBuilder() .apiKey(new TextAnalyticsApiKeyCredential("{api_key}")) .endpoint("{endpoint}") .buildClient(); List<TextDocumentInput> inputs = Arrays.asList( new TextDocumentInput("1", "The hotel was dark and unclean. The restauran...
class AnalyzeSentimentBatchDocuments { /** * Main method to invoke this demo about how to analyze the sentiments of a batch input text. * * @param args Unused arguments to the program. */ }
class AnalyzeSentimentBatchDocuments { /** * Main method to invoke this demo about how to analyze the sentiments of a batch input text. * * @param args Unused arguments to the program. */ }
Yup. Found this when reviewed. Thanks for pointing this out
public static void main(String[] args) { TextAnalyticsClient client = new TextAnalyticsClientBuilder() .apiKey(new TextAnalyticsApiKeyCredential("b2f8b7b697c348dcb0e30055d49f3d0f")) .endpoint("https: .buildClient(); List<TextDocumentInput> inputs = Arrays.asList( new TextDocumentInput("1", "The hotel was dark and uncle...
.apiKey(new TextAnalyticsApiKeyCredential("b2f8b7b697c348dcb0e30055d49f3d0f"))
public static void main(String[] args) { TextAnalyticsClient client = new TextAnalyticsClientBuilder() .apiKey(new TextAnalyticsApiKeyCredential("{api_key}")) .endpoint("{endpoint}") .buildClient(); List<TextDocumentInput> inputs = Arrays.asList( new TextDocumentInput("1", "The hotel was dark and unclean. The restauran...
class AnalyzeSentimentBatchDocuments { /** * Main method to invoke this demo about how to analyze the sentiments of a batch input text. * * @param args Unused arguments to the program. */ }
class AnalyzeSentimentBatchDocuments { /** * Main method to invoke this demo about how to analyze the sentiments of a batch input text. * * @param args Unused arguments to the program. */ }
we need to rotate that key too
public static void main(String[] args) { TextAnalyticsClient client = new TextAnalyticsClientBuilder() .apiKey(new TextAnalyticsApiKeyCredential("b2f8b7b697c348dcb0e30055d49f3d0f")) .endpoint("https: .buildClient(); List<TextDocumentInput> inputs = Arrays.asList( new TextDocumentInput("1", "The hotel was dark and uncle...
.apiKey(new TextAnalyticsApiKeyCredential("b2f8b7b697c348dcb0e30055d49f3d0f"))
public static void main(String[] args) { TextAnalyticsClient client = new TextAnalyticsClientBuilder() .apiKey(new TextAnalyticsApiKeyCredential("{api_key}")) .endpoint("{endpoint}") .buildClient(); List<TextDocumentInput> inputs = Arrays.asList( new TextDocumentInput("1", "The hotel was dark and unclean. The restauran...
class AnalyzeSentimentBatchDocuments { /** * Main method to invoke this demo about how to analyze the sentiments of a batch input text. * * @param args Unused arguments to the program. */ }
class AnalyzeSentimentBatchDocuments { /** * Main method to invoke this demo about how to analyze the sentiments of a batch input text. * * @param args Unused arguments to the program. */ }
nit: Extracted phrases, may be to match what with the rest.
public static void main(String[] args) { TextAnalyticsApiKeyCredential credential = new TextAnalyticsApiKeyCredential("{api_key}"); TextAnalyticsAsyncClient client = new TextAnalyticsClientBuilder() .apiKey(credential) .endpoint("{endpoint}") .buildAsyncClient(); String text = "My cat might need to see a veterinarian."...
System.out.println("Recognized phrases:");
public static void main(String[] args) { TextAnalyticsApiKeyCredential credential = new TextAnalyticsApiKeyCredential("{api_key}"); TextAnalyticsAsyncClient client = new TextAnalyticsClientBuilder() .apiKey(credential) .endpoint("{endpoint}") .buildAsyncClient(); String text = "My cat might need to see a veterinarian."...
class RotateApiKeyAsync { /** * Main method to invoke this demo about how to rotate the existing API key of text analytics client. * * @param args Unused arguments to the program. */ }
class RotateApiKeyAsync { /** * Main method to invoke this demo about how to rotate the existing API key of text analytics client. * * @param args Unused arguments to the program. */ }
Maybe we can turn it into a negative test case
void listConfigurationSettingsSelectFieldsRunner(BiFunction<List<ConfigurationSetting>, SettingSelector, Iterable<ConfigurationSetting>> testRunner) { final String label = "my-first-mylabel"; final String label2 = "my-second-mylabel"; final int numberToCreate = 8; final Map<String, String> tags = new HashMap<>(); tags....
.setLabelFilter("my-second*")
void listConfigurationSettingsSelectFieldsRunner(BiFunction<List<ConfigurationSetting>, SettingSelector, Iterable<ConfigurationSetting>> testRunner) { final String label = "my-first-mylabel"; final String label2 = "my-second-mylabel"; final int numberToCreate = 8; final Map<String, String> tags = new HashMap<>(); tags....
class ConfigurationClientTestBase extends TestBase { private static final String AZURE_APPCONFIG_CONNECTION_STRING = "AZURE_APPCONFIG_CONNECTION_STRING"; private static final String KEY_PREFIX = "key"; private static final String LABEL_PREFIX = "label"; private static final int PREFIX_LENGTH = 8; private static final i...
class ConfigurationClientTestBase extends TestBase { private static final String AZURE_APPCONFIG_CONNECTION_STRING = "AZURE_APPCONFIG_CONNECTION_STRING"; private static final String KEY_PREFIX = "key"; private static final String LABEL_PREFIX = "label"; private static final int PREFIX_LENGTH = 8; private static final i...
if in the future, the service team start to support it again. Then we need to update the negative test case again?
void listConfigurationSettingsSelectFieldsRunner(BiFunction<List<ConfigurationSetting>, SettingSelector, Iterable<ConfigurationSetting>> testRunner) { final String label = "my-first-mylabel"; final String label2 = "my-second-mylabel"; final int numberToCreate = 8; final Map<String, String> tags = new HashMap<>(); tags....
.setLabelFilter("my-second*")
void listConfigurationSettingsSelectFieldsRunner(BiFunction<List<ConfigurationSetting>, SettingSelector, Iterable<ConfigurationSetting>> testRunner) { final String label = "my-first-mylabel"; final String label2 = "my-second-mylabel"; final int numberToCreate = 8; final Map<String, String> tags = new HashMap<>(); tags....
class ConfigurationClientTestBase extends TestBase { private static final String AZURE_APPCONFIG_CONNECTION_STRING = "AZURE_APPCONFIG_CONNECTION_STRING"; private static final String KEY_PREFIX = "key"; private static final String LABEL_PREFIX = "label"; private static final int PREFIX_LENGTH = 8; private static final i...
class ConfigurationClientTestBase extends TestBase { private static final String AZURE_APPCONFIG_CONNECTION_STRING = "AZURE_APPCONFIG_CONNECTION_STRING"; private static final String KEY_PREFIX = "key"; private static final String LABEL_PREFIX = "label"; private static final int PREFIX_LENGTH = 8; private static final i...
This would be a service API change. So, I hope the API version would be ramped and we'd expect the old API version to continue throwing the 400.
void listConfigurationSettingsSelectFieldsRunner(BiFunction<List<ConfigurationSetting>, SettingSelector, Iterable<ConfigurationSetting>> testRunner) { final String label = "my-first-mylabel"; final String label2 = "my-second-mylabel"; final int numberToCreate = 8; final Map<String, String> tags = new HashMap<>(); tags....
.setLabelFilter("my-second*")
void listConfigurationSettingsSelectFieldsRunner(BiFunction<List<ConfigurationSetting>, SettingSelector, Iterable<ConfigurationSetting>> testRunner) { final String label = "my-first-mylabel"; final String label2 = "my-second-mylabel"; final int numberToCreate = 8; final Map<String, String> tags = new HashMap<>(); tags....
class ConfigurationClientTestBase extends TestBase { private static final String AZURE_APPCONFIG_CONNECTION_STRING = "AZURE_APPCONFIG_CONNECTION_STRING"; private static final String KEY_PREFIX = "key"; private static final String LABEL_PREFIX = "label"; private static final int PREFIX_LENGTH = 8; private static final i...
class ConfigurationClientTestBase extends TestBase { private static final String AZURE_APPCONFIG_CONNECTION_STRING = "AZURE_APPCONFIG_CONNECTION_STRING"; private static final String KEY_PREFIX = "key"; private static final String LABEL_PREFIX = "label"; private static final int PREFIX_LENGTH = 8; private static final i...
make sense to me. I will add the negative test case
void listConfigurationSettingsSelectFieldsRunner(BiFunction<List<ConfigurationSetting>, SettingSelector, Iterable<ConfigurationSetting>> testRunner) { final String label = "my-first-mylabel"; final String label2 = "my-second-mylabel"; final int numberToCreate = 8; final Map<String, String> tags = new HashMap<>(); tags....
.setLabelFilter("my-second*")
void listConfigurationSettingsSelectFieldsRunner(BiFunction<List<ConfigurationSetting>, SettingSelector, Iterable<ConfigurationSetting>> testRunner) { final String label = "my-first-mylabel"; final String label2 = "my-second-mylabel"; final int numberToCreate = 8; final Map<String, String> tags = new HashMap<>(); tags....
class ConfigurationClientTestBase extends TestBase { private static final String AZURE_APPCONFIG_CONNECTION_STRING = "AZURE_APPCONFIG_CONNECTION_STRING"; private static final String KEY_PREFIX = "key"; private static final String LABEL_PREFIX = "label"; private static final int PREFIX_LENGTH = 8; private static final i...
class ConfigurationClientTestBase extends TestBase { private static final String AZURE_APPCONFIG_CONNECTION_STRING = "AZURE_APPCONFIG_CONNECTION_STRING"; private static final String KEY_PREFIX = "key"; private static final String LABEL_PREFIX = "label"; private static final int PREFIX_LENGTH = 8; private static final i...
are these constants anywhere?
public static BlobHttpHeaders extractHttpHeaders(List<FileAttribute<?>> fileAttributes, ClientLogger logger) { BlobHttpHeaders headers = new BlobHttpHeaders(); for (Iterator<FileAttribute<?>> it = fileAttributes.iterator(); it.hasNext();) { FileAttribute<?> attr = it.next(); boolean propertyFound = true; switch (attr.n...
case "Content-Type":
public static BlobHttpHeaders extractHttpHeaders(List<FileAttribute<?>> fileAttributes, ClientLogger logger) { BlobHttpHeaders headers = new BlobHttpHeaders(); for (Iterator<FileAttribute<?>> it = fileAttributes.iterator(); it.hasNext();) { FileAttribute<?> attr = it.next(); boolean propertyFound = true; switch (attr.n...
class Utility { public static <T extends Exception> T logError(ClientLogger logger, T e) { logger.error(e.getMessage()); return e; } /* Note that this will remove the properties from the list of attributes as it finds them. */ public static Map<String, String> convertAttributesToMetadata(List<FileAttribute<?>> fileAttr...
class Utility { public static <T extends Exception> T logError(ClientLogger logger, T e) { logger.error(e.getMessage()); return e; } /* Note that this will remove the properties from the list of attributes as it finds them. */ public static Map<String, String> convertAttributesToMetadata(List<FileAttribute<?>> fileAttr...
while loop might be more suitable?
public void queryItemsWithContinuationTokenAndPageSize() throws Exception{ List<String> actualIds = new ArrayList<>(); CosmosItemProperties properties = getDocumentDefinition(UUID.randomUUID().toString()); container.createItem(properties); actualIds.add(properties.getId()); properties = getDocumentDefinition(UUID.rando...
for (; feedResponse.hasNext(); ) {
public void queryItemsWithContinuationTokenAndPageSize() throws Exception{ List<String> actualIds = new ArrayList<>(); CosmosItemProperties properties = getDocumentDefinition(UUID.randomUUID().toString()); container.createItem(properties); actualIds.add(properties.getId()); properties = getDocumentDefinition(UUID.rando...
class CosmosItemTest extends TestSuiteBase { private CosmosClient client; private CosmosContainer container; @Factory(dataProvider = "clientBuilders") public CosmosItemTest(CosmosClientBuilder clientBuilder) { super(clientBuilder); } @BeforeClass(groups = {"simple"}, timeOut = SETUP_TIMEOUT) public void before_CosmosIt...
class CosmosItemTest extends TestSuiteBase { private CosmosClient client; private CosmosContainer container; @Factory(dataProvider = "clientBuilders") public CosmosItemTest(CosmosClientBuilder clientBuilder) { super(clientBuilder); } @BeforeClass(groups = {"simple"}, timeOut = SETUP_TIMEOUT) public void before_CosmosIt...
yeah, it will be. Stupid intelliJ suggested this :P I will update it.
public void queryItemsWithContinuationTokenAndPageSize() throws Exception{ List<String> actualIds = new ArrayList<>(); CosmosItemProperties properties = getDocumentDefinition(UUID.randomUUID().toString()); container.createItem(properties); actualIds.add(properties.getId()); properties = getDocumentDefinition(UUID.rando...
for (; feedResponse.hasNext(); ) {
public void queryItemsWithContinuationTokenAndPageSize() throws Exception{ List<String> actualIds = new ArrayList<>(); CosmosItemProperties properties = getDocumentDefinition(UUID.randomUUID().toString()); container.createItem(properties); actualIds.add(properties.getId()); properties = getDocumentDefinition(UUID.rando...
class CosmosItemTest extends TestSuiteBase { private CosmosClient client; private CosmosContainer container; @Factory(dataProvider = "clientBuilders") public CosmosItemTest(CosmosClientBuilder clientBuilder) { super(clientBuilder); } @BeforeClass(groups = {"simple"}, timeOut = SETUP_TIMEOUT) public void before_CosmosIt...
class CosmosItemTest extends TestSuiteBase { private CosmosClient client; private CosmosContainer container; @Factory(dataProvider = "clientBuilders") public CosmosItemTest(CosmosClientBuilder clientBuilder) { super(clientBuilder); } @BeforeClass(groups = {"simple"}, timeOut = SETUP_TIMEOUT) public void before_CosmosIt...
Removed cache as per offline discussion
private Mono<DatabaseAccount> getDatabaseAccountAsync(URI serviceEndpoint) { final GlobalEndpointManager that = this; Callable<Mono<DatabaseAccount>> fetchDatabaseAccount = () -> { return that.owner.getDatabaseAccountFromEndpoint(serviceEndpoint).doOnNext(databaseAccount -> { if(databaseAccount != null) { this.latestDa...
databaseAccountAsyncCache.set(StringUtils.EMPTY, obsoleteValue);
private Mono<DatabaseAccount> getDatabaseAccountAsync(URI serviceEndpoint) { return this.owner.getDatabaseAccountFromEndpoint(serviceEndpoint) .doOnNext(databaseAccount -> { if(databaseAccount != null) { this.latestDatabaseAccount = databaseAccount; } logger.debug("account retrieved: {}", databaseAccount); }).single();...
class GlobalEndpointManager implements AutoCloseable { private static final Logger logger = LoggerFactory.getLogger(GlobalEndpointManager.class); private final int backgroundRefreshLocationTimeIntervalInMS; private final LocationCache locationCache; private final URI defaultEndpoint; private final ConnectionPolicy conn...
class GlobalEndpointManager implements AutoCloseable { private static final Logger logger = LoggerFactory.getLogger(GlobalEndpointManager.class); private final int backgroundRefreshLocationTimeIntervalInMS; private final LocationCache locationCache; private final URI defaultEndpoint; private final ConnectionPolicy conn...
Should be uploading `indexedDoc`. I'm getting paranoid now that we've made this mistake in many places and copy-pasted. 😬
public void getDynamicDocumentCannotAlwaysDetermineCorrectType() { createHotelIndex(); client = getSearchIndexClientBuilder(INDEX_NAME).buildClient(); List<Document> rooms = new ArrayList<>(); rooms.add(new Document(Collections.singletonMap("baseRate", NaN))); Document indexedDoc = new Document(); indexedDoc.put("Hotel...
client.index(new IndexBatch<>().addUploadAction(expectedDoc));
public void getDynamicDocumentCannotAlwaysDetermineCorrectType() { createHotelIndex(); client = getSearchIndexClientBuilder(INDEX_NAME).buildClient(); Document indexedDoc = new Document(); indexedDoc.put("HotelId", "1"); indexedDoc.put("HotelName", "2015-02-11T12:58:00Z"); indexedDoc.put("Location", GeoPoint.create(40....
class LookupSyncTests extends LookupTestBase { private SearchIndexClient client; @Test public void canGetStaticallyTypedDocument() throws ParseException { createHotelIndex(); client = getSearchIndexClientBuilder(INDEX_NAME).buildClient(); Hotel expected = prepareExpectedHotel(); uploadDocument(client, expected); Docume...
class LookupSyncTests extends SearchIndexClientTestBase { private static final String INDEX_NAME = "hotels"; private SearchIndexClient client; @Test public void canGetStaticallyTypedDocument() throws ParseException { createHotelIndex(); client = getSearchIndexClientBuilder(INDEX_NAME).buildClient(); Hotel expected = pr...
Ah, right. Making changes in UserAgent one. Forgot to update here. Thanks!
private void getKeyClient(HttpClient httpClient, KeyServiceVersion serviceVersion) { HttpPipeline httpPipeline = getHttpPipeline(httpClient, serviceVersion); client = new KeyClientBuilder() .vaultUrl(getEndpoint()) .pipeline(httpPipeline) .buildClient(); }
.buildClient();
private void getKeyClient(HttpClient httpClient, KeyServiceVersion serviceVersion) { HttpPipeline httpPipeline = getHttpPipeline(httpClient, serviceVersion); client = new KeyClientBuilder() .vaultUrl(getEndpoint()) .pipeline(httpPipeline) .serviceVersion(serviceVersion) .buildClient(); }
class KeyClientTest extends KeyClientTestBase { private KeyClient client; @Override protected void beforeTest() { beforeTestSetup(); } /** * Tests that a key can be created in the key vault. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void setKey(HttpClient httpCl...
class KeyClientTest extends KeyClientTestBase { private KeyClient client; @Override protected void beforeTest() { beforeTestSetup(); } /** * Tests that a key can be created in the key vault. */ @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) @MethodSource("getTestParameters") public void setKey(HttpClient httpCl...
Using `indexDoc` now
public void getDynamicDocumentCannotAlwaysDetermineCorrectType() { createHotelIndex(); client = getSearchIndexClientBuilder(INDEX_NAME).buildClient(); List<Document> rooms = new ArrayList<>(); rooms.add(new Document(Collections.singletonMap("baseRate", NaN))); Document indexedDoc = new Document(); indexedDoc.put("Hotel...
client.index(new IndexBatch<>().addUploadAction(expectedDoc));
public void getDynamicDocumentCannotAlwaysDetermineCorrectType() { createHotelIndex(); client = getSearchIndexClientBuilder(INDEX_NAME).buildClient(); Document indexedDoc = new Document(); indexedDoc.put("HotelId", "1"); indexedDoc.put("HotelName", "2015-02-11T12:58:00Z"); indexedDoc.put("Location", GeoPoint.create(40....
class LookupSyncTests extends LookupTestBase { private SearchIndexClient client; @Test public void canGetStaticallyTypedDocument() throws ParseException { createHotelIndex(); client = getSearchIndexClientBuilder(INDEX_NAME).buildClient(); Hotel expected = prepareExpectedHotel(); uploadDocument(client, expected); Docume...
class LookupSyncTests extends SearchIndexClientTestBase { private static final String INDEX_NAME = "hotels"; private SearchIndexClient client; @Test public void canGetStaticallyTypedDocument() throws ParseException { createHotelIndex(); client = getSearchIndexClientBuilder(INDEX_NAME).buildClient(); Hotel expected = pr...
You might want to raise the exception with the inner error here when the error is null.
public Mono<DetectedLanguage> detectLanguage(String text, String countryHint) { return detectLanguageBatch(Collections.singletonList(text), countryHint, null) .map(documentCollection -> { final Iterator<DetectLanguageResult> iterator = documentCollection.iterator(); if (!iterator.hasNext()) { throw logger.logExceptionA...
throw logger.logExceptionAsError(Transforms.toTextAnalyticsException(languageResult.getError()));
public Mono<DetectedLanguage> detectLanguage(String text, String countryHint) { return detectLanguageBatch(Collections.singletonList(text), countryHint, null) .map(documentCollection -> { final Iterator<DetectLanguageResult> iterator = documentCollection.iterator(); if (!iterator.hasNext()) { throw logger.logExceptionA...
class TextAnalyticsAsyncClient { private final ClientLogger logger = new ClientLogger(TextAnalyticsAsyncClient.class); private final TextAnalyticsClientImpl service; private final TextAnalyticsServiceVersion serviceVersion; private final String defaultCountryHint; private final String defaultLanguage; final DetectLangu...
class TextAnalyticsAsyncClient { private final ClientLogger logger = new ClientLogger(TextAnalyticsAsyncClient.class); private final TextAnalyticsClientImpl service; private final TextAnalyticsServiceVersion serviceVersion; private final String defaultCountryHint; private final String defaultLanguage; final DetectLangu...
`documentCollection` 's error is either the `InnerError` or `TextAnalyticsError`. before calling .map(), the caller already take care of the scenario transform, such that ` ``` Mono<Response<DocumentResultCollection<DetectLanguageResult>>> detectLanguageBatchWithResponse() called toDocumentResultCollection() w...
public Mono<DetectedLanguage> detectLanguage(String text, String countryHint) { return detectLanguageBatch(Collections.singletonList(text), countryHint, null) .map(documentCollection -> { final Iterator<DetectLanguageResult> iterator = documentCollection.iterator(); if (!iterator.hasNext()) { throw logger.logExceptionA...
throw logger.logExceptionAsError(Transforms.toTextAnalyticsException(languageResult.getError()));
public Mono<DetectedLanguage> detectLanguage(String text, String countryHint) { return detectLanguageBatch(Collections.singletonList(text), countryHint, null) .map(documentCollection -> { final Iterator<DetectLanguageResult> iterator = documentCollection.iterator(); if (!iterator.hasNext()) { throw logger.logExceptionA...
class TextAnalyticsAsyncClient { private final ClientLogger logger = new ClientLogger(TextAnalyticsAsyncClient.class); private final TextAnalyticsClientImpl service; private final TextAnalyticsServiceVersion serviceVersion; private final String defaultCountryHint; private final String defaultLanguage; final DetectLangu...
class TextAnalyticsAsyncClient { private final ClientLogger logger = new ClientLogger(TextAnalyticsAsyncClient.class); private final TextAnalyticsClientImpl service; private final TextAnalyticsServiceVersion serviceVersion; private final String defaultCountryHint; private final String defaultLanguage; final DetectLangu...
We do this because there is another type with this name, right? is it the generated one? what is the difference between both?
private AnalyzeSentimentResult convertToAnalyzeSentimentResult(final DocumentSentiment documentSentiment) { final SentimentLabel documentSentimentLabel = SentimentLabel.fromString(documentSentiment. getSentiment().toString()); if (documentSentimentLabel == null) { logger.logExceptionAsWarning( new RuntimeException(Stri...
final com.azure.ai.textanalytics.implementation.models.SentimentConfidenceScorePerLabel
private AnalyzeSentimentResult convertToAnalyzeSentimentResult(final DocumentSentiment documentSentiment) { final SentimentLabel documentSentimentLabel = SentimentLabel.fromString(documentSentiment. getSentiment().toString()); if (documentSentimentLabel == null) { logger.logExceptionAsWarning( new RuntimeException(Stri...
class AnalyzeSentimentAsyncClient { private final ClientLogger logger = new ClientLogger(AnalyzeSentimentAsyncClient.class); private final TextAnalyticsClientImpl service; /** * Create a {@code AnalyzeSentimentAsyncClient} that sends requests to the Text Analytics services's sentiment * analysis endpoint. * * @param se...
class AnalyzeSentimentAsyncClient { private final ClientLogger logger = new ClientLogger(AnalyzeSentimentAsyncClient.class); private final TextAnalyticsClientImpl service; /** * Create a {@code AnalyzeSentimentAsyncClient} that sends requests to the Text Analytics services's sentiment * analysis endpoint. * * @param se...
Yes. There is one generated one. Auto-generated one has setter methods.
private AnalyzeSentimentResult convertToAnalyzeSentimentResult(final DocumentSentiment documentSentiment) { final SentimentLabel documentSentimentLabel = SentimentLabel.fromString(documentSentiment. getSentiment().toString()); if (documentSentimentLabel == null) { logger.logExceptionAsWarning( new RuntimeException(Stri...
final com.azure.ai.textanalytics.implementation.models.SentimentConfidenceScorePerLabel
private AnalyzeSentimentResult convertToAnalyzeSentimentResult(final DocumentSentiment documentSentiment) { final SentimentLabel documentSentimentLabel = SentimentLabel.fromString(documentSentiment. getSentiment().toString()); if (documentSentimentLabel == null) { logger.logExceptionAsWarning( new RuntimeException(Stri...
class AnalyzeSentimentAsyncClient { private final ClientLogger logger = new ClientLogger(AnalyzeSentimentAsyncClient.class); private final TextAnalyticsClientImpl service; /** * Create a {@code AnalyzeSentimentAsyncClient} that sends requests to the Text Analytics services's sentiment * analysis endpoint. * * @param se...
class AnalyzeSentimentAsyncClient { private final ClientLogger logger = new ClientLogger(AnalyzeSentimentAsyncClient.class); private final TextAnalyticsClientImpl service; /** * Create a {@code AnalyzeSentimentAsyncClient} that sends requests to the Text Analytics services's sentiment * analysis endpoint. * * @param se...
and why we can't use that one?
private AnalyzeSentimentResult convertToAnalyzeSentimentResult(final DocumentSentiment documentSentiment) { final SentimentLabel documentSentimentLabel = SentimentLabel.fromString(documentSentiment. getSentiment().toString()); if (documentSentimentLabel == null) { logger.logExceptionAsWarning( new RuntimeException(Stri...
final com.azure.ai.textanalytics.implementation.models.SentimentConfidenceScorePerLabel
private AnalyzeSentimentResult convertToAnalyzeSentimentResult(final DocumentSentiment documentSentiment) { final SentimentLabel documentSentimentLabel = SentimentLabel.fromString(documentSentiment. getSentiment().toString()); if (documentSentimentLabel == null) { logger.logExceptionAsWarning( new RuntimeException(Stri...
class AnalyzeSentimentAsyncClient { private final ClientLogger logger = new ClientLogger(AnalyzeSentimentAsyncClient.class); private final TextAnalyticsClientImpl service; /** * Create a {@code AnalyzeSentimentAsyncClient} that sends requests to the Text Analytics services's sentiment * analysis endpoint. * * @param se...
class AnalyzeSentimentAsyncClient { private final ClientLogger logger = new ClientLogger(AnalyzeSentimentAsyncClient.class); private final TextAnalyticsClientImpl service; /** * Create a {@code AnalyzeSentimentAsyncClient} that sends requests to the Text Analytics services's sentiment * analysis endpoint. * * @param se...
Is this the autogenerated one? why we use one here and in other places the one from `com.azure.ai.textanalytics.implementation.models.SentimentConfidenceScorePerLabel`
private AnalyzeSentimentResult convertToAnalyzeSentimentResult(final DocumentSentiment documentSentiment) { final SentimentLabel documentSentimentLabel = SentimentLabel.fromString(documentSentiment. getSentiment().toString()); if (documentSentimentLabel == null) { logger.logExceptionAsWarning( new RuntimeException(Stri...
new SentimentConfidenceScorePerLabel(confidenceScorePerSentence.getNegative(),
private AnalyzeSentimentResult convertToAnalyzeSentimentResult(final DocumentSentiment documentSentiment) { final SentimentLabel documentSentimentLabel = SentimentLabel.fromString(documentSentiment. getSentiment().toString()); if (documentSentimentLabel == null) { logger.logExceptionAsWarning( new RuntimeException(Stri...
class AnalyzeSentimentAsyncClient { private final ClientLogger logger = new ClientLogger(AnalyzeSentimentAsyncClient.class); private final TextAnalyticsClientImpl service; /** * Create a {@code AnalyzeSentimentAsyncClient} that sends requests to the Text Analytics services's sentiment * analysis endpoint. * * @param se...
class AnalyzeSentimentAsyncClient { private final ClientLogger logger = new ClientLogger(AnalyzeSentimentAsyncClient.class); private final TextAnalyticsClientImpl service; /** * Create a {@code AnalyzeSentimentAsyncClient} that sends requests to the Text Analytics services's sentiment * analysis endpoint. * * @param se...
It might be me and my limited knowledge of Java. It just seems strange how we are using for some things one and not other
private AnalyzeSentimentResult convertToAnalyzeSentimentResult(final DocumentSentiment documentSentiment) { final SentimentLabel documentSentimentLabel = SentimentLabel.fromString(documentSentiment. getSentiment().toString()); if (documentSentimentLabel == null) { logger.logExceptionAsWarning( new RuntimeException(Stri...
new SentimentConfidenceScorePerLabel(confidenceScorePerSentence.getNegative(),
private AnalyzeSentimentResult convertToAnalyzeSentimentResult(final DocumentSentiment documentSentiment) { final SentimentLabel documentSentimentLabel = SentimentLabel.fromString(documentSentiment. getSentiment().toString()); if (documentSentimentLabel == null) { logger.logExceptionAsWarning( new RuntimeException(Stri...
class AnalyzeSentimentAsyncClient { private final ClientLogger logger = new ClientLogger(AnalyzeSentimentAsyncClient.class); private final TextAnalyticsClientImpl service; /** * Create a {@code AnalyzeSentimentAsyncClient} that sends requests to the Text Analytics services's sentiment * analysis endpoint. * * @param se...
class AnalyzeSentimentAsyncClient { private final ClientLogger logger = new ClientLogger(AnalyzeSentimentAsyncClient.class); private final TextAnalyticsClientImpl service; /** * Create a {@code AnalyzeSentimentAsyncClient} that sends requests to the Text Analytics services's sentiment * analysis endpoint. * * @param se...
NIT: will never be empty
public Mono<DetectedLanguage> detectLanguage(String text, String countryHint) { return detectLanguageBatch(Collections.singletonList(text), countryHint, null) .map(documentCollection -> { final Iterator<DetectLanguageResult> iterator = documentCollection.iterator(); if (!iterator.hasNext()) { throw logger.logExceptionA...
public Mono<DetectedLanguage> detectLanguage(String text, String countryHint) { return detectLanguageBatch(Collections.singletonList(text), countryHint, null) .map(documentCollection -> { final Iterator<DetectLanguageResult> iterator = documentCollection.iterator(); if (!iterator.hasNext()) { throw logger.logExceptionA...
class TextAnalyticsAsyncClient { private final ClientLogger logger = new ClientLogger(TextAnalyticsAsyncClient.class); private final TextAnalyticsClientImpl service; private final TextAnalyticsServiceVersion serviceVersion; private final String defaultCountryHint; private final String defaultLanguage; final DetectLangu...
class TextAnalyticsAsyncClient { private final ClientLogger logger = new ClientLogger(TextAnalyticsAsyncClient.class); private final TextAnalyticsClientImpl service; private final TextAnalyticsServiceVersion serviceVersion; private final String defaultCountryHint; private final String defaultLanguage; final DetectLangu...
You don't want to explore the setter to users and it is bad to change auto-generated code. It could be removed when doing code-gene with some settings. Created an issue to regenerate code base: https://github.com/Azure/azure-sdk-for-java/issues/8344
private AnalyzeSentimentResult convertToAnalyzeSentimentResult(final DocumentSentiment documentSentiment) { final SentimentLabel documentSentimentLabel = SentimentLabel.fromString(documentSentiment. getSentiment().toString()); if (documentSentimentLabel == null) { logger.logExceptionAsWarning( new RuntimeException(Stri...
final com.azure.ai.textanalytics.implementation.models.SentimentConfidenceScorePerLabel
private AnalyzeSentimentResult convertToAnalyzeSentimentResult(final DocumentSentiment documentSentiment) { final SentimentLabel documentSentimentLabel = SentimentLabel.fromString(documentSentiment. getSentiment().toString()); if (documentSentimentLabel == null) { logger.logExceptionAsWarning( new RuntimeException(Stri...
class AnalyzeSentimentAsyncClient { private final ClientLogger logger = new ClientLogger(AnalyzeSentimentAsyncClient.class); private final TextAnalyticsClientImpl service; /** * Create a {@code AnalyzeSentimentAsyncClient} that sends requests to the Text Analytics services's sentiment * analysis endpoint. * * @param se...
class AnalyzeSentimentAsyncClient { private final ClientLogger logger = new ClientLogger(AnalyzeSentimentAsyncClient.class); private final TextAnalyticsClientImpl service; /** * Create a {@code AnalyzeSentimentAsyncClient} that sends requests to the Text Analytics services's sentiment * analysis endpoint. * * @param se...
This one is not autogenerated one and you don't want to explore an autogenerated class to user. Another place that using autogenerated one is for internal mapping to non-autogenerated class.
private AnalyzeSentimentResult convertToAnalyzeSentimentResult(final DocumentSentiment documentSentiment) { final SentimentLabel documentSentimentLabel = SentimentLabel.fromString(documentSentiment. getSentiment().toString()); if (documentSentimentLabel == null) { logger.logExceptionAsWarning( new RuntimeException(Stri...
new SentimentConfidenceScorePerLabel(confidenceScorePerSentence.getNegative(),
private AnalyzeSentimentResult convertToAnalyzeSentimentResult(final DocumentSentiment documentSentiment) { final SentimentLabel documentSentimentLabel = SentimentLabel.fromString(documentSentiment. getSentiment().toString()); if (documentSentimentLabel == null) { logger.logExceptionAsWarning( new RuntimeException(Stri...
class AnalyzeSentimentAsyncClient { private final ClientLogger logger = new ClientLogger(AnalyzeSentimentAsyncClient.class); private final TextAnalyticsClientImpl service; /** * Create a {@code AnalyzeSentimentAsyncClient} that sends requests to the Text Analytics services's sentiment * analysis endpoint. * * @param se...
class AnalyzeSentimentAsyncClient { private final ClientLogger logger = new ClientLogger(AnalyzeSentimentAsyncClient.class); private final TextAnalyticsClientImpl service; /** * Create a {@code AnalyzeSentimentAsyncClient} that sends requests to the Text Analytics services's sentiment * analysis endpoint. * * @param se...
is there a reason why there are so many format changes in the PR?
public void detectLanguage() { String inputText = "Bonjour tout le monde"; textAnalyticsAsyncClient.detectLanguage(inputText).subscribe(detectedLanguage -> System.out.printf("Detected language name: %s, ISO 6391 Name: %s, score: %.2f.%n", detectedLanguage.getName(), detectedLanguage.getIso6391Name(), detectedLanguage.g...
detectedLanguage.getName(), detectedLanguage.getIso6391Name(), detectedLanguage.getScore()));
public void detectLanguage() { String inputText = "Bonjour tout le monde"; textAnalyticsAsyncClient.detectLanguage(inputText).subscribe(detectedLanguage -> System.out.printf("Detected language name: %s, ISO 6391 Name: %s, score: %.2f.%n", detectedLanguage.getName(), detectedLanguage.getIso6391Name(), detectedLanguage.g...
class TextAnalyticsAsyncClientJavaDocCodeSnippets { TextAnalyticsAsyncClient textAnalyticsAsyncClient = createTextAnalyticsAsyncClient(); /** * Code snippet for creating a {@link TextAnalyticsAsyncClient} * * @return The TextAnalyticsAsyncClient object */ public TextAnalyticsAsyncClient createTextAnalyticsAsyncClient()...
class TextAnalyticsAsyncClientJavaDocCodeSnippets { TextAnalyticsAsyncClient textAnalyticsAsyncClient = createTextAnalyticsAsyncClient(); /** * Code snippet for creating a {@link TextAnalyticsAsyncClient} * * @return The TextAnalyticsAsyncClient object */ public TextAnalyticsAsyncClient createTextAnalyticsAsyncClient()...
short line. Java use a tool to embeded code to readme, so maintaining a short line number is better for user experience.
public void detectLanguage() { String inputText = "Bonjour tout le monde"; textAnalyticsAsyncClient.detectLanguage(inputText).subscribe(detectedLanguage -> System.out.printf("Detected language name: %s, ISO 6391 Name: %s, score: %.2f.%n", detectedLanguage.getName(), detectedLanguage.getIso6391Name(), detectedLanguage.g...
detectedLanguage.getName(), detectedLanguage.getIso6391Name(), detectedLanguage.getScore()));
public void detectLanguage() { String inputText = "Bonjour tout le monde"; textAnalyticsAsyncClient.detectLanguage(inputText).subscribe(detectedLanguage -> System.out.printf("Detected language name: %s, ISO 6391 Name: %s, score: %.2f.%n", detectedLanguage.getName(), detectedLanguage.getIso6391Name(), detectedLanguage.g...
class TextAnalyticsAsyncClientJavaDocCodeSnippets { TextAnalyticsAsyncClient textAnalyticsAsyncClient = createTextAnalyticsAsyncClient(); /** * Code snippet for creating a {@link TextAnalyticsAsyncClient} * * @return The TextAnalyticsAsyncClient object */ public TextAnalyticsAsyncClient createTextAnalyticsAsyncClient()...
class TextAnalyticsAsyncClientJavaDocCodeSnippets { TextAnalyticsAsyncClient textAnalyticsAsyncClient = createTextAnalyticsAsyncClient(); /** * Code snippet for creating a {@link TextAnalyticsAsyncClient} * * @return The TextAnalyticsAsyncClient object */ public TextAnalyticsAsyncClient createTextAnalyticsAsyncClient()...
ugh so confusing. Thanks for clarifying it Shawn :)
private AnalyzeSentimentResult convertToAnalyzeSentimentResult(final DocumentSentiment documentSentiment) { final SentimentLabel documentSentimentLabel = SentimentLabel.fromString(documentSentiment. getSentiment().toString()); if (documentSentimentLabel == null) { logger.logExceptionAsWarning( new RuntimeException(Stri...
new SentimentConfidenceScorePerLabel(confidenceScorePerSentence.getNegative(),
private AnalyzeSentimentResult convertToAnalyzeSentimentResult(final DocumentSentiment documentSentiment) { final SentimentLabel documentSentimentLabel = SentimentLabel.fromString(documentSentiment. getSentiment().toString()); if (documentSentimentLabel == null) { logger.logExceptionAsWarning( new RuntimeException(Stri...
class AnalyzeSentimentAsyncClient { private final ClientLogger logger = new ClientLogger(AnalyzeSentimentAsyncClient.class); private final TextAnalyticsClientImpl service; /** * Create a {@code AnalyzeSentimentAsyncClient} that sends requests to the Text Analytics services's sentiment * analysis endpoint. * * @param se...
class AnalyzeSentimentAsyncClient { private final ClientLogger logger = new ClientLogger(AnalyzeSentimentAsyncClient.class); private final TextAnalyticsClientImpl service; /** * Create a {@code AnalyzeSentimentAsyncClient} that sends requests to the Text Analytics services's sentiment * analysis endpoint. * * @param se...
Can you catch `Exception` here? We don't want any exception to be directly thrown
public Mono<AccessToken> getToken(TokenRequestContext request) { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId + "/"; if (pubClient == null) { try { PersistentTokenCacheAccessAspect accessAspect = new PersistentTokenCacheAccessAspect(); pubClient = PublicClientApplication.build...
} catch (IOException | PlatformNotSupportedException e) {
public Mono<AccessToken> getToken(TokenRequestContext request) { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId + "/"; if (pubClient == null) { try { PersistentTokenCacheAccessAspect accessAspect = new PersistentTokenCacheAccessAspect(); pubClient = PublicClientApplication.build...
class SharedTokenCacheCredential implements TokenCredential { private final String username; private final String clientId; private final String tenantId; private final IdentityClientOptions options; private PublicClientApplication pubClient = null; /** * Creates an instance of the Shared Token Cache Credential Provide...
class SharedTokenCacheCredential implements TokenCredential { private final String username; private final String clientId; private final String tenantId; private final IdentityClientOptions options; private PublicClientApplication pubClient = null; /** * Creates an instance of the Shared Token Cache Credential Provide...
done
public Mono<AccessToken> getToken(TokenRequestContext request) { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId + "/"; if (pubClient == null) { try { PersistentTokenCacheAccessAspect accessAspect = new PersistentTokenCacheAccessAspect(); pubClient = PublicClientApplication.build...
} catch (IOException | PlatformNotSupportedException e) {
public Mono<AccessToken> getToken(TokenRequestContext request) { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId + "/"; if (pubClient == null) { try { PersistentTokenCacheAccessAspect accessAspect = new PersistentTokenCacheAccessAspect(); pubClient = PublicClientApplication.build...
class SharedTokenCacheCredential implements TokenCredential { private final String username; private final String clientId; private final String tenantId; private final IdentityClientOptions options; private PublicClientApplication pubClient = null; /** * Creates an instance of the Shared Token Cache Credential Provide...
class SharedTokenCacheCredential implements TokenCredential { private final String username; private final String clientId; private final String tenantId; private final IdentityClientOptions options; private PublicClientApplication pubClient = null; /** * Creates an instance of the Shared Token Cache Credential Provide...
if the method takes the Context parameter, shouldn't it be `withResponse`?
public void handlingException() { List<DetectLanguageInput> inputs = Arrays.asList( new DetectLanguageInput("1", "This is written in English.", "us"), new DetectLanguageInput("1", "Este es un document escrito en Español.", "es") ); try { textAnalyticsClient.detectLanguageBatch(inputs, null, Context.NONE); } catch (Http...
textAnalyticsClient.detectLanguageBatch(inputs, null, Context.NONE);
public void handlingException() { List<DetectLanguageInput> inputs = Arrays.asList( new DetectLanguageInput("1", "This is written in English.", "us"), new DetectLanguageInput("1", "Este es un documento escrito en Español.", "es") ); try { textAnalyticsClient.detectLanguageBatch(inputs, null, Context.NONE); } catch (Ht...
class ReadmeSamples { private TextAnalyticsClient textAnalyticsClient = new TextAnalyticsClientBuilder().buildClient(); /** * Code snippet for configuring http client. */ public void configureHttpClient() { HttpClient client = new NettyAsyncHttpClientBuilder() .port(8080) .wiretap(true) .build(); } /** * Code snippet f...
class ReadmeSamples { private TextAnalyticsClient textAnalyticsClient = new TextAnalyticsClientBuilder().buildClient(); /** * Code snippet for configuring http client. */ public void configureHttpClient() { HttpClient client = new NettyAsyncHttpClientBuilder() .port(8080) .wiretap(true) .build(); } /** * Code snippet f...
There will be no "withResponse" for pagination. See the pagination example: https://azure.github.io/azure-sdk/java_design.html#pagination
public void handlingException() { List<DetectLanguageInput> inputs = Arrays.asList( new DetectLanguageInput("1", "This is written in English.", "us"), new DetectLanguageInput("1", "Este es un document escrito en Español.", "es") ); try { textAnalyticsClient.detectLanguageBatch(inputs, null, Context.NONE); } catch (Http...
textAnalyticsClient.detectLanguageBatch(inputs, null, Context.NONE);
public void handlingException() { List<DetectLanguageInput> inputs = Arrays.asList( new DetectLanguageInput("1", "This is written in English.", "us"), new DetectLanguageInput("1", "Este es un documento escrito en Español.", "es") ); try { textAnalyticsClient.detectLanguageBatch(inputs, null, Context.NONE); } catch (Ht...
class ReadmeSamples { private TextAnalyticsClient textAnalyticsClient = new TextAnalyticsClientBuilder().buildClient(); /** * Code snippet for configuring http client. */ public void configureHttpClient() { HttpClient client = new NettyAsyncHttpClientBuilder() .port(8080) .wiretap(true) .build(); } /** * Code snippet f...
class ReadmeSamples { private TextAnalyticsClient textAnalyticsClient = new TextAnalyticsClientBuilder().buildClient(); /** * Code snippet for configuring http client. */ public void configureHttpClient() { HttpClient client = new NettyAsyncHttpClientBuilder() .port(8080) .wiretap(true) .build(); } /** * Code snippet f...
where are we doing the initialization blocking call now? If the global endpoint manager is not fully initialized with first databaseAccount fetch could this return null?
private void initializeGatewayConfigurationReader() { this.gatewayConfigurationReader = new GatewayServiceConfigurationReader(this.serviceEndpoint, this.globalEndpointManager); DatabaseAccount databaseAccount = this.globalEndpointManager.getLatestDatabaseAccount(); this.useMultipleWriteLocations = this.connectionPolicy...
DatabaseAccount databaseAccount = this.globalEndpointManager.getLatestDatabaseAccount();
private void initializeGatewayConfigurationReader() { this.gatewayConfigurationReader = new GatewayServiceConfigurationReader(this.globalEndpointManager); DatabaseAccount databaseAccount = this.globalEndpointManager.getLatestDatabaseAccount(); assert(databaseAccount != null); this.useMultipleWriteLocations = this.conne...
class RxDocumentClientImpl implements AsyncDocumentClient, IAuthorizationTokenProvider { private final static ObjectMapper mapper = Utils.getSimpleObjectMapper(); private final Logger logger = LoggerFactory.getLogger(RxDocumentClientImpl.class); private final String masterKeyOrResourceToken; private final URI serviceEn...
class RxDocumentClientImpl implements AsyncDocumentClient, IAuthorizationTokenProvider { private final static ObjectMapper mapper = Utils.getSimpleObjectMapper(); private final Logger logger = LoggerFactory.getLogger(RxDocumentClientImpl.class); private final String masterKeyOrResourceToken; private final URI serviceEn...
there is a time window where GlobalEndpointManager is instantiated but hasn't fetched DatabaseAccount, within that period how do we ensure this never returns null?
public DatabaseAccount getLatestDatabaseAccount() { return this.latestDatabaseAccount; }
return this.latestDatabaseAccount;
public DatabaseAccount getLatestDatabaseAccount() { return this.latestDatabaseAccount; }
class GlobalEndpointManager implements AutoCloseable { private static final Logger logger = LoggerFactory.getLogger(GlobalEndpointManager.class); private final int backgroundRefreshLocationTimeIntervalInMS; private final LocationCache locationCache; private final URI defaultEndpoint; private final ConnectionPolicy conn...
class GlobalEndpointManager implements AutoCloseable { private static final Logger logger = LoggerFactory.getLogger(GlobalEndpointManager.class); private final int backgroundRefreshLocationTimeIntervalInMS; private final LocationCache locationCache; private final URI defaultEndpoint; private final ConnectionPolicy conn...
GatewayServiceConfigurationReader constructor is doing blocking call on async cache , so for first time if cache in null it will hit the BE
private void initializeGatewayConfigurationReader() { this.gatewayConfigurationReader = new GatewayServiceConfigurationReader(this.serviceEndpoint, this.globalEndpointManager); DatabaseAccount databaseAccount = this.globalEndpointManager.getLatestDatabaseAccount(); this.useMultipleWriteLocations = this.connectionPolicy...
DatabaseAccount databaseAccount = this.globalEndpointManager.getLatestDatabaseAccount();
private void initializeGatewayConfigurationReader() { this.gatewayConfigurationReader = new GatewayServiceConfigurationReader(this.globalEndpointManager); DatabaseAccount databaseAccount = this.globalEndpointManager.getLatestDatabaseAccount(); assert(databaseAccount != null); this.useMultipleWriteLocations = this.conne...
class RxDocumentClientImpl implements AsyncDocumentClient, IAuthorizationTokenProvider { private final static ObjectMapper mapper = Utils.getSimpleObjectMapper(); private final Logger logger = LoggerFactory.getLogger(RxDocumentClientImpl.class); private final String masterKeyOrResourceToken; private final URI serviceEn...
class RxDocumentClientImpl implements AsyncDocumentClient, IAuthorizationTokenProvider { private final static ObjectMapper mapper = Utils.getSimpleObjectMapper(); private final Logger logger = LoggerFactory.getLogger(RxDocumentClientImpl.class); private final String masterKeyOrResourceToken; private final URI serviceEn...
We are calling init on GlobalEndpointManager from RxDocumentClientImpl which will update this value , any future call if return null due to any exception or error we will not update latestDatabaseAccount and async cahce , they will hold the previous not null value
public DatabaseAccount getLatestDatabaseAccount() { return this.latestDatabaseAccount; }
return this.latestDatabaseAccount;
public DatabaseAccount getLatestDatabaseAccount() { return this.latestDatabaseAccount; }
class GlobalEndpointManager implements AutoCloseable { private static final Logger logger = LoggerFactory.getLogger(GlobalEndpointManager.class); private final int backgroundRefreshLocationTimeIntervalInMS; private final LocationCache locationCache; private final URI defaultEndpoint; private final ConnectionPolicy conn...
class GlobalEndpointManager implements AutoCloseable { private static final Logger logger = LoggerFactory.getLogger(GlobalEndpointManager.class); private final int backgroundRefreshLocationTimeIntervalInMS; private final LocationCache locationCache; private final URI defaultEndpoint; private final ConnectionPolicy conn...
Please document the new API saying what you said above.
public DatabaseAccount getLatestDatabaseAccount() { return this.latestDatabaseAccount; }
return this.latestDatabaseAccount;
public DatabaseAccount getLatestDatabaseAccount() { return this.latestDatabaseAccount; }
class GlobalEndpointManager implements AutoCloseable { private static final Logger logger = LoggerFactory.getLogger(GlobalEndpointManager.class); private final int backgroundRefreshLocationTimeIntervalInMS; private final LocationCache locationCache; private final URI defaultEndpoint; private final ConnectionPolicy conn...
class GlobalEndpointManager implements AutoCloseable { private static final Logger logger = LoggerFactory.getLogger(GlobalEndpointManager.class); private final int backgroundRefreshLocationTimeIntervalInMS; private final LocationCache locationCache; private final URI defaultEndpoint; private final ConnectionPolicy conn...