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 |
|---|---|---|---|---|---|
I don't think a random nonce (even generated by a cryptographic RNG) is considered secure with AESGCM. Because of this I believe we decided not to do any local AESGCM encryption and always defer to the service. @heaths could you confirm? | Mono<EncryptResult> encryptAsync(EncryptOptions encryptOptions, Context context, JsonWebKey jsonWebKey) {
this.key = getKey(jsonWebKey);
if (key == null || key.length == 0) {
throw logger.logExceptionAsError(new IllegalArgumentException("Key is empty."));
}
EncryptionAlgorithm algorithm = encryptOptions.getAlgorithm();
Algorithm baseAlgorithm = AlgorithmResolver.DEFAULT.get(algorithm.toString());
if (!(baseAlgorithm instanceof SymmetricEncryptionAlgorithm)) {
return Mono.error(new NoSuchAlgorithmException(algorithm.toString()));
}
SymmetricEncryptionAlgorithm symmetricEncryptionAlgorithm = (SymmetricEncryptionAlgorithm) baseAlgorithm;
ICryptoTransform transform;
byte[] iv = encryptOptions.getIv();
byte[] additionalAuthenticatedData = encryptOptions.getAdditionalAuthenticatedData();
if (iv == null) {
if (isGcm(algorithm)) {
iv = generateRandomByteArray(GCM_NONCE_SIZE);
} else if (isAes(algorithm)) {
iv = generateRandomByteArray(AES_BLOCK_SIZE);
} else {
throw logger.logExceptionAsError(
new IllegalStateException("Encryption algorithm provided is not supported: " + algorithm));
}
}
try {
transform = symmetricEncryptionAlgorithm.createEncryptor(this.key, iv, additionalAuthenticatedData,
null);
} catch (Exception e) {
return Mono.error(e);
}
byte[] encrypted;
try {
encrypted = transform.doFinal(encryptOptions.getPlainText());
} catch (Exception e) {
return Mono.error(e);
}
byte[] cipherText;
byte[] authenticationTag;
if (isGcm(algorithm)) {
cipherText = Arrays.copyOfRange(encrypted, 0, encryptOptions.getPlainText().length);
authenticationTag = Arrays.copyOfRange(encrypted, encryptOptions.getPlainText().length, encrypted.length);
} else if (isAes(algorithm)) {
cipherText = encrypted;
authenticationTag = null;
} else {
throw logger.logExceptionAsError(
new IllegalStateException("Encryption algorithm provided is not supported: " + algorithm));
}
return Mono.just(new EncryptResult(cipherText, algorithm, jsonWebKey.getId(), iv, additionalAuthenticatedData,
authenticationTag));
} | iv = generateRandomByteArray(GCM_NONCE_SIZE); | Mono<EncryptResult> encryptAsync(EncryptOptions encryptOptions, Context context, JsonWebKey jsonWebKey) {
this.key = getKey(jsonWebKey);
if (key == null || key.length == 0) {
throw logger.logExceptionAsError(new IllegalArgumentException("Key is empty."));
}
EncryptionAlgorithm algorithm = encryptOptions.getAlgorithm();
Algorithm baseAlgorithm = AlgorithmResolver.DEFAULT.get(algorithm.toString());
if (!(baseAlgorithm instanceof SymmetricEncryptionAlgorithm)) {
return Mono.error(new NoSuchAlgorithmException(algorithm.toString()));
}
SymmetricEncryptionAlgorithm symmetricEncryptionAlgorithm = (SymmetricEncryptionAlgorithm) baseAlgorithm;
ICryptoTransform transform;
byte[] iv = encryptOptions.getIv();
byte[] additionalAuthenticatedData = encryptOptions.getAdditionalAuthenticatedData();
if (iv == null) {
if (isGcm(algorithm)) {
iv = generateRandomByteArray(GCM_NONCE_SIZE);
} else if (isAes(algorithm)) {
iv = generateRandomByteArray(AES_BLOCK_SIZE);
} else {
throw logger.logExceptionAsError(
new IllegalStateException("Encryption algorithm provided is not supported: " + algorithm));
}
}
try {
transform = symmetricEncryptionAlgorithm.createEncryptor(this.key, iv, additionalAuthenticatedData,
null);
} catch (Exception e) {
return Mono.error(e);
}
byte[] encrypted;
try {
encrypted = transform.doFinal(encryptOptions.getPlainText());
} catch (Exception e) {
return Mono.error(e);
}
byte[] cipherText;
byte[] authenticationTag;
if (isGcm(algorithm)) {
cipherText = Arrays.copyOfRange(encrypted, 0, encryptOptions.getPlainText().length);
authenticationTag = Arrays.copyOfRange(encrypted, encryptOptions.getPlainText().length, encrypted.length);
} else if (isAes(algorithm)) {
cipherText = encrypted;
authenticationTag = null;
} else {
throw logger.logExceptionAsError(
new IllegalStateException("Encryption algorithm provided is not supported: " + algorithm));
}
return Mono.just(new EncryptResult(cipherText, algorithm, jsonWebKey.getId(), iv, additionalAuthenticatedData,
authenticationTag));
} | class SymmetricKeyCryptographyClient extends LocalKeyCryptographyClient {
static final int AES_BLOCK_SIZE = 16;
static final int GCM_NONCE_SIZE = 12;
private final ClientLogger logger = new ClientLogger(SymmetricKeyCryptographyClient.class);
private byte[] key;
/**
* Creates a {@link SymmetricKeyCryptographyClient} to perform local cryptography operations.
*
* @param serviceClient The client to route the requests through.
*/
SymmetricKeyCryptographyClient(CryptographyServiceClient serviceClient) {
super(serviceClient);
}
SymmetricKeyCryptographyClient(JsonWebKey key, CryptographyServiceClient serviceClient) {
super(serviceClient);
this.key = key.toAes().getEncoded();
}
private byte[] getKey(JsonWebKey key) {
if (this.key == null) {
this.key = key.toAes().getEncoded();
}
return this.key;
}
@Override
@Override
Mono<DecryptResult> decryptAsync(DecryptOptions decryptOptions, Context context, JsonWebKey jsonWebKey) {
this.key = getKey(jsonWebKey);
if (key == null || key.length == 0) {
throw logger.logExceptionAsError(new IllegalArgumentException("Key is empty."));
}
EncryptionAlgorithm algorithm = decryptOptions.getAlgorithm();
Algorithm baseAlgorithm = AlgorithmResolver.DEFAULT.get(algorithm.toString());
if (!(baseAlgorithm instanceof SymmetricEncryptionAlgorithm)) {
return Mono.error(new NoSuchAlgorithmException(algorithm.toString()));
}
SymmetricEncryptionAlgorithm symmetricEncryptionAlgorithm = (SymmetricEncryptionAlgorithm) baseAlgorithm;
ICryptoTransform transform;
byte[] iv = Objects.requireNonNull(decryptOptions.getIv(), "Initialization vector cannot be null in local decryption operations.");
byte[] additionalAuthenticatedData = decryptOptions.getAdditionalAuthenticatedData();
byte[] authenticationTag = decryptOptions.getAuthenticationTag();
try {
transform = symmetricEncryptionAlgorithm.createDecryptor(this.key, iv, additionalAuthenticatedData, authenticationTag);
} catch (Exception e) {
return Mono.error(e);
}
byte[] decrypted;
byte[] cipherText;
if (isGcm(algorithm)) {
cipherText = new byte[decryptOptions.getCipherText().length + authenticationTag.length];
System.arraycopy(decryptOptions.getCipherText(), 0, cipherText, 0, decryptOptions.getCipherText().length);
System.arraycopy(authenticationTag, 0, cipherText, decryptOptions.getCipherText().length, authenticationTag.length);
} else if (isAes(algorithm)) {
cipherText = decryptOptions.getCipherText();
} else {
throw logger.logExceptionAsError(
new IllegalStateException("Encryption algorithm provided is not supported: " + algorithm));
}
try {
decrypted = transform.doFinal(cipherText);
} catch (Exception e) {
return Mono.error(e);
}
return Mono.just(new DecryptResult(decrypted, algorithm, jsonWebKey.getId()));
}
@Override
Mono<SignResult> signAsync(SignatureAlgorithm algorithm, byte[] digest, Context context, JsonWebKey key) {
return Mono.error(new UnsupportedOperationException("Sign operation not supported for OCT/Symmetric key"));
}
@Override
Mono<VerifyResult> verifyAsync(SignatureAlgorithm algorithm, byte[] digest, byte[] signature, Context context,
JsonWebKey key) {
return Mono.error(new UnsupportedOperationException("Verify operation not supported for OCT/Symmetric key"));
}
@Override
Mono<WrapResult> wrapKeyAsync(KeyWrapAlgorithm algorithm, byte[] key, Context context, JsonWebKey jsonWebKey) {
this.key = getKey(jsonWebKey);
if (key == null || key.length == 0) {
throw logger.logExceptionAsError(new IllegalArgumentException("key"));
}
Algorithm baseAlgorithm = AlgorithmResolver.DEFAULT.get(algorithm.toString());
if (!(baseAlgorithm instanceof LocalKeyWrapAlgorithm)) {
return Mono.error(new NoSuchAlgorithmException(algorithm.toString()));
}
LocalKeyWrapAlgorithm localKeyWrapAlgorithm = (LocalKeyWrapAlgorithm) baseAlgorithm;
ICryptoTransform transform;
try {
transform = localKeyWrapAlgorithm.createEncryptor(this.key, null, null);
} catch (Exception e) {
return Mono.error(e);
}
byte[] encrypted;
try {
encrypted = transform.doFinal(key);
} catch (Exception e) {
return Mono.error(e);
}
return Mono.just(new WrapResult(encrypted, algorithm, jsonWebKey.getId()));
}
@Override
Mono<UnwrapResult> unwrapKeyAsync(KeyWrapAlgorithm algorithm, byte[] encryptedKey, Context context, JsonWebKey jsonWebKey) {
this.key = getKey(jsonWebKey);
Algorithm baseAlgorithm = AlgorithmResolver.DEFAULT.get(algorithm.toString());
if (!(baseAlgorithm instanceof LocalKeyWrapAlgorithm)) {
return Mono.error(new NoSuchAlgorithmException(algorithm.toString()));
}
LocalKeyWrapAlgorithm localKeyWrapAlgorithm = (LocalKeyWrapAlgorithm) baseAlgorithm;
ICryptoTransform transform;
try {
transform = localKeyWrapAlgorithm.createDecryptor(this.key, null, null);
} catch (Exception e) {
return Mono.error(e);
}
byte[] decrypted;
try {
decrypted = transform.doFinal(encryptedKey);
} catch (Exception e) {
return Mono.error(e);
}
return Mono.just(new UnwrapResult(decrypted, algorithm, jsonWebKey.getId()));
}
@Override
Mono<SignResult> signDataAsync(SignatureAlgorithm algorithm, byte[] data, Context context, JsonWebKey key) {
return signAsync(algorithm, data, context, key);
}
@Override
Mono<VerifyResult> verifyDataAsync(SignatureAlgorithm algorithm, byte[] data, byte[] signature, Context context,
JsonWebKey key) {
return verifyAsync(algorithm, data, signature, context, key);
}
private byte[] generateRandomByteArray(int sizeInBytes) {
byte[] iv = new byte[0];
SecureRandom randomSecureRandom;
try {
randomSecureRandom = SecureRandom.getInstance("SHA1PRNG");
iv = new byte[sizeInBytes];
randomSecureRandom.nextBytes(iv);
} catch (NoSuchAlgorithmException e) {
logger.logThrowableAsError(e);
}
return iv;
}
private boolean isGcm(EncryptionAlgorithm encryptionAlgorithm) {
return (encryptionAlgorithm == EncryptionAlgorithm.A128GCM
|| encryptionAlgorithm == EncryptionAlgorithm.A192GCM
|| encryptionAlgorithm == EncryptionAlgorithm.A256GCM);
}
private boolean isAes(EncryptionAlgorithm encryptionAlgorithm) {
return (encryptionAlgorithm == EncryptionAlgorithm.A128CBC
|| encryptionAlgorithm == EncryptionAlgorithm.A192CBC
|| encryptionAlgorithm == EncryptionAlgorithm.A256CBC
|| encryptionAlgorithm == EncryptionAlgorithm.A128CBCPAD
|| encryptionAlgorithm == EncryptionAlgorithm.A192CBCPAD
|| encryptionAlgorithm == EncryptionAlgorithm.A256CBCPAD);
}
} | class SymmetricKeyCryptographyClient extends LocalKeyCryptographyClient {
static final int AES_BLOCK_SIZE = 16;
static final int GCM_NONCE_SIZE = 12;
private final ClientLogger logger = new ClientLogger(SymmetricKeyCryptographyClient.class);
private byte[] key;
/**
* Creates a {@link SymmetricKeyCryptographyClient} to perform local cryptography operations.
*
* @param serviceClient The client to route the requests through.
*/
SymmetricKeyCryptographyClient(CryptographyServiceClient serviceClient) {
super(serviceClient);
}
SymmetricKeyCryptographyClient(JsonWebKey key, CryptographyServiceClient serviceClient) {
super(serviceClient);
this.key = key.toAes().getEncoded();
}
private byte[] getKey(JsonWebKey key) {
if (this.key == null) {
this.key = key.toAes().getEncoded();
}
return this.key;
}
@Override
@Override
Mono<DecryptResult> decryptAsync(DecryptOptions decryptOptions, Context context, JsonWebKey jsonWebKey) {
this.key = getKey(jsonWebKey);
if (key == null || key.length == 0) {
throw logger.logExceptionAsError(new IllegalArgumentException("Key is empty."));
}
EncryptionAlgorithm algorithm = decryptOptions.getAlgorithm();
Algorithm baseAlgorithm = AlgorithmResolver.DEFAULT.get(algorithm.toString());
if (!(baseAlgorithm instanceof SymmetricEncryptionAlgorithm)) {
return Mono.error(new NoSuchAlgorithmException(algorithm.toString()));
}
SymmetricEncryptionAlgorithm symmetricEncryptionAlgorithm = (SymmetricEncryptionAlgorithm) baseAlgorithm;
ICryptoTransform transform;
byte[] iv = Objects.requireNonNull(decryptOptions.getIv(), "Initialization vector cannot be null in local decryption operations.");
byte[] additionalAuthenticatedData = decryptOptions.getAdditionalAuthenticatedData();
byte[] authenticationTag = decryptOptions.getAuthenticationTag();
try {
transform = symmetricEncryptionAlgorithm.createDecryptor(this.key, iv, additionalAuthenticatedData, authenticationTag);
} catch (Exception e) {
return Mono.error(e);
}
byte[] decrypted;
byte[] cipherText;
if (isGcm(algorithm)) {
cipherText = new byte[decryptOptions.getCipherText().length + authenticationTag.length];
System.arraycopy(decryptOptions.getCipherText(), 0, cipherText, 0, decryptOptions.getCipherText().length);
System.arraycopy(authenticationTag, 0, cipherText, decryptOptions.getCipherText().length, authenticationTag.length);
} else if (isAes(algorithm)) {
cipherText = decryptOptions.getCipherText();
} else {
throw logger.logExceptionAsError(
new IllegalStateException("Encryption algorithm provided is not supported: " + algorithm));
}
try {
decrypted = transform.doFinal(cipherText);
} catch (Exception e) {
return Mono.error(e);
}
return Mono.just(new DecryptResult(decrypted, algorithm, jsonWebKey.getId()));
}
@Override
Mono<SignResult> signAsync(SignatureAlgorithm algorithm, byte[] digest, Context context, JsonWebKey key) {
return Mono.error(new UnsupportedOperationException("Sign operation not supported for OCT/Symmetric key"));
}
@Override
Mono<VerifyResult> verifyAsync(SignatureAlgorithm algorithm, byte[] digest, byte[] signature, Context context,
JsonWebKey key) {
return Mono.error(new UnsupportedOperationException("Verify operation not supported for OCT/Symmetric key"));
}
@Override
Mono<WrapResult> wrapKeyAsync(KeyWrapAlgorithm algorithm, byte[] key, Context context, JsonWebKey jsonWebKey) {
this.key = getKey(jsonWebKey);
if (key == null || key.length == 0) {
throw logger.logExceptionAsError(new IllegalArgumentException("key"));
}
Algorithm baseAlgorithm = AlgorithmResolver.DEFAULT.get(algorithm.toString());
if (!(baseAlgorithm instanceof LocalKeyWrapAlgorithm)) {
return Mono.error(new NoSuchAlgorithmException(algorithm.toString()));
}
LocalKeyWrapAlgorithm localKeyWrapAlgorithm = (LocalKeyWrapAlgorithm) baseAlgorithm;
ICryptoTransform transform;
try {
transform = localKeyWrapAlgorithm.createEncryptor(this.key, null, null);
} catch (Exception e) {
return Mono.error(e);
}
byte[] encrypted;
try {
encrypted = transform.doFinal(key);
} catch (Exception e) {
return Mono.error(e);
}
return Mono.just(new WrapResult(encrypted, algorithm, jsonWebKey.getId()));
}
@Override
Mono<UnwrapResult> unwrapKeyAsync(KeyWrapAlgorithm algorithm, byte[] encryptedKey, Context context, JsonWebKey jsonWebKey) {
this.key = getKey(jsonWebKey);
Algorithm baseAlgorithm = AlgorithmResolver.DEFAULT.get(algorithm.toString());
if (!(baseAlgorithm instanceof LocalKeyWrapAlgorithm)) {
return Mono.error(new NoSuchAlgorithmException(algorithm.toString()));
}
LocalKeyWrapAlgorithm localKeyWrapAlgorithm = (LocalKeyWrapAlgorithm) baseAlgorithm;
ICryptoTransform transform;
try {
transform = localKeyWrapAlgorithm.createDecryptor(this.key, null, null);
} catch (Exception e) {
return Mono.error(e);
}
byte[] decrypted;
try {
decrypted = transform.doFinal(encryptedKey);
} catch (Exception e) {
return Mono.error(e);
}
return Mono.just(new UnwrapResult(decrypted, algorithm, jsonWebKey.getId()));
}
@Override
Mono<SignResult> signDataAsync(SignatureAlgorithm algorithm, byte[] data, Context context, JsonWebKey key) {
return signAsync(algorithm, data, context, key);
}
@Override
Mono<VerifyResult> verifyDataAsync(SignatureAlgorithm algorithm, byte[] data, byte[] signature, Context context,
JsonWebKey key) {
return verifyAsync(algorithm, data, signature, context, key);
}
private byte[] generateRandomByteArray(int sizeInBytes) {
byte[] iv = new byte[0];
SecureRandom randomSecureRandom;
try {
randomSecureRandom = SecureRandom.getInstance("SHA1PRNG");
iv = new byte[sizeInBytes];
randomSecureRandom.nextBytes(iv);
} catch (NoSuchAlgorithmException e) {
logger.logThrowableAsError(e);
}
return iv;
}
private boolean isGcm(EncryptionAlgorithm encryptionAlgorithm) {
return (encryptionAlgorithm == EncryptionAlgorithm.A128GCM
|| encryptionAlgorithm == EncryptionAlgorithm.A192GCM
|| encryptionAlgorithm == EncryptionAlgorithm.A256GCM);
}
private boolean isAes(EncryptionAlgorithm encryptionAlgorithm) {
return (encryptionAlgorithm == EncryptionAlgorithm.A128CBC
|| encryptionAlgorithm == EncryptionAlgorithm.A192CBC
|| encryptionAlgorithm == EncryptionAlgorithm.A256CBC
|| encryptionAlgorithm == EncryptionAlgorithm.A128CBCPAD
|| encryptionAlgorithm == EncryptionAlgorithm.A192CBCPAD
|| encryptionAlgorithm == EncryptionAlgorithm.A256CBCPAD);
}
} |
You are right, I just talked to Heath and he confirmed this, thanks! | Mono<EncryptResult> encryptAsync(EncryptOptions encryptOptions, Context context, JsonWebKey jsonWebKey) {
this.key = getKey(jsonWebKey);
if (key == null || key.length == 0) {
throw logger.logExceptionAsError(new IllegalArgumentException("Key is empty."));
}
EncryptionAlgorithm algorithm = encryptOptions.getAlgorithm();
Algorithm baseAlgorithm = AlgorithmResolver.DEFAULT.get(algorithm.toString());
if (!(baseAlgorithm instanceof SymmetricEncryptionAlgorithm)) {
return Mono.error(new NoSuchAlgorithmException(algorithm.toString()));
}
SymmetricEncryptionAlgorithm symmetricEncryptionAlgorithm = (SymmetricEncryptionAlgorithm) baseAlgorithm;
ICryptoTransform transform;
byte[] iv = encryptOptions.getIv();
byte[] additionalAuthenticatedData = encryptOptions.getAdditionalAuthenticatedData();
if (iv == null) {
if (isGcm(algorithm)) {
iv = generateRandomByteArray(GCM_NONCE_SIZE);
} else if (isAes(algorithm)) {
iv = generateRandomByteArray(AES_BLOCK_SIZE);
} else {
throw logger.logExceptionAsError(
new IllegalStateException("Encryption algorithm provided is not supported: " + algorithm));
}
}
try {
transform = symmetricEncryptionAlgorithm.createEncryptor(this.key, iv, additionalAuthenticatedData,
null);
} catch (Exception e) {
return Mono.error(e);
}
byte[] encrypted;
try {
encrypted = transform.doFinal(encryptOptions.getPlainText());
} catch (Exception e) {
return Mono.error(e);
}
byte[] cipherText;
byte[] authenticationTag;
if (isGcm(algorithm)) {
cipherText = Arrays.copyOfRange(encrypted, 0, encryptOptions.getPlainText().length);
authenticationTag = Arrays.copyOfRange(encrypted, encryptOptions.getPlainText().length, encrypted.length);
} else if (isAes(algorithm)) {
cipherText = encrypted;
authenticationTag = null;
} else {
throw logger.logExceptionAsError(
new IllegalStateException("Encryption algorithm provided is not supported: " + algorithm));
}
return Mono.just(new EncryptResult(cipherText, algorithm, jsonWebKey.getId(), iv, additionalAuthenticatedData,
authenticationTag));
} | iv = generateRandomByteArray(GCM_NONCE_SIZE); | Mono<EncryptResult> encryptAsync(EncryptOptions encryptOptions, Context context, JsonWebKey jsonWebKey) {
this.key = getKey(jsonWebKey);
if (key == null || key.length == 0) {
throw logger.logExceptionAsError(new IllegalArgumentException("Key is empty."));
}
EncryptionAlgorithm algorithm = encryptOptions.getAlgorithm();
Algorithm baseAlgorithm = AlgorithmResolver.DEFAULT.get(algorithm.toString());
if (!(baseAlgorithm instanceof SymmetricEncryptionAlgorithm)) {
return Mono.error(new NoSuchAlgorithmException(algorithm.toString()));
}
SymmetricEncryptionAlgorithm symmetricEncryptionAlgorithm = (SymmetricEncryptionAlgorithm) baseAlgorithm;
ICryptoTransform transform;
byte[] iv = encryptOptions.getIv();
byte[] additionalAuthenticatedData = encryptOptions.getAdditionalAuthenticatedData();
if (iv == null) {
if (isGcm(algorithm)) {
iv = generateRandomByteArray(GCM_NONCE_SIZE);
} else if (isAes(algorithm)) {
iv = generateRandomByteArray(AES_BLOCK_SIZE);
} else {
throw logger.logExceptionAsError(
new IllegalStateException("Encryption algorithm provided is not supported: " + algorithm));
}
}
try {
transform = symmetricEncryptionAlgorithm.createEncryptor(this.key, iv, additionalAuthenticatedData,
null);
} catch (Exception e) {
return Mono.error(e);
}
byte[] encrypted;
try {
encrypted = transform.doFinal(encryptOptions.getPlainText());
} catch (Exception e) {
return Mono.error(e);
}
byte[] cipherText;
byte[] authenticationTag;
if (isGcm(algorithm)) {
cipherText = Arrays.copyOfRange(encrypted, 0, encryptOptions.getPlainText().length);
authenticationTag = Arrays.copyOfRange(encrypted, encryptOptions.getPlainText().length, encrypted.length);
} else if (isAes(algorithm)) {
cipherText = encrypted;
authenticationTag = null;
} else {
throw logger.logExceptionAsError(
new IllegalStateException("Encryption algorithm provided is not supported: " + algorithm));
}
return Mono.just(new EncryptResult(cipherText, algorithm, jsonWebKey.getId(), iv, additionalAuthenticatedData,
authenticationTag));
} | class SymmetricKeyCryptographyClient extends LocalKeyCryptographyClient {
static final int AES_BLOCK_SIZE = 16;
static final int GCM_NONCE_SIZE = 12;
private final ClientLogger logger = new ClientLogger(SymmetricKeyCryptographyClient.class);
private byte[] key;
/**
* Creates a {@link SymmetricKeyCryptographyClient} to perform local cryptography operations.
*
* @param serviceClient The client to route the requests through.
*/
SymmetricKeyCryptographyClient(CryptographyServiceClient serviceClient) {
super(serviceClient);
}
SymmetricKeyCryptographyClient(JsonWebKey key, CryptographyServiceClient serviceClient) {
super(serviceClient);
this.key = key.toAes().getEncoded();
}
private byte[] getKey(JsonWebKey key) {
if (this.key == null) {
this.key = key.toAes().getEncoded();
}
return this.key;
}
@Override
@Override
Mono<DecryptResult> decryptAsync(DecryptOptions decryptOptions, Context context, JsonWebKey jsonWebKey) {
this.key = getKey(jsonWebKey);
if (key == null || key.length == 0) {
throw logger.logExceptionAsError(new IllegalArgumentException("Key is empty."));
}
EncryptionAlgorithm algorithm = decryptOptions.getAlgorithm();
Algorithm baseAlgorithm = AlgorithmResolver.DEFAULT.get(algorithm.toString());
if (!(baseAlgorithm instanceof SymmetricEncryptionAlgorithm)) {
return Mono.error(new NoSuchAlgorithmException(algorithm.toString()));
}
SymmetricEncryptionAlgorithm symmetricEncryptionAlgorithm = (SymmetricEncryptionAlgorithm) baseAlgorithm;
ICryptoTransform transform;
byte[] iv = Objects.requireNonNull(decryptOptions.getIv(), "Initialization vector cannot be null in local decryption operations.");
byte[] additionalAuthenticatedData = decryptOptions.getAdditionalAuthenticatedData();
byte[] authenticationTag = decryptOptions.getAuthenticationTag();
try {
transform = symmetricEncryptionAlgorithm.createDecryptor(this.key, iv, additionalAuthenticatedData, authenticationTag);
} catch (Exception e) {
return Mono.error(e);
}
byte[] decrypted;
byte[] cipherText;
if (isGcm(algorithm)) {
cipherText = new byte[decryptOptions.getCipherText().length + authenticationTag.length];
System.arraycopy(decryptOptions.getCipherText(), 0, cipherText, 0, decryptOptions.getCipherText().length);
System.arraycopy(authenticationTag, 0, cipherText, decryptOptions.getCipherText().length, authenticationTag.length);
} else if (isAes(algorithm)) {
cipherText = decryptOptions.getCipherText();
} else {
throw logger.logExceptionAsError(
new IllegalStateException("Encryption algorithm provided is not supported: " + algorithm));
}
try {
decrypted = transform.doFinal(cipherText);
} catch (Exception e) {
return Mono.error(e);
}
return Mono.just(new DecryptResult(decrypted, algorithm, jsonWebKey.getId()));
}
@Override
Mono<SignResult> signAsync(SignatureAlgorithm algorithm, byte[] digest, Context context, JsonWebKey key) {
return Mono.error(new UnsupportedOperationException("Sign operation not supported for OCT/Symmetric key"));
}
@Override
Mono<VerifyResult> verifyAsync(SignatureAlgorithm algorithm, byte[] digest, byte[] signature, Context context,
JsonWebKey key) {
return Mono.error(new UnsupportedOperationException("Verify operation not supported for OCT/Symmetric key"));
}
@Override
Mono<WrapResult> wrapKeyAsync(KeyWrapAlgorithm algorithm, byte[] key, Context context, JsonWebKey jsonWebKey) {
this.key = getKey(jsonWebKey);
if (key == null || key.length == 0) {
throw logger.logExceptionAsError(new IllegalArgumentException("key"));
}
Algorithm baseAlgorithm = AlgorithmResolver.DEFAULT.get(algorithm.toString());
if (!(baseAlgorithm instanceof LocalKeyWrapAlgorithm)) {
return Mono.error(new NoSuchAlgorithmException(algorithm.toString()));
}
LocalKeyWrapAlgorithm localKeyWrapAlgorithm = (LocalKeyWrapAlgorithm) baseAlgorithm;
ICryptoTransform transform;
try {
transform = localKeyWrapAlgorithm.createEncryptor(this.key, null, null);
} catch (Exception e) {
return Mono.error(e);
}
byte[] encrypted;
try {
encrypted = transform.doFinal(key);
} catch (Exception e) {
return Mono.error(e);
}
return Mono.just(new WrapResult(encrypted, algorithm, jsonWebKey.getId()));
}
@Override
Mono<UnwrapResult> unwrapKeyAsync(KeyWrapAlgorithm algorithm, byte[] encryptedKey, Context context, JsonWebKey jsonWebKey) {
this.key = getKey(jsonWebKey);
Algorithm baseAlgorithm = AlgorithmResolver.DEFAULT.get(algorithm.toString());
if (!(baseAlgorithm instanceof LocalKeyWrapAlgorithm)) {
return Mono.error(new NoSuchAlgorithmException(algorithm.toString()));
}
LocalKeyWrapAlgorithm localKeyWrapAlgorithm = (LocalKeyWrapAlgorithm) baseAlgorithm;
ICryptoTransform transform;
try {
transform = localKeyWrapAlgorithm.createDecryptor(this.key, null, null);
} catch (Exception e) {
return Mono.error(e);
}
byte[] decrypted;
try {
decrypted = transform.doFinal(encryptedKey);
} catch (Exception e) {
return Mono.error(e);
}
return Mono.just(new UnwrapResult(decrypted, algorithm, jsonWebKey.getId()));
}
@Override
Mono<SignResult> signDataAsync(SignatureAlgorithm algorithm, byte[] data, Context context, JsonWebKey key) {
return signAsync(algorithm, data, context, key);
}
@Override
Mono<VerifyResult> verifyDataAsync(SignatureAlgorithm algorithm, byte[] data, byte[] signature, Context context,
JsonWebKey key) {
return verifyAsync(algorithm, data, signature, context, key);
}
private byte[] generateRandomByteArray(int sizeInBytes) {
byte[] iv = new byte[0];
SecureRandom randomSecureRandom;
try {
randomSecureRandom = SecureRandom.getInstance("SHA1PRNG");
iv = new byte[sizeInBytes];
randomSecureRandom.nextBytes(iv);
} catch (NoSuchAlgorithmException e) {
logger.logThrowableAsError(e);
}
return iv;
}
private boolean isGcm(EncryptionAlgorithm encryptionAlgorithm) {
return (encryptionAlgorithm == EncryptionAlgorithm.A128GCM
|| encryptionAlgorithm == EncryptionAlgorithm.A192GCM
|| encryptionAlgorithm == EncryptionAlgorithm.A256GCM);
}
private boolean isAes(EncryptionAlgorithm encryptionAlgorithm) {
return (encryptionAlgorithm == EncryptionAlgorithm.A128CBC
|| encryptionAlgorithm == EncryptionAlgorithm.A192CBC
|| encryptionAlgorithm == EncryptionAlgorithm.A256CBC
|| encryptionAlgorithm == EncryptionAlgorithm.A128CBCPAD
|| encryptionAlgorithm == EncryptionAlgorithm.A192CBCPAD
|| encryptionAlgorithm == EncryptionAlgorithm.A256CBCPAD);
}
} | class SymmetricKeyCryptographyClient extends LocalKeyCryptographyClient {
static final int AES_BLOCK_SIZE = 16;
static final int GCM_NONCE_SIZE = 12;
private final ClientLogger logger = new ClientLogger(SymmetricKeyCryptographyClient.class);
private byte[] key;
/**
* Creates a {@link SymmetricKeyCryptographyClient} to perform local cryptography operations.
*
* @param serviceClient The client to route the requests through.
*/
SymmetricKeyCryptographyClient(CryptographyServiceClient serviceClient) {
super(serviceClient);
}
SymmetricKeyCryptographyClient(JsonWebKey key, CryptographyServiceClient serviceClient) {
super(serviceClient);
this.key = key.toAes().getEncoded();
}
private byte[] getKey(JsonWebKey key) {
if (this.key == null) {
this.key = key.toAes().getEncoded();
}
return this.key;
}
@Override
@Override
Mono<DecryptResult> decryptAsync(DecryptOptions decryptOptions, Context context, JsonWebKey jsonWebKey) {
this.key = getKey(jsonWebKey);
if (key == null || key.length == 0) {
throw logger.logExceptionAsError(new IllegalArgumentException("Key is empty."));
}
EncryptionAlgorithm algorithm = decryptOptions.getAlgorithm();
Algorithm baseAlgorithm = AlgorithmResolver.DEFAULT.get(algorithm.toString());
if (!(baseAlgorithm instanceof SymmetricEncryptionAlgorithm)) {
return Mono.error(new NoSuchAlgorithmException(algorithm.toString()));
}
SymmetricEncryptionAlgorithm symmetricEncryptionAlgorithm = (SymmetricEncryptionAlgorithm) baseAlgorithm;
ICryptoTransform transform;
byte[] iv = Objects.requireNonNull(decryptOptions.getIv(), "Initialization vector cannot be null in local decryption operations.");
byte[] additionalAuthenticatedData = decryptOptions.getAdditionalAuthenticatedData();
byte[] authenticationTag = decryptOptions.getAuthenticationTag();
try {
transform = symmetricEncryptionAlgorithm.createDecryptor(this.key, iv, additionalAuthenticatedData, authenticationTag);
} catch (Exception e) {
return Mono.error(e);
}
byte[] decrypted;
byte[] cipherText;
if (isGcm(algorithm)) {
cipherText = new byte[decryptOptions.getCipherText().length + authenticationTag.length];
System.arraycopy(decryptOptions.getCipherText(), 0, cipherText, 0, decryptOptions.getCipherText().length);
System.arraycopy(authenticationTag, 0, cipherText, decryptOptions.getCipherText().length, authenticationTag.length);
} else if (isAes(algorithm)) {
cipherText = decryptOptions.getCipherText();
} else {
throw logger.logExceptionAsError(
new IllegalStateException("Encryption algorithm provided is not supported: " + algorithm));
}
try {
decrypted = transform.doFinal(cipherText);
} catch (Exception e) {
return Mono.error(e);
}
return Mono.just(new DecryptResult(decrypted, algorithm, jsonWebKey.getId()));
}
@Override
Mono<SignResult> signAsync(SignatureAlgorithm algorithm, byte[] digest, Context context, JsonWebKey key) {
return Mono.error(new UnsupportedOperationException("Sign operation not supported for OCT/Symmetric key"));
}
@Override
Mono<VerifyResult> verifyAsync(SignatureAlgorithm algorithm, byte[] digest, byte[] signature, Context context,
JsonWebKey key) {
return Mono.error(new UnsupportedOperationException("Verify operation not supported for OCT/Symmetric key"));
}
@Override
Mono<WrapResult> wrapKeyAsync(KeyWrapAlgorithm algorithm, byte[] key, Context context, JsonWebKey jsonWebKey) {
this.key = getKey(jsonWebKey);
if (key == null || key.length == 0) {
throw logger.logExceptionAsError(new IllegalArgumentException("key"));
}
Algorithm baseAlgorithm = AlgorithmResolver.DEFAULT.get(algorithm.toString());
if (!(baseAlgorithm instanceof LocalKeyWrapAlgorithm)) {
return Mono.error(new NoSuchAlgorithmException(algorithm.toString()));
}
LocalKeyWrapAlgorithm localKeyWrapAlgorithm = (LocalKeyWrapAlgorithm) baseAlgorithm;
ICryptoTransform transform;
try {
transform = localKeyWrapAlgorithm.createEncryptor(this.key, null, null);
} catch (Exception e) {
return Mono.error(e);
}
byte[] encrypted;
try {
encrypted = transform.doFinal(key);
} catch (Exception e) {
return Mono.error(e);
}
return Mono.just(new WrapResult(encrypted, algorithm, jsonWebKey.getId()));
}
@Override
Mono<UnwrapResult> unwrapKeyAsync(KeyWrapAlgorithm algorithm, byte[] encryptedKey, Context context, JsonWebKey jsonWebKey) {
this.key = getKey(jsonWebKey);
Algorithm baseAlgorithm = AlgorithmResolver.DEFAULT.get(algorithm.toString());
if (!(baseAlgorithm instanceof LocalKeyWrapAlgorithm)) {
return Mono.error(new NoSuchAlgorithmException(algorithm.toString()));
}
LocalKeyWrapAlgorithm localKeyWrapAlgorithm = (LocalKeyWrapAlgorithm) baseAlgorithm;
ICryptoTransform transform;
try {
transform = localKeyWrapAlgorithm.createDecryptor(this.key, null, null);
} catch (Exception e) {
return Mono.error(e);
}
byte[] decrypted;
try {
decrypted = transform.doFinal(encryptedKey);
} catch (Exception e) {
return Mono.error(e);
}
return Mono.just(new UnwrapResult(decrypted, algorithm, jsonWebKey.getId()));
}
@Override
Mono<SignResult> signDataAsync(SignatureAlgorithm algorithm, byte[] data, Context context, JsonWebKey key) {
return signAsync(algorithm, data, context, key);
}
@Override
Mono<VerifyResult> verifyDataAsync(SignatureAlgorithm algorithm, byte[] data, byte[] signature, Context context,
JsonWebKey key) {
return verifyAsync(algorithm, data, signature, context, key);
}
private byte[] generateRandomByteArray(int sizeInBytes) {
byte[] iv = new byte[0];
SecureRandom randomSecureRandom;
try {
randomSecureRandom = SecureRandom.getInstance("SHA1PRNG");
iv = new byte[sizeInBytes];
randomSecureRandom.nextBytes(iv);
} catch (NoSuchAlgorithmException e) {
logger.logThrowableAsError(e);
}
return iv;
}
private boolean isGcm(EncryptionAlgorithm encryptionAlgorithm) {
return (encryptionAlgorithm == EncryptionAlgorithm.A128GCM
|| encryptionAlgorithm == EncryptionAlgorithm.A192GCM
|| encryptionAlgorithm == EncryptionAlgorithm.A256GCM);
}
private boolean isAes(EncryptionAlgorithm encryptionAlgorithm) {
return (encryptionAlgorithm == EncryptionAlgorithm.A128CBC
|| encryptionAlgorithm == EncryptionAlgorithm.A192CBC
|| encryptionAlgorithm == EncryptionAlgorithm.A256CBC
|| encryptionAlgorithm == EncryptionAlgorithm.A128CBCPAD
|| encryptionAlgorithm == EncryptionAlgorithm.A192CBCPAD
|| encryptionAlgorithm == EncryptionAlgorithm.A256CBCPAD);
}
} |
I will remove the local GCM implementation in a separate PR. | Mono<EncryptResult> encryptAsync(EncryptOptions encryptOptions, Context context, JsonWebKey jsonWebKey) {
this.key = getKey(jsonWebKey);
if (key == null || key.length == 0) {
throw logger.logExceptionAsError(new IllegalArgumentException("Key is empty."));
}
EncryptionAlgorithm algorithm = encryptOptions.getAlgorithm();
Algorithm baseAlgorithm = AlgorithmResolver.DEFAULT.get(algorithm.toString());
if (!(baseAlgorithm instanceof SymmetricEncryptionAlgorithm)) {
return Mono.error(new NoSuchAlgorithmException(algorithm.toString()));
}
SymmetricEncryptionAlgorithm symmetricEncryptionAlgorithm = (SymmetricEncryptionAlgorithm) baseAlgorithm;
ICryptoTransform transform;
byte[] iv = encryptOptions.getIv();
byte[] additionalAuthenticatedData = encryptOptions.getAdditionalAuthenticatedData();
if (iv == null) {
if (isGcm(algorithm)) {
iv = generateRandomByteArray(GCM_NONCE_SIZE);
} else if (isAes(algorithm)) {
iv = generateRandomByteArray(AES_BLOCK_SIZE);
} else {
throw logger.logExceptionAsError(
new IllegalStateException("Encryption algorithm provided is not supported: " + algorithm));
}
}
try {
transform = symmetricEncryptionAlgorithm.createEncryptor(this.key, iv, additionalAuthenticatedData,
null);
} catch (Exception e) {
return Mono.error(e);
}
byte[] encrypted;
try {
encrypted = transform.doFinal(encryptOptions.getPlainText());
} catch (Exception e) {
return Mono.error(e);
}
byte[] cipherText;
byte[] authenticationTag;
if (isGcm(algorithm)) {
cipherText = Arrays.copyOfRange(encrypted, 0, encryptOptions.getPlainText().length);
authenticationTag = Arrays.copyOfRange(encrypted, encryptOptions.getPlainText().length, encrypted.length);
} else if (isAes(algorithm)) {
cipherText = encrypted;
authenticationTag = null;
} else {
throw logger.logExceptionAsError(
new IllegalStateException("Encryption algorithm provided is not supported: " + algorithm));
}
return Mono.just(new EncryptResult(cipherText, algorithm, jsonWebKey.getId(), iv, additionalAuthenticatedData,
authenticationTag));
} | iv = generateRandomByteArray(GCM_NONCE_SIZE); | Mono<EncryptResult> encryptAsync(EncryptOptions encryptOptions, Context context, JsonWebKey jsonWebKey) {
this.key = getKey(jsonWebKey);
if (key == null || key.length == 0) {
throw logger.logExceptionAsError(new IllegalArgumentException("Key is empty."));
}
EncryptionAlgorithm algorithm = encryptOptions.getAlgorithm();
Algorithm baseAlgorithm = AlgorithmResolver.DEFAULT.get(algorithm.toString());
if (!(baseAlgorithm instanceof SymmetricEncryptionAlgorithm)) {
return Mono.error(new NoSuchAlgorithmException(algorithm.toString()));
}
SymmetricEncryptionAlgorithm symmetricEncryptionAlgorithm = (SymmetricEncryptionAlgorithm) baseAlgorithm;
ICryptoTransform transform;
byte[] iv = encryptOptions.getIv();
byte[] additionalAuthenticatedData = encryptOptions.getAdditionalAuthenticatedData();
if (iv == null) {
if (isGcm(algorithm)) {
iv = generateRandomByteArray(GCM_NONCE_SIZE);
} else if (isAes(algorithm)) {
iv = generateRandomByteArray(AES_BLOCK_SIZE);
} else {
throw logger.logExceptionAsError(
new IllegalStateException("Encryption algorithm provided is not supported: " + algorithm));
}
}
try {
transform = symmetricEncryptionAlgorithm.createEncryptor(this.key, iv, additionalAuthenticatedData,
null);
} catch (Exception e) {
return Mono.error(e);
}
byte[] encrypted;
try {
encrypted = transform.doFinal(encryptOptions.getPlainText());
} catch (Exception e) {
return Mono.error(e);
}
byte[] cipherText;
byte[] authenticationTag;
if (isGcm(algorithm)) {
cipherText = Arrays.copyOfRange(encrypted, 0, encryptOptions.getPlainText().length);
authenticationTag = Arrays.copyOfRange(encrypted, encryptOptions.getPlainText().length, encrypted.length);
} else if (isAes(algorithm)) {
cipherText = encrypted;
authenticationTag = null;
} else {
throw logger.logExceptionAsError(
new IllegalStateException("Encryption algorithm provided is not supported: " + algorithm));
}
return Mono.just(new EncryptResult(cipherText, algorithm, jsonWebKey.getId(), iv, additionalAuthenticatedData,
authenticationTag));
} | class SymmetricKeyCryptographyClient extends LocalKeyCryptographyClient {
static final int AES_BLOCK_SIZE = 16;
static final int GCM_NONCE_SIZE = 12;
private final ClientLogger logger = new ClientLogger(SymmetricKeyCryptographyClient.class);
private byte[] key;
/**
* Creates a {@link SymmetricKeyCryptographyClient} to perform local cryptography operations.
*
* @param serviceClient The client to route the requests through.
*/
SymmetricKeyCryptographyClient(CryptographyServiceClient serviceClient) {
super(serviceClient);
}
SymmetricKeyCryptographyClient(JsonWebKey key, CryptographyServiceClient serviceClient) {
super(serviceClient);
this.key = key.toAes().getEncoded();
}
private byte[] getKey(JsonWebKey key) {
if (this.key == null) {
this.key = key.toAes().getEncoded();
}
return this.key;
}
@Override
@Override
Mono<DecryptResult> decryptAsync(DecryptOptions decryptOptions, Context context, JsonWebKey jsonWebKey) {
this.key = getKey(jsonWebKey);
if (key == null || key.length == 0) {
throw logger.logExceptionAsError(new IllegalArgumentException("Key is empty."));
}
EncryptionAlgorithm algorithm = decryptOptions.getAlgorithm();
Algorithm baseAlgorithm = AlgorithmResolver.DEFAULT.get(algorithm.toString());
if (!(baseAlgorithm instanceof SymmetricEncryptionAlgorithm)) {
return Mono.error(new NoSuchAlgorithmException(algorithm.toString()));
}
SymmetricEncryptionAlgorithm symmetricEncryptionAlgorithm = (SymmetricEncryptionAlgorithm) baseAlgorithm;
ICryptoTransform transform;
byte[] iv = Objects.requireNonNull(decryptOptions.getIv(), "Initialization vector cannot be null in local decryption operations.");
byte[] additionalAuthenticatedData = decryptOptions.getAdditionalAuthenticatedData();
byte[] authenticationTag = decryptOptions.getAuthenticationTag();
try {
transform = symmetricEncryptionAlgorithm.createDecryptor(this.key, iv, additionalAuthenticatedData, authenticationTag);
} catch (Exception e) {
return Mono.error(e);
}
byte[] decrypted;
byte[] cipherText;
if (isGcm(algorithm)) {
cipherText = new byte[decryptOptions.getCipherText().length + authenticationTag.length];
System.arraycopy(decryptOptions.getCipherText(), 0, cipherText, 0, decryptOptions.getCipherText().length);
System.arraycopy(authenticationTag, 0, cipherText, decryptOptions.getCipherText().length, authenticationTag.length);
} else if (isAes(algorithm)) {
cipherText = decryptOptions.getCipherText();
} else {
throw logger.logExceptionAsError(
new IllegalStateException("Encryption algorithm provided is not supported: " + algorithm));
}
try {
decrypted = transform.doFinal(cipherText);
} catch (Exception e) {
return Mono.error(e);
}
return Mono.just(new DecryptResult(decrypted, algorithm, jsonWebKey.getId()));
}
@Override
Mono<SignResult> signAsync(SignatureAlgorithm algorithm, byte[] digest, Context context, JsonWebKey key) {
return Mono.error(new UnsupportedOperationException("Sign operation not supported for OCT/Symmetric key"));
}
@Override
Mono<VerifyResult> verifyAsync(SignatureAlgorithm algorithm, byte[] digest, byte[] signature, Context context,
JsonWebKey key) {
return Mono.error(new UnsupportedOperationException("Verify operation not supported for OCT/Symmetric key"));
}
@Override
Mono<WrapResult> wrapKeyAsync(KeyWrapAlgorithm algorithm, byte[] key, Context context, JsonWebKey jsonWebKey) {
this.key = getKey(jsonWebKey);
if (key == null || key.length == 0) {
throw logger.logExceptionAsError(new IllegalArgumentException("key"));
}
Algorithm baseAlgorithm = AlgorithmResolver.DEFAULT.get(algorithm.toString());
if (!(baseAlgorithm instanceof LocalKeyWrapAlgorithm)) {
return Mono.error(new NoSuchAlgorithmException(algorithm.toString()));
}
LocalKeyWrapAlgorithm localKeyWrapAlgorithm = (LocalKeyWrapAlgorithm) baseAlgorithm;
ICryptoTransform transform;
try {
transform = localKeyWrapAlgorithm.createEncryptor(this.key, null, null);
} catch (Exception e) {
return Mono.error(e);
}
byte[] encrypted;
try {
encrypted = transform.doFinal(key);
} catch (Exception e) {
return Mono.error(e);
}
return Mono.just(new WrapResult(encrypted, algorithm, jsonWebKey.getId()));
}
@Override
Mono<UnwrapResult> unwrapKeyAsync(KeyWrapAlgorithm algorithm, byte[] encryptedKey, Context context, JsonWebKey jsonWebKey) {
this.key = getKey(jsonWebKey);
Algorithm baseAlgorithm = AlgorithmResolver.DEFAULT.get(algorithm.toString());
if (!(baseAlgorithm instanceof LocalKeyWrapAlgorithm)) {
return Mono.error(new NoSuchAlgorithmException(algorithm.toString()));
}
LocalKeyWrapAlgorithm localKeyWrapAlgorithm = (LocalKeyWrapAlgorithm) baseAlgorithm;
ICryptoTransform transform;
try {
transform = localKeyWrapAlgorithm.createDecryptor(this.key, null, null);
} catch (Exception e) {
return Mono.error(e);
}
byte[] decrypted;
try {
decrypted = transform.doFinal(encryptedKey);
} catch (Exception e) {
return Mono.error(e);
}
return Mono.just(new UnwrapResult(decrypted, algorithm, jsonWebKey.getId()));
}
@Override
Mono<SignResult> signDataAsync(SignatureAlgorithm algorithm, byte[] data, Context context, JsonWebKey key) {
return signAsync(algorithm, data, context, key);
}
@Override
Mono<VerifyResult> verifyDataAsync(SignatureAlgorithm algorithm, byte[] data, byte[] signature, Context context,
JsonWebKey key) {
return verifyAsync(algorithm, data, signature, context, key);
}
private byte[] generateRandomByteArray(int sizeInBytes) {
byte[] iv = new byte[0];
SecureRandom randomSecureRandom;
try {
randomSecureRandom = SecureRandom.getInstance("SHA1PRNG");
iv = new byte[sizeInBytes];
randomSecureRandom.nextBytes(iv);
} catch (NoSuchAlgorithmException e) {
logger.logThrowableAsError(e);
}
return iv;
}
private boolean isGcm(EncryptionAlgorithm encryptionAlgorithm) {
return (encryptionAlgorithm == EncryptionAlgorithm.A128GCM
|| encryptionAlgorithm == EncryptionAlgorithm.A192GCM
|| encryptionAlgorithm == EncryptionAlgorithm.A256GCM);
}
private boolean isAes(EncryptionAlgorithm encryptionAlgorithm) {
return (encryptionAlgorithm == EncryptionAlgorithm.A128CBC
|| encryptionAlgorithm == EncryptionAlgorithm.A192CBC
|| encryptionAlgorithm == EncryptionAlgorithm.A256CBC
|| encryptionAlgorithm == EncryptionAlgorithm.A128CBCPAD
|| encryptionAlgorithm == EncryptionAlgorithm.A192CBCPAD
|| encryptionAlgorithm == EncryptionAlgorithm.A256CBCPAD);
}
} | class SymmetricKeyCryptographyClient extends LocalKeyCryptographyClient {
static final int AES_BLOCK_SIZE = 16;
static final int GCM_NONCE_SIZE = 12;
private final ClientLogger logger = new ClientLogger(SymmetricKeyCryptographyClient.class);
private byte[] key;
/**
* Creates a {@link SymmetricKeyCryptographyClient} to perform local cryptography operations.
*
* @param serviceClient The client to route the requests through.
*/
SymmetricKeyCryptographyClient(CryptographyServiceClient serviceClient) {
super(serviceClient);
}
SymmetricKeyCryptographyClient(JsonWebKey key, CryptographyServiceClient serviceClient) {
super(serviceClient);
this.key = key.toAes().getEncoded();
}
private byte[] getKey(JsonWebKey key) {
if (this.key == null) {
this.key = key.toAes().getEncoded();
}
return this.key;
}
@Override
@Override
Mono<DecryptResult> decryptAsync(DecryptOptions decryptOptions, Context context, JsonWebKey jsonWebKey) {
this.key = getKey(jsonWebKey);
if (key == null || key.length == 0) {
throw logger.logExceptionAsError(new IllegalArgumentException("Key is empty."));
}
EncryptionAlgorithm algorithm = decryptOptions.getAlgorithm();
Algorithm baseAlgorithm = AlgorithmResolver.DEFAULT.get(algorithm.toString());
if (!(baseAlgorithm instanceof SymmetricEncryptionAlgorithm)) {
return Mono.error(new NoSuchAlgorithmException(algorithm.toString()));
}
SymmetricEncryptionAlgorithm symmetricEncryptionAlgorithm = (SymmetricEncryptionAlgorithm) baseAlgorithm;
ICryptoTransform transform;
byte[] iv = Objects.requireNonNull(decryptOptions.getIv(), "Initialization vector cannot be null in local decryption operations.");
byte[] additionalAuthenticatedData = decryptOptions.getAdditionalAuthenticatedData();
byte[] authenticationTag = decryptOptions.getAuthenticationTag();
try {
transform = symmetricEncryptionAlgorithm.createDecryptor(this.key, iv, additionalAuthenticatedData, authenticationTag);
} catch (Exception e) {
return Mono.error(e);
}
byte[] decrypted;
byte[] cipherText;
if (isGcm(algorithm)) {
cipherText = new byte[decryptOptions.getCipherText().length + authenticationTag.length];
System.arraycopy(decryptOptions.getCipherText(), 0, cipherText, 0, decryptOptions.getCipherText().length);
System.arraycopy(authenticationTag, 0, cipherText, decryptOptions.getCipherText().length, authenticationTag.length);
} else if (isAes(algorithm)) {
cipherText = decryptOptions.getCipherText();
} else {
throw logger.logExceptionAsError(
new IllegalStateException("Encryption algorithm provided is not supported: " + algorithm));
}
try {
decrypted = transform.doFinal(cipherText);
} catch (Exception e) {
return Mono.error(e);
}
return Mono.just(new DecryptResult(decrypted, algorithm, jsonWebKey.getId()));
}
@Override
Mono<SignResult> signAsync(SignatureAlgorithm algorithm, byte[] digest, Context context, JsonWebKey key) {
return Mono.error(new UnsupportedOperationException("Sign operation not supported for OCT/Symmetric key"));
}
@Override
Mono<VerifyResult> verifyAsync(SignatureAlgorithm algorithm, byte[] digest, byte[] signature, Context context,
JsonWebKey key) {
return Mono.error(new UnsupportedOperationException("Verify operation not supported for OCT/Symmetric key"));
}
@Override
Mono<WrapResult> wrapKeyAsync(KeyWrapAlgorithm algorithm, byte[] key, Context context, JsonWebKey jsonWebKey) {
this.key = getKey(jsonWebKey);
if (key == null || key.length == 0) {
throw logger.logExceptionAsError(new IllegalArgumentException("key"));
}
Algorithm baseAlgorithm = AlgorithmResolver.DEFAULT.get(algorithm.toString());
if (!(baseAlgorithm instanceof LocalKeyWrapAlgorithm)) {
return Mono.error(new NoSuchAlgorithmException(algorithm.toString()));
}
LocalKeyWrapAlgorithm localKeyWrapAlgorithm = (LocalKeyWrapAlgorithm) baseAlgorithm;
ICryptoTransform transform;
try {
transform = localKeyWrapAlgorithm.createEncryptor(this.key, null, null);
} catch (Exception e) {
return Mono.error(e);
}
byte[] encrypted;
try {
encrypted = transform.doFinal(key);
} catch (Exception e) {
return Mono.error(e);
}
return Mono.just(new WrapResult(encrypted, algorithm, jsonWebKey.getId()));
}
@Override
Mono<UnwrapResult> unwrapKeyAsync(KeyWrapAlgorithm algorithm, byte[] encryptedKey, Context context, JsonWebKey jsonWebKey) {
this.key = getKey(jsonWebKey);
Algorithm baseAlgorithm = AlgorithmResolver.DEFAULT.get(algorithm.toString());
if (!(baseAlgorithm instanceof LocalKeyWrapAlgorithm)) {
return Mono.error(new NoSuchAlgorithmException(algorithm.toString()));
}
LocalKeyWrapAlgorithm localKeyWrapAlgorithm = (LocalKeyWrapAlgorithm) baseAlgorithm;
ICryptoTransform transform;
try {
transform = localKeyWrapAlgorithm.createDecryptor(this.key, null, null);
} catch (Exception e) {
return Mono.error(e);
}
byte[] decrypted;
try {
decrypted = transform.doFinal(encryptedKey);
} catch (Exception e) {
return Mono.error(e);
}
return Mono.just(new UnwrapResult(decrypted, algorithm, jsonWebKey.getId()));
}
@Override
Mono<SignResult> signDataAsync(SignatureAlgorithm algorithm, byte[] data, Context context, JsonWebKey key) {
return signAsync(algorithm, data, context, key);
}
@Override
Mono<VerifyResult> verifyDataAsync(SignatureAlgorithm algorithm, byte[] data, byte[] signature, Context context,
JsonWebKey key) {
return verifyAsync(algorithm, data, signature, context, key);
}
private byte[] generateRandomByteArray(int sizeInBytes) {
byte[] iv = new byte[0];
SecureRandom randomSecureRandom;
try {
randomSecureRandom = SecureRandom.getInstance("SHA1PRNG");
iv = new byte[sizeInBytes];
randomSecureRandom.nextBytes(iv);
} catch (NoSuchAlgorithmException e) {
logger.logThrowableAsError(e);
}
return iv;
}
private boolean isGcm(EncryptionAlgorithm encryptionAlgorithm) {
return (encryptionAlgorithm == EncryptionAlgorithm.A128GCM
|| encryptionAlgorithm == EncryptionAlgorithm.A192GCM
|| encryptionAlgorithm == EncryptionAlgorithm.A256GCM);
}
private boolean isAes(EncryptionAlgorithm encryptionAlgorithm) {
return (encryptionAlgorithm == EncryptionAlgorithm.A128CBC
|| encryptionAlgorithm == EncryptionAlgorithm.A192CBC
|| encryptionAlgorithm == EncryptionAlgorithm.A256CBC
|| encryptionAlgorithm == EncryptionAlgorithm.A128CBCPAD
|| encryptionAlgorithm == EncryptionAlgorithm.A192CBCPAD
|| encryptionAlgorithm == EncryptionAlgorithm.A256CBCPAD);
}
} |
This block can be: this.authenticationTag = authenticationTag != null ? Base64Url.encode(authenticationTag) : null; | public KeyOperationParameters setAuthenticationTag(byte[] authenticationTag) {
if (authenticationTag == null) {
this.authenticationTag = null;
} else {
this.authenticationTag = Base64Url.encode(authenticationTag);
}
return this;
} | if (authenticationTag == null) { | public KeyOperationParameters setAuthenticationTag(byte[] authenticationTag) {
this.authenticationTag = authenticationTag != null ? Base64Url.encode(authenticationTag) : null;
return this;
} | class KeyOperationParameters {
private static final byte[] EMPTY_ARRAY = new byte[0];
/**
* algorithm identifier. Possible values include: 'RSA-OAEP',
* 'RSA-OAEP-256', 'RSA1_5'.
*/
@JsonProperty(value = "alg", required = true)
private EncryptionAlgorithm algorithm;
/**
* The value property.
*/
@JsonProperty(value = "value", required = true)
private Base64Url value;
/**
* Initialization vector for symmetric algorithms.
*/
@JsonProperty(value = "iv")
private Base64Url iv;
/**
* Additional data to authenticate but not encrypt/decrypt when using authenticated crypto algorithms.
*/
@JsonProperty(value = "aad")
private Base64Url additionalAuthenticatedData;
/**
* The tag to authenticate when performing decryption with an authenticated algorithm.
*/
@JsonProperty(value = "tag")
private Base64Url authenticationTag;
/**
* Get the algorithm value.
*
* @return the algorithm value
*/
public EncryptionAlgorithm getAlgorithm() {
return this.algorithm;
}
/**
* Set the algorithm value.
*
* @param algorithm the algorithm value to set
* @return the KeyOperationsParameters object itself.
*/
public KeyOperationParameters setAlgorithm(EncryptionAlgorithm algorithm) {
this.algorithm = algorithm;
return this;
}
/**
* Get the value value.
*
* @return the value value
*/
public byte[] getValue() {
if (this.value == null) {
return EMPTY_ARRAY;
}
return this.value.decodedBytes();
}
/**
* Set the value value.
*
* @param value the value value to set
* @return the KeyOperationsParameters object itself.
*/
public KeyOperationParameters setValue(byte[] value) {
if (value == null) {
this.value = null;
} else {
this.value = Base64Url.encode(value);
}
return this;
}
/**
* Get the initialization vector to be used in the cryptographic operation using a symmetric algorithm.
*
* @return The initialization vector.
*/
public byte[] getIv() {
if (this.iv == null) {
return EMPTY_ARRAY;
}
return this.iv.decodedBytes();
}
/**
* Set the initialization vector to be used in the cryptographic operation using a symmetric algorithm.
*
* @param iv The initialization vector to set.
* @return The updated {@link KeyOperationParameters} object.
*/
public KeyOperationParameters setIv(byte[] iv) {
if (iv == null) {
this.iv = null;
} else {
this.iv = Base64Url.encode(iv);
}
return this;
}
/**
* Get additional data to authenticate but not encrypt/decrypt when using authenticated crypto algorithms.
*
* @return The additional authenticated data.
*/
public byte[] getAdditionalAuthenticatedData() {
if (this.additionalAuthenticatedData == null) {
return EMPTY_ARRAY;
}
return this.additionalAuthenticatedData.decodedBytes();
}
/**
* Set additional data to authenticate but not encrypt/decrypt when using authenticated crypto algorithms.
*
* @param additionalAuthenticatedData The additional authenticated data.
* @return The updated {@link KeyOperationParameters} object.
*/
public KeyOperationParameters setAdditionalAuthenticatedData(byte[] additionalAuthenticatedData) {
if (additionalAuthenticatedData == null) {
this.additionalAuthenticatedData = null;
} else {
this.additionalAuthenticatedData = Base64Url.encode(additionalAuthenticatedData);
}
return this;
}
/**
* Get the tag to authenticate when performing decryption with an authenticated algorithm.
*
* @return The authentication tag.
*/
public byte[] getAuthenticationTag() {
if (this.authenticationTag == null) {
return EMPTY_ARRAY;
}
return this.authenticationTag.decodedBytes();
}
/**
* Set the tag to authenticate when performing decryption with an authenticated algorithm.
*
* @param authenticationTag The tag to set.
* @return The updated {@link KeyOperationParameters} object.
*/
} | class KeyOperationParameters {
private static final byte[] EMPTY_ARRAY = new byte[0];
/**
* Algorithm identifier. Possible values include: 'RSA-OAEP',
* 'RSA-OAEP-256', 'RSA1_5'.
*/
@JsonProperty(value = "alg", required = true)
private EncryptionAlgorithm algorithm;
/**
* The value property.
*/
@JsonProperty(value = "value", required = true)
private Base64Url value;
/**
* Initialization vector for symmetric algorithms.
*/
@JsonProperty(value = "iv")
private Base64Url iv;
/**
* Additional data to authenticate but not encrypt/decrypt when using authenticated crypto algorithms.
*/
@JsonProperty(value = "aad")
private Base64Url additionalAuthenticatedData;
/**
* The tag to authenticate when performing decryption with an authenticated algorithm.
*/
@JsonProperty(value = "tag")
private Base64Url authenticationTag;
/**
* Get the algorithm value.
*
* @return the algorithm value
*/
public EncryptionAlgorithm getAlgorithm() {
return this.algorithm;
}
/**
* Set the algorithm value.
*
* @param algorithm the algorithm value to set
* @return the KeyOperationsParameters object itself.
*/
public KeyOperationParameters setAlgorithm(EncryptionAlgorithm algorithm) {
this.algorithm = algorithm;
return this;
}
/**
* Get the value value.
*
* @return the value value
*/
public byte[] getValue() {
if (this.value == null) {
return EMPTY_ARRAY;
}
return this.value.decodedBytes();
}
/**
* Set the value value.
*
* @param value the value value to set
* @return the KeyOperationsParameters object itself.
*/
public KeyOperationParameters setValue(byte[] value) {
this.value = value != null ? Base64Url.encode(value) : null;
return this;
}
/**
* Get the initialization vector to be used in the cryptographic operation using a symmetric algorithm.
*
* @return The initialization vector.
*/
public byte[] getIv() {
if (this.iv == null) {
return EMPTY_ARRAY;
}
return this.iv.decodedBytes();
}
/**
* Set the initialization vector to be used in the cryptographic operation using a symmetric algorithm.
*
* @param iv The initialization vector to set.
* @return The updated {@link KeyOperationParameters} object.
*/
public KeyOperationParameters setIv(byte[] iv) {
this.iv = iv != null ? Base64Url.encode(iv) : null;
return this;
}
/**
* Get additional data to authenticate but not encrypt/decrypt when using authenticated crypto algorithms.
*
* @return The additional authenticated data.
*/
public byte[] getAdditionalAuthenticatedData() {
if (this.additionalAuthenticatedData == null) {
return EMPTY_ARRAY;
}
return this.additionalAuthenticatedData.decodedBytes();
}
/**
* Set additional data to authenticate but not encrypt/decrypt when using authenticated crypto algorithms.
*
* @param additionalAuthenticatedData The additional authenticated data.
* @return The updated {@link KeyOperationParameters} object.
*/
public KeyOperationParameters setAdditionalAuthenticatedData(byte[] additionalAuthenticatedData) {
this.additionalAuthenticatedData =
additionalAuthenticatedData != null ? Base64Url.encode(additionalAuthenticatedData) : null;
return this;
}
/**
* Get the tag to authenticate when performing decryption with an authenticated algorithm.
*
* @return The authentication tag.
*/
public byte[] getAuthenticationTag() {
if (this.authenticationTag == null) {
return EMPTY_ARRAY;
}
return this.authenticationTag.decodedBytes();
}
/**
* Set the tag to authenticate when performing decryption with an authenticated algorithm.
*
* @param authenticationTag The tag to set.
* @return The updated {@link KeyOperationParameters} object.
*/
} |
yea it was decided in the crypto board meeting that we won't be doing local GCM encryption due to random IVs not being secure. | Mono<EncryptResult> encryptAsync(EncryptOptions encryptOptions, Context context, JsonWebKey jsonWebKey) {
this.key = getKey(jsonWebKey);
if (key == null || key.length == 0) {
throw logger.logExceptionAsError(new IllegalArgumentException("Key is empty."));
}
EncryptionAlgorithm algorithm = encryptOptions.getAlgorithm();
Algorithm baseAlgorithm = AlgorithmResolver.DEFAULT.get(algorithm.toString());
if (!(baseAlgorithm instanceof SymmetricEncryptionAlgorithm)) {
return Mono.error(new NoSuchAlgorithmException(algorithm.toString()));
}
SymmetricEncryptionAlgorithm symmetricEncryptionAlgorithm = (SymmetricEncryptionAlgorithm) baseAlgorithm;
ICryptoTransform transform;
byte[] iv = encryptOptions.getIv();
byte[] additionalAuthenticatedData = encryptOptions.getAdditionalAuthenticatedData();
if (iv == null) {
if (isGcm(algorithm)) {
iv = generateRandomByteArray(GCM_NONCE_SIZE);
} else if (isAes(algorithm)) {
iv = generateRandomByteArray(AES_BLOCK_SIZE);
} else {
throw logger.logExceptionAsError(
new IllegalStateException("Encryption algorithm provided is not supported: " + algorithm));
}
}
try {
transform = symmetricEncryptionAlgorithm.createEncryptor(this.key, iv, additionalAuthenticatedData,
null);
} catch (Exception e) {
return Mono.error(e);
}
byte[] encrypted;
try {
encrypted = transform.doFinal(encryptOptions.getPlainText());
} catch (Exception e) {
return Mono.error(e);
}
byte[] cipherText;
byte[] authenticationTag;
if (isGcm(algorithm)) {
cipherText = Arrays.copyOfRange(encrypted, 0, encryptOptions.getPlainText().length);
authenticationTag = Arrays.copyOfRange(encrypted, encryptOptions.getPlainText().length, encrypted.length);
} else if (isAes(algorithm)) {
cipherText = encrypted;
authenticationTag = null;
} else {
throw logger.logExceptionAsError(
new IllegalStateException("Encryption algorithm provided is not supported: " + algorithm));
}
return Mono.just(new EncryptResult(cipherText, algorithm, jsonWebKey.getId(), iv, additionalAuthenticatedData,
authenticationTag));
} | iv = generateRandomByteArray(GCM_NONCE_SIZE); | Mono<EncryptResult> encryptAsync(EncryptOptions encryptOptions, Context context, JsonWebKey jsonWebKey) {
this.key = getKey(jsonWebKey);
if (key == null || key.length == 0) {
throw logger.logExceptionAsError(new IllegalArgumentException("Key is empty."));
}
EncryptionAlgorithm algorithm = encryptOptions.getAlgorithm();
Algorithm baseAlgorithm = AlgorithmResolver.DEFAULT.get(algorithm.toString());
if (!(baseAlgorithm instanceof SymmetricEncryptionAlgorithm)) {
return Mono.error(new NoSuchAlgorithmException(algorithm.toString()));
}
SymmetricEncryptionAlgorithm symmetricEncryptionAlgorithm = (SymmetricEncryptionAlgorithm) baseAlgorithm;
ICryptoTransform transform;
byte[] iv = encryptOptions.getIv();
byte[] additionalAuthenticatedData = encryptOptions.getAdditionalAuthenticatedData();
if (iv == null) {
if (isGcm(algorithm)) {
iv = generateRandomByteArray(GCM_NONCE_SIZE);
} else if (isAes(algorithm)) {
iv = generateRandomByteArray(AES_BLOCK_SIZE);
} else {
throw logger.logExceptionAsError(
new IllegalStateException("Encryption algorithm provided is not supported: " + algorithm));
}
}
try {
transform = symmetricEncryptionAlgorithm.createEncryptor(this.key, iv, additionalAuthenticatedData,
null);
} catch (Exception e) {
return Mono.error(e);
}
byte[] encrypted;
try {
encrypted = transform.doFinal(encryptOptions.getPlainText());
} catch (Exception e) {
return Mono.error(e);
}
byte[] cipherText;
byte[] authenticationTag;
if (isGcm(algorithm)) {
cipherText = Arrays.copyOfRange(encrypted, 0, encryptOptions.getPlainText().length);
authenticationTag = Arrays.copyOfRange(encrypted, encryptOptions.getPlainText().length, encrypted.length);
} else if (isAes(algorithm)) {
cipherText = encrypted;
authenticationTag = null;
} else {
throw logger.logExceptionAsError(
new IllegalStateException("Encryption algorithm provided is not supported: " + algorithm));
}
return Mono.just(new EncryptResult(cipherText, algorithm, jsonWebKey.getId(), iv, additionalAuthenticatedData,
authenticationTag));
} | class SymmetricKeyCryptographyClient extends LocalKeyCryptographyClient {
static final int AES_BLOCK_SIZE = 16;
static final int GCM_NONCE_SIZE = 12;
private final ClientLogger logger = new ClientLogger(SymmetricKeyCryptographyClient.class);
private byte[] key;
/**
* Creates a {@link SymmetricKeyCryptographyClient} to perform local cryptography operations.
*
* @param serviceClient The client to route the requests through.
*/
SymmetricKeyCryptographyClient(CryptographyServiceClient serviceClient) {
super(serviceClient);
}
SymmetricKeyCryptographyClient(JsonWebKey key, CryptographyServiceClient serviceClient) {
super(serviceClient);
this.key = key.toAes().getEncoded();
}
private byte[] getKey(JsonWebKey key) {
if (this.key == null) {
this.key = key.toAes().getEncoded();
}
return this.key;
}
@Override
@Override
Mono<DecryptResult> decryptAsync(DecryptOptions decryptOptions, Context context, JsonWebKey jsonWebKey) {
this.key = getKey(jsonWebKey);
if (key == null || key.length == 0) {
throw logger.logExceptionAsError(new IllegalArgumentException("Key is empty."));
}
EncryptionAlgorithm algorithm = decryptOptions.getAlgorithm();
Algorithm baseAlgorithm = AlgorithmResolver.DEFAULT.get(algorithm.toString());
if (!(baseAlgorithm instanceof SymmetricEncryptionAlgorithm)) {
return Mono.error(new NoSuchAlgorithmException(algorithm.toString()));
}
SymmetricEncryptionAlgorithm symmetricEncryptionAlgorithm = (SymmetricEncryptionAlgorithm) baseAlgorithm;
ICryptoTransform transform;
byte[] iv = Objects.requireNonNull(decryptOptions.getIv(), "Initialization vector cannot be null in local decryption operations.");
byte[] additionalAuthenticatedData = decryptOptions.getAdditionalAuthenticatedData();
byte[] authenticationTag = decryptOptions.getAuthenticationTag();
try {
transform = symmetricEncryptionAlgorithm.createDecryptor(this.key, iv, additionalAuthenticatedData, authenticationTag);
} catch (Exception e) {
return Mono.error(e);
}
byte[] decrypted;
byte[] cipherText;
if (isGcm(algorithm)) {
cipherText = new byte[decryptOptions.getCipherText().length + authenticationTag.length];
System.arraycopy(decryptOptions.getCipherText(), 0, cipherText, 0, decryptOptions.getCipherText().length);
System.arraycopy(authenticationTag, 0, cipherText, decryptOptions.getCipherText().length, authenticationTag.length);
} else if (isAes(algorithm)) {
cipherText = decryptOptions.getCipherText();
} else {
throw logger.logExceptionAsError(
new IllegalStateException("Encryption algorithm provided is not supported: " + algorithm));
}
try {
decrypted = transform.doFinal(cipherText);
} catch (Exception e) {
return Mono.error(e);
}
return Mono.just(new DecryptResult(decrypted, algorithm, jsonWebKey.getId()));
}
@Override
Mono<SignResult> signAsync(SignatureAlgorithm algorithm, byte[] digest, Context context, JsonWebKey key) {
return Mono.error(new UnsupportedOperationException("Sign operation not supported for OCT/Symmetric key"));
}
@Override
Mono<VerifyResult> verifyAsync(SignatureAlgorithm algorithm, byte[] digest, byte[] signature, Context context,
JsonWebKey key) {
return Mono.error(new UnsupportedOperationException("Verify operation not supported for OCT/Symmetric key"));
}
@Override
Mono<WrapResult> wrapKeyAsync(KeyWrapAlgorithm algorithm, byte[] key, Context context, JsonWebKey jsonWebKey) {
this.key = getKey(jsonWebKey);
if (key == null || key.length == 0) {
throw logger.logExceptionAsError(new IllegalArgumentException("key"));
}
Algorithm baseAlgorithm = AlgorithmResolver.DEFAULT.get(algorithm.toString());
if (!(baseAlgorithm instanceof LocalKeyWrapAlgorithm)) {
return Mono.error(new NoSuchAlgorithmException(algorithm.toString()));
}
LocalKeyWrapAlgorithm localKeyWrapAlgorithm = (LocalKeyWrapAlgorithm) baseAlgorithm;
ICryptoTransform transform;
try {
transform = localKeyWrapAlgorithm.createEncryptor(this.key, null, null);
} catch (Exception e) {
return Mono.error(e);
}
byte[] encrypted;
try {
encrypted = transform.doFinal(key);
} catch (Exception e) {
return Mono.error(e);
}
return Mono.just(new WrapResult(encrypted, algorithm, jsonWebKey.getId()));
}
@Override
Mono<UnwrapResult> unwrapKeyAsync(KeyWrapAlgorithm algorithm, byte[] encryptedKey, Context context, JsonWebKey jsonWebKey) {
this.key = getKey(jsonWebKey);
Algorithm baseAlgorithm = AlgorithmResolver.DEFAULT.get(algorithm.toString());
if (!(baseAlgorithm instanceof LocalKeyWrapAlgorithm)) {
return Mono.error(new NoSuchAlgorithmException(algorithm.toString()));
}
LocalKeyWrapAlgorithm localKeyWrapAlgorithm = (LocalKeyWrapAlgorithm) baseAlgorithm;
ICryptoTransform transform;
try {
transform = localKeyWrapAlgorithm.createDecryptor(this.key, null, null);
} catch (Exception e) {
return Mono.error(e);
}
byte[] decrypted;
try {
decrypted = transform.doFinal(encryptedKey);
} catch (Exception e) {
return Mono.error(e);
}
return Mono.just(new UnwrapResult(decrypted, algorithm, jsonWebKey.getId()));
}
@Override
Mono<SignResult> signDataAsync(SignatureAlgorithm algorithm, byte[] data, Context context, JsonWebKey key) {
return signAsync(algorithm, data, context, key);
}
@Override
Mono<VerifyResult> verifyDataAsync(SignatureAlgorithm algorithm, byte[] data, byte[] signature, Context context,
JsonWebKey key) {
return verifyAsync(algorithm, data, signature, context, key);
}
private byte[] generateRandomByteArray(int sizeInBytes) {
byte[] iv = new byte[0];
SecureRandom randomSecureRandom;
try {
randomSecureRandom = SecureRandom.getInstance("SHA1PRNG");
iv = new byte[sizeInBytes];
randomSecureRandom.nextBytes(iv);
} catch (NoSuchAlgorithmException e) {
logger.logThrowableAsError(e);
}
return iv;
}
private boolean isGcm(EncryptionAlgorithm encryptionAlgorithm) {
return (encryptionAlgorithm == EncryptionAlgorithm.A128GCM
|| encryptionAlgorithm == EncryptionAlgorithm.A192GCM
|| encryptionAlgorithm == EncryptionAlgorithm.A256GCM);
}
private boolean isAes(EncryptionAlgorithm encryptionAlgorithm) {
return (encryptionAlgorithm == EncryptionAlgorithm.A128CBC
|| encryptionAlgorithm == EncryptionAlgorithm.A192CBC
|| encryptionAlgorithm == EncryptionAlgorithm.A256CBC
|| encryptionAlgorithm == EncryptionAlgorithm.A128CBCPAD
|| encryptionAlgorithm == EncryptionAlgorithm.A192CBCPAD
|| encryptionAlgorithm == EncryptionAlgorithm.A256CBCPAD);
}
} | class SymmetricKeyCryptographyClient extends LocalKeyCryptographyClient {
static final int AES_BLOCK_SIZE = 16;
static final int GCM_NONCE_SIZE = 12;
private final ClientLogger logger = new ClientLogger(SymmetricKeyCryptographyClient.class);
private byte[] key;
/**
* Creates a {@link SymmetricKeyCryptographyClient} to perform local cryptography operations.
*
* @param serviceClient The client to route the requests through.
*/
SymmetricKeyCryptographyClient(CryptographyServiceClient serviceClient) {
super(serviceClient);
}
SymmetricKeyCryptographyClient(JsonWebKey key, CryptographyServiceClient serviceClient) {
super(serviceClient);
this.key = key.toAes().getEncoded();
}
private byte[] getKey(JsonWebKey key) {
if (this.key == null) {
this.key = key.toAes().getEncoded();
}
return this.key;
}
@Override
@Override
Mono<DecryptResult> decryptAsync(DecryptOptions decryptOptions, Context context, JsonWebKey jsonWebKey) {
this.key = getKey(jsonWebKey);
if (key == null || key.length == 0) {
throw logger.logExceptionAsError(new IllegalArgumentException("Key is empty."));
}
EncryptionAlgorithm algorithm = decryptOptions.getAlgorithm();
Algorithm baseAlgorithm = AlgorithmResolver.DEFAULT.get(algorithm.toString());
if (!(baseAlgorithm instanceof SymmetricEncryptionAlgorithm)) {
return Mono.error(new NoSuchAlgorithmException(algorithm.toString()));
}
SymmetricEncryptionAlgorithm symmetricEncryptionAlgorithm = (SymmetricEncryptionAlgorithm) baseAlgorithm;
ICryptoTransform transform;
byte[] iv = Objects.requireNonNull(decryptOptions.getIv(), "Initialization vector cannot be null in local decryption operations.");
byte[] additionalAuthenticatedData = decryptOptions.getAdditionalAuthenticatedData();
byte[] authenticationTag = decryptOptions.getAuthenticationTag();
try {
transform = symmetricEncryptionAlgorithm.createDecryptor(this.key, iv, additionalAuthenticatedData, authenticationTag);
} catch (Exception e) {
return Mono.error(e);
}
byte[] decrypted;
byte[] cipherText;
if (isGcm(algorithm)) {
cipherText = new byte[decryptOptions.getCipherText().length + authenticationTag.length];
System.arraycopy(decryptOptions.getCipherText(), 0, cipherText, 0, decryptOptions.getCipherText().length);
System.arraycopy(authenticationTag, 0, cipherText, decryptOptions.getCipherText().length, authenticationTag.length);
} else if (isAes(algorithm)) {
cipherText = decryptOptions.getCipherText();
} else {
throw logger.logExceptionAsError(
new IllegalStateException("Encryption algorithm provided is not supported: " + algorithm));
}
try {
decrypted = transform.doFinal(cipherText);
} catch (Exception e) {
return Mono.error(e);
}
return Mono.just(new DecryptResult(decrypted, algorithm, jsonWebKey.getId()));
}
@Override
Mono<SignResult> signAsync(SignatureAlgorithm algorithm, byte[] digest, Context context, JsonWebKey key) {
return Mono.error(new UnsupportedOperationException("Sign operation not supported for OCT/Symmetric key"));
}
@Override
Mono<VerifyResult> verifyAsync(SignatureAlgorithm algorithm, byte[] digest, byte[] signature, Context context,
JsonWebKey key) {
return Mono.error(new UnsupportedOperationException("Verify operation not supported for OCT/Symmetric key"));
}
@Override
Mono<WrapResult> wrapKeyAsync(KeyWrapAlgorithm algorithm, byte[] key, Context context, JsonWebKey jsonWebKey) {
this.key = getKey(jsonWebKey);
if (key == null || key.length == 0) {
throw logger.logExceptionAsError(new IllegalArgumentException("key"));
}
Algorithm baseAlgorithm = AlgorithmResolver.DEFAULT.get(algorithm.toString());
if (!(baseAlgorithm instanceof LocalKeyWrapAlgorithm)) {
return Mono.error(new NoSuchAlgorithmException(algorithm.toString()));
}
LocalKeyWrapAlgorithm localKeyWrapAlgorithm = (LocalKeyWrapAlgorithm) baseAlgorithm;
ICryptoTransform transform;
try {
transform = localKeyWrapAlgorithm.createEncryptor(this.key, null, null);
} catch (Exception e) {
return Mono.error(e);
}
byte[] encrypted;
try {
encrypted = transform.doFinal(key);
} catch (Exception e) {
return Mono.error(e);
}
return Mono.just(new WrapResult(encrypted, algorithm, jsonWebKey.getId()));
}
@Override
Mono<UnwrapResult> unwrapKeyAsync(KeyWrapAlgorithm algorithm, byte[] encryptedKey, Context context, JsonWebKey jsonWebKey) {
this.key = getKey(jsonWebKey);
Algorithm baseAlgorithm = AlgorithmResolver.DEFAULT.get(algorithm.toString());
if (!(baseAlgorithm instanceof LocalKeyWrapAlgorithm)) {
return Mono.error(new NoSuchAlgorithmException(algorithm.toString()));
}
LocalKeyWrapAlgorithm localKeyWrapAlgorithm = (LocalKeyWrapAlgorithm) baseAlgorithm;
ICryptoTransform transform;
try {
transform = localKeyWrapAlgorithm.createDecryptor(this.key, null, null);
} catch (Exception e) {
return Mono.error(e);
}
byte[] decrypted;
try {
decrypted = transform.doFinal(encryptedKey);
} catch (Exception e) {
return Mono.error(e);
}
return Mono.just(new UnwrapResult(decrypted, algorithm, jsonWebKey.getId()));
}
@Override
Mono<SignResult> signDataAsync(SignatureAlgorithm algorithm, byte[] data, Context context, JsonWebKey key) {
return signAsync(algorithm, data, context, key);
}
@Override
Mono<VerifyResult> verifyDataAsync(SignatureAlgorithm algorithm, byte[] data, byte[] signature, Context context,
JsonWebKey key) {
return verifyAsync(algorithm, data, signature, context, key);
}
private byte[] generateRandomByteArray(int sizeInBytes) {
byte[] iv = new byte[0];
SecureRandom randomSecureRandom;
try {
randomSecureRandom = SecureRandom.getInstance("SHA1PRNG");
iv = new byte[sizeInBytes];
randomSecureRandom.nextBytes(iv);
} catch (NoSuchAlgorithmException e) {
logger.logThrowableAsError(e);
}
return iv;
}
private boolean isGcm(EncryptionAlgorithm encryptionAlgorithm) {
return (encryptionAlgorithm == EncryptionAlgorithm.A128GCM
|| encryptionAlgorithm == EncryptionAlgorithm.A192GCM
|| encryptionAlgorithm == EncryptionAlgorithm.A256GCM);
}
private boolean isAes(EncryptionAlgorithm encryptionAlgorithm) {
return (encryptionAlgorithm == EncryptionAlgorithm.A128CBC
|| encryptionAlgorithm == EncryptionAlgorithm.A192CBC
|| encryptionAlgorithm == EncryptionAlgorithm.A256CBC
|| encryptionAlgorithm == EncryptionAlgorithm.A128CBCPAD
|| encryptionAlgorithm == EncryptionAlgorithm.A192CBCPAD
|| encryptionAlgorithm == EncryptionAlgorithm.A256CBCPAD);
}
} |
Does this not attempt to authenticate the request before initially sending it? | public Mono<HttpResponse> process(HttpPipelineCallContext context, HttpPipelineNextPolicy next) {
if ("http".equals(context.getHttpRequest().getUrl().getProtocol())) {
return Mono.error(new RuntimeException("token credentials require a URL using the HTTPS protocol scheme"));
}
HttpPipelineNextPolicy nextPolicy = next.clone();
return Mono.defer(() -> next.process())
.flatMap(httpResponse -> {
String authHeader = httpResponse.getHeaderValue(WWW_AUTHENTICATE);
if (httpResponse.getStatusCode() == 401 && authHeader != null) {
return tryGetTokenRequestContext(context, httpResponse)
.flatMap(trc -> authenticateRequest(context, trc)
.then(Mono.defer(() -> nextPolicy.process())))
.switchIfEmpty(Mono.just(httpResponse));
}
return Mono.just(httpResponse);
});
} | return Mono.defer(() -> next.process()) | public Mono<HttpResponse> process(HttpPipelineCallContext context, HttpPipelineNextPolicy next) {
if ("http".equals(context.getHttpRequest().getUrl().getProtocol())) {
return Mono.error(new RuntimeException("token credentials require a URL using the HTTPS protocol scheme"));
}
HttpPipelineNextPolicy nextPolicy = next.clone();
return onBeforeRequest(context)
.then(Mono.defer(() -> next.process()))
.flatMap(httpResponse -> {
String authHeader = httpResponse.getHeaderValue(WWW_AUTHENTICATE);
if (httpResponse.getStatusCode() == 401 && authHeader != null) {
return onChallenge(context, httpResponse).flatMap(retry -> {
if (retry) {
return nextPolicy.process();
} else {
return Mono.just(httpResponse);
}
});
}
return Mono.just(httpResponse);
});
} | class BearerTokenAuthenticationChallengePolicy implements HttpPipelinePolicy {
private static final String AUTHORIZATION_HEADER = "Authorization";
private static final String BEARER = "Bearer";
public static final String WWW_AUTHENTICATE = "WWW-Authenticate";
private final TokenRequestContext defaultTokenRequestContext;
private final AccessTokenCacheImpl cache;
/**
* Creates BearerTokenAuthenticationChallengePolicy.
*
* @param credential the token credential to authenticate the request
* @param scopes the scopes of authentication the credential should get token for
*/
public BearerTokenAuthenticationChallengePolicy(TokenCredential credential, String... scopes) {
Objects.requireNonNull(credential);
this.defaultTokenRequestContext = new TokenRequestContext().addScopes(scopes);
this.cache = new AccessTokenCacheImpl(credential, defaultTokenRequestContext);
}
/**
* Hanles the authentication challenge in the event a 401 response with a WWW-Authenticate authentication
* challenge header is received after the initial request and returns appropriate {@link TokenRequestContext} to
* be used to re-authentication.
*
* @param context The request context.
* @param response The Http Response containing the authentication challenge header.
* @return A {@link Mono} containing {@link TokenRequestContext}
*/
public Mono<TokenRequestContext> tryGetTokenRequestContext(HttpPipelineCallContext context, HttpResponse response) {
return Mono.empty();
}
@Override
/**
* Authenticates the request with the bearer token acquired using the specified {@code tokenRequestContext}
*
* @param context the HTTP pipeline context.
* @param tokenRequestContext the token request conext to be used for token acquisition.
* @return a {@link Mono} containing {@link Void}
*/
public Mono<Void> authenticateRequest(HttpPipelineCallContext context, TokenRequestContext tokenRequestContext) {
return cache.getToken(tokenRequestContext)
.flatMap(token -> {
context.getHttpRequest().getHeaders().set(AUTHORIZATION_HEADER, BEARER + " " + token.getToken());
return Mono.empty();
});
}
/**
* Authenticates the request with the bearer token acquired using the default {@link TokenRequestContext} containing
* the scopes specified at policy construction time.
*
* @param context the HTTP pipeline context.
* @return a {@link Mono} containing {@link Void}
*/
public Mono<Void> authenticateRequest(HttpPipelineCallContext context) {
return cache.getToken(defaultTokenRequestContext)
.flatMap(token -> {
context.getHttpRequest().getHeaders().set(AUTHORIZATION_HEADER, BEARER + " " + token.getToken());
return Mono.empty();
});
}
} | class BearerTokenAuthenticationChallengePolicy implements HttpPipelinePolicy {
private static final String AUTHORIZATION_HEADER = "Authorization";
private static final String BEARER = "Bearer";
public static final String WWW_AUTHENTICATE = "WWW-Authenticate";
private final AccessTokenCacheImpl cache;
/**
* Creates BearerTokenAuthenticationChallengePolicy.
*
* @param credential the token credential to authenticate the request
*/
public BearerTokenAuthenticationChallengePolicy(TokenCredential credential) {
Objects.requireNonNull(credential);
this.cache = new AccessTokenCacheImpl(credential);
}
/**
* Executed before sending the initial request and authenticates the request.
*
* @param context The request context.
* @return A {@link Mono} containing {@link Void}
*/
public Mono<Void> onBeforeRequest(HttpPipelineCallContext context) {
return Mono.empty();
}
/**
* Handles the authentication challenge in the event a 401 response with a WWW-Authenticate authentication
* challenge header is received after the initial request and returns appropriate {@link TokenRequestContext} to
* be used for re-authentication.
*
* @param context The request context.
* @param response The Http Response containing the authentication challenge header.
* @return A {@link Mono} containing {@link TokenRequestContext}
*/
public Mono<Boolean> onChallenge(HttpPipelineCallContext context, HttpResponse response) {
return Mono.just(false);
}
@Override
/**
* Authorizes the request with the bearer token acquired using the specified {@code tokenRequestContext}
*
* @param context the HTTP pipeline context.
* @param tokenRequestContext the token request conext to be used for token acquisition.
* @return a {@link Mono} containing {@link Void}
*/
public Mono<Void> authorizeRequest(HttpPipelineCallContext context, TokenRequestContext tokenRequestContext) {
return cache.getToken(tokenRequestContext)
.flatMap(token -> {
context.getHttpRequest().getHeaders().set(AUTHORIZATION_HEADER, BEARER + " " + token.getToken());
return Mono.empty();
});
}
} |
nit: `CoreUtils.isNullOrEmpty(scopes)` | public Mono<Void> onBeforeRequest(HttpPipelineCallContext context) {
return Mono.defer(() -> {
TokenRequestContext trc;
String[] scopes = this.scopes;
if (scopes == null || scopes.length == 0) {
scopes = new String[1];
scopes[0] = ARMScopeHelper.getDefaultScopeFromRequest(
context.getHttpRequest(), environment);
}
trc = new TokenRequestContext().addScopes(scopes);
context.setData(ARM_SCOPES_KEY, scopes);
return authorizeRequest(context, trc);
});
} | if (scopes == null || scopes.length == 0) { | public Mono<Void> onBeforeRequest(HttpPipelineCallContext context) {
return Mono.defer(() -> {
String[] scopes = this.scopes;
scopes = getScopes(context, scopes);
context.setData(ARM_SCOPES_KEY, scopes);
return authorizeRequest(context, new TokenRequestContext().addScopes(scopes));
});
} | class ARMChallengeAuthenticationPolicy extends BearerTokenAuthenticationChallengePolicy {
private static final Pattern AUTHENTICATION_CHALLENGE_PATTERN =
Pattern.compile("(\\w+) ((?:\\w+=\".*?\"(?:, )?)+)(?:, )?");
private static final Pattern AUTHENTICATION_CHALLENGE_PARAMS_PATTERN =
Pattern.compile("(?:(\\w+)=\"([^\"\"]*)\")+");
private static final String CLAIMS_PARAMETER = "claims";
private final String[] scopes;
private final AzureEnvironment environment;
private static final String ARM_SCOPES_KEY = "ARMScopes";
/**
* Creates ARMChallengeAuthenticationPolicy.
*
* @param credential the token credential to authenticate the request
* @param environment the environment with endpoints for authentication
* @param scopes the scopes used in credential, using default scopes when empty
*/
public ARMChallengeAuthenticationPolicy(TokenCredential credential,
AzureEnvironment environment, String... scopes) {
super(credential);
this.scopes = scopes;
this.environment = environment;
}
@Override
@Override
public Mono<Boolean> onChallenge(HttpPipelineCallContext context, HttpResponse response) {
return Mono.defer(() -> {
String authHeader = response.getHeaderValue(WWW_AUTHENTICATE);
if (response.getStatusCode() == 401 && authHeader != null) {
List<AuthenticationChallenge> challenges = parseChallenges(authHeader);
for (AuthenticationChallenge authenticationChallenge : challenges) {
Map<String, String> extractedChallengeParams =
parseChallengeParams(authenticationChallenge.getChallengeParameters());
if (extractedChallengeParams.containsKey(CLAIMS_PARAMETER)) {
String claims = new String(Base64.getUrlDecoder()
.decode(extractedChallengeParams.get(CLAIMS_PARAMETER)), StandardCharsets.UTF_8);
String[] scopes;
try {
scopes = (String[]) context.getData(ARM_SCOPES_KEY).get();
} catch (NoSuchElementException e) {
scopes = this.scopes;
}
if (scopes == null || scopes.length == 0) {
scopes = new String[1];
scopes[0] = ARMScopeHelper.getDefaultScopeFromRequest(
context.getHttpRequest(), environment);
}
return authorizeRequest(context, new TokenRequestContext()
.addScopes(scopes).setClaims(claims))
.flatMap(b -> Mono.just(true));
}
}
}
return Mono.just(false);
});
}
List<AuthenticationChallenge> parseChallenges(String header) {
Matcher matcher = AUTHENTICATION_CHALLENGE_PATTERN.matcher(header);
List<AuthenticationChallenge> challenges = new ArrayList<>();
while (matcher.find()) {
challenges.add(new AuthenticationChallenge(matcher.group(1), matcher.group(2)));
}
return challenges;
}
Map<String, String> parseChallengeParams(String challengeParams) {
Matcher matcher = AUTHENTICATION_CHALLENGE_PARAMS_PATTERN.matcher(challengeParams);
Map<String, String> challengeParameters = new HashMap<>();
while (matcher.find()) {
challengeParameters.put(matcher.group(1), matcher.group(2));
}
return challengeParameters;
}
} | class ARMChallengeAuthenticationPolicy extends BearerTokenAuthenticationChallengePolicy {
private static final Pattern AUTHENTICATION_CHALLENGE_PATTERN =
Pattern.compile("(\\w+) ((?:\\w+=\".*?\"(?:, )?)+)(?:, )?");
private static final Pattern AUTHENTICATION_CHALLENGE_PARAMS_PATTERN =
Pattern.compile("(?:(\\w+)=\"([^\"\"]*)\")+");
private static final String CLAIMS_PARAMETER = "claims";
private final String[] scopes;
private final AzureEnvironment environment;
private static final String ARM_SCOPES_KEY = "ARMScopes";
/**
* Creates ARMChallengeAuthenticationPolicy.
*
* @param credential the token credential to authenticate the request
* @param environment the environment with endpoints for authentication
* @param scopes the scopes used in credential, using default scopes when empty
*/
public ARMChallengeAuthenticationPolicy(TokenCredential credential,
AzureEnvironment environment, String... scopes) {
super(credential);
this.scopes = scopes;
this.environment = environment;
}
@Override
@Override
public Mono<Boolean> onChallenge(HttpPipelineCallContext context, HttpResponse response) {
return Mono.defer(() -> {
String authHeader = response.getHeaderValue(WWW_AUTHENTICATE);
if (!(response.getStatusCode() == 401 && authHeader != null)) {
return Mono.just(false);
} else {
List<AuthenticationChallenge> challenges = parseChallenges(authHeader);
for (AuthenticationChallenge authenticationChallenge : challenges) {
Map<String, String> extractedChallengeParams =
parseChallengeParams(authenticationChallenge.getChallengeParameters());
if (extractedChallengeParams.containsKey(CLAIMS_PARAMETER)) {
String claims = new String(Base64.getUrlDecoder()
.decode(extractedChallengeParams.get(CLAIMS_PARAMETER)), StandardCharsets.UTF_8);
String[] scopes;
try {
scopes = (String[]) context.getData(ARM_SCOPES_KEY).get();
} catch (NoSuchElementException e) {
scopes = this.scopes;
}
scopes = getScopes(context, scopes);
return authorizeRequest(context, new TokenRequestContext()
.addScopes(scopes).setClaims(claims))
.flatMap(b -> Mono.just(true));
}
}
return Mono.just(false);
}
});
}
private String[] getScopes(HttpPipelineCallContext context, String[] scopes) {
if (CoreUtils.isNullOrEmpty(scopes)) {
scopes = new String[1];
scopes[0] = ARMScopeHelper.getDefaultScopeFromRequest(
context.getHttpRequest(), environment);
}
return scopes;
}
List<AuthenticationChallenge> parseChallenges(String header) {
Matcher matcher = AUTHENTICATION_CHALLENGE_PATTERN.matcher(header);
List<AuthenticationChallenge> challenges = new ArrayList<>();
while (matcher.find()) {
challenges.add(new AuthenticationChallenge(matcher.group(1), matcher.group(2)));
}
return challenges;
}
Map<String, String> parseChallengeParams(String challengeParams) {
Matcher matcher = AUTHENTICATION_CHALLENGE_PARAMS_PATTERN.matcher(challengeParams);
Map<String, String> challengeParameters = new HashMap<>();
while (matcher.find()) {
challengeParameters.put(matcher.group(1), matcher.group(2));
}
return challengeParameters;
}
} |
We should add null checks for "from" and "to": e.g. `Objects.requireNonNull(from, "'from' cannot be null.");` | public Mono<SmsSendResult> send(String from, String to, String message) {
return send(from, to, message, null);
} | return send(from, to, message, null); | public Mono<SmsSendResult> send(String from, String to, String message) {
return send(from, to, message, null);
} | class SmsAsyncClient {
private final AzureCommunicationSMSServiceImpl smsServiceClient;
private final ClientLogger logger = new ClientLogger(SmsAsyncClient.class);
SmsAsyncClient(AzureCommunicationSMSServiceImpl smsServiceClient) {
this.smsServiceClient = smsServiceClient;
}
/**
* Sends an SMS message from a phone number that belongs to the authenticated account.
* Phone number has to be in the format 000 - 00 - 00
*
* @param from Number that is sending the message.
* @param to The recipient's phone number.
* @param message message to send to recipient.
* @return response for a successful send Sms request.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
/**
* Sends an SMS message from a phone number that belongs to the authenticated account.
*
* @param from Number that is sending the message.
* @param to The recipient's phone number.
* @param message message to send to recipient.
* @param smsOptions set options on the SMS request, like enable delivery report, which sends a report
* for this message to the Azure Resource Event Grid.
* @return response for a successful send Sms request.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<SmsSendResult> send(String from, String to, String message,
SmsSendOptions smsOptions) {
List<String> recipients = new ArrayList<String>();
recipients.add(to);
SendMessageRequest request = createSendMessageRequest(from, recipients, message, smsOptions);
try {
Mono<Response<SmsSendResponse>> responseMono = withContext(context -> this.smsServiceClient.getSms().sendWithResponseAsync(request, context));
Response<SmsSendResponse> response = responseMono.block();
SmsSendResponse smsSendResponse = response.getValue();
List<SmsSendResult> result = convertSmsResults(smsSendResponse.getValue());
if (result.size() == 1) {
return Mono.just(result.get(0));
} else {
return monoError(logger, new NullPointerException("no response"));
}
} catch (NullPointerException ex) {
return monoError(logger, ex);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Sends an SMS message from a phone number that belongs to the authenticated account.
*
* @param from Number that is sending the message.
* @param to A list of the recipient's phone numbers.
* @param message message to send to recipient.
* @return response for a successful send Sms request.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Iterable<SmsSendResult>> send(String from, Iterable<String> to, String message) {
return send(from, to, message, null);
}
/**
* Sends an SMS message from a phone number that belongs to the authenticated account.
*
* @param from Number that is sending the message.
* @param to A list of the recipient's phone numbers.
* @param message message to send to recipient.
* @param smsOptions set options on the SMS request, like enable delivery report, which sends a report
* for this message to the Azure Resource Event Grid
* @return response for a successful send Sms request.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Iterable<SmsSendResult>> send(String from, Iterable<String> to, String message, SmsSendOptions smsOptions) {
SendMessageRequest request = createSendMessageRequest(from, to, message, smsOptions);
try {
Mono<Response<SmsSendResponse>> responseMono = withContext(context -> this.smsServiceClient.getSms().sendWithResponseAsync(request, context));
Response<SmsSendResponse> response = responseMono.block();
SmsSendResponse smsSendResponse = response.getValue();
List<SmsSendResult> result = convertSmsResults(smsSendResponse.getValue());
return Mono.just(result);
} catch (NullPointerException ex) {
return monoError(logger, ex);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
private List<SmsSendResult> convertSmsResults(Iterable<SmsSendResponseItem> resultsIterable) {
List <SmsSendResult> iterableWrapper = new ArrayList<>();
for (SmsSendResponseItem item : resultsIterable
) {
iterableWrapper.add(new SmsSendResult(item));
}
return iterableWrapper;
}
private SendMessageRequest createSendMessageRequest(String from, Iterable<String> smsRecipient, String message,
SmsSendOptions smsOptions) {
SendMessageRequest request = new SendMessageRequest();
List<SmsRecipient> recipients = new ArrayList<SmsRecipient>();
for (String s : smsRecipient) {
recipients.add(new SmsRecipient().setTo(s));
}
request.setFrom(from);
request.setSmsRecipients(recipients);
request.setMessage(message);
request.setSmsSendOptions(smsOptions);
return request;
}
} | class SmsAsyncClient {
private final AzureCommunicationSMSServiceImpl smsServiceClient;
private final ClientLogger logger = new ClientLogger(SmsAsyncClient.class);
SmsAsyncClient(AzureCommunicationSMSServiceImpl smsServiceClient) {
this.smsServiceClient = smsServiceClient;
}
/**
* Sends an SMS message from a phone number that belongs to the authenticated account.
* Phone number has to be in the format 000 - 00 - 00
*
* @param from Number that is sending the message.
* @param to The recipient's phone number.
* @param message message to send to recipient.
* @return response for a successful send Sms request.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
/**
* Sends an SMS message from a phone number that belongs to the authenticated account.
*
* @param from Number that is sending the message.
* @param to The recipient's phone number.
* @param message message to send to recipient.
* @param smsOptions set options on the SMS request, like enable delivery report, which sends a report
* for this message to the Azure Resource Event Grid.
* @return response for a successful send Sms request.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<SmsSendResult> send(String from, String to, String message, SmsSendOptions smsOptions) {
List<String> recipients = new ArrayList<String>();
recipients.add(to);
SendMessageRequest request = createSendMessageRequest(from, recipients, message, smsOptions);
try {
Objects.requireNonNull(from, "'from' cannot be null.");
Objects.requireNonNull(to, "'to' cannot be null.");
Mono<Response<SmsSendResponse>> responseMono = withContext(context -> this.smsServiceClient.getSms().sendWithResponseAsync(request, context));
Response<SmsSendResponse> response = responseMono.block();
SmsSendResponse smsSendResponse = response.getValue();
List<SmsSendResult> result = convertSmsResults(smsSendResponse.getValue());
if (result.size() == 1) {
return Mono.just(result.get(0));
} else {
return monoError(logger, new NullPointerException("no response"));
}
} catch (NullPointerException ex) {
return monoError(logger, ex);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Sends an SMS message from a phone number that belongs to the authenticated account.
*
* @param from Number that is sending the message.
* @param to A list of the recipient's phone numbers.
* @param message message to send to recipient.
* @return response for a successful send Sms request.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Iterable<SmsSendResult>> send(String from, Iterable<String> to, String message) {
return send(from, to, message, null);
}
/**
* Sends an SMS message from a phone number that belongs to the authenticated account.
*
* @param from Number that is sending the message.
* @param to A list of the recipient's phone numbers.
* @param message message to send to recipient.
* @param smsOptions set options on the SMS request, like enable delivery report, which sends a report
* for this message to the Azure Resource Event Grid.
* @return response for a successful send Sms request.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Iterable<SmsSendResult>> send(String from, Iterable<String> to, String message, SmsSendOptions smsOptions) {
SendMessageRequest request = createSendMessageRequest(from, to, message, smsOptions);
try {
Objects.requireNonNull(from, "'from' cannot be null.");
Objects.requireNonNull(to, "'to' cannot be null.");
Mono<Response<SmsSendResponse>> responseMono = withContext(context -> this.smsServiceClient.getSms().sendWithResponseAsync(request, context));
Response<SmsSendResponse> response = responseMono.block();
SmsSendResponse smsSendResponse = response.getValue();
List<SmsSendResult> result = convertSmsResults(smsSendResponse.getValue());
return Mono.just(result);
} catch (NullPointerException ex) {
return monoError(logger, ex);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
private List<SmsSendResult> convertSmsResults(Iterable<SmsSendResponseItem> resultsIterable) {
List <SmsSendResult> iterableWrapper = new ArrayList<>();
for (SmsSendResponseItem item : resultsIterable
) {
iterableWrapper.add(new SmsSendResult(item));
}
return iterableWrapper;
}
private SendMessageRequest createSendMessageRequest(String from, Iterable<String> smsRecipient, String message, SmsSendOptions smsOptions) {
SendMessageRequest request = new SendMessageRequest();
List<SmsRecipient> recipients = new ArrayList<SmsRecipient>();
for (String s : smsRecipient) {
recipients.add(new SmsRecipient().setTo(s));
}
request.setFrom(from)
.setSmsRecipients(recipients)
.setMessage(message)
.setSmsSendOptions(smsOptions);
return request;
}
} |
Same as above. DOnt need to specify null pointer exception | public Mono<Iterable<SmsSendResult>> send(String from, Iterable<String> to, String message, SmsSendOptions smsOptions) {
SendMessageRequest request = createSendMessageRequest(from, to, message, smsOptions);
try {
Mono<Response<SmsSendResponse>> responseMono = withContext(context -> this.smsServiceClient.getSms().sendWithResponseAsync(request, context));
Response<SmsSendResponse> response = responseMono.block();
SmsSendResponse smsSendResponse = response.getValue();
List<SmsSendResult> result = convertSmsResults(smsSendResponse.getValue());
return Mono.just(result);
} catch (NullPointerException ex) {
return monoError(logger, ex);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
} | } catch (NullPointerException ex) { | return monoError(logger, ex);
} catch (RuntimeException ex) {
return monoError(logger, ex);
} | class SmsAsyncClient {
private final AzureCommunicationSMSServiceImpl smsServiceClient;
private final ClientLogger logger = new ClientLogger(SmsAsyncClient.class);
SmsAsyncClient(AzureCommunicationSMSServiceImpl smsServiceClient) {
this.smsServiceClient = smsServiceClient;
}
/**
* Sends an SMS message from a phone number that belongs to the authenticated account.
* Phone number has to be in the format 000 - 00 - 00
*
* @param from Number that is sending the message.
* @param to The recipient's phone number.
* @param message message to send to recipient.
* @return response for a successful send Sms request.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<SmsSendResult> send(String from, String to, String message) {
return send(from, to, message, null);
}
/**
* Sends an SMS message from a phone number that belongs to the authenticated account.
*
* @param from Number that is sending the message.
* @param to The recipient's phone number.
* @param message message to send to recipient.
* @param smsOptions set options on the SMS request, like enable delivery report, which sends a report
* for this message to the Azure Resource Event Grid.
* @return response for a successful send Sms request.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<SmsSendResult> send(String from, String to, String message,
SmsSendOptions smsOptions) {
List<String> recipients = new ArrayList<String>();
recipients.add(to);
SendMessageRequest request = createSendMessageRequest(from, recipients, message, smsOptions);
try {
Mono<Response<SmsSendResponse>> responseMono = withContext(context -> this.smsServiceClient.getSms().sendWithResponseAsync(request, context));
Response<SmsSendResponse> response = responseMono.block();
SmsSendResponse smsSendResponse = response.getValue();
List<SmsSendResult> result = convertSmsResults(smsSendResponse.getValue());
if (result.size() == 1) {
return Mono.just(result.get(0));
} else {
return monoError(logger, new NullPointerException("no response"));
}
} catch (NullPointerException ex) {
}
/**
* Sends an SMS message from a phone number that belongs to the authenticated account.
*
* @param from Number that is sending the message.
* @param to A list of the recipient's phone numbers.
* @param message message to send to recipient.
* @return response for a successful send Sms request.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Iterable<SmsSendResult>> send(String from, Iterable<String> to, String message) {
return send(from, to, message, null);
}
/**
* Sends an SMS message from a phone number that belongs to the authenticated account.
*
* @param from Number that is sending the message.
* @param to A list of the recipient's phone numbers.
* @param message message to send to recipient.
* @param smsOptions set options on the SMS request, like enable delivery report, which sends a report
* for this message to the Azure Resource Event Grid
* @return response for a successful send Sms request.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Iterable<SmsSendResult>> send(String from, Iterable<String> to, String message, SmsSendOptions smsOptions) {
SendMessageRequest request = createSendMessageRequest(from, to, message, smsOptions);
try {
Mono<Response<SmsSendResponse>> responseMono = withContext(context -> this.smsServiceClient.getSms().sendWithResponseAsync(request, context));
Response<SmsSendResponse> response = responseMono.block();
SmsSendResponse smsSendResponse = response.getValue();
List<SmsSendResult> result = convertSmsResults(smsSendResponse.getValue());
return Mono.just(result);
} catch (NullPointerException ex) {
return monoError(logger, ex);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
private List<SmsSendResult> convertSmsResults(Iterable<SmsSendResponseItem> resultsIterable) {
List <SmsSendResult> iterableWrapper = new ArrayList<>();
for (SmsSendResponseItem item : resultsIterable
) {
iterableWrapper.add(new SmsSendResult(item));
}
return iterableWrapper;
}
private SendMessageRequest createSendMessageRequest(String from, Iterable<String> smsRecipient, String message,
SmsSendOptions smsOptions) {
SendMessageRequest request = new SendMessageRequest();
List<SmsRecipient> recipients = new ArrayList<SmsRecipient>();
for (String s : smsRecipient) {
recipients.add(new SmsRecipient().setTo(s));
}
request.setFrom(from);
request.setSmsRecipients(recipients);
request.setMessage(message);
request.setSmsSendOptions(smsOptions);
return request;
}
} | class SmsAsyncClient {
private final AzureCommunicationSMSServiceImpl smsServiceClient;
private final ClientLogger logger = new ClientLogger(SmsAsyncClient.class);
SmsAsyncClient(AzureCommunicationSMSServiceImpl smsServiceClient) {
this.smsServiceClient = smsServiceClient;
}
/**
* Sends an SMS message from a phone number that belongs to the authenticated account.
* Phone number has to be in the format 000 - 00 - 00
*
* @param from Number that is sending the message.
* @param to The recipient's phone number.
* @param message message to send to recipient.
* @return response for a successful send Sms request.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<SmsSendResult> send(String from, String to, String message) {
return send(from, to, message, null);
}
/**
* Sends an SMS message from a phone number that belongs to the authenticated account.
*
* @param from Number that is sending the message.
* @param to The recipient's phone number.
* @param message message to send to recipient.
* @param smsOptions set options on the SMS request, like enable delivery report, which sends a report
* for this message to the Azure Resource Event Grid.
* @return response for a successful send Sms request.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<SmsSendResult> send(String from, String to, String message, SmsSendOptions smsOptions) {
List<String> recipients = new ArrayList<String>();
recipients.add(to);
SendMessageRequest request = createSendMessageRequest(from, recipients, message, smsOptions);
try {
Objects.requireNonNull(from, "'from' cannot be null.");
Objects.requireNonNull(to, "'to' cannot be null.");
Mono<Response<SmsSendResponse>> responseMono = withContext(context -> this.smsServiceClient.getSms().sendWithResponseAsync(request, context));
Response<SmsSendResponse> response = responseMono.block();
SmsSendResponse smsSendResponse = response.getValue();
List<SmsSendResult> result = convertSmsResults(smsSendResponse.getValue());
if (result.size() == 1) {
return Mono.just(result.get(0));
} else {
return monoError(logger, new NullPointerException("no response"));
}
} catch (NullPointerException ex) {
}
/**
* Sends an SMS message from a phone number that belongs to the authenticated account.
*
* @param from Number that is sending the message.
* @param to A list of the recipient's phone numbers.
* @param message message to send to recipient.
* @return response for a successful send Sms request.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Iterable<SmsSendResult>> send(String from, Iterable<String> to, String message) {
return send(from, to, message, null);
}
/**
* Sends an SMS message from a phone number that belongs to the authenticated account.
*
* @param from Number that is sending the message.
* @param to A list of the recipient's phone numbers.
* @param message message to send to recipient.
* @param smsOptions set options on the SMS request, like enable delivery report, which sends a report
* for this message to the Azure Resource Event Grid.
* @return response for a successful send Sms request.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Iterable<SmsSendResult>> send(String from, Iterable<String> to, String message, SmsSendOptions smsOptions) {
SendMessageRequest request = createSendMessageRequest(from, to, message, smsOptions);
try {
Objects.requireNonNull(from, "'from' cannot be null.");
Objects.requireNonNull(to, "'to' cannot be null.");
Mono<Response<SmsSendResponse>> responseMono = withContext(context -> this.smsServiceClient.getSms().sendWithResponseAsync(request, context));
Response<SmsSendResponse> response = responseMono.block();
SmsSendResponse smsSendResponse = response.getValue();
List<SmsSendResult> result = convertSmsResults(smsSendResponse.getValue());
return Mono.just(result);
} catch (NullPointerException ex) {
return monoError(logger, ex);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
private List<SmsSendResult> convertSmsResults(Iterable<SmsSendResponseItem> resultsIterable) {
List <SmsSendResult> iterableWrapper = new ArrayList<>();
for (SmsSendResponseItem item : resultsIterable
) {
iterableWrapper.add(new SmsSendResult(item));
}
return iterableWrapper;
}
private SendMessageRequest createSendMessageRequest(String from, Iterable<String> smsRecipient, String message, SmsSendOptions smsOptions) {
SendMessageRequest request = new SendMessageRequest();
List<SmsRecipient> recipients = new ArrayList<SmsRecipient>();
for (String s : smsRecipient) {
recipients.add(new SmsRecipient().setTo(s));
}
request.setFrom(from)
.setSmsRecipients(recipients)
.setMessage(message)
.setSmsSendOptions(smsOptions);
return request;
}
} |
The names that you pass in should be the name of the test, and it should be unique for all the test cases | public void sendToMultipleUsers(HttpClient httpClient) {
to = new ArrayList<String>();
to.add(TO_PHONE_NUMBER);
SmsClientBuilder builder = getSmsClient(httpClient);
asyncClient = setupAsyncClient(builder, "send");
Mono<Iterable<SmsSendResult>> response = asyncClient.send(FROM_PHONE_NUMBER, to, MESSAGE, null);
StepVerifier.create(response)
.assertNext(item -> {
assertNotNull(item);
})
.verifyComplete();
} | asyncClient = setupAsyncClient(builder, "send"); | public void sendToMultipleUsers(HttpClient httpClient) {
to = new ArrayList<String>();
to.add(SMS_SERVICE_PHONE_NUMBER);
SmsClientBuilder builder = getSmsClient(httpClient);
asyncClient = setupAsyncClient(builder, "sendToMultipleUsers");
Mono<Iterable<SmsSendResult>> response = asyncClient.send(SMS_SERVICE_PHONE_NUMBER, to, MESSAGE, null);
StepVerifier.create(response)
.assertNext(item -> {
assertNotNull(item);
})
.verifyComplete();
} | class SmsAsyncClientTests extends SmsTestBase {
private List<String> to;
private SmsAsyncClient asyncClient;
@Override
protected void beforeTest() {
super.beforeTest();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void createAsyncClientUsingConnectionString(HttpClient httpClient) {
to = new ArrayList<String>();
to.add(TO_PHONE_NUMBER);
SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient);
asyncClient = setupAsyncClient(builder, "createAsyncSmsClientUsingConnectionString");
assertNotNull(asyncClient);
Mono<Iterable<SmsSendResult>> response = asyncClient.send(FROM_PHONE_NUMBER, to, MESSAGE, null);
StepVerifier.create(response)
.assertNext(item -> {
assertNotNull(item);
})
.verifyComplete();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void sendSmsUsingTokenCredential(HttpClient httpClient) {
TokenCredential tokenCredential = new DefaultAzureCredentialBuilder().build();
to = new ArrayList<>();
to.add(TO_PHONE_NUMBER);
SmsClientBuilder builder = getSmsClientWithToken(httpClient, tokenCredential);
asyncClient = setupAsyncClient(builder, "createAsyncSmsClientUsingConnectionString");
assertNotNull(asyncClient);
Mono<Iterable<SmsSendResult>> response = asyncClient.send(FROM_PHONE_NUMBER, to, MESSAGE, null);
StepVerifier.create(response)
.assertNext(item -> {
assertNotNull(item);
})
.verifyComplete();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void sendToSingleUser(HttpClient httpClient) {
SmsClientBuilder builder = getSmsClient(httpClient);
asyncClient = setupAsyncClient(builder, "send");
Mono<SmsSendResult> response = asyncClient.send(FROM_PHONE_NUMBER, TO_PHONE_NUMBER, MESSAGE, null);
StepVerifier.create(response)
.assertNext(item -> {
assertNotNull(item);
})
.verifyComplete();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void sendToSingleUserWithOptions(HttpClient httpClient) {
SmsSendOptions options = new SmsSendOptions();
options.setDeliveryReportEnabled(true);
options.setTag("New Tag");
SmsClientBuilder builder = getSmsClient(httpClient);
asyncClient = setupAsyncClient(builder, "send");
Mono<SmsSendResult> response = asyncClient.send(FROM_PHONE_NUMBER, TO_PHONE_NUMBER, MESSAGE, options);
StepVerifier.create(response)
.assertNext(item -> {
assertNotNull(item);
})
.verifyComplete();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void sendToMultipleUsersWithOptions(HttpClient httpClient) {
SmsSendOptions options = new SmsSendOptions();
options.setDeliveryReportEnabled(true);
options.setTag("New Tag");
to = new ArrayList<String>();
to.add(TO_PHONE_NUMBER);
SmsClientBuilder builder = getSmsClient(httpClient);
asyncClient = setupAsyncClient(builder, "send");
Mono<Iterable<SmsSendResult>> response = asyncClient.send(FROM_PHONE_NUMBER, to, MESSAGE, options);
StepVerifier.create(response)
.assertNext(item -> {
assertNotNull(item);
})
.verifyComplete();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void sendToIncorrectPhoneNumber(HttpClient httpClient) {
to = new ArrayList<String>();
to.add(FAIL_PHONE_NUMBER);
SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient);
asyncClient = setupAsyncClient(builder, "createAsyncSmsClientUsingConnectionString");
assertNotNull(asyncClient);
Mono<Iterable<SmsSendResult>> response = asyncClient.send(FROM_PHONE_NUMBER, to, MESSAGE, null);
assertNotNull(response);
StepVerifier.create(response)
.assertNext(item -> {
assertNotNull(item);
})
.verifyComplete();
}
private SmsAsyncClient setupAsyncClient(SmsClientBuilder builder, String testName) {
return addLoggingPolicy(builder, testName).buildAsyncClient();
}
} | class SmsAsyncClientTests extends SmsTestBase {
private List<String> to;
private SmsAsyncClient asyncClient;
@Override
protected void beforeTest() {
super.beforeTest();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void createAsyncClientUsingConnectionString(HttpClient httpClient) {
to = new ArrayList<String>();
to.add(SMS_SERVICE_PHONE_NUMBER);
SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient);
asyncClient = setupAsyncClient(builder, "createAsyncSmsClientUsingConnectionString");
assertNotNull(asyncClient);
Mono<Iterable<SmsSendResult>> response = asyncClient.send(SMS_SERVICE_PHONE_NUMBER, to, MESSAGE, null);
StepVerifier.create(response)
.assertNext(item -> {
assertNotNull(item);
})
.verifyComplete();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void sendSmsUsingTokenCredential(HttpClient httpClient) {
TokenCredential tokenCredential = new DefaultAzureCredentialBuilder().build();
to = new ArrayList<>();
to.add(SMS_SERVICE_PHONE_NUMBER);
SmsClientBuilder builder = getSmsClientWithToken(httpClient, tokenCredential);
asyncClient = setupAsyncClient(builder, "sendSmsUsingTokenCredential");
assertNotNull(asyncClient);
Mono<Iterable<SmsSendResult>> response = asyncClient.send(SMS_SERVICE_PHONE_NUMBER, to, MESSAGE, null);
StepVerifier.create(response)
.assertNext(item -> {
assertNotNull(item);
})
.verifyComplete();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void sendToSingleUser(HttpClient httpClient) {
SmsClientBuilder builder = getSmsClient(httpClient);
asyncClient = setupAsyncClient(builder, "sendToSingleUser");
Mono<SmsSendResult> response = asyncClient.send(SMS_SERVICE_PHONE_NUMBER, SMS_SERVICE_PHONE_NUMBER, MESSAGE, null);
StepVerifier.create(response)
.assertNext(item -> {
assertNotNull(item);
})
.verifyComplete();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void sendToSingleUserWithOptions(HttpClient httpClient) {
SmsSendOptions options = new SmsSendOptions();
options.setDeliveryReportEnabled(true);
options.setTag("New Tag");
SmsClientBuilder builder = getSmsClient(httpClient);
asyncClient = setupAsyncClient(builder, "sendToSingleUserWithOptions");
Mono<SmsSendResult> response = asyncClient.send(SMS_SERVICE_PHONE_NUMBER, SMS_SERVICE_PHONE_NUMBER, MESSAGE, options);
StepVerifier.create(response)
.assertNext(item -> {
assertNotNull(item);
})
.verifyComplete();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void sendToMultipleUsersWithOptions(HttpClient httpClient) {
SmsSendOptions options = new SmsSendOptions();
options.setDeliveryReportEnabled(true);
options.setTag("New Tag");
to = new ArrayList<String>();
to.add(SMS_SERVICE_PHONE_NUMBER);
SmsClientBuilder builder = getSmsClient(httpClient);
asyncClient = setupAsyncClient(builder, "sendToMultipleUsersWithOptions");
Mono<Iterable<SmsSendResult>> response = asyncClient.send(SMS_SERVICE_PHONE_NUMBER, to, MESSAGE, options);
StepVerifier.create(response)
.assertNext(item -> {
assertNotNull(item);
})
.verifyComplete();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void sendFromFakeNumber(HttpClient httpClient) {
SmsSendOptions options = new SmsSendOptions();
options.setDeliveryReportEnabled(true);
options.setTag("New Tag");
SmsClientBuilder builder = getSmsClient(httpClient);
asyncClient = setupAsyncClient(builder, "sendFromFakeNumber");
Mono<SmsSendResult> response = asyncClient.send("+155512345678", SMS_SERVICE_PHONE_NUMBER, MESSAGE, options);
StepVerifier.create(response)
.expectErrorMatches(exception ->
((HttpResponseException) exception).getResponse().getStatusCode() == 400
).verify();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void sendFromUnauthorizedNumber(HttpClient httpClient) {
SmsSendOptions options = new SmsSendOptions();
options.setDeliveryReportEnabled(true);
options.setTag("New Tag");
SmsClientBuilder builder = getSmsClient(httpClient);
asyncClient = setupAsyncClient(builder, "sendFromUnauthorizedNumber");
Mono<SmsSendResult> response = asyncClient.send("+18007342577", SMS_SERVICE_PHONE_NUMBER, MESSAGE, options);
StepVerifier.create(response)
.expectErrorMatches(exception ->
((HttpResponseException) exception).getResponse().getStatusCode() == 404
).verify();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void sendIdempotencyCheck(HttpClient httpClient) {
SmsSendOptions options = new SmsSendOptions();
options.setDeliveryReportEnabled(true);
options.setTag("New Tag");
SmsClientBuilder builder = getSmsClient(httpClient);
asyncClient = setupAsyncClient(builder, "sendIdempotencyCheck");
Mono<SmsSendResult> response1 = asyncClient.send(SMS_SERVICE_PHONE_NUMBER, SMS_SERVICE_PHONE_NUMBER, MESSAGE, options);
StepVerifier.create(response1)
.assertNext(item -> {
assertNotNull(item);
})
.verifyComplete();
assertTrue(response1.block().isSuccessful());
Mono<SmsSendResult> response2 = asyncClient.send(SMS_SERVICE_PHONE_NUMBER, SMS_SERVICE_PHONE_NUMBER, MESSAGE, options);
StepVerifier.create(response2)
.assertNext(item -> {
assertNotNull(item);
})
.verifyComplete();
assertTrue(response2.block().isSuccessful());
assertNotEquals(response1.block().getMessageId(), response2.block().getMessageId());
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void sendToIncorrectPhoneNumber(HttpClient httpClient) {
to = new ArrayList<String>();
to.add("+155512345678");
SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient);
asyncClient = setupAsyncClient(builder, "sendToIncorrectPhoneNumber");
assertNotNull(asyncClient);
Mono<Iterable<SmsSendResult>> response = asyncClient.send(SMS_SERVICE_PHONE_NUMBER, to, MESSAGE, null);
assertNotNull(response);
StepVerifier.create(response)
.assertNext(item -> {
assertNotNull(item);
})
.verifyComplete();
Iterable<SmsSendResult> smsSendResults = response.block();
for (SmsSendResult result : smsSendResults) {
assertFalse(result.isSuccessful());
assertEquals(result.getHttpStatusCode(), 400);
}
}
private SmsAsyncClient setupAsyncClient(SmsClientBuilder builder, String testName) {
return addLoggingPolicy(builder, testName).buildAsyncClient();
}
} |
name needs to be updated. | public void sendFromFakeNumber(HttpClient httpClient) {
SmsSendOptions options = new SmsSendOptions();
options.setDeliveryReportEnabled(true);
options.setTag("New Tag");
SmsClientBuilder builder = getSmsClient(httpClient);
client = setupSyncClient(builder, "sendToSingleUserWithOptions");
try {
SmsSendResult response = client.send("+155512345678", SMS_SERVICE_PHONE_NUMBER, MESSAGE, options);
} catch (Exception exception) {
assertEquals(400, ((HttpResponseException) exception).getResponse().getStatusCode());
}
} | client = setupSyncClient(builder, "sendToSingleUserWithOptions"); | public void sendFromFakeNumber(HttpClient httpClient) {
SmsSendOptions options = new SmsSendOptions();
options.setDeliveryReportEnabled(true);
options.setTag("New Tag");
SmsClientBuilder builder = getSmsClient(httpClient);
client = setupSyncClient(builder, "sendFromFakeNumber");
try {
SmsSendResult response = client.send("+155512345678", SMS_SERVICE_PHONE_NUMBER, MESSAGE, options);
} catch (Exception exception) {
assertEquals(400, ((HttpResponseException) exception).getResponse().getStatusCode());
}
} | class SmsClientTests extends SmsTestBase {
private List<String> to;
private SmsClient client;
@Override
protected void beforeTest() {
super.beforeTest();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void createSyncClientUsingConnectionString(HttpClient httpClient) {
to = new ArrayList<String>();
to.add(SMS_SERVICE_PHONE_NUMBER);
SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient);
client = setupSyncClient(builder, "createSyncClientUsingConnectionString");
assertNotNull(client);
Iterable<SmsSendResult> response = client.send(SMS_SERVICE_PHONE_NUMBER, to, MESSAGE, null, Context.NONE);
assertNotNull(response);
for (SmsSendResult r : response) {
assertTrue(r.isSuccessful());
assertNull(r.getErrorMessage());
}
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void builderNoEndpoint(HttpClient httpClient) {
SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient);
builder
.endpoint(null)
.httpClient(new NoOpHttpClient());
assertThrows(Exception.class, () -> {
builder.buildAsyncClient();
});
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void builderServiceVersion(HttpClient httpClient) {
assertNotNull(SmsServiceVersion.getLatest());
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void builderNotRetryPolicy(HttpClient httpClient) {
SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient);
builder.retryPolicy(null);
client = setupSyncClient(builder, "builderNotRetryPolicy");
assertNotNull(client);
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void sendSmsUsingTokenCredential(HttpClient httpClient) {
TokenCredential tokenCredential = new DefaultAzureCredentialBuilder().build();
to = new ArrayList<>();
to.add(SMS_SERVICE_PHONE_NUMBER);
SmsClientBuilder builder = getSmsClientWithToken(httpClient, tokenCredential);
client = setupSyncClient(builder, "sendSmsUsingTokenCredential");
assertNotNull(client);
Iterable<SmsSendResult> response = client.send(SMS_SERVICE_PHONE_NUMBER, to, MESSAGE, null, Context.NONE);
assertNotNull(response);
for (SmsSendResult r : response) {
assertTrue(r.isSuccessful());
}
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void sendToIncorrectPhoneNumber(HttpClient httpClient) {
to = new ArrayList<String>();
to.add("+155512345678");
SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient);
client = setupSyncClient(builder, "sendToIncorrectPhoneNumber");
assertNotNull(client);
Iterable<SmsSendResult> response = client.send(SMS_SERVICE_PHONE_NUMBER, to, MESSAGE, null, Context.NONE);
assertNotNull(response);
for (SmsSendResult r : response) {
assertFalse(r.isSuccessful());
}
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void sendFromUnauthorizedNumber(HttpClient httpClient) {
SmsSendOptions options = new SmsSendOptions();
options.setDeliveryReportEnabled(true);
options.setTag("New Tag");
SmsClientBuilder builder = getSmsClient(httpClient);
client = setupSyncClient(builder, "sendFromUnauthorizedNumber");
try {
SmsSendResult response = client.send("+18007342577", SMS_SERVICE_PHONE_NUMBER, MESSAGE, options, Context.NONE);
} catch (Exception exception) {
assertEquals(404, ((HttpResponseException) exception).getResponse().getStatusCode());
}
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void sendToMultipleUsers(HttpClient httpClient) {
to = new ArrayList<String>();
to.add(SMS_SERVICE_PHONE_NUMBER);
SmsClientBuilder builder = getSmsClient(httpClient);
client = setupSyncClient(builder, "sendToMultipleUsers");
Iterable<SmsSendResult> response = client.send(SMS_SERVICE_PHONE_NUMBER, to, MESSAGE);
assertNotNull(response);
for (SmsSendResult r : response) {
assertTrue(r.isSuccessful());
}
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void sendToMultipleUsersWithOptions(HttpClient httpClient) {
SmsSendOptions options = new SmsSendOptions();
options.setDeliveryReportEnabled(true);
options.setTag("New Tag");
to = new ArrayList<String>();
to.add(SMS_SERVICE_PHONE_NUMBER);
SmsClientBuilder builder = getSmsClient(httpClient);
client = setupSyncClient(builder, "sendToMultipleUsersWithOptions");
Iterable<SmsSendResult> response = client.send(SMS_SERVICE_PHONE_NUMBER, to, MESSAGE, options, Context.NONE);
assertNotNull(response);
for (SmsSendResult r : response) {
assertTrue(r.isSuccessful());
}
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void sendToSingleUser(HttpClient httpClient) {
SmsClientBuilder builder = getSmsClient(httpClient);
client = setupSyncClient(builder, "sendToSingleUser");
SmsSendResult response = client.send(SMS_SERVICE_PHONE_NUMBER, SMS_SERVICE_PHONE_NUMBER, MESSAGE);
assertNotNull(response);
assertTrue(response.isSuccessful());
assertNull(response.getErrorMessage());
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void sendIdempotencyCheck(HttpClient httpClient) {
SmsSendOptions options = new SmsSendOptions();
options.setDeliveryReportEnabled(true);
options.setTag("New Tag");
SmsClientBuilder builder = getSmsClient(httpClient);
client = setupSyncClient(builder, "sendToSingleUserWithOptions");
SmsSendResult response1 = client.send(SMS_SERVICE_PHONE_NUMBER, SMS_SERVICE_PHONE_NUMBER, MESSAGE, options);
assertTrue(response1.isSuccessful());
SmsSendResult response2 = client.send(SMS_SERVICE_PHONE_NUMBER, SMS_SERVICE_PHONE_NUMBER, MESSAGE, options);
assertTrue(response2.isSuccessful());
assertNotEquals(response1.getMessageId(), response2.getMessageId());
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void sendToSingleUserWithOptions(HttpClient httpClient) {
SmsSendOptions options = new SmsSendOptions();
options.setDeliveryReportEnabled(true);
options.setTag("New Tag");
to = new ArrayList<String>();
to.add(SMS_SERVICE_PHONE_NUMBER);
SmsClientBuilder builder = getSmsClient(httpClient);
client = setupSyncClient(builder, "sendToSingleUserWithOptions");
SmsSendResult response = client.send(SMS_SERVICE_PHONE_NUMBER, SMS_SERVICE_PHONE_NUMBER, MESSAGE, options, Context.NONE);
assertNotNull(response);
assertTrue(response.isSuccessful());
}
private SmsClient setupSyncClient(SmsClientBuilder builder, String testName) {
return addLoggingPolicy(builder, testName).buildClient();
}
} | class SmsClientTests extends SmsTestBase {
private List<String> to;
private SmsClient client;
@Override
protected void beforeTest() {
super.beforeTest();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void createSyncClientUsingConnectionString(HttpClient httpClient) {
to = new ArrayList<String>();
to.add(SMS_SERVICE_PHONE_NUMBER);
SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient);
client = setupSyncClient(builder, "createSyncClientUsingConnectionString");
assertNotNull(client);
Iterable<SmsSendResult> response = client.send(SMS_SERVICE_PHONE_NUMBER, to, MESSAGE, null, Context.NONE);
assertNotNull(response);
for (SmsSendResult r : response) {
assertTrue(r.isSuccessful());
assertNull(r.getErrorMessage());
}
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void builderNoEndpoint(HttpClient httpClient) {
SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient);
builder
.endpoint(null)
.httpClient(new NoOpHttpClient());
assertThrows(Exception.class, () -> {
builder.buildAsyncClient();
});
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void builderServiceVersion(HttpClient httpClient) {
assertNotNull(SmsServiceVersion.getLatest());
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void builderTestsConfigurations(HttpClient httpClient) {
SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient);
builder.retryPolicy(null);
AzureKeyCredential credential = new AzureKeyCredential(ACCESSKEY);
HttpPipelinePolicy[] policies = new HttpPipelinePolicy[2];
policies[0] = new HmacAuthenticationPolicy(credential);
policies[1] = new UserAgentPolicy();
HttpPipeline pipeline = new HttpPipelineBuilder()
.policies(policies)
.httpClient(httpClient)
.build();
builder.pipeline(pipeline);
client = setupSyncClient(builder, "builderTestsConfigurations");
assertNotNull(client);
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void builderNotRetryPolicy(HttpClient httpClient) {
SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient);
builder.retryPolicy(null);
client = setupSyncClient(builder, "builderNotRetryPolicy");
assertNotNull(client);
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void sendSmsUsingTokenCredential(HttpClient httpClient) {
TokenCredential tokenCredential = new DefaultAzureCredentialBuilder().build();
to = new ArrayList<>();
to.add(SMS_SERVICE_PHONE_NUMBER);
SmsClientBuilder builder = getSmsClientWithToken(httpClient, tokenCredential);
client = setupSyncClient(builder, "sendSmsUsingTokenCredential");
assertNotNull(client);
Iterable<SmsSendResult> response = client.send(SMS_SERVICE_PHONE_NUMBER, to, MESSAGE, null, Context.NONE);
assertNotNull(response);
for (SmsSendResult r : response) {
assertTrue(r.isSuccessful());
}
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void sendToIncorrectPhoneNumber(HttpClient httpClient) {
to = new ArrayList<String>();
to.add("+155512345678");
SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient);
client = setupSyncClient(builder, "sendToIncorrectPhoneNumber");
assertNotNull(client);
Iterable<SmsSendResult> response = client.send(SMS_SERVICE_PHONE_NUMBER, to, MESSAGE, null, Context.NONE);
assertNotNull(response);
for (SmsSendResult r : response) {
assertFalse(r.isSuccessful());
}
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void sendFromUnauthorizedNumber(HttpClient httpClient) {
SmsSendOptions options = new SmsSendOptions();
options.setDeliveryReportEnabled(true);
options.setTag("New Tag");
SmsClientBuilder builder = getSmsClient(httpClient);
client = setupSyncClient(builder, "sendFromUnauthorizedNumber");
try {
SmsSendResult response = client.send("+18007342577", SMS_SERVICE_PHONE_NUMBER, MESSAGE, options, Context.NONE);
} catch (Exception exception) {
assertEquals(404, ((HttpResponseException) exception).getResponse().getStatusCode());
}
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void sendToMultipleUsers(HttpClient httpClient) {
to = new ArrayList<String>();
to.add(SMS_SERVICE_PHONE_NUMBER);
SmsClientBuilder builder = getSmsClient(httpClient);
client = setupSyncClient(builder, "sendToMultipleUsers");
Iterable<SmsSendResult> response = client.send(SMS_SERVICE_PHONE_NUMBER, to, MESSAGE);
assertNotNull(response);
for (SmsSendResult r : response) {
assertTrue(r.isSuccessful());
}
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void sendToMultipleUsersWithOptions(HttpClient httpClient) {
SmsSendOptions options = new SmsSendOptions();
options.setDeliveryReportEnabled(true);
options.setTag("New Tag");
to = new ArrayList<String>();
to.add(SMS_SERVICE_PHONE_NUMBER);
SmsClientBuilder builder = getSmsClient(httpClient);
client = setupSyncClient(builder, "sendToMultipleUsersWithOptions");
Iterable<SmsSendResult> response = client.send(SMS_SERVICE_PHONE_NUMBER, to, MESSAGE, options, Context.NONE);
assertNotNull(response);
for (SmsSendResult r : response) {
assertTrue(r.isSuccessful());
}
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void sendToSingleUser(HttpClient httpClient) {
SmsClientBuilder builder = getSmsClient(httpClient);
client = setupSyncClient(builder, "sendToSingleUser");
SmsSendResult response = client.send(SMS_SERVICE_PHONE_NUMBER, SMS_SERVICE_PHONE_NUMBER, MESSAGE);
assertNotNull(response);
assertTrue(response.isSuccessful());
assertNull(response.getErrorMessage());
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void sendIdempotencyCheck(HttpClient httpClient) {
SmsSendOptions options = new SmsSendOptions();
options.setDeliveryReportEnabled(true);
options.setTag("New Tag");
SmsClientBuilder builder = getSmsClient(httpClient);
client = setupSyncClient(builder, "sendIdempotencyCheck");
SmsSendResult response1 = client.send(SMS_SERVICE_PHONE_NUMBER, SMS_SERVICE_PHONE_NUMBER, MESSAGE, options);
assertTrue(response1.isSuccessful());
SmsSendResult response2 = client.send(SMS_SERVICE_PHONE_NUMBER, SMS_SERVICE_PHONE_NUMBER, MESSAGE, options);
assertTrue(response2.isSuccessful());
assertNotEquals(response1.getMessageId(), response2.getMessageId());
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void sendToSingleUserWithOptions(HttpClient httpClient) {
SmsSendOptions options = new SmsSendOptions();
options.setDeliveryReportEnabled(true);
options.setTag("New Tag");
to = new ArrayList<String>();
to.add(SMS_SERVICE_PHONE_NUMBER);
SmsClientBuilder builder = getSmsClient(httpClient);
client = setupSyncClient(builder, "sendToSingleUserWithOptions");
SmsSendResult response = client.send(SMS_SERVICE_PHONE_NUMBER, SMS_SERVICE_PHONE_NUMBER, MESSAGE, options, Context.NONE);
assertNotNull(response);
assertTrue(response.isSuccessful());
}
private SmsClient setupSyncClient(SmsClientBuilder builder, String testName) {
return addLoggingPolicy(builder, testName).buildClient();
}
} |
name needs to be udpated | public void sendIdempotencyCheck(HttpClient httpClient) {
SmsSendOptions options = new SmsSendOptions();
options.setDeliveryReportEnabled(true);
options.setTag("New Tag");
SmsClientBuilder builder = getSmsClient(httpClient);
asyncClient = setupAsyncClient(builder, "sendToSingleUserWithOptions");
Mono<SmsSendResult> response1 = asyncClient.send(SMS_SERVICE_PHONE_NUMBER, SMS_SERVICE_PHONE_NUMBER, MESSAGE, options);
StepVerifier.create(response1)
.assertNext(item -> {
assertNotNull(item);
})
.verifyComplete();
assertTrue(response1.block().isSuccessful());
Mono<SmsSendResult> response2 = asyncClient.send(SMS_SERVICE_PHONE_NUMBER, SMS_SERVICE_PHONE_NUMBER, MESSAGE, options);
StepVerifier.create(response2)
.assertNext(item -> {
assertNotNull(item);
})
.verifyComplete();
assertTrue(response2.block().isSuccessful());
assertNotEquals(response1.block().getMessageId(), response2.block().getMessageId());
} | asyncClient = setupAsyncClient(builder, "sendToSingleUserWithOptions"); | public void sendIdempotencyCheck(HttpClient httpClient) {
SmsSendOptions options = new SmsSendOptions();
options.setDeliveryReportEnabled(true);
options.setTag("New Tag");
SmsClientBuilder builder = getSmsClient(httpClient);
asyncClient = setupAsyncClient(builder, "sendIdempotencyCheck");
Mono<SmsSendResult> response1 = asyncClient.send(SMS_SERVICE_PHONE_NUMBER, SMS_SERVICE_PHONE_NUMBER, MESSAGE, options);
StepVerifier.create(response1)
.assertNext(item -> {
assertNotNull(item);
})
.verifyComplete();
assertTrue(response1.block().isSuccessful());
Mono<SmsSendResult> response2 = asyncClient.send(SMS_SERVICE_PHONE_NUMBER, SMS_SERVICE_PHONE_NUMBER, MESSAGE, options);
StepVerifier.create(response2)
.assertNext(item -> {
assertNotNull(item);
})
.verifyComplete();
assertTrue(response2.block().isSuccessful());
assertNotEquals(response1.block().getMessageId(), response2.block().getMessageId());
} | class SmsAsyncClientTests extends SmsTestBase {
private List<String> to;
private SmsAsyncClient asyncClient;
@Override
protected void beforeTest() {
super.beforeTest();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void createAsyncClientUsingConnectionString(HttpClient httpClient) {
to = new ArrayList<String>();
to.add(SMS_SERVICE_PHONE_NUMBER);
SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient);
asyncClient = setupAsyncClient(builder, "createAsyncSmsClientUsingConnectionString");
assertNotNull(asyncClient);
Mono<Iterable<SmsSendResult>> response = asyncClient.send(SMS_SERVICE_PHONE_NUMBER, to, MESSAGE, null);
StepVerifier.create(response)
.assertNext(item -> {
assertNotNull(item);
})
.verifyComplete();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void sendSmsUsingTokenCredential(HttpClient httpClient) {
TokenCredential tokenCredential = new DefaultAzureCredentialBuilder().build();
to = new ArrayList<>();
to.add(SMS_SERVICE_PHONE_NUMBER);
SmsClientBuilder builder = getSmsClientWithToken(httpClient, tokenCredential);
asyncClient = setupAsyncClient(builder, "sendSmsUsingTokenCredential");
assertNotNull(asyncClient);
Mono<Iterable<SmsSendResult>> response = asyncClient.send(SMS_SERVICE_PHONE_NUMBER, to, MESSAGE, null);
StepVerifier.create(response)
.assertNext(item -> {
assertNotNull(item);
})
.verifyComplete();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void sendToMultipleUsers(HttpClient httpClient) {
to = new ArrayList<String>();
to.add(SMS_SERVICE_PHONE_NUMBER);
SmsClientBuilder builder = getSmsClient(httpClient);
asyncClient = setupAsyncClient(builder, "sendToMultipleUsers");
Mono<Iterable<SmsSendResult>> response = asyncClient.send(SMS_SERVICE_PHONE_NUMBER, to, MESSAGE, null);
StepVerifier.create(response)
.assertNext(item -> {
assertNotNull(item);
})
.verifyComplete();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void sendToSingleUser(HttpClient httpClient) {
SmsClientBuilder builder = getSmsClient(httpClient);
asyncClient = setupAsyncClient(builder, "sendToSingleUser");
Mono<SmsSendResult> response = asyncClient.send(SMS_SERVICE_PHONE_NUMBER, SMS_SERVICE_PHONE_NUMBER, MESSAGE, null);
StepVerifier.create(response)
.assertNext(item -> {
assertNotNull(item);
})
.verifyComplete();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void sendToSingleUserWithOptions(HttpClient httpClient) {
SmsSendOptions options = new SmsSendOptions();
options.setDeliveryReportEnabled(true);
options.setTag("New Tag");
SmsClientBuilder builder = getSmsClient(httpClient);
asyncClient = setupAsyncClient(builder, "sendToSingleUserWithOptions");
Mono<SmsSendResult> response = asyncClient.send(SMS_SERVICE_PHONE_NUMBER, SMS_SERVICE_PHONE_NUMBER, MESSAGE, options);
StepVerifier.create(response)
.assertNext(item -> {
assertNotNull(item);
})
.verifyComplete();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void sendToMultipleUsersWithOptions(HttpClient httpClient) {
SmsSendOptions options = new SmsSendOptions();
options.setDeliveryReportEnabled(true);
options.setTag("New Tag");
to = new ArrayList<String>();
to.add(SMS_SERVICE_PHONE_NUMBER);
SmsClientBuilder builder = getSmsClient(httpClient);
asyncClient = setupAsyncClient(builder, "sendToMultipleUsersWithOptions");
Mono<Iterable<SmsSendResult>> response = asyncClient.send(SMS_SERVICE_PHONE_NUMBER, to, MESSAGE, options);
StepVerifier.create(response)
.assertNext(item -> {
assertNotNull(item);
})
.verifyComplete();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void sendFromFakeNumber(HttpClient httpClient) {
SmsSendOptions options = new SmsSendOptions();
options.setDeliveryReportEnabled(true);
options.setTag("New Tag");
SmsClientBuilder builder = getSmsClient(httpClient);
asyncClient = setupAsyncClient(builder, "sendToSingleUserWithOptions");
Mono<SmsSendResult> response = asyncClient.send("+155512345678", SMS_SERVICE_PHONE_NUMBER, MESSAGE, options);
StepVerifier.create(response)
.expectErrorMatches(exception ->
((HttpResponseException) exception).getResponse().getStatusCode() == 400
).verify();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void sendFromUnauthorizedNumber(HttpClient httpClient) {
SmsSendOptions options = new SmsSendOptions();
options.setDeliveryReportEnabled(true);
options.setTag("New Tag");
SmsClientBuilder builder = getSmsClient(httpClient);
asyncClient = setupAsyncClient(builder, "sendFromUnauthorizedNumber");
Mono<SmsSendResult> response = asyncClient.send("+18007342577", SMS_SERVICE_PHONE_NUMBER, MESSAGE, options);
StepVerifier.create(response)
.expectErrorMatches(exception ->
((HttpResponseException) exception).getResponse().getStatusCode() == 404
).verify();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void sendToIncorrectPhoneNumber(HttpClient httpClient) {
to = new ArrayList<String>();
to.add("+155512345678");
SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient);
asyncClient = setupAsyncClient(builder, "sendToIncorrectPhoneNumber");
assertNotNull(asyncClient);
Mono<Iterable<SmsSendResult>> response = asyncClient.send(SMS_SERVICE_PHONE_NUMBER, to, MESSAGE, null);
assertNotNull(response);
StepVerifier.create(response)
.assertNext(item -> {
assertNotNull(item);
})
.verifyComplete();
Iterable<SmsSendResult> smsSendResults = response.block();
for (SmsSendResult result : smsSendResults) {
assertFalse(result.isSuccessful());
assertEquals(result.getHttpStatusCode(), 400);
}
}
private SmsAsyncClient setupAsyncClient(SmsClientBuilder builder, String testName) {
return addLoggingPolicy(builder, testName).buildAsyncClient();
}
} | class SmsAsyncClientTests extends SmsTestBase {
private List<String> to;
private SmsAsyncClient asyncClient;
@Override
protected void beforeTest() {
super.beforeTest();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void createAsyncClientUsingConnectionString(HttpClient httpClient) {
to = new ArrayList<String>();
to.add(SMS_SERVICE_PHONE_NUMBER);
SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient);
asyncClient = setupAsyncClient(builder, "createAsyncSmsClientUsingConnectionString");
assertNotNull(asyncClient);
Mono<Iterable<SmsSendResult>> response = asyncClient.send(SMS_SERVICE_PHONE_NUMBER, to, MESSAGE, null);
StepVerifier.create(response)
.assertNext(item -> {
assertNotNull(item);
})
.verifyComplete();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void sendSmsUsingTokenCredential(HttpClient httpClient) {
TokenCredential tokenCredential = new DefaultAzureCredentialBuilder().build();
to = new ArrayList<>();
to.add(SMS_SERVICE_PHONE_NUMBER);
SmsClientBuilder builder = getSmsClientWithToken(httpClient, tokenCredential);
asyncClient = setupAsyncClient(builder, "sendSmsUsingTokenCredential");
assertNotNull(asyncClient);
Mono<Iterable<SmsSendResult>> response = asyncClient.send(SMS_SERVICE_PHONE_NUMBER, to, MESSAGE, null);
StepVerifier.create(response)
.assertNext(item -> {
assertNotNull(item);
})
.verifyComplete();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void sendToMultipleUsers(HttpClient httpClient) {
to = new ArrayList<String>();
to.add(SMS_SERVICE_PHONE_NUMBER);
SmsClientBuilder builder = getSmsClient(httpClient);
asyncClient = setupAsyncClient(builder, "sendToMultipleUsers");
Mono<Iterable<SmsSendResult>> response = asyncClient.send(SMS_SERVICE_PHONE_NUMBER, to, MESSAGE, null);
StepVerifier.create(response)
.assertNext(item -> {
assertNotNull(item);
})
.verifyComplete();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void sendToSingleUser(HttpClient httpClient) {
SmsClientBuilder builder = getSmsClient(httpClient);
asyncClient = setupAsyncClient(builder, "sendToSingleUser");
Mono<SmsSendResult> response = asyncClient.send(SMS_SERVICE_PHONE_NUMBER, SMS_SERVICE_PHONE_NUMBER, MESSAGE, null);
StepVerifier.create(response)
.assertNext(item -> {
assertNotNull(item);
})
.verifyComplete();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void sendToSingleUserWithOptions(HttpClient httpClient) {
SmsSendOptions options = new SmsSendOptions();
options.setDeliveryReportEnabled(true);
options.setTag("New Tag");
SmsClientBuilder builder = getSmsClient(httpClient);
asyncClient = setupAsyncClient(builder, "sendToSingleUserWithOptions");
Mono<SmsSendResult> response = asyncClient.send(SMS_SERVICE_PHONE_NUMBER, SMS_SERVICE_PHONE_NUMBER, MESSAGE, options);
StepVerifier.create(response)
.assertNext(item -> {
assertNotNull(item);
})
.verifyComplete();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void sendToMultipleUsersWithOptions(HttpClient httpClient) {
SmsSendOptions options = new SmsSendOptions();
options.setDeliveryReportEnabled(true);
options.setTag("New Tag");
to = new ArrayList<String>();
to.add(SMS_SERVICE_PHONE_NUMBER);
SmsClientBuilder builder = getSmsClient(httpClient);
asyncClient = setupAsyncClient(builder, "sendToMultipleUsersWithOptions");
Mono<Iterable<SmsSendResult>> response = asyncClient.send(SMS_SERVICE_PHONE_NUMBER, to, MESSAGE, options);
StepVerifier.create(response)
.assertNext(item -> {
assertNotNull(item);
})
.verifyComplete();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void sendFromFakeNumber(HttpClient httpClient) {
SmsSendOptions options = new SmsSendOptions();
options.setDeliveryReportEnabled(true);
options.setTag("New Tag");
SmsClientBuilder builder = getSmsClient(httpClient);
asyncClient = setupAsyncClient(builder, "sendFromFakeNumber");
Mono<SmsSendResult> response = asyncClient.send("+155512345678", SMS_SERVICE_PHONE_NUMBER, MESSAGE, options);
StepVerifier.create(response)
.expectErrorMatches(exception ->
((HttpResponseException) exception).getResponse().getStatusCode() == 400
).verify();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void sendFromUnauthorizedNumber(HttpClient httpClient) {
SmsSendOptions options = new SmsSendOptions();
options.setDeliveryReportEnabled(true);
options.setTag("New Tag");
SmsClientBuilder builder = getSmsClient(httpClient);
asyncClient = setupAsyncClient(builder, "sendFromUnauthorizedNumber");
Mono<SmsSendResult> response = asyncClient.send("+18007342577", SMS_SERVICE_PHONE_NUMBER, MESSAGE, options);
StepVerifier.create(response)
.expectErrorMatches(exception ->
((HttpResponseException) exception).getResponse().getStatusCode() == 404
).verify();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void sendToIncorrectPhoneNumber(HttpClient httpClient) {
to = new ArrayList<String>();
to.add("+155512345678");
SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient);
asyncClient = setupAsyncClient(builder, "sendToIncorrectPhoneNumber");
assertNotNull(asyncClient);
Mono<Iterable<SmsSendResult>> response = asyncClient.send(SMS_SERVICE_PHONE_NUMBER, to, MESSAGE, null);
assertNotNull(response);
StepVerifier.create(response)
.assertNext(item -> {
assertNotNull(item);
})
.verifyComplete();
Iterable<SmsSendResult> smsSendResults = response.block();
for (SmsSendResult result : smsSendResults) {
assertFalse(result.isSuccessful());
assertEquals(result.getHttpStatusCode(), 400);
}
}
private SmsAsyncClient setupAsyncClient(SmsClientBuilder builder, String testName) {
return addLoggingPolicy(builder, testName).buildAsyncClient();
}
} |
Name needs to be updated, can you please check all these parameters to make sure they match the test name? | public void sendFromFakeNumber(HttpClient httpClient) {
SmsSendOptions options = new SmsSendOptions();
options.setDeliveryReportEnabled(true);
options.setTag("New Tag");
SmsClientBuilder builder = getSmsClient(httpClient);
asyncClient = setupAsyncClient(builder, "sendToSingleUserWithOptions");
Mono<SmsSendResult> response = asyncClient.send("+155512345678", SMS_SERVICE_PHONE_NUMBER, MESSAGE, options);
StepVerifier.create(response)
.expectErrorMatches(exception ->
((HttpResponseException) exception).getResponse().getStatusCode() == 400
).verify();
} | asyncClient = setupAsyncClient(builder, "sendToSingleUserWithOptions"); | public void sendFromFakeNumber(HttpClient httpClient) {
SmsSendOptions options = new SmsSendOptions();
options.setDeliveryReportEnabled(true);
options.setTag("New Tag");
SmsClientBuilder builder = getSmsClient(httpClient);
asyncClient = setupAsyncClient(builder, "sendFromFakeNumber");
Mono<SmsSendResult> response = asyncClient.send("+155512345678", SMS_SERVICE_PHONE_NUMBER, MESSAGE, options);
StepVerifier.create(response)
.expectErrorMatches(exception ->
((HttpResponseException) exception).getResponse().getStatusCode() == 400
).verify();
} | class SmsAsyncClientTests extends SmsTestBase {
private List<String> to;
private SmsAsyncClient asyncClient;
@Override
protected void beforeTest() {
super.beforeTest();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void createAsyncClientUsingConnectionString(HttpClient httpClient) {
to = new ArrayList<String>();
to.add(SMS_SERVICE_PHONE_NUMBER);
SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient);
asyncClient = setupAsyncClient(builder, "createAsyncSmsClientUsingConnectionString");
assertNotNull(asyncClient);
Mono<Iterable<SmsSendResult>> response = asyncClient.send(SMS_SERVICE_PHONE_NUMBER, to, MESSAGE, null);
StepVerifier.create(response)
.assertNext(item -> {
assertNotNull(item);
})
.verifyComplete();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void sendSmsUsingTokenCredential(HttpClient httpClient) {
TokenCredential tokenCredential = new DefaultAzureCredentialBuilder().build();
to = new ArrayList<>();
to.add(SMS_SERVICE_PHONE_NUMBER);
SmsClientBuilder builder = getSmsClientWithToken(httpClient, tokenCredential);
asyncClient = setupAsyncClient(builder, "sendSmsUsingTokenCredential");
assertNotNull(asyncClient);
Mono<Iterable<SmsSendResult>> response = asyncClient.send(SMS_SERVICE_PHONE_NUMBER, to, MESSAGE, null);
StepVerifier.create(response)
.assertNext(item -> {
assertNotNull(item);
})
.verifyComplete();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void sendToMultipleUsers(HttpClient httpClient) {
to = new ArrayList<String>();
to.add(SMS_SERVICE_PHONE_NUMBER);
SmsClientBuilder builder = getSmsClient(httpClient);
asyncClient = setupAsyncClient(builder, "sendToMultipleUsers");
Mono<Iterable<SmsSendResult>> response = asyncClient.send(SMS_SERVICE_PHONE_NUMBER, to, MESSAGE, null);
StepVerifier.create(response)
.assertNext(item -> {
assertNotNull(item);
})
.verifyComplete();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void sendToSingleUser(HttpClient httpClient) {
SmsClientBuilder builder = getSmsClient(httpClient);
asyncClient = setupAsyncClient(builder, "sendToSingleUser");
Mono<SmsSendResult> response = asyncClient.send(SMS_SERVICE_PHONE_NUMBER, SMS_SERVICE_PHONE_NUMBER, MESSAGE, null);
StepVerifier.create(response)
.assertNext(item -> {
assertNotNull(item);
})
.verifyComplete();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void sendToSingleUserWithOptions(HttpClient httpClient) {
SmsSendOptions options = new SmsSendOptions();
options.setDeliveryReportEnabled(true);
options.setTag("New Tag");
SmsClientBuilder builder = getSmsClient(httpClient);
asyncClient = setupAsyncClient(builder, "sendToSingleUserWithOptions");
Mono<SmsSendResult> response = asyncClient.send(SMS_SERVICE_PHONE_NUMBER, SMS_SERVICE_PHONE_NUMBER, MESSAGE, options);
StepVerifier.create(response)
.assertNext(item -> {
assertNotNull(item);
})
.verifyComplete();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void sendToMultipleUsersWithOptions(HttpClient httpClient) {
SmsSendOptions options = new SmsSendOptions();
options.setDeliveryReportEnabled(true);
options.setTag("New Tag");
to = new ArrayList<String>();
to.add(SMS_SERVICE_PHONE_NUMBER);
SmsClientBuilder builder = getSmsClient(httpClient);
asyncClient = setupAsyncClient(builder, "sendToMultipleUsersWithOptions");
Mono<Iterable<SmsSendResult>> response = asyncClient.send(SMS_SERVICE_PHONE_NUMBER, to, MESSAGE, options);
StepVerifier.create(response)
.assertNext(item -> {
assertNotNull(item);
})
.verifyComplete();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void sendFromUnauthorizedNumber(HttpClient httpClient) {
SmsSendOptions options = new SmsSendOptions();
options.setDeliveryReportEnabled(true);
options.setTag("New Tag");
SmsClientBuilder builder = getSmsClient(httpClient);
asyncClient = setupAsyncClient(builder, "sendFromUnauthorizedNumber");
Mono<SmsSendResult> response = asyncClient.send("+18007342577", SMS_SERVICE_PHONE_NUMBER, MESSAGE, options);
StepVerifier.create(response)
.expectErrorMatches(exception ->
((HttpResponseException) exception).getResponse().getStatusCode() == 404
).verify();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void sendIdempotencyCheck(HttpClient httpClient) {
SmsSendOptions options = new SmsSendOptions();
options.setDeliveryReportEnabled(true);
options.setTag("New Tag");
SmsClientBuilder builder = getSmsClient(httpClient);
asyncClient = setupAsyncClient(builder, "sendToSingleUserWithOptions");
Mono<SmsSendResult> response1 = asyncClient.send(SMS_SERVICE_PHONE_NUMBER, SMS_SERVICE_PHONE_NUMBER, MESSAGE, options);
StepVerifier.create(response1)
.assertNext(item -> {
assertNotNull(item);
})
.verifyComplete();
assertTrue(response1.block().isSuccessful());
Mono<SmsSendResult> response2 = asyncClient.send(SMS_SERVICE_PHONE_NUMBER, SMS_SERVICE_PHONE_NUMBER, MESSAGE, options);
StepVerifier.create(response2)
.assertNext(item -> {
assertNotNull(item);
})
.verifyComplete();
assertTrue(response2.block().isSuccessful());
assertNotEquals(response1.block().getMessageId(), response2.block().getMessageId());
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void sendToIncorrectPhoneNumber(HttpClient httpClient) {
to = new ArrayList<String>();
to.add("+155512345678");
SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient);
asyncClient = setupAsyncClient(builder, "sendToIncorrectPhoneNumber");
assertNotNull(asyncClient);
Mono<Iterable<SmsSendResult>> response = asyncClient.send(SMS_SERVICE_PHONE_NUMBER, to, MESSAGE, null);
assertNotNull(response);
StepVerifier.create(response)
.assertNext(item -> {
assertNotNull(item);
})
.verifyComplete();
Iterable<SmsSendResult> smsSendResults = response.block();
for (SmsSendResult result : smsSendResults) {
assertFalse(result.isSuccessful());
assertEquals(result.getHttpStatusCode(), 400);
}
}
private SmsAsyncClient setupAsyncClient(SmsClientBuilder builder, String testName) {
return addLoggingPolicy(builder, testName).buildAsyncClient();
}
} | class SmsAsyncClientTests extends SmsTestBase {
private List<String> to;
private SmsAsyncClient asyncClient;
@Override
protected void beforeTest() {
super.beforeTest();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void createAsyncClientUsingConnectionString(HttpClient httpClient) {
to = new ArrayList<String>();
to.add(SMS_SERVICE_PHONE_NUMBER);
SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient);
asyncClient = setupAsyncClient(builder, "createAsyncSmsClientUsingConnectionString");
assertNotNull(asyncClient);
Mono<Iterable<SmsSendResult>> response = asyncClient.send(SMS_SERVICE_PHONE_NUMBER, to, MESSAGE, null);
StepVerifier.create(response)
.assertNext(item -> {
assertNotNull(item);
})
.verifyComplete();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void sendSmsUsingTokenCredential(HttpClient httpClient) {
TokenCredential tokenCredential = new DefaultAzureCredentialBuilder().build();
to = new ArrayList<>();
to.add(SMS_SERVICE_PHONE_NUMBER);
SmsClientBuilder builder = getSmsClientWithToken(httpClient, tokenCredential);
asyncClient = setupAsyncClient(builder, "sendSmsUsingTokenCredential");
assertNotNull(asyncClient);
Mono<Iterable<SmsSendResult>> response = asyncClient.send(SMS_SERVICE_PHONE_NUMBER, to, MESSAGE, null);
StepVerifier.create(response)
.assertNext(item -> {
assertNotNull(item);
})
.verifyComplete();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void sendToMultipleUsers(HttpClient httpClient) {
to = new ArrayList<String>();
to.add(SMS_SERVICE_PHONE_NUMBER);
SmsClientBuilder builder = getSmsClient(httpClient);
asyncClient = setupAsyncClient(builder, "sendToMultipleUsers");
Mono<Iterable<SmsSendResult>> response = asyncClient.send(SMS_SERVICE_PHONE_NUMBER, to, MESSAGE, null);
StepVerifier.create(response)
.assertNext(item -> {
assertNotNull(item);
})
.verifyComplete();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void sendToSingleUser(HttpClient httpClient) {
SmsClientBuilder builder = getSmsClient(httpClient);
asyncClient = setupAsyncClient(builder, "sendToSingleUser");
Mono<SmsSendResult> response = asyncClient.send(SMS_SERVICE_PHONE_NUMBER, SMS_SERVICE_PHONE_NUMBER, MESSAGE, null);
StepVerifier.create(response)
.assertNext(item -> {
assertNotNull(item);
})
.verifyComplete();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void sendToSingleUserWithOptions(HttpClient httpClient) {
SmsSendOptions options = new SmsSendOptions();
options.setDeliveryReportEnabled(true);
options.setTag("New Tag");
SmsClientBuilder builder = getSmsClient(httpClient);
asyncClient = setupAsyncClient(builder, "sendToSingleUserWithOptions");
Mono<SmsSendResult> response = asyncClient.send(SMS_SERVICE_PHONE_NUMBER, SMS_SERVICE_PHONE_NUMBER, MESSAGE, options);
StepVerifier.create(response)
.assertNext(item -> {
assertNotNull(item);
})
.verifyComplete();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void sendToMultipleUsersWithOptions(HttpClient httpClient) {
SmsSendOptions options = new SmsSendOptions();
options.setDeliveryReportEnabled(true);
options.setTag("New Tag");
to = new ArrayList<String>();
to.add(SMS_SERVICE_PHONE_NUMBER);
SmsClientBuilder builder = getSmsClient(httpClient);
asyncClient = setupAsyncClient(builder, "sendToMultipleUsersWithOptions");
Mono<Iterable<SmsSendResult>> response = asyncClient.send(SMS_SERVICE_PHONE_NUMBER, to, MESSAGE, options);
StepVerifier.create(response)
.assertNext(item -> {
assertNotNull(item);
})
.verifyComplete();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void sendFromUnauthorizedNumber(HttpClient httpClient) {
SmsSendOptions options = new SmsSendOptions();
options.setDeliveryReportEnabled(true);
options.setTag("New Tag");
SmsClientBuilder builder = getSmsClient(httpClient);
asyncClient = setupAsyncClient(builder, "sendFromUnauthorizedNumber");
Mono<SmsSendResult> response = asyncClient.send("+18007342577", SMS_SERVICE_PHONE_NUMBER, MESSAGE, options);
StepVerifier.create(response)
.expectErrorMatches(exception ->
((HttpResponseException) exception).getResponse().getStatusCode() == 404
).verify();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void sendIdempotencyCheck(HttpClient httpClient) {
SmsSendOptions options = new SmsSendOptions();
options.setDeliveryReportEnabled(true);
options.setTag("New Tag");
SmsClientBuilder builder = getSmsClient(httpClient);
asyncClient = setupAsyncClient(builder, "sendIdempotencyCheck");
Mono<SmsSendResult> response1 = asyncClient.send(SMS_SERVICE_PHONE_NUMBER, SMS_SERVICE_PHONE_NUMBER, MESSAGE, options);
StepVerifier.create(response1)
.assertNext(item -> {
assertNotNull(item);
})
.verifyComplete();
assertTrue(response1.block().isSuccessful());
Mono<SmsSendResult> response2 = asyncClient.send(SMS_SERVICE_PHONE_NUMBER, SMS_SERVICE_PHONE_NUMBER, MESSAGE, options);
StepVerifier.create(response2)
.assertNext(item -> {
assertNotNull(item);
})
.verifyComplete();
assertTrue(response2.block().isSuccessful());
assertNotEquals(response1.block().getMessageId(), response2.block().getMessageId());
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void sendToIncorrectPhoneNumber(HttpClient httpClient) {
to = new ArrayList<String>();
to.add("+155512345678");
SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient);
asyncClient = setupAsyncClient(builder, "sendToIncorrectPhoneNumber");
assertNotNull(asyncClient);
Mono<Iterable<SmsSendResult>> response = asyncClient.send(SMS_SERVICE_PHONE_NUMBER, to, MESSAGE, null);
assertNotNull(response);
StepVerifier.create(response)
.assertNext(item -> {
assertNotNull(item);
})
.verifyComplete();
Iterable<SmsSendResult> smsSendResults = response.block();
for (SmsSendResult result : smsSendResults) {
assertFalse(result.isSuccessful());
assertEquals(result.getHttpStatusCode(), 400);
}
}
private SmsAsyncClient setupAsyncClient(SmsClientBuilder builder, String testName) {
return addLoggingPolicy(builder, testName).buildAsyncClient();
}
} |
"additionally" "add", but prefer if you just remove this comment all together | public void sendMessageToMultipleRecipients(SmsClient smsClient) {
SmsSendOptions options = new SmsSendOptions();
options.setDeliveryReportEnabled(true);
options.setTag("Tag"); /* Optional */
Iterable<SmsSendResult> responseMultiplePhones = smsClient.send(
"<from-phone-number>",
new ArrayList<String>(Arrays.asList("<to-phone-number1>", "<to-phone-number2>")),
"your message",
options /* Optional */,
null);
for (SmsSendResult messageResponseItem : responseMultiplePhones) {
System.out.println("MessageId sent to " + messageResponseItem.getTo() + ": " + messageResponseItem.getMessageId());
}
} | public void sendMessageToMultipleRecipients(SmsClient smsClient) {
SmsSendOptions options = new SmsSendOptions();
options.setDeliveryReportEnabled(true);
options.setTag("Tag"); /* Optional */
Iterable<SmsSendResult> responseMultiplePhones = smsClient.send(
"<from-phone-number>",
new ArrayList<String>(Arrays.asList("<to-phone-number1>", "<to-phone-number2>")),
"your message",
options /* Optional */,
null);
for (SmsSendResult messageResponseItem : responseMultiplePhones) {
System.out.println("MessageId sent to " + messageResponseItem.getTo() + ": " + messageResponseItem.getMessageId());
}
} | class ReadmeSamples {
public void createSmsClient() {
String endpoint = "https:
AzureKeyCredential azureKeyCredential = new AzureKeyCredential("SECRET");
HttpClient httpClient = new NettyAsyncHttpClientBuilder().build();
SmsClientBuilder smsClientBuilder = new SmsClientBuilder();
smsClientBuilder.endpoint(endpoint)
.credential(azureKeyCredential)
.httpClient(httpClient);
SmsClient smsClient = smsClientBuilder.buildClient();
}
public void createSmsClientWithConnectionString() {
HttpClient httpClient = new NettyAsyncHttpClientBuilder().build();
String connectionString = "<connection_string>";
SmsClient smsClient = new SmsClientBuilder()
.connectionString(connectionString)
.httpClient(httpClient)
.buildClient();
}
public void sendMessageToOneRecipient(SmsClient smsClient) {
SmsSendOptions options = new SmsSendOptions();
options.setDeliveryReportEnabled(true);
options.setTag("Tag"); /* Optional */
SmsSendResult response = smsClient.send(
"<from-phone-number>",
"<to-phone-number>",
"your message",
options /* Optional */);
System.out.println("MessageId: " + response.getMessageId());
}
} | class ReadmeSamples {
public void createSmsClient() {
String endpoint = "https:
AzureKeyCredential azureKeyCredential = new AzureKeyCredential("SECRET");
HttpClient httpClient = new NettyAsyncHttpClientBuilder().build();
SmsClientBuilder smsClientBuilder = new SmsClientBuilder();
smsClientBuilder.endpoint(endpoint)
.credential(azureKeyCredential)
.httpClient(httpClient);
SmsClient smsClient = smsClientBuilder.buildClient();
}
public void createSmsClientWithConnectionString() {
HttpClient httpClient = new NettyAsyncHttpClientBuilder().build();
String connectionString = "<connection_string>";
SmsClient smsClient = new SmsClientBuilder()
.connectionString(connectionString)
.httpClient(httpClient)
.buildClient();
}
public void sendMessageToOneRecipient(SmsClient smsClient) {
SmsSendOptions options = new SmsSendOptions();
options.setDeliveryReportEnabled(true);
options.setTag("Tag"); /* Optional */
SmsSendResult response = smsClient.send(
"<from-phone-number>",
"<to-phone-number>",
"your message",
options /* Optional */);
System.out.println("MessageId: " + response.getMessageId());
}
} | |
You should never block in an async client. | public Mono<SmsSendResult> send(String from, String to, String message, SmsSendOptions smsOptions) {
List<String> recipients = new ArrayList<String>();
recipients.add(to);
SendMessageRequest request = createSendMessageRequest(from, recipients, message, smsOptions);
try {
Objects.requireNonNull(from, "'from' cannot be null.");
Objects.requireNonNull(to, "'to' cannot be null.");
Mono<Response<SmsSendResponse>> responseMono = withContext(context -> this.smsServiceClient.getSms().sendWithResponseAsync(request, context));
Response<SmsSendResponse> response = responseMono.block();
SmsSendResponse smsSendResponse = response.getValue();
List<SmsSendResult> result = convertSmsResults(smsSendResponse.getValue());
if (result.size() == 1) {
return Mono.just(result.get(0));
} else {
return monoError(logger, new NullPointerException("no response"));
}
} catch (NullPointerException ex) {
return monoError(logger, ex);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
} | Response<SmsSendResponse> response = responseMono.block(); | public Mono<SmsSendResult> send(String from, String to, String message, SmsSendOptions smsOptions) {
List<String> recipients = new ArrayList<String>();
recipients.add(to);
SendMessageRequest request = createSendMessageRequest(from, recipients, message, smsOptions);
try {
Objects.requireNonNull(from, "'from' cannot be null.");
Objects.requireNonNull(to, "'to' cannot be null.");
Mono<Response<SmsSendResponse>> responseMono = withContext(context -> this.smsServiceClient.getSms().sendWithResponseAsync(request, context));
Response<SmsSendResponse> response = responseMono.block();
SmsSendResponse smsSendResponse = response.getValue();
List<SmsSendResult> result = convertSmsResults(smsSendResponse.getValue());
if (result.size() == 1) {
return Mono.just(result.get(0));
} else {
return monoError(logger, new NullPointerException("no response"));
}
} catch (NullPointerException ex) {
return monoError(logger, ex);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
} | class SmsAsyncClient {
private final AzureCommunicationSMSServiceImpl smsServiceClient;
private final ClientLogger logger = new ClientLogger(SmsAsyncClient.class);
SmsAsyncClient(AzureCommunicationSMSServiceImpl smsServiceClient) {
this.smsServiceClient = smsServiceClient;
}
/**
* Sends an SMS message from a phone number that belongs to the authenticated account.
* Phone number has to be in the format 000 - 00 - 00
*
* @param from Number that is sending the message.
* @param to The recipient's phone number.
* @param message message to send to recipient.
* @return response for a successful send Sms request.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<SmsSendResult> send(String from, String to, String message) {
return send(from, to, message, null);
}
/**
* Sends an SMS message from a phone number that belongs to the authenticated account.
*
* @param from Number that is sending the message.
* @param to The recipient's phone number.
* @param message message to send to recipient.
* @param smsOptions set options on the SMS request, like enable delivery report, which sends a report
* for this message to the Azure Resource Event Grid.
* @return response for a successful send Sms request.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
/**
* Sends an SMS message from a phone number that belongs to the authenticated account.
*
* @param from Number that is sending the message.
* @param to A list of the recipient's phone numbers.
* @param message message to send to recipient.
* @return response for a successful send Sms request.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Iterable<SmsSendResult>> send(String from, Iterable<String> to, String message) {
return send(from, to, message, null);
}
/**
* Sends an SMS message from a phone number that belongs to the authenticated account.
*
* @param from Number that is sending the message.
* @param to A list of the recipient's phone numbers.
* @param message message to send to recipient.
* @param smsOptions set options on the SMS request, like enable delivery report, which sends a report
* for this message to the Azure Resource Event Grid.
* @return response for a successful send Sms request.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Iterable<SmsSendResult>> send(String from, Iterable<String> to, String message, SmsSendOptions smsOptions) {
SendMessageRequest request = createSendMessageRequest(from, to, message, smsOptions);
try {
Objects.requireNonNull(from, "'from' cannot be null.");
Objects.requireNonNull(to, "'to' cannot be null.");
Mono<Response<SmsSendResponse>> responseMono = withContext(context -> this.smsServiceClient.getSms().sendWithResponseAsync(request, context));
Response<SmsSendResponse> response = responseMono.block();
SmsSendResponse smsSendResponse = response.getValue();
List<SmsSendResult> result = convertSmsResults(smsSendResponse.getValue());
return Mono.just(result);
} catch (NullPointerException ex) {
return monoError(logger, ex);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
private List<SmsSendResult> convertSmsResults(Iterable<SmsSendResponseItem> resultsIterable) {
List <SmsSendResult> iterableWrapper = new ArrayList<>();
for (SmsSendResponseItem item : resultsIterable
) {
iterableWrapper.add(new SmsSendResult(item));
}
return iterableWrapper;
}
private SendMessageRequest createSendMessageRequest(String from, Iterable<String> smsRecipient, String message, SmsSendOptions smsOptions) {
SendMessageRequest request = new SendMessageRequest();
List<SmsRecipient> recipients = new ArrayList<SmsRecipient>();
for (String s : smsRecipient) {
recipients.add(new SmsRecipient().setTo(s));
}
request.setFrom(from)
.setSmsRecipients(recipients)
.setMessage(message)
.setSmsSendOptions(smsOptions);
return request;
}
} | class SmsAsyncClient {
private final AzureCommunicationSMSServiceImpl smsServiceClient;
private final ClientLogger logger = new ClientLogger(SmsAsyncClient.class);
SmsAsyncClient(AzureCommunicationSMSServiceImpl smsServiceClient) {
this.smsServiceClient = smsServiceClient;
}
/**
* Sends an SMS message from a phone number that belongs to the authenticated account.
* Phone number has to be in the format 000 - 00 - 00
*
* @param from Number that is sending the message.
* @param to The recipient's phone number.
* @param message message to send to recipient.
* @return response for a successful send Sms request.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<SmsSendResult> send(String from, String to, String message) {
return send(from, to, message, null);
}
/**
* Sends an SMS message from a phone number that belongs to the authenticated account.
*
* @param from Number that is sending the message.
* @param to The recipient's phone number.
* @param message message to send to recipient.
* @param smsOptions set options on the SMS request, like enable delivery report, which sends a report
* for this message to the Azure Resource Event Grid.
* @return response for a successful send Sms request.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
/**
* Sends an SMS message from a phone number that belongs to the authenticated account.
*
* @param from Number that is sending the message.
* @param to A list of the recipient's phone numbers.
* @param message message to send to recipient.
* @return response for a successful send Sms request.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Iterable<SmsSendResult>> send(String from, Iterable<String> to, String message) {
return send(from, to, message, null);
}
/**
* Sends an SMS message from a phone number that belongs to the authenticated account.
*
* @param from Number that is sending the message.
* @param to A list of the recipient's phone numbers.
* @param message message to send to recipient.
* @param smsOptions set options on the SMS request, like enable delivery report, which sends a report
* for this message to the Azure Resource Event Grid.
* @return response for a successful send Sms request.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Iterable<SmsSendResult>> send(String from, Iterable<String> to, String message, SmsSendOptions smsOptions) {
SendMessageRequest request = createSendMessageRequest(from, to, message, smsOptions);
try {
Objects.requireNonNull(from, "'from' cannot be null.");
Objects.requireNonNull(to, "'to' cannot be null.");
Mono<Response<SmsSendResponse>> responseMono = withContext(context -> this.smsServiceClient.getSms().sendWithResponseAsync(request, context));
Response<SmsSendResponse> response = responseMono.block();
SmsSendResponse smsSendResponse = response.getValue();
List<SmsSendResult> result = convertSmsResults(smsSendResponse.getValue());
return Mono.just(result);
} catch (NullPointerException ex) {
return monoError(logger, ex);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
private List<SmsSendResult> convertSmsResults(Iterable<SmsSendResponseItem> resultsIterable) {
List <SmsSendResult> iterableWrapper = new ArrayList<>();
for (SmsSendResponseItem item : resultsIterable
) {
iterableWrapper.add(new SmsSendResult(item));
}
return iterableWrapper;
}
private SendMessageRequest createSendMessageRequest(String from, Iterable<String> smsRecipient, String message, SmsSendOptions smsOptions) {
SendMessageRequest request = new SendMessageRequest();
List<SmsRecipient> recipients = new ArrayList<SmsRecipient>();
for (String s : smsRecipient) {
recipients.add(new SmsRecipient().setTo(s));
}
request.setFrom(from)
.setSmsRecipients(recipients)
.setMessage(message)
.setSmsSendOptions(smsOptions);
return request;
}
} |
Add proper comment here to indicate what does this condition `if (StringUtils.isEmpty(tenantId))` mean | public void afterPropertiesSet() {
if (StringUtils.isEmpty(tenantId)) {
if (StringUtils.isEmpty(tenant) && StringUtils.isEmpty(baseUri)) {
throw new AADB2CConfigurationException("'tenant' and 'baseUri' at least configure one item.");
}
if (!userFlows.keySet().contains(loginFlow)) {
throw new AADB2CConfigurationException("Sign in user flow key '"
+ loginFlow + "' is not in 'user-flows' map.");
}
}
} | if (StringUtils.isEmpty(tenantId)) { | public void afterPropertiesSet() {
if (StringUtils.isEmpty(tenantId)) {
if (StringUtils.isEmpty(tenant) && StringUtils.isEmpty(baseUri)) {
throw new AADB2CConfigurationException("'tenant' and 'baseUri' at least configure one item.");
}
if (!userFlows.keySet().contains(loginFlow)) {
throw new AADB2CConfigurationException("Sign in user flow key '"
+ loginFlow + "' is not in 'user-flows' map.");
}
}
} | class AADB2CProperties implements InitializingBean {
public static final String DEFAULT_LOGOUT_SUCCESS_URL = "http:
public static final String PREFIX = "azure.activedirectory.b2c";
private static final String TENANT_NAME_PART_REGEX = "([A-Za-z0-9]+\\.)";
/**
* The default user flow key 'sign-up-or-sign-in'.
*/
protected static final String DEFAULT_KEY_SIGN_UP_OR_SIGN_IN = "sign-up-or-sign-in";
/**
* The default user flow key 'password-reset'.
*/
protected static final String DEFAULT_KEY_PASSWORD_RESET = "password-reset";
/**
* The name of the b2c tenant.
* @deprecated It's recommended to use 'baseUri' instead.
*/
@Deprecated
private String tenant;
/**
* The name of the b2c tenant id.
*/
private String tenantId;
/**
* App ID URI which might be used in the <code>"aud"</code> claim of an token.
*/
private String appIdUri;
/**
* Connection Timeout for the JWKSet Remote URL call.
*/
private int jwtConnectTimeout = RemoteJWKSet.DEFAULT_HTTP_CONNECT_TIMEOUT; /* milliseconds */
/**
* Read Timeout for the JWKSet Remote URL call.
*/
private int jwtReadTimeout = RemoteJWKSet.DEFAULT_HTTP_READ_TIMEOUT; /* milliseconds */
/**
* Size limit in Bytes of the JWKSet Remote URL call.
*/
private int jwtSizeLimit = RemoteJWKSet.DEFAULT_HTTP_SIZE_LIMIT; /* bytes */
/**
* The application ID that registered under b2c tenant.
*/
@NotBlank(message = "client ID should not be blank")
private String clientId;
/**
* The application secret that registered under b2c tenant.
*/
private String clientSecret;
@URL(message = "logout success should be valid URL")
private String logoutSuccessUrl = DEFAULT_LOGOUT_SUCCESS_URL;
private Map<String, Object> authenticateAdditionalParameters;
/**
* User name attribute name
*/
private String userNameAttributeName;
/**
* Telemetry data will be collected if true, or disable data collection.
*/
private boolean allowTelemetry = true;
private String replyUrl = "{baseUrl}/login/oauth2/code/";
/**
* AAD B2C endpoint base uri.
*/
@URL(message = "baseUri should be valid URL")
private String baseUri;
/**
* Specify the primary sign in flow key.
*/
private String loginFlow = DEFAULT_KEY_SIGN_UP_OR_SIGN_IN;
private Map<String, String> userFlows = new HashMap<>();
@Override
protected String getPasswordReset() {
Optional<String> keyOptional = userFlows.keySet()
.stream()
.filter(key -> key.equalsIgnoreCase(DEFAULT_KEY_PASSWORD_RESET))
.findAny();
return keyOptional.isPresent() ? userFlows.get(keyOptional.get()) : null;
}
public String getBaseUri() {
if (StringUtils.hasText(tenant) && StringUtils.isEmpty(baseUri)) {
return String.format("https:
}
return baseUri;
}
public void setBaseUri(String baseUri) {
this.baseUri = baseUri;
}
public void setTenant(String tenant) {
this.tenant = tenant;
}
/**
* Get tenant name for Telemetry
* @return tenant name
* @throws AADB2CConfigurationException resolve tenant name failed
*/
@DeprecatedConfigurationProperty(
reason = "Configuration updated to baseUri",
replacement = "azure.activedirectory.b2c.base-uri")
public String getTenant() {
if (StringUtils.hasText(baseUri)) {
Matcher matcher = Pattern.compile(TENANT_NAME_PART_REGEX).matcher(baseUri);
if (matcher.find()) {
String matched = matcher.group();
return matched.substring(0, matched.length() - 1);
}
throw new AADB2CConfigurationException("Unable to resolve the 'tenant' name.");
}
return tenant;
}
public Map<String, String> getUserFlows() {
return userFlows;
}
public void setUserFlows(Map<String, String> userFlows) {
this.userFlows = userFlows;
}
public String getLoginFlow() {
return loginFlow;
}
public void setLoginFlow(String loginFlow) {
this.loginFlow = loginFlow;
}
public String getClientId() {
return clientId;
}
public void setClientId(String clientId) {
this.clientId = clientId;
}
public String getClientSecret() {
return clientSecret;
}
public void setClientSecret(String clientSecret) {
this.clientSecret = clientSecret;
}
public String getLogoutSuccessUrl() {
return logoutSuccessUrl;
}
public void setLogoutSuccessUrl(String logoutSuccessUrl) {
this.logoutSuccessUrl = logoutSuccessUrl;
}
public Map<String, Object> getAuthenticateAdditionalParameters() {
return authenticateAdditionalParameters;
}
public void setAuthenticateAdditionalParameters(Map<String, Object> authenticateAdditionalParameters) {
this.authenticateAdditionalParameters = authenticateAdditionalParameters;
}
public boolean isAllowTelemetry() {
return allowTelemetry;
}
public void setAllowTelemetry(boolean allowTelemetry) {
this.allowTelemetry = allowTelemetry;
}
public String getUserNameAttributeName() {
return userNameAttributeName;
}
public void setUserNameAttributeName(String userNameAttributeName) {
this.userNameAttributeName = userNameAttributeName;
}
public String getReplyUrl() {
return replyUrl;
}
public void setReplyUrl(String replyUrl) {
this.replyUrl = replyUrl;
}
public String getAppIdUri() {
return appIdUri;
}
public void setAppIdUri(String appIdUri) {
this.appIdUri = appIdUri;
}
public int getJwtConnectTimeout() {
return jwtConnectTimeout;
}
public void setJwtConnectTimeout(int jwtConnectTimeout) {
this.jwtConnectTimeout = jwtConnectTimeout;
}
public int getJwtReadTimeout() {
return jwtReadTimeout;
}
public void setJwtReadTimeout(int jwtReadTimeout) {
this.jwtReadTimeout = jwtReadTimeout;
}
public int getJwtSizeLimit() {
return jwtSizeLimit;
}
public void setJwtSizeLimit(int jwtSizeLimit) {
this.jwtSizeLimit = jwtSizeLimit;
}
public String getTenantId() {
return tenantId;
}
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
} | class AADB2CProperties implements InitializingBean {
public static final String DEFAULT_LOGOUT_SUCCESS_URL = "http:
public static final String PREFIX = "azure.activedirectory.b2c";
private static final String TENANT_NAME_PART_REGEX = "([A-Za-z0-9]+\\.)";
/**
* The default user flow key 'sign-up-or-sign-in'.
*/
protected static final String DEFAULT_KEY_SIGN_UP_OR_SIGN_IN = "sign-up-or-sign-in";
/**
* The default user flow key 'password-reset'.
*/
protected static final String DEFAULT_KEY_PASSWORD_RESET = "password-reset";
/**
* The name of the b2c tenant.
* @deprecated It's recommended to use 'baseUri' instead.
*/
@Deprecated
private String tenant;
/**
* The name of the b2c tenant id.
*/
private String tenantId;
/**
* App ID URI which might be used in the <code>"aud"</code> claim of an token.
*/
private String appIdUri;
/**
* Connection Timeout for the JWKSet Remote URL call.
*/
private int jwtConnectTimeout = RemoteJWKSet.DEFAULT_HTTP_CONNECT_TIMEOUT; /* milliseconds */
/**
* Read Timeout for the JWKSet Remote URL call.
*/
private int jwtReadTimeout = RemoteJWKSet.DEFAULT_HTTP_READ_TIMEOUT; /* milliseconds */
/**
* Size limit in Bytes of the JWKSet Remote URL call.
*/
private int jwtSizeLimit = RemoteJWKSet.DEFAULT_HTTP_SIZE_LIMIT; /* bytes */
/**
* The application ID that registered under b2c tenant.
*/
@NotBlank(message = "client ID should not be blank")
private String clientId;
/**
* The application secret that registered under b2c tenant.
*/
private String clientSecret;
@URL(message = "logout success should be valid URL")
private String logoutSuccessUrl = DEFAULT_LOGOUT_SUCCESS_URL;
private Map<String, Object> authenticateAdditionalParameters;
/**
* User name attribute name
*/
private String userNameAttributeName;
/**
* Telemetry data will be collected if true, or disable data collection.
*/
private boolean allowTelemetry = true;
private String replyUrl = "{baseUrl}/login/oauth2/code/";
/**
* AAD B2C endpoint base uri.
*/
@URL(message = "baseUri should be valid URL")
private String baseUri;
/**
* Specify the primary sign in flow key.
*/
private String loginFlow = DEFAULT_KEY_SIGN_UP_OR_SIGN_IN;
private Map<String, String> userFlows = new HashMap<>();
@Override
protected String getPasswordReset() {
Optional<String> keyOptional = userFlows.keySet()
.stream()
.filter(key -> key.equalsIgnoreCase(DEFAULT_KEY_PASSWORD_RESET))
.findAny();
return keyOptional.isPresent() ? userFlows.get(keyOptional.get()) : null;
}
public String getBaseUri() {
if (StringUtils.hasText(tenant) && StringUtils.isEmpty(baseUri)) {
return String.format("https:
}
return baseUri;
}
public void setBaseUri(String baseUri) {
this.baseUri = baseUri;
}
public void setTenant(String tenant) {
this.tenant = tenant;
}
/**
* Get tenant name for Telemetry
* @return tenant name
* @throws AADB2CConfigurationException resolve tenant name failed
*/
@DeprecatedConfigurationProperty(
reason = "Configuration updated to baseUri",
replacement = "azure.activedirectory.b2c.base-uri")
public String getTenant() {
if (StringUtils.hasText(baseUri)) {
Matcher matcher = Pattern.compile(TENANT_NAME_PART_REGEX).matcher(baseUri);
if (matcher.find()) {
String matched = matcher.group();
return matched.substring(0, matched.length() - 1);
}
throw new AADB2CConfigurationException("Unable to resolve the 'tenant' name.");
}
return tenant;
}
public Map<String, String> getUserFlows() {
return userFlows;
}
public void setUserFlows(Map<String, String> userFlows) {
this.userFlows = userFlows;
}
public String getLoginFlow() {
return loginFlow;
}
public void setLoginFlow(String loginFlow) {
this.loginFlow = loginFlow;
}
public String getClientId() {
return clientId;
}
public void setClientId(String clientId) {
this.clientId = clientId;
}
public String getClientSecret() {
return clientSecret;
}
public void setClientSecret(String clientSecret) {
this.clientSecret = clientSecret;
}
public String getLogoutSuccessUrl() {
return logoutSuccessUrl;
}
public void setLogoutSuccessUrl(String logoutSuccessUrl) {
this.logoutSuccessUrl = logoutSuccessUrl;
}
public Map<String, Object> getAuthenticateAdditionalParameters() {
return authenticateAdditionalParameters;
}
public void setAuthenticateAdditionalParameters(Map<String, Object> authenticateAdditionalParameters) {
this.authenticateAdditionalParameters = authenticateAdditionalParameters;
}
public boolean isAllowTelemetry() {
return allowTelemetry;
}
public void setAllowTelemetry(boolean allowTelemetry) {
this.allowTelemetry = allowTelemetry;
}
public String getUserNameAttributeName() {
return userNameAttributeName;
}
public void setUserNameAttributeName(String userNameAttributeName) {
this.userNameAttributeName = userNameAttributeName;
}
public String getReplyUrl() {
return replyUrl;
}
public void setReplyUrl(String replyUrl) {
this.replyUrl = replyUrl;
}
public String getAppIdUri() {
return appIdUri;
}
public void setAppIdUri(String appIdUri) {
this.appIdUri = appIdUri;
}
public int getJwtConnectTimeout() {
return jwtConnectTimeout;
}
public void setJwtConnectTimeout(int jwtConnectTimeout) {
this.jwtConnectTimeout = jwtConnectTimeout;
}
public int getJwtReadTimeout() {
return jwtReadTimeout;
}
public void setJwtReadTimeout(int jwtReadTimeout) {
this.jwtReadTimeout = jwtReadTimeout;
}
public int getJwtSizeLimit() {
return jwtSizeLimit;
}
public void setJwtSizeLimit(int jwtSizeLimit) {
this.jwtSizeLimit = jwtSizeLimit;
}
public String getTenantId() {
return tenantId;
}
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
} |
Is there a user story for this? I feel like it is a user error if we are expecting a Queue and it returns a Topic instead and I would expect an error. | private Response<QueueProperties> deserializeQueue(Response<Object> response) {
final QueueDescriptionEntry entry = deserialize(response.getValue(), QueueDescriptionEntry.class);
if (entry == null) {
return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null);
} else if (entry.getContent() == null) {
logger.info("entry.getContent() is null. The entity may not exist. {}", entry);
return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null);
} else if (entry.getContent().getQueueDescription() == null) {
final TopicDescriptionEntry entryTopic = deserialize(response.getValue(), TopicDescriptionEntry.class);
if (entryTopic != null && entryTopic.getContent() != null && entryTopic.getContent().getTopicDescription() != null) {
throw logger.logExceptionAsError(
new RuntimeException(String.format("'[%s]' is not a queue, it is a topic.", entryTopic.getTitle())));
}
}
final QueueProperties result = EntityHelper.toModel(entry.getContent().getQueueDescription());
final String queueName = getTitleValue(entry.getTitle());
EntityHelper.setQueueName(result, queueName);
return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), result);
} | } else if (entry.getContent().getQueueDescription() == null) { | private Response<QueueProperties> deserializeQueue(Response<Object> response) {
final QueueDescriptionEntry entry = deserialize(response.getValue(), QueueDescriptionEntry.class);
if (entry == null) {
return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null);
} else if (entry.getContent() == null) {
logger.info("entry.getContent() is null. The entity may not exist. {}", entry);
return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null);
} else if (entry.getContent().getQueueDescription() == null) {
final TopicDescriptionEntry entryTopic = deserialize(response.getValue(), TopicDescriptionEntry.class);
if (entryTopic != null && entryTopic.getContent() != null && entryTopic.getContent().getTopicDescription() != null) {
logger.warning("'{}' is not a queue, it is a topic.", entryTopic.getTitle());
return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null);
}
}
final QueueProperties result = EntityHelper.toModel(entry.getContent().getQueueDescription());
final String queueName = getTitleValue(entry.getTitle());
EntityHelper.setQueueName(result, queueName);
return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), result);
} | class ServiceBusAdministrationAsyncClient {
private static final String SERVICE_BUS_TRACING_NAMESPACE_VALUE = "Microsoft.ServiceBus";
private static final String CONTENT_TYPE = "application/xml";
private static final String QUEUES_ENTITY_TYPE = "queues";
private static final String TOPICS_ENTITY_TYPE = "topics";
private static final int NUMBER_OF_ELEMENTS = 100;
private final ServiceBusManagementClientImpl managementClient;
private final EntitiesImpl entityClient;
private final ClientLogger logger = new ClientLogger(ServiceBusAdministrationAsyncClient.class);
private final ServiceBusManagementSerializer serializer;
private final RulesImpl rulesClient;
/**
* Creates a new instance with the given management client and serializer.
*
* @param managementClient Client to make management calls.
* @param serializer Serializer to deserialize ATOM XML responses.
*/
ServiceBusAdministrationAsyncClient(ServiceBusManagementClientImpl managementClient,
ServiceBusManagementSerializer serializer) {
this.serializer = Objects.requireNonNull(serializer, "'serializer' cannot be null.");
this.managementClient = Objects.requireNonNull(managementClient, "'managementClient' cannot be null.");
this.entityClient = managementClient.getEntities();
this.rulesClient = managementClient.getRules();
}
/**
* Creates a queue with the given name.
*
* @param queueName Name of the queue to create.
*
* @return A Mono that completes with information about the created queue.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If the request body was invalid, the queue quota is exceeded, or an error
* occurred processing the request.
* @throws NullPointerException if {@code queueName} is null.
* @throws IllegalArgumentException if {@code queueName} is an empty string.
* @throws ResourceExistsException if a queue exists with the same {@code queueName}.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<QueueProperties> createQueue(String queueName) {
try {
return createQueue(queueName, new CreateQueueOptions());
} catch (RuntimeException e) {
return monoError(logger, e);
}
}
/**
* Creates a queue with the {@link CreateQueueOptions} and given queue name.
*
* @param queueName Name of the queue to create.
* @param queueOptions Options about the queue to create.
*
* @return A Mono that completes with information about the created queue.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If the request body was invalid, the queue quota is exceeded, or an error
* occurred processing the request.
* @throws IllegalArgumentException if {@code queueName} is an empty string.
* @throws NullPointerException if {@code queueName} or {@code queueOptions} is null.
* @throws ResourceExistsException if a queue exists with the same {@link QueueProperties
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<QueueProperties> createQueue(String queueName, CreateQueueOptions queueOptions) {
return createQueueWithResponse(queueName, queueOptions).map(Response::getValue);
}
/**
* Creates a queue and returns the created queue in addition to the HTTP response.
*
* @param queueName Name of the queue to create.
* @param queueOptions Options about the queue to create.
*
* @return A Mono that returns the created queue in addition to the HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If the request body was invalid, the queue quota is exceeded, or an error
* occurred processing the request.
* @throws IllegalArgumentException if {@code queueName} is an empty string.
* @throws NullPointerException if {@code queueName} or {@code queueOptions} is null.
* @throws ResourceExistsException if a queue exists with the same {@link QueueProperties
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<QueueProperties>> createQueueWithResponse(String queueName, CreateQueueOptions queueOptions) {
return withContext(context -> createQueueWithResponse(queueName, queueOptions, context));
}
/**
* Creates a rule under the given topic and subscription
*
* @param topicName Name of the topic associated with rule.
* @param subscriptionName Name of the subscription associated with the rule.
* @param ruleName Name of the rule.
*
* @return A Mono that completes with information about the created rule.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If the request body was invalid, the quota is exceeded, or an error occurred
* processing the request.
* @throws IllegalArgumentException if {@code topicName} or {@code ruleName} are are empty strings.
* @throws NullPointerException if {@code topicName} or {@code ruleName} are are null.
* @throws ResourceExistsException if a rule exists with the same topic, subscription, and rule name.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<RuleProperties> createRule(String topicName, String subscriptionName, String ruleName) {
try {
return createRule(topicName, subscriptionName, ruleName, new CreateRuleOptions());
} catch (RuntimeException e) {
return monoError(logger, e);
}
}
/**
* Creates a rule with the {@link CreateRuleOptions}.
*
* @param topicName Name of the topic associated with rule.
* @param subscriptionName Name of the subscription associated with the rule.
* @param ruleName Name of the rule.
* @param ruleOptions Information about the rule to create.
*
* @return A Mono that completes with information about the created rule.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If the request body was invalid, the quota is exceeded, or an error occurred
* processing the request.
* @throws IllegalArgumentException if {@code topicName} or {@code ruleName} are are empty strings.
* @throws NullPointerException if {@code topicName}, {@code ruleName}, or {@code ruleOptions}
* are are null.
* @throws ResourceExistsException if a rule exists with the same topic and rule name.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<RuleProperties> createRule(String topicName, String subscriptionName, String ruleName,
CreateRuleOptions ruleOptions) {
return createRuleWithResponse(topicName, subscriptionName, ruleName, ruleOptions)
.map(Response::getValue);
}
/**
* Creates a rule and returns the created rule in addition to the HTTP response.
*
* @param topicName Name of the topic associated with rule.
* @param subscriptionName Name of the subscription associated with the rule.
* @param ruleName Name of the rule.
* @param ruleOptions Information about the rule to create.
*
* @return A Mono that returns the created rule in addition to the HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If the request body was invalid, the quota is exceeded, or an error occurred
* processing the request.
* @throws IllegalArgumentException if {@code topicName} or {@code ruleName} are are empty strings.
* @throws NullPointerException if {@code topicName}, {@code ruleName}, or {@code ruleOptions}
* are are null.
* @throws ResourceExistsException if a rule exists with the same topic and rule name.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<RuleProperties>> createRuleWithResponse(String topicName, String subscriptionName,
String ruleName, CreateRuleOptions ruleOptions) {
return withContext(context -> createRuleWithResponse(topicName, subscriptionName, ruleName, ruleOptions,
context));
}
/**
* Creates a subscription with the given topic and subscription names.
*
* @param topicName Name of the topic associated with subscription.
* @param subscriptionName Name of the subscription.
*
* @return A Mono that completes with information about the created subscription.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If the request body was invalid, the quota is exceeded, or an error occurred
* processing the request.
* @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} are are empty strings.
* @throws NullPointerException if {@code topicName} or {@code subscriptionName} are are null.
* @throws ResourceExistsException if a subscription exists with the same topic and subscription name.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<SubscriptionProperties> createSubscription(String topicName, String subscriptionName) {
try {
return createSubscription(topicName, subscriptionName, new CreateSubscriptionOptions());
} catch (RuntimeException e) {
return monoError(logger, e);
}
}
/**
* Creates a subscription with the {@link CreateSubscriptionOptions}.
*
* @param topicName Name of the topic associated with subscription.
* @param subscriptionName Name of the subscription.
* @param subscriptionOptions Information about the subscription to create.
*
* @return A Mono that completes with information about the created subscription.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If the request body was invalid, the quota is exceeded, or an error occurred
* processing the request.
* @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} are are empty strings.
* @throws NullPointerException if {@code topicName}, {@code subscriptionName}, or {@code subscriptionOptions}
* are are null.
* @throws ResourceExistsException if a subscription exists with the same topic and subscription name.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<SubscriptionProperties> createSubscription(String topicName, String subscriptionName,
CreateSubscriptionOptions subscriptionOptions) {
return createSubscriptionWithResponse(topicName, subscriptionName, subscriptionOptions)
.map(Response::getValue);
}
/**
* Creates a subscription and returns the created subscription in addition to the HTTP response.
*
* @param topicName Name of the topic associated with subscription.
* @param subscriptionName Name of the subscription.
* @param subscriptionOptions Information about the subscription to create.
*
* @return A Mono that returns the created subscription in addition to the HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If the request body was invalid, the quota is exceeded, or an error occurred
* processing the request.
* @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} are are empty strings.
* @throws NullPointerException if {@code topicName}, {@code subscriptionName}, or {@code subscriptionOptions}
* are are null.
* @throws ResourceExistsException if a subscription exists with the same topic and subscription name.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<SubscriptionProperties>> createSubscriptionWithResponse(String topicName,
String subscriptionName, CreateSubscriptionOptions subscriptionOptions) {
return withContext(context -> createSubscriptionWithResponse(topicName, subscriptionName, subscriptionOptions,
context));
}
/**
* Creates a topic with the given name.
*
* @param topicName Name of the topic to create.
*
* @return A Mono that completes with information about the created topic.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If the request body was invalid, the topic quota is exceeded, or an error
* occurred processing the request.
* @throws NullPointerException if {@code topicName} is null.
* @throws IllegalArgumentException if {@code topicName} is an empty string.
* @throws ResourceExistsException if a topic exists with the same {@code topicName}.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<TopicProperties> createTopic(String topicName) {
try {
return createTopic(topicName, new CreateTopicOptions());
} catch (RuntimeException e) {
return monoError(logger, e);
}
}
/**
* Creates a topic with the {@link CreateTopicOptions}.
*
* @param topicName Name of the topic to create.
* @param topicOptions The options used to create the topic.
*
* @return A Mono that completes with information about the created topic.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If the request body was invalid, the topic quota is exceeded, or an error
* occurred processing the request.
* @throws IllegalArgumentException if {@code topicName} is an empty string.
* @throws NullPointerException if {@code topicName} or {@code topicOptions} is null.
* @throws ResourceExistsException if a topic exists with the same {@code topicName}.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<TopicProperties> createTopic(String topicName, CreateTopicOptions topicOptions) {
return createTopicWithResponse(topicName, topicOptions).map(Response::getValue);
}
/**
* Creates a topic and returns the created topic in addition to the HTTP response.
*
* @param topicName Name of the topic to create.
* @param topicOptions The options used to create the topic.
*
* @return A Mono that returns the created topic in addition to the HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If the request body was invalid, the topic quota is exceeded, or an error
* occurred processing the request.
* @throws IllegalArgumentException if {@link TopicProperties
* string.
* @throws NullPointerException if {@code topicName} or {@code topicOptions} is null.
* @throws ResourceExistsException if a topic exists with the same {@code topicName}.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<TopicProperties>> createTopicWithResponse(String topicName, CreateTopicOptions topicOptions) {
return withContext(context -> createTopicWithResponse(topicName, topicOptions, context));
}
/**
* Deletes a queue the matching {@code queueName}.
*
* @param queueName Name of queue to delete.
*
* @return A Mono that completes when the queue is deleted.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws NullPointerException if {@code queueName} is null.
* @throws IllegalArgumentException if {@code queueName} is an empty string.
* @throws ResourceNotFoundException if the {@code queueName} does not exist.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Void> deleteQueue(String queueName) {
return deleteQueueWithResponse(queueName).then();
}
/**
* Deletes a queue the matching {@code queueName} and returns the HTTP response.
*
* @param queueName Name of queue to delete.
*
* @return A Mono that completes when the queue is deleted and returns the HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws NullPointerException if {@code queueName} is null.
* @throws IllegalArgumentException if {@code queueName} is an empty string.
* @throws ResourceNotFoundException if the {@code queueName} does not exist.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Void>> deleteQueueWithResponse(String queueName) {
return withContext(context -> deleteQueueWithResponse(queueName, context));
}
/**
* Deletes a rule the matching {@code ruleName}.
*
* @param topicName Name of topic associated with rule to delete.
* @param subscriptionName Name of the subscription associated with the rule to delete.
* @param ruleName Name of rule to delete.
*
* @return A Mono that completes when the rule is deleted.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code topicName} or {@code ruleName} is an empty string.
* @throws NullPointerException if {@code topicName} or {@code ruleName} is null.
* @throws ResourceNotFoundException if the {@code ruleName} does not exist.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Void> deleteRule(String topicName, String subscriptionName, String ruleName) {
return deleteRuleWithResponse(topicName, subscriptionName, ruleName).then();
}
/**
* Deletes a rule the matching {@code ruleName} and returns the HTTP response.
*
* @param topicName Name of topic associated with rule to delete.
* @param subscriptionName Name of the subscription associated with the rule to delete.
* @param ruleName Name of rule to delete.
*
* @return A Mono that completes when the rule is deleted and returns the HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code topicName}, {@code subscriptionName}, or {@code ruleName} is an
* empty string.
* @throws NullPointerException if {@code topicName}, {@code subscriptionName}, or {@code ruleName} is null.
* @throws ResourceNotFoundException if the {@code ruleName} does not exist.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Void>> deleteRuleWithResponse(String topicName, String subscriptionName,
String ruleName) {
return withContext(context -> deleteRuleWithResponse(topicName, subscriptionName, ruleName, context));
}
/**
* Deletes a subscription the matching {@code subscriptionName}.
*
* @param topicName Name of topic associated with subscription to delete.
* @param subscriptionName Name of subscription to delete.
*
* @return A Mono that completes when the subscription is deleted.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} is an empty string.
* @throws NullPointerException if {@code topicName} or {@code subscriptionName} is null.
* @throws ResourceNotFoundException if the {@code subscriptionName} does not exist.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Void> deleteSubscription(String topicName, String subscriptionName) {
return deleteSubscriptionWithResponse(topicName, subscriptionName).then();
}
/**
* Deletes a subscription the matching {@code subscriptionName} and returns the HTTP response.
*
* @param topicName Name of topic associated with subscription to delete.
* @param subscriptionName Name of subscription to delete.
*
* @return A Mono that completes when the subscription is deleted and returns the HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} is an empty string.
* @throws NullPointerException if {@code topicName} or {@code subscriptionName} is null.
* @throws ResourceNotFoundException if the {@code subscriptionName} does not exist.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Void>> deleteSubscriptionWithResponse(String topicName, String subscriptionName) {
return withContext(context -> deleteSubscriptionWithResponse(topicName, subscriptionName, context));
}
/**
* Deletes a topic the matching {@code topicName}.
*
* @param topicName Name of topic to delete.
*
* @return A Mono that completes when the topic is deleted.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code topicName} is an empty string.
* @throws NullPointerException if {@code topicName} is null.
* @throws ResourceNotFoundException if the {@code topicName} does not exist.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Void> deleteTopic(String topicName) {
return deleteTopicWithResponse(topicName).then();
}
/**
* Deletes a topic the matching {@code topicName} and returns the HTTP response.
*
* @param topicName Name of topic to delete.
*
* @return A Mono that completes when the topic is deleted and returns the HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code topicName} is an empty string.
* @throws NullPointerException if {@code topicName} is null.
* @throws ResourceNotFoundException if the {@code topicName} does not exist.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Void>> deleteTopicWithResponse(String topicName) {
return withContext(context -> deleteTopicWithResponse(topicName, context));
}
/**
* Gets information about the queue.
*
* @param queueName Name of queue to get information about.
*
* @return A Mono that completes with information about the queue.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code queueName} is an empty string.
* @throws NullPointerException if {@code queueName} is null.
* @throws ResourceNotFoundException if the {@code queueName} does not exist.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<QueueProperties> getQueue(String queueName) {
return getQueueWithResponse(queueName).map(Response::getValue);
}
/**
* Gets information about the queue along with its HTTP response.
*
* @param queueName Name of queue to get information about.
*
* @return A Mono that completes with information about the queue and the associated HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code queueName} is an empty string.
* @throws NullPointerException if {@code queueName} is null.
* @throws ResourceNotFoundException if the {@code queueName} does not exist.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<QueueProperties>> getQueueWithResponse(String queueName) {
return withContext(context -> getQueueWithResponse(queueName, context, Function.identity()));
}
/**
* Gets whether or not a queue with {@code queueName} exists in the Service Bus namespace.
*
* @param queueName Name of the queue.
*
* @return A Mono that completes indicating whether or not the queue exists.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code queueName} is an empty string.
* @throws NullPointerException if {@code queueName} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Boolean> getQueueExists(String queueName) {
return getQueueExistsWithResponse(queueName).map(Response::getValue);
}
/**
* Gets whether or not a queue with {@code queueName} exists in the Service Bus namespace.
*
* @param queueName Name of the queue.
*
* @return A Mono that completes indicating whether or not the queue exists along with its HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code queueName} is an empty string.
* @throws NullPointerException if {@code queueName} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Boolean>> getQueueExistsWithResponse(String queueName) {
return getEntityExistsWithResponse(getQueueWithResponse(queueName));
}
/**
* Gets runtime properties about the queue.
*
* @param queueName Name of queue to get information about.
*
* @return A Mono that completes with runtime properties about the queue.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code queueName} is an empty string.
* @throws NullPointerException if {@code queueName} is null.
* @throws ResourceNotFoundException if the {@code queueName} does not exist.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<QueueRuntimeProperties> getQueueRuntimeProperties(String queueName) {
return getQueueRuntimePropertiesWithResponse(queueName).map(response -> response.getValue());
}
/**
* Gets runtime properties about the queue along with its HTTP response.
*
* @param queueName Name of queue to get information about.
*
* @return A Mono that completes with runtime properties about the queue and the associated HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code queueName} is an empty string.
* @throws NullPointerException if {@code queueName} is null.
* @throws ResourceNotFoundException if the {@code queueName} does not exist.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<QueueRuntimeProperties>> getQueueRuntimePropertiesWithResponse(String queueName) {
return withContext(context -> getQueueWithResponse(queueName, context, QueueRuntimeProperties::new));
}
/**
* Gets information about the Service Bus namespace.
*
* @return A Mono that completes with information about the Service Bus namespace.
* @throws ClientAuthenticationException if the client's credentials do not have access to the namespace.
* @throws HttpResponseException If error occurred processing the request.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<NamespaceProperties> getNamespaceProperties() {
return getNamespacePropertiesWithResponse().map(Response::getValue);
}
/**
* Gets information about the Service Bus namespace along with its HTTP response.
*
* @return A Mono that completes with information about the namespace and the associated HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<NamespaceProperties>> getNamespacePropertiesWithResponse() {
return withContext(this::getNamespacePropertiesWithResponse);
}
/**
* Gets a rule from the service namespace.
*
* Only following data types are deserialized in Filters and Action parameters - string, int, long, boolean, double,
* and OffsetDateTime. Other data types would return its string value.
*
* @param topicName The name of the topic relative to service bus namespace.
* @param subscriptionName The subscription name the rule belongs to.
* @param ruleName The name of the rule to retrieve.
*
* @return The associated rule.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<RuleProperties> getRule(String topicName, String subscriptionName, String ruleName) {
return getRuleWithResponse(topicName, subscriptionName, ruleName).map(response -> response.getValue());
}
/**
* Gets a rule from the service namespace.
*
* Only following data types are deserialized in Filters and Action parameters - string, int, long, bool, double,
* and OffsetDateTime. Other data types would return its string value.
*
* @param topicName The name of the topic relative to service bus namespace.
* @param subscriptionName The subscription name the rule belongs to.
* @param ruleName The name of the rule to retrieve.
*
* @return The associated rule with the corresponding HTTP response.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<RuleProperties>> getRuleWithResponse(String topicName, String subscriptionName,
String ruleName) {
return withContext(context -> getRuleWithResponse(topicName, subscriptionName, ruleName, context));
}
/**
* Gets information about the queue.
*
* @param topicName Name of topic associated with subscription.
* @param subscriptionName Name of subscription to get information about.
*
* @return A Mono that completes with information about the subscription.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} are empty strings.
* @throws NullPointerException if {@code topicName} or {@code subscriptionName} are null.
* @throws ResourceNotFoundException if the {@code subscriptionName} does not exist in the {@code topicName}.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<SubscriptionProperties> getSubscription(String topicName, String subscriptionName) {
return getSubscriptionWithResponse(topicName, subscriptionName).map(Response::getValue);
}
/**
* Gets information about the subscription along with its HTTP response.
*
* @param topicName Name of topic associated with subscription.
* @param subscriptionName Name of subscription to get information about.
*
* @return A Mono that completes with information about the subscription and the associated HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} are empty strings.
* @throws NullPointerException if {@code topicName} or {@code subscriptionName} are null.
* @throws ResourceNotFoundException if the {@code subscriptionName} does not exist.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<SubscriptionProperties>> getSubscriptionWithResponse(String topicName,
String subscriptionName) {
return withContext(context -> getSubscriptionWithResponse(topicName, subscriptionName, context,
Function.identity()));
}
/**
* Gets whether or not a subscription within a topic exists.
*
* @param topicName Name of topic associated with subscription.
* @param subscriptionName Name of the subscription.
*
* @return A Mono that completes indicating whether or not the subscription exists.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code subscriptionName} is an empty string.
* @throws NullPointerException if {@code subscriptionName} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Boolean> getSubscriptionExists(String topicName, String subscriptionName) {
return getSubscriptionExistsWithResponse(topicName, subscriptionName).map(Response::getValue);
}
/**
* Gets whether or not a subscription within a topic exists.
*
* @param topicName Name of topic associated with subscription.
* @param subscriptionName Name of the subscription.
*
* @return A Mono that completes indicating whether or not the subscription exists along with its HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code subscriptionName} is an empty string.
* @throws NullPointerException if {@code subscriptionName} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Boolean>> getSubscriptionExistsWithResponse(String topicName, String subscriptionName) {
return getEntityExistsWithResponse(getSubscriptionWithResponse(topicName, subscriptionName));
}
/**
* Gets runtime properties about the subscription.
*
* @param topicName Name of topic associated with subscription.
* @param subscriptionName Name of subscription to get information about.
*
* @return A Mono that completes with runtime properties about the subscription.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} are empty strings.
* @throws NullPointerException if {@code topicName} or {@code subscriptionName} are null.
* @throws ResourceNotFoundException if the {@code subscriptionName} does not exist.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<SubscriptionRuntimeProperties> getSubscriptionRuntimeProperties(
String topicName, String subscriptionName) {
return getSubscriptionRuntimePropertiesWithResponse(topicName, subscriptionName)
.map(response -> response.getValue());
}
/**
* Gets runtime properties about the subscription.
*
* @param topicName Name of topic associated with subscription.
* @param subscriptionName Name of subscription to get information about.
*
* @return A Mono that completes with runtime properties about the subscription.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code subscriptionName} is an empty string.
* @throws NullPointerException if {@code subscriptionName} is null.
* @throws ResourceNotFoundException if the {@code subscriptionName} does not exist.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<SubscriptionRuntimeProperties>> getSubscriptionRuntimePropertiesWithResponse(
String topicName, String subscriptionName) {
return withContext(context -> getSubscriptionWithResponse(topicName, subscriptionName, context,
SubscriptionRuntimeProperties::new));
}
/**
* Gets information about the topic.
*
* @param topicName Name of topic to get information about.
*
* @return A Mono that completes with information about the topic.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code topicName} is an empty string.
* @throws NullPointerException if {@code topicName} is null.
* @throws ResourceNotFoundException if the {@code topicName} does not exist.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<TopicProperties> getTopic(String topicName) {
return getTopicWithResponse(topicName).map(Response::getValue);
}
/**
* Gets information about the topic along with its HTTP response.
*
* @param topicName Name of topic to get information about.
*
* @return A Mono that completes with information about the topic and the associated HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code topicName} is an empty string.
* @throws NullPointerException if {@code topicName} is null.
* @throws ResourceNotFoundException if the {@code topicName} does not exist.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<TopicProperties>> getTopicWithResponse(String topicName) {
return withContext(context -> getTopicWithResponse(topicName, context, Function.identity()));
}
/**
* Gets whether or not a topic with {@code topicName} exists in the Service Bus namespace.
*
* @param topicName Name of the topic.
*
* @return A Mono that completes indicating whether or not the topic exists.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code topicName} is an empty string.
* @throws NullPointerException if {@code topicName} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Boolean> getTopicExists(String topicName) {
return getTopicExistsWithResponse(topicName).map(Response::getValue);
}
/**
* Gets whether or not a topic with {@code topicName} exists in the Service Bus namespace.
*
* @param topicName Name of the topic.
*
* @return A Mono that completes indicating whether or not the topic exists along with its HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code topicName} is an empty string.
* @throws NullPointerException if {@code topicName} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Boolean>> getTopicExistsWithResponse(String topicName) {
return getEntityExistsWithResponse(getTopicWithResponse(topicName));
}
/**
* Gets runtime properties about the topic.
*
* @param topicName Name of topic to get information about.
*
* @return A Mono that completes with runtime properties about the topic.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code topicName} is an empty string.
* @throws NullPointerException if {@code topicName} is null.
* @throws ResourceNotFoundException if the {@code topicName} does not exist.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<TopicRuntimeProperties> getTopicRuntimeProperties(String topicName) {
return getTopicRuntimePropertiesWithResponse(topicName).map(response -> response.getValue());
}
/**
* Gets runtime properties about the topic with its HTTP response.
*
* @param topicName Name of topic to get information about.
*
* @return A Mono that completes with runtime properties about the topic and the associated HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code topicName} is an empty string.
* @throws NullPointerException if {@code topicName} is null.
* @throws ResourceNotFoundException if the {@code topicName} does not exist.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<TopicRuntimeProperties>> getTopicRuntimePropertiesWithResponse(String topicName) {
return withContext(context -> getTopicWithResponse(topicName, context, TopicRuntimeProperties::new));
}
/**
* Fetches all the queues in the Service Bus namespace.
*
* @return A Flux of {@link QueueProperties queues} in the Service Bus namespace.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @see <a href="https:
* authorization rules</a>
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux<QueueProperties> listQueues() {
return new PagedFlux<>(
() -> withContext(context -> listQueuesFirstPage(context)),
token -> withContext(context -> listQueuesNextPage(token, context)));
}
/**
* Fetches all the rules for a topic and subscription.
*
* @param topicName The topic name under which all the rules need to be retrieved.
* @param subscriptionName The name of the subscription for which all rules need to be retrieved.
*
* @return A Flux of {@link RuleProperties rules} for the {@code topicName} and {@code subscriptionName}.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws NullPointerException if {@code topicName} or {@code subscriptionName} is null.
* @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} is an empty string.
* @see <a href="https:
* authorization rules</a>
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux<RuleProperties> listRules(String topicName, String subscriptionName) {
if (topicName == null) {
return pagedFluxError(logger, new NullPointerException("'topicName' cannot be null."));
} else if (topicName.isEmpty()) {
return pagedFluxError(logger, new IllegalArgumentException("'topicName' cannot be an empty string."));
}
return new PagedFlux<>(
() -> withContext(context -> listRulesFirstPage(topicName, subscriptionName, context)),
token -> withContext(context -> listRulesNextPage(topicName, subscriptionName, token, context)));
}
/**
* Fetches all the subscriptions for a topic.
*
* @param topicName The topic name under which all the subscriptions need to be retrieved.
*
* @return A Flux of {@link SubscriptionProperties subscriptions} for the {@code topicName}.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws NullPointerException if {@code topicName} is null.
* @throws IllegalArgumentException if {@code topicName} is an empty string.
* @see <a href="https:
* authorization rules</a>
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux<SubscriptionProperties> listSubscriptions(String topicName) {
if (topicName == null) {
return pagedFluxError(logger, new NullPointerException("'topicName' cannot be null."));
} else if (topicName.isEmpty()) {
return pagedFluxError(logger, new IllegalArgumentException("'topicName' cannot be an empty string."));
}
return new PagedFlux<>(
() -> withContext(context -> listSubscriptionsFirstPage(topicName, context)),
token -> withContext(context -> listSubscriptionsNextPage(topicName, token, context)));
}
/**
* Fetches all the topics in the Service Bus namespace.
*
* @return A Flux of {@link TopicProperties topics} in the Service Bus namespace.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @see <a href="https:
* authorization rules</a>
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux<TopicProperties> listTopics() {
return new PagedFlux<>(
() -> withContext(context -> listTopicsFirstPage(context)),
token -> withContext(context -> listTopicsNextPage(token, context)));
}
/**
* Updates a queue with the given {@link QueueProperties}. The {@link QueueProperties} must be fully populated as
* all of the properties are replaced. If a property is not set the service default value is used.
*
* The suggested flow is:
* <ol>
* <li>{@link
* <li>Update the required elements.</li>
* <li>Pass the updated description into this method.</li>
* </ol>
*
* <p>
* There are a subset of properties that can be updated. More information can be found in the links below. They are:
* <ul>
* <li>{@link QueueProperties
* <li>{@link QueueProperties
* <li>{@link QueueProperties
* </li>
* <li>{@link QueueProperties
* </ul>
*
* @param queue Information about the queue to update. You must provide all the property values that are desired
* on the updated entity. Any values not provided are set to the service default values.
*
* @return A Mono that completes with the updated queue.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If the request body was invalid, the queue quota is exceeded, or an error
* occurred processing the request.
* @throws NullPointerException if {@code queue} is null.
* @see <a href="https:
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<QueueProperties> updateQueue(QueueProperties queue) {
return updateQueueWithResponse(queue).map(Response::getValue);
}
/**
* Updates a queue with the given {@link QueueProperties}. The {@link QueueProperties} must be fully populated as
* all of the properties are replaced. If a property is not set the service default value is used.
*
* The suggested flow is:
* <ol>
* <li>{@link
* <li>Update the required elements.</li>
* <li>Pass the updated description into this method.</li>
* </ol>
*
* <p>
* There are a subset of properties that can be updated. More information can be found in the links below. They are:
* <ul>
* <li>{@link QueueProperties
* <li>{@link QueueProperties
* <li>{@link QueueProperties
* </li>
* <li>{@link QueueProperties
* </ul>
*
* @param queue Information about the queue to update. You must provide all the property values that are desired
* on the updated entity. Any values not provided are set to the service default values.
*
* @return A Mono that returns the updated queue in addition to the HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If the request body was invalid, the queue quota is exceeded, or an error
* occurred processing the request.
* @throws NullPointerException if {@code queue} is null.
* @see <a href="https:
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<QueueProperties>> updateQueueWithResponse(QueueProperties queue) {
return withContext(context -> updateQueueWithResponse(queue, context));
}
/**
* Updates a rule with the given {@link RuleProperties}. The {@link RuleProperties} must be fully populated as all
* of the properties are replaced. If a property is not set the service default value is used.
*
* The suggested flow is:
* <ol>
* <li>{@link
* <li>Update the required elements.</li>
* <li>Pass the updated description into this method.</li>
* </ol>
*
* @param topicName The topic name under which the rule is updated.
* @param subscriptionName The name of the subscription for which the rule is updated.
* @param rule Information about the rule to update. You must provide all the property values that are desired
* on the updated entity. Any values not provided are set to the service default values.
*
* @return A Mono that returns the updated rule.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If the request body was invalid, the rule quota is exceeded, or an error
* occurred processing the request.
* @throws IllegalArgumentException if {@link RuleProperties
* @throws NullPointerException if {@code rule} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<RuleProperties> updateRule(String topicName, String subscriptionName, RuleProperties rule) {
return updateRuleWithResponse(topicName, subscriptionName, rule).map(Response::getValue);
}
/**
* Updates a rule with the given {@link RuleProperties}. The {@link RuleProperties} must be fully populated as all
* of the properties are replaced. If a property is not set the service default value is used.
*
* The suggested flow is:
* <ol>
* <li>{@link
* <li>Update the required elements.</li>
* <li>Pass the updated description into this method.</li>
* </ol>
*
* @param topicName The topic name under which the rule is updated.
* @param subscriptionName The name of the subscription for which the rule is updated.
* @param rule Information about the rule to update. You must provide all the property values that are desired
* on the updated entity. Any values not provided are set to the service default values.
*
* @return A Mono that returns the updated rule in addition to the HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If the request body was invalid, the rule quota is exceeded, or an error
* occurred processing the request.
* @throws IllegalArgumentException if {@link RuleProperties
* @throws NullPointerException if {@code rule} is null.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<RuleProperties>> updateRuleWithResponse(String topicName, String subscriptionName,
RuleProperties rule) {
return withContext(context -> updateRuleWithResponse(topicName, subscriptionName, rule, context));
}
/**
* Updates a subscription with the given {@link SubscriptionProperties}. The {@link SubscriptionProperties} must be
* fully populated as all of the properties are replaced. If a property is not set the service default value is
* used.
*
* The suggested flow is:
* <ol>
* <li>{@link
* <li>Update the required elements.</li>
* <li>Pass the updated description into this method.</li>
* </ol>
*
* <p>
* There are a subset of properties that can be updated. More information can be found in the links below. They are:
* <ul>
* <li>{@link SubscriptionProperties
* <li>{@link SubscriptionProperties
* <li>{@link SubscriptionProperties
* </ul>
*
* @param subscription Information about the subscription to update. You must provide all the property values
* that are desired on the updated entity. Any values not provided are set to the service default values.
*
* @return A Mono that returns the updated subscription.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If the request body was invalid, the subscription quota is exceeded, or an
* error occurred processing the request.
* @throws IllegalArgumentException if {@link SubscriptionProperties
* SubscriptionProperties
* @throws NullPointerException if {@code subscription} is null.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<SubscriptionProperties> updateSubscription(SubscriptionProperties subscription) {
return updateSubscriptionWithResponse(subscription).map(Response::getValue);
}
/**
* Updates a subscription with the given {@link SubscriptionProperties}. The {@link SubscriptionProperties} must be
* fully populated as all of the properties are replaced. If a property is not set the service default value is
* used.
*
* The suggested flow is:
* <ol>
* <li>{@link
* <li>Update the required elements.</li>
* <li>Pass the updated description into this method.</li>
* </ol>
*
* <p>
* There are a subset of properties that can be updated. More information can be found in the links below. They are:
* <ul>
* <li>{@link SubscriptionProperties
* <li>{@link SubscriptionProperties
* <li>{@link SubscriptionProperties
* </ul>
*
* @param subscription Information about the subscription to update. You must provide all the property values
* that are desired on the updated entity. Any values not provided are set to the service default values.
*
* @return A Mono that returns the updated subscription in addition to the HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If the request body was invalid, the subscription quota is exceeded, or an
* error occurred processing the request.
* @throws IllegalArgumentException if {@link SubscriptionProperties
* SubscriptionProperties
* @throws NullPointerException if {@code subscription} is null.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<SubscriptionProperties>> updateSubscriptionWithResponse(
SubscriptionProperties subscription) {
return withContext(context -> updateSubscriptionWithResponse(subscription, context));
}
/**
* Updates a topic with the given {@link TopicProperties}. The {@link TopicProperties} must be fully populated as
* all of the properties are replaced. If a property is not set the service default value is used.
*
* The suggested flow is:
* <ol>
* <li>{@link
* <li>Update the required elements.</li>
* <li>Pass the updated description into this method.</li>
* </ol>
*
* <p>
* There are a subset of properties that can be updated. More information can be found in the links below. They are:
* <ul>
* <li>{@link TopicProperties
* <li>{@link TopicProperties
* </li>
* </ul>
*
* @param topic Information about the topic to update. You must provide all the property values that are desired
* on the updated entity. Any values not provided are set to the service default values.
*
* @return A Mono that completes with the updated topic.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If the request body was invalid, the topic quota is exceeded, or an error
* occurred processing the request.
* @throws IllegalArgumentException if {@link TopicProperties
* string.
* @throws NullPointerException if {@code topic} is null.
* @see <a href="https:
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<TopicProperties> updateTopic(TopicProperties topic) {
return updateTopicWithResponse(topic).map(Response::getValue);
}
/**
* Updates a topic with the given {@link TopicProperties}. The {@link TopicProperties} must be fully populated as
* all of the properties are replaced. If a property is not set the service default value is used.
*
* The suggested flow is:
* <ol>
* <li>{@link
* <li>Update the required elements.</li>
* <li>Pass the updated description into this method.</li>
* </ol>
*
* <p>
* There are a subset of properties that can be updated. More information can be found in the links below. They are:
* <ul>
* <li>{@link TopicProperties
* <li>{@link TopicProperties
* </li>
* </ul>
*
* @param topic Information about the topic to update. You must provide all the property values that are desired
* on the updated entity. Any values not provided are set to the service default values.
*
* @return A Mono that completes with the updated topic and its HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If the request body was invalid, the topic quota is exceeded, or an error
* occurred processing the request.
* @throws IllegalArgumentException if {@link TopicProperties
* string.
* @throws NullPointerException if {@code topic} is null.
* @see <a href="https:
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<TopicProperties>> updateTopicWithResponse(TopicProperties topic) {
return withContext(context -> updateTopicWithResponse(topic, context));
}
/**
* Creates a queue with its context.
*
* @param createQueueOptions Queue to create.
* @param context Context to pass into request.
*
* @return A Mono that completes with the created {@link QueueProperties}.
*/
Mono<Response<QueueProperties>> createQueueWithResponse(String queueName, CreateQueueOptions createQueueOptions,
Context context) {
if (queueName == null) {
return monoError(logger, new NullPointerException("'queueName' cannot be null."));
} else if (queueName.isEmpty()) {
return monoError(logger, new IllegalArgumentException("'queueName' cannot be empty."));
}
if (createQueueOptions == null) {
return monoError(logger, new NullPointerException("'createQueueOptions' cannot be null."));
} else if (context == null) {
return monoError(logger, new NullPointerException("'context' cannot be null."));
}
final QueueDescription description = EntityHelper.getQueueDescription(createQueueOptions);
final CreateQueueBodyContent content = new CreateQueueBodyContent()
.setType(CONTENT_TYPE)
.setQueueDescription(description);
final CreateQueueBody createEntity = new CreateQueueBody()
.setContent(content);
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
try {
return entityClient.putWithResponseAsync(queueName, createEntity, null, withTracing)
.onErrorMap(ServiceBusAdministrationAsyncClient::mapException)
.map(this::deserializeQueue);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Creates a rule with its context.
*
* @param ruleOptions Rule to create.
* @param context Context to pass into request.
*
* @return A Mono that completes with the created {@link RuleProperties}.
*/
Mono<Response<RuleProperties>> createRuleWithResponse(String topicName, String subscriptionName, String ruleName,
CreateRuleOptions ruleOptions, Context context) {
if (topicName == null) {
return monoError(logger, new NullPointerException("'topicName' cannot be null."));
} else if (topicName.isEmpty()) {
return monoError(logger, new IllegalArgumentException("'topicName' cannot be empty."));
}
if (subscriptionName == null) {
return monoError(logger, new NullPointerException("'subscriptionName' cannot be null."));
} else if (subscriptionName.isEmpty()) {
return monoError(logger, new IllegalArgumentException("'subscriptionName' cannot be empty."));
}
if (ruleName == null) {
return monoError(logger, new NullPointerException("'ruleName' cannot be null."));
} else if (ruleName.isEmpty()) {
return monoError(logger, new IllegalArgumentException("'ruleName' cannot be empty."));
}
if (ruleOptions == null) {
return monoError(logger, new NullPointerException("'rule' cannot be null."));
}
final RuleActionImpl action = ruleOptions.getAction() != null
? EntityHelper.toImplementation(ruleOptions.getAction())
: null;
final RuleFilterImpl filter = ruleOptions.getFilter() != null
? EntityHelper.toImplementation(ruleOptions.getFilter())
: null;
final RuleDescription rule = new RuleDescription()
.setAction(action)
.setFilter(filter)
.setName(ruleName);
final CreateRuleBodyContent content = new CreateRuleBodyContent()
.setType(CONTENT_TYPE)
.setRuleDescription(rule);
final CreateRuleBody createEntity = new CreateRuleBody().setContent(content);
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
try {
return managementClient.getRules().putWithResponseAsync(topicName, subscriptionName, ruleName, createEntity,
null, withTracing)
.onErrorMap(ServiceBusAdministrationAsyncClient::mapException)
.map(response -> deserializeRule(response));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Creates a subscription with its context.
*
* @param subscriptionOptions Subscription to create.
* @param context Context to pass into request.
*
* @return A Mono that completes with the created {@link SubscriptionProperties}.
*/
Mono<Response<SubscriptionProperties>> createSubscriptionWithResponse(String topicName, String subscriptionName,
CreateSubscriptionOptions subscriptionOptions, Context context) {
if (topicName == null) {
return monoError(logger, new NullPointerException("'topicName' cannot be null."));
} else if (topicName.isEmpty()) {
return monoError(logger, new IllegalArgumentException("'topicName' cannot be empty."));
}
if (subscriptionName == null) {
return monoError(logger, new NullPointerException("'subscriptionName' cannot be null."));
} else if (subscriptionName.isEmpty()) {
return monoError(logger, new IllegalArgumentException("'subscriptionName' cannot be empty."));
}
if (subscriptionOptions == null) {
return monoError(logger, new NullPointerException("'subscription' cannot be null."));
}
final SubscriptionDescription subscription = EntityHelper.getSubscriptionDescription(subscriptionOptions);
final CreateSubscriptionBodyContent content = new CreateSubscriptionBodyContent()
.setType(CONTENT_TYPE)
.setSubscriptionDescription(subscription);
final CreateSubscriptionBody createEntity = new CreateSubscriptionBody().setContent(content);
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
try {
return managementClient.getSubscriptions().putWithResponseAsync(topicName, subscriptionName, createEntity,
null, withTracing)
.onErrorMap(ServiceBusAdministrationAsyncClient::mapException)
.map(response -> deserializeSubscription(topicName, response));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Creates a topicOptions with its context.
*
* @param topicOptions Topic to create.
* @param context Context to pass into request.
*
* @return A Mono that completes with the created {@link TopicProperties}.
*/
Mono<Response<TopicProperties>> createTopicWithResponse(String topicName, CreateTopicOptions topicOptions,
Context context) {
if (topicName == null) {
return monoError(logger, new NullPointerException("'topicName' cannot be null."));
} else if (topicName.isEmpty()) {
return monoError(logger, new IllegalArgumentException("'topicName' cannot be empty."));
}
if (topicOptions == null) {
return monoError(logger, new NullPointerException("'topicOptions' cannot be null"));
} else if (context == null) {
return monoError(logger, new NullPointerException("'context' cannot be null."));
}
final TopicDescription topic = EntityHelper.getTopicDescription(topicOptions);
final CreateTopicBodyContent content = new CreateTopicBodyContent()
.setType(CONTENT_TYPE)
.setTopicDescription(topic);
final CreateTopicBody createEntity = new CreateTopicBody()
.setContent(content);
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
try {
return entityClient.putWithResponseAsync(topicName, createEntity, null, withTracing)
.onErrorMap(ServiceBusAdministrationAsyncClient::mapException)
.map(this::deserializeTopic);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Deletes a queue with its context.
*
* @param queueName Name of queue to delete.
* @param context Context to pass into request.
*
* @return A Mono that completes when the queue is deleted.
*/
Mono<Response<Void>> deleteQueueWithResponse(String queueName, Context context) {
if (queueName == null) {
return monoError(logger, new NullPointerException("'queueName' cannot be null"));
} else if (queueName.isEmpty()) {
return monoError(logger, new IllegalArgumentException("'queueName' cannot be an empty string."));
} else if (context == null) {
return monoError(logger, new NullPointerException("'context' cannot be null."));
}
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
try {
return entityClient.deleteWithResponseAsync(queueName, withTracing)
.onErrorMap(ServiceBusAdministrationAsyncClient::mapException)
.map(response -> {
return new SimpleResponse<>(response.getRequest(), response.getStatusCode(),
response.getHeaders(), null);
});
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Deletes a queue with its context.
*
* @param topicName Name of topic to delete.
* @param subscriptionName Name of the subscription for the rule.
* @param ruleName Name of the rule.
* @param context Context to pass into request.
*
* @return A Mono that completes with the created {@link QueueProperties}.
*/
Mono<Response<Void>> deleteRuleWithResponse(String topicName, String subscriptionName, String ruleName,
Context context) {
if (topicName == null) {
return monoError(logger, new NullPointerException("'topicName' cannot be null"));
} else if (topicName.isEmpty()) {
return monoError(logger, new IllegalArgumentException("'topicName' cannot be an empty string."));
} else if (subscriptionName == null) {
return monoError(logger, new NullPointerException("'subscriptionName' cannot be null"));
} else if (subscriptionName.isEmpty()) {
return monoError(logger, new IllegalArgumentException("'subscriptionName' cannot be an empty string."));
} else if (ruleName == null) {
return monoError(logger, new NullPointerException("'ruleName' cannot be null"));
} else if (ruleName.isEmpty()) {
return monoError(logger, new IllegalArgumentException("'ruleName' cannot be an empty string."));
} else if (context == null) {
return monoError(logger, new NullPointerException("'context' cannot be null."));
}
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
try {
return rulesClient.deleteWithResponseAsync(topicName, subscriptionName, ruleName, withTracing)
.onErrorMap(ServiceBusAdministrationAsyncClient::mapException)
.map(response -> new SimpleResponse<>(response.getRequest(), response.getStatusCode(),
response.getHeaders(), null));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Deletes a subscription with its context.
*
* @param topicName Name of topic associated with subscription to delete.
* @param subscriptionName Name of subscription to delete.
* @param context Context to pass into request.
*
* @return A Mono that completes with the created {@link SubscriptionProperties}.
*/
Mono<Response<Void>> deleteSubscriptionWithResponse(String topicName, String subscriptionName, Context context) {
if (subscriptionName == null) {
return monoError(logger, new NullPointerException("'subscriptionName' cannot be null"));
} else if (subscriptionName.isEmpty()) {
return monoError(logger, new IllegalArgumentException("'subscriptionName' cannot be an empty string."));
} else if (topicName == null) {
return monoError(logger, new NullPointerException("'topicName' cannot be null"));
} else if (topicName.isEmpty()) {
return monoError(logger, new IllegalArgumentException("'topicName' cannot be an empty string."));
} else if (context == null) {
return monoError(logger, new NullPointerException("'context' cannot be null."));
}
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
try {
return managementClient.getSubscriptions().deleteWithResponseAsync(topicName, subscriptionName,
withTracing)
.onErrorMap(ServiceBusAdministrationAsyncClient::mapException)
.map(response -> new SimpleResponse<>(response.getRequest(), response.getStatusCode(),
response.getHeaders(), null));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Deletes a topic with its context.
*
* @param topicName Name of topic to delete.
* @param context Context to pass into request.
*
* @return A Mono that completes with the created {@link TopicProperties}.
*/
Mono<Response<Void>> deleteTopicWithResponse(String topicName, Context context) {
if (topicName == null) {
return monoError(logger, new NullPointerException("'topicName' cannot be null"));
} else if (topicName.isEmpty()) {
return monoError(logger, new IllegalArgumentException("'topicName' cannot be an empty string."));
} else if (context == null) {
return monoError(logger, new NullPointerException("'context' cannot be null."));
}
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
try {
return entityClient.deleteWithResponseAsync(topicName, withTracing)
.onErrorMap(ServiceBusAdministrationAsyncClient::mapException)
.map(response -> new SimpleResponse<>(response.getRequest(), response.getStatusCode(),
response.getHeaders(), null));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Gets whether an entity exists.
*
* @param getEntityOperation Operation to get information about entity. If {@link ResourceNotFoundException} is
* thrown, then it is mapped to false.
* @param <T> Entity type.
*
* @return True if the entity exists, false otherwise.
*/
<T> Mono<Response<Boolean>> getEntityExistsWithResponse(Mono<Response<T>> getEntityOperation) {
return getEntityOperation.map(response -> {
final boolean exists = response.getValue() != null;
return (Response<Boolean>) new SimpleResponse<>(response.getRequest(), response.getStatusCode(),
response.getHeaders(), exists);
})
.onErrorResume(ResourceNotFoundException.class, exception -> {
final HttpResponse response = exception.getResponse();
final Response<Boolean> result = new SimpleResponse<>(response.getRequest(), response.getStatusCode(),
response.getHeaders(), false);
return Mono.just(result);
});
}
/**
* Gets a queue with its context.
*
* @param queueName Name of queue to fetch information for.
* @param context Context to pass into request.
*
* @return A Mono that completes with the {@link QueueProperties}.
*/
<T> Mono<Response<T>> getQueueWithResponse(String queueName, Context context,
Function<QueueProperties, T> mapper) {
if (queueName == null) {
return monoError(logger, new NullPointerException("'queueName' cannot be null"));
} else if (queueName.isEmpty()) {
return monoError(logger, new IllegalArgumentException("'queueName' cannot be empty."));
} else if (context == null) {
return monoError(logger, new NullPointerException("'context' cannot be null."));
}
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
try {
return entityClient.getWithResponseAsync(queueName, true, withTracing)
.onErrorMap(ServiceBusAdministrationAsyncClient::mapException)
.handle((response, sink) -> {
final Response<QueueProperties> deserialize = deserializeQueue(response);
if (deserialize.getValue() == null) {
final HttpResponse notFoundResponse = new EntityNotFoundHttpResponse<>(deserialize);
sink.error(new ResourceNotFoundException(String.format("Queue '%s' does not exist.", queueName),
notFoundResponse));
} else {
final T mapped = mapper.apply(deserialize.getValue());
sink.next(new SimpleResponse<>(response.getRequest(), response.getStatusCode(),
response.getHeaders(), mapped));
}
});
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<RuleProperties>> getRuleWithResponse(String topicName, String subscriptionName,
String ruleName, Context context) {
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
try {
return rulesClient.getWithResponseAsync(topicName, subscriptionName, ruleName, true, withTracing)
.onErrorMap(ServiceBusAdministrationAsyncClient::mapException)
.map(this::deserializeRule);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Gets a subscription with its context.
*
* @param topicName Name of the topic associated with the subscription.
* @param subscriptionName Name of subscription to fetch information for.
* @param context Context to pass into request.
*
* @return A Mono that completes with the {@link SubscriptionProperties}.
*/
<T> Mono<Response<T>> getSubscriptionWithResponse(String topicName, String subscriptionName, Context context,
Function<SubscriptionProperties, T> mapper) {
if (topicName == null) {
return monoError(logger, new NullPointerException("'topicName' cannot be null."));
} else if (topicName.isEmpty()) {
return monoError(logger, new IllegalArgumentException("'topicName' cannot be an empty string."));
} else if (subscriptionName == null) {
return monoError(logger, new NullPointerException("'subscriptionName' cannot be null."));
} else if (subscriptionName.isEmpty()) {
return monoError(logger, new IllegalArgumentException("'subscriptionName' cannot be an empty string."));
} else if (context == null) {
return monoError(logger, new NullPointerException("'context' cannot be null."));
}
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
try {
return managementClient.getSubscriptions().getWithResponseAsync(topicName, subscriptionName, true,
withTracing)
.onErrorMap(ServiceBusAdministrationAsyncClient::mapException)
.handle((response, sink) -> {
final Response<SubscriptionProperties> deserialize = deserializeSubscription(topicName, response);
if (deserialize.getValue() == null) {
final HttpResponse notFoundResponse = new EntityNotFoundHttpResponse<>(deserialize);
sink.error(new ResourceNotFoundException(String.format(
"Subscription '%s' in topic '%s' does not exist.", topicName, subscriptionName),
notFoundResponse));
} else {
final T mapped = mapper.apply(deserialize.getValue());
sink.next(new SimpleResponse<>(response.getRequest(), response.getStatusCode(),
response.getHeaders(), mapped));
}
});
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Gets the namespace properties with its context.
*
* @param context Context to pass into request.
*
* @return A Mono that completes with the {@link NamespaceProperties}.
*/
Mono<Response<NamespaceProperties>> getNamespacePropertiesWithResponse(Context context) {
return managementClient.getNamespaces().getWithResponseAsync(context).handle((response, sink) -> {
final NamespacePropertiesEntry entry = response.getValue();
if (entry == null || entry.getContent() == null) {
sink.error(new AzureException(
"There was no content inside namespace response. Entry: " + response));
return;
}
final NamespaceProperties namespaceProperties = entry.getContent().getNamespaceProperties();
final Response<NamespaceProperties> result = new SimpleResponse<>(response.getRequest(),
response.getStatusCode(), response.getHeaders(), namespaceProperties);
sink.next(result);
});
}
/**
* Gets a topic with its context.
*
* @param topicName Name of topic to fetch information for.
* @param context Context to pass into request.
*
* @return A Mono that completes with the {@link TopicProperties}.
*/
<T> Mono<Response<T>> getTopicWithResponse(String topicName, Context context,
Function<TopicProperties, T> mapper) {
if (topicName == null) {
return monoError(logger, new NullPointerException("'topicName' cannot be null"));
} else if (topicName.isEmpty()) {
return monoError(logger, new IllegalArgumentException("'topicName' cannot be empty."));
} else if (context == null) {
return monoError(logger, new NullPointerException("'context' cannot be null."));
}
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
try {
return entityClient.getWithResponseAsync(topicName, true, withTracing)
.onErrorMap(ServiceBusAdministrationAsyncClient::mapException)
.handle((response, sink) -> {
final Response<TopicProperties> deserialize = deserializeTopic(response);
if (deserialize.getValue() == null) {
final HttpResponse notFoundResponse = new EntityNotFoundHttpResponse<>(deserialize);
sink.error(new ResourceNotFoundException(String.format("Topic '%s' does not exist.", topicName),
notFoundResponse));
} else {
final T mapped = mapper.apply(deserialize.getValue());
sink.next(new SimpleResponse<>(response.getRequest(), response.getStatusCode(),
response.getHeaders(), mapped));
}
});
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Gets the first page of queues with context.
*
* @param context Context to pass into request.
*
* @return A Mono that completes with a page of queues.
*/
Mono<PagedResponse<QueueProperties>> listQueuesFirstPage(Context context) {
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
try {
return listQueues(0, withTracing);
} catch (RuntimeException e) {
return monoError(logger, e);
}
}
/**
* Gets the next page of queues with context.
*
* @param continuationToken Number of items to skip in feed.
* @param context Context to pass into request.
*
* @return A Mono that completes with a page of queues or empty if there are no items left.
*/
Mono<PagedResponse<QueueProperties>> listQueuesNextPage(String continuationToken, Context context) {
if (continuationToken == null || continuationToken.isEmpty()) {
return Mono.empty();
}
try {
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
final int skip = Integer.parseInt(continuationToken);
return listQueues(skip, withTracing);
} catch (RuntimeException e) {
return monoError(logger, e);
}
}
/**
* Gets the first page of rules with context.
*
* @param context Context to pass into request.
*
* @return A Mono that completes with a page of rules.
*/
Mono<PagedResponse<RuleProperties>> listRulesFirstPage(String topicName, String subscriptionName, Context context) {
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
try {
return listRules(topicName, subscriptionName, 0, withTracing);
} catch (RuntimeException e) {
return monoError(logger, e);
}
}
/**
* Gets the next page of rules with context.
*
* @param continuationToken Number of items to skip in feed.
* @param context Context to pass into request.
*
* @return A Mono that completes with a page of rules or empty if there are no items left.
*/
Mono<PagedResponse<RuleProperties>> listRulesNextPage(String topicName, String subscriptionName,
String continuationToken, Context context) {
if (continuationToken == null || continuationToken.isEmpty()) {
return Mono.empty();
}
try {
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
final int skip = Integer.parseInt(continuationToken);
return listRules(topicName, subscriptionName, skip, withTracing);
} catch (RuntimeException e) {
return monoError(logger, e);
}
}
/**
* Gets the first page of subscriptions with context.
*
* @param context Context to pass into request.
*
* @return A Mono that completes with a page of subscriptions.
*/
Mono<PagedResponse<SubscriptionProperties>> listSubscriptionsFirstPage(String topicName, Context context) {
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
try {
return listSubscriptions(topicName, 0, withTracing);
} catch (RuntimeException e) {
return monoError(logger, e);
}
}
/**
* Gets the next page of subscriptions with context.
*
* @param continuationToken Number of items to skip in feed.
* @param context Context to pass into request.
*
* @return A Mono that completes with a page of subscriptions or empty if there are no items left.
*/
Mono<PagedResponse<SubscriptionProperties>> listSubscriptionsNextPage(String topicName, String continuationToken,
Context context) {
if (continuationToken == null || continuationToken.isEmpty()) {
return Mono.empty();
}
try {
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
final int skip = Integer.parseInt(continuationToken);
return listSubscriptions(topicName, skip, withTracing);
} catch (RuntimeException e) {
return monoError(logger, e);
}
}
/**
* Gets the first page of topics with context.
*
* @param context Context to pass into request.
*
* @return A Mono that completes with a page of topics.
*/
Mono<PagedResponse<TopicProperties>> listTopicsFirstPage(Context context) {
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
try {
return listTopics(0, withTracing);
} catch (RuntimeException e) {
return monoError(logger, e);
}
}
/**
* Gets the next page of topics with context.
*
* @param continuationToken Number of items to skip in feed.
* @param context Context to pass into request.
*
* @return A Mono that completes with a page of topics or empty if there are no items left.
*/
Mono<PagedResponse<TopicProperties>> listTopicsNextPage(String continuationToken, Context context) {
if (continuationToken == null || continuationToken.isEmpty()) {
return Mono.empty();
}
try {
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
final int skip = Integer.parseInt(continuationToken);
return listTopics(skip, withTracing);
} catch (RuntimeException e) {
return monoError(logger, e);
}
}
/**
* Updates a queue with its context.
*
* @param queue Information about the queue to update. You must provide all the property values that are desired
* on the updated entity. Any values not provided are set to the service default values.
* @param context Context to pass into request.
*
* @return A Mono that completes with the updated {@link QueueProperties}.
*/
Mono<Response<QueueProperties>> updateQueueWithResponse(QueueProperties queue, Context context) {
if (queue == null) {
return monoError(logger, new NullPointerException("'queue' cannot be null"));
} else if (context == null) {
return monoError(logger, new NullPointerException("'context' cannot be null."));
}
final QueueDescription queueDescription = EntityHelper.toImplementation(queue);
final CreateQueueBodyContent content = new CreateQueueBodyContent()
.setType(CONTENT_TYPE)
.setQueueDescription(queueDescription);
final CreateQueueBody createEntity = new CreateQueueBody()
.setContent(content);
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
try {
return entityClient.putWithResponseAsync(queue.getName(), createEntity, "*", withTracing)
.onErrorMap(ServiceBusAdministrationAsyncClient::mapException)
.map(response -> deserializeQueue(response));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Updates a rule with its context.
*
* @param rule Information about the rule to update. You must provide all the property values that are desired
* on the updated entity. Any values not provided are set to the service default values.
* @param context Context to pass into request.
*
* @return A Mono that completes with the updated {@link RuleProperties}.
*/
Mono<Response<RuleProperties>> updateRuleWithResponse(String topicName, String subscriptionName,
RuleProperties rule, Context context) {
if (rule == null) {
return monoError(logger, new NullPointerException("'rule' cannot be null"));
} else if (context == null) {
return monoError(logger, new NullPointerException("'context' cannot be null."));
}
final RuleDescription implementation = EntityHelper.toImplementation(rule);
final CreateRuleBodyContent content = new CreateRuleBodyContent()
.setType(CONTENT_TYPE)
.setRuleDescription(implementation);
final CreateRuleBody ruleBody = new CreateRuleBody()
.setContent(content);
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
try {
return managementClient.getRules().putWithResponseAsync(topicName, subscriptionName, rule.getName(),
ruleBody, "*", withTracing)
.onErrorMap(ServiceBusAdministrationAsyncClient::mapException)
.map(response -> deserializeRule(response));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Updates a subscription with its context.
*
* @param subscription Information about the subscription to update. You must provide all the property values
* that are desired on the updated entity. Any values not provided are set to the service default values.
* @param context Context to pass into request.
*
* @return A Mono that completes with the updated {@link SubscriptionProperties}.
*/
Mono<Response<SubscriptionProperties>> updateSubscriptionWithResponse(SubscriptionProperties subscription,
Context context) {
if (subscription == null) {
return monoError(logger, new NullPointerException("'subscription' cannot be null"));
} else if (context == null) {
return monoError(logger, new NullPointerException("'context' cannot be null."));
}
final String topicName = subscription.getTopicName();
final String subscriptionName = subscription.getSubscriptionName();
final SubscriptionDescription implementation = EntityHelper.toImplementation(subscription);
final CreateSubscriptionBodyContent content = new CreateSubscriptionBodyContent()
.setType(CONTENT_TYPE)
.setSubscriptionDescription(implementation);
final CreateSubscriptionBody createEntity = new CreateSubscriptionBody()
.setContent(content);
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
try {
return managementClient.getSubscriptions().putWithResponseAsync(topicName, subscriptionName, createEntity,
"*", withTracing)
.onErrorMap(ServiceBusAdministrationAsyncClient::mapException)
.map(response -> deserializeSubscription(topicName, response));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Updates a topic with its context.
*
* @param topic Information about the topic to update. You must provide all the property values that are desired
* on the updated entity. Any values not provided are set to the service default values.
* @param context Context to pass into request.
*
* @return A Mono that completes with the updated {@link TopicProperties}.
*/
Mono<Response<TopicProperties>> updateTopicWithResponse(TopicProperties topic, Context context) {
if (topic == null) {
return monoError(logger, new NullPointerException("'topic' cannot be null"));
} else if (context == null) {
return monoError(logger, new NullPointerException("'context' cannot be null."));
}
final TopicDescription implementation = EntityHelper.toImplementation(topic);
final CreateTopicBodyContent content = new CreateTopicBodyContent()
.setType(CONTENT_TYPE)
.setTopicDescription(implementation);
final CreateTopicBody createEntity = new CreateTopicBody()
.setContent(content);
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
try {
return entityClient.putWithResponseAsync(topic.getName(), createEntity, "*", withTracing)
.onErrorMap(ServiceBusAdministrationAsyncClient::mapException)
.map(response -> deserializeTopic(response));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
private <T> T deserialize(Object object, Class<T> clazz) {
if (object == null) {
return null;
}
final String contents = String.valueOf(object);
if (contents.isEmpty()) {
return null;
}
try {
return serializer.deserialize(contents, clazz);
} catch (IOException e) {
throw logger.logExceptionAsError(new RuntimeException(String.format(
"Exception while deserializing. Body: [%s]. Class: %s", contents, clazz), e));
}
}
/**
* Given an HTTP response, will deserialize it into a strongly typed Response object.
*
* @param response HTTP response to deserialize response body from.
* @param clazz Class to deserialize response type into.
* @param <T> Class type to deserialize response into.
*
* @return A Response with a strongly typed response value.
*/
private <T> Response<T> deserialize(Response<Object> response, Class<T> clazz) {
final T deserialize = deserialize(response.getValue(), clazz);
return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(),
deserialize);
}
/**
* Converts a Response into its corresponding {@link QueueDescriptionEntry} then mapped into {@link
* QueueProperties}.
*
* @param response HTTP Response to deserialize.
*
* @return The corresponding HTTP response with convenience properties set.
*/
/**
* Converts a Response into its corresponding {@link RuleDescriptionEntry} then mapped into {@link RuleProperties}.
*
* @param response HTTP Response to deserialize.
*
* @return The corresponding HTTP response with convenience properties set.
*/
private Response<RuleProperties> deserializeRule(Response<Object> response) {
final RuleDescriptionEntry entry = deserialize(response.getValue(), RuleDescriptionEntry.class);
if (entry == null) {
return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null);
} else if (entry.getContent() == null) {
logger.info("entry.getContent() is null. The entity may not exist. {}", entry);
return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null);
}
final RuleDescription description = entry.getContent().getRuleDescription();
final RuleProperties result = EntityHelper.toModel(description);
return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), result);
}
/**
* Converts a Response into its corresponding {@link SubscriptionDescriptionEntry} then mapped into {@link
* SubscriptionProperties}.
*
* @param response HTTP Response to deserialize.
*
* @return The corresponding HTTP response with convenience properties set.
*/
private Response<SubscriptionProperties> deserializeSubscription(String topicName, Response<Object> response) {
final SubscriptionDescriptionEntry entry = deserialize(response.getValue(), SubscriptionDescriptionEntry.class);
if (entry == null) {
return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null);
} else if (entry.getContent() == null) {
logger.warning("entry.getContent() is null. There should have been content returned. Entry: {}", entry);
return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null);
}
final SubscriptionProperties subscription = EntityHelper.toModel(
entry.getContent().getSubscriptionDescription());
final String subscriptionName = getTitleValue(entry.getTitle());
EntityHelper.setSubscriptionName(subscription, subscriptionName);
EntityHelper.setTopicName(subscription, topicName);
return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(),
subscription);
}
/**
* Converts a Response into its corresponding {@link TopicDescriptionEntry} then mapped into {@link
* QueueProperties}.
*
* @param response HTTP Response to deserialize.
*
* @return The corresponding HTTP response with convenience properties set.
*/
private Response<TopicProperties> deserializeTopic(Response<Object> response) {
final TopicDescriptionEntry entry = deserialize(response.getValue(), TopicDescriptionEntry.class);
if (entry == null) {
return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null);
} else if (entry.getContent() == null) {
logger.warning("entry.getContent() is null. There should have been content returned. Entry: {}", entry);
return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null);
} else if (entry.getContent().getTopicDescription() == null) {
final QueueDescriptionEntry entryTopic = deserialize(response.getValue(), QueueDescriptionEntry.class);
if (entryTopic != null && entryTopic.getContent() != null && entryTopic.getContent().getQueueDescription() != null) {
throw logger.logExceptionAsError(
new RuntimeException(String.format("'[%s]' is not a topic, it is a queue.", entryTopic.getTitle())));
}
}
final TopicProperties result = EntityHelper.toModel(entry.getContent().getTopicDescription());
final String topicName = getTitleValue(entry.getTitle());
EntityHelper.setTopicName(result, topicName);
return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), result);
}
/**
* Creates a {@link FeedPage} given the elements and a set of response links to get the next link from.
*
* @param entities Entities in the feed.
* @param responseLinks Links returned from the feed.
* @param <TResult> Type of Service Bus entities in page.
*
* @return A {@link FeedPage} indicating whether this can be continued or not.
* @throws MalformedURLException if the "next" page link does not contain a well-formed URL.
*/
private <TResult, TFeed> FeedPage<TResult> extractPage(Response<TFeed> response, List<TResult> entities,
List<ResponseLink> responseLinks)
throws MalformedURLException, UnsupportedEncodingException {
final Optional<ResponseLink> nextLink = responseLinks.stream()
.filter(link -> link.getRel().equalsIgnoreCase("next"))
.findFirst();
if (!nextLink.isPresent()) {
return new FeedPage<>(response.getStatusCode(), response.getHeaders(), response.getRequest(), entities);
}
final URL url = new URL(nextLink.get().getHref());
final String decode = URLDecoder.decode(url.getQuery(), StandardCharsets.UTF_8.name());
final Optional<Integer> skipParameter = Arrays.stream(decode.split("&|&"))
.map(part -> part.split("=", 2))
.filter(parts -> parts[0].equalsIgnoreCase("$skip") && parts.length == 2)
.map(parts -> Integer.valueOf(parts[1]))
.findFirst();
if (skipParameter.isPresent()) {
return new FeedPage<>(response.getStatusCode(), response.getHeaders(), response.getRequest(), entities,
skipParameter.get());
} else {
logger.warning("There should have been a skip parameter for the next page.");
return new FeedPage<>(response.getStatusCode(), response.getHeaders(), response.getRequest(), entities);
}
}
/**
* Helper method that invokes the service method, extracts the data and translates it to a PagedResponse.
*
* @param skip Number of elements to skip.
* @param context Context for the query.
*
* @return A Mono that completes with a paged response of queues.
*/
private Mono<PagedResponse<QueueProperties>> listQueues(int skip, Context context) {
return managementClient.listEntitiesWithResponseAsync(QUEUES_ENTITY_TYPE, skip, NUMBER_OF_ELEMENTS, context)
.onErrorMap(ServiceBusAdministrationAsyncClient::mapException)
.flatMap(response -> {
final Response<QueueDescriptionFeed> feedResponse = deserialize(response, QueueDescriptionFeed.class);
final QueueDescriptionFeed feed = feedResponse.getValue();
if (feed == null) {
logger.warning("Could not deserialize QueueDescriptionFeed. skip {}, top: {}", skip,
NUMBER_OF_ELEMENTS);
return Mono.empty();
}
final List<QueueProperties> entities = feed.getEntry().stream()
.filter(e -> e.getContent() != null && e.getContent().getQueueDescription() != null)
.map(e -> {
final String queueName = getTitleValue(e.getTitle());
final QueueProperties queueProperties = EntityHelper.toModel(
e.getContent().getQueueDescription());
EntityHelper.setQueueName(queueProperties, queueName);
return queueProperties;
})
.collect(Collectors.toList());
try {
return Mono.just(extractPage(feedResponse, entities, feed.getLink()));
} catch (MalformedURLException | UnsupportedEncodingException error) {
return Mono.error(new RuntimeException("Could not parse response into FeedPage<QueueDescription>",
error));
}
});
}
/**
* Helper method that invokes the service method, extracts the data and translates it to a PagedResponse.
*
* @param skip Number of elements to skip.
* @param context Context for the query.
*
* @return A Mono that completes with a paged response of rules.
*/
private Mono<PagedResponse<RuleProperties>> listRules(String topicName, String subscriptionName, int skip,
Context context) {
return managementClient.listRulesWithResponseAsync(topicName, subscriptionName, skip, NUMBER_OF_ELEMENTS,
context)
.onErrorMap(ServiceBusAdministrationAsyncClient::mapException)
.flatMap(response -> {
final Response<RuleDescriptionFeed> feedResponse = deserialize(response,
RuleDescriptionFeed.class);
final RuleDescriptionFeed feed = feedResponse.getValue();
if (feed == null) {
logger.warning("Could not deserialize RuleDescriptionFeed. skip {}, top: {}", skip,
NUMBER_OF_ELEMENTS);
return Mono.empty();
}
final List<RuleProperties> entities = feed.getEntry().stream()
.filter(e -> e.getContent() != null && e.getContent().getRuleDescription() != null)
.map(e -> {
return EntityHelper.toModel(e.getContent().getRuleDescription());
})
.collect(Collectors.toList());
try {
return Mono.just(extractPage(feedResponse, entities, feed.getLink()));
} catch (MalformedURLException | UnsupportedEncodingException error) {
return Mono.error(new RuntimeException(
"Could not parse response into FeedPage<RuleDescription>", error));
}
});
}
/**
* Helper method that invokes the service method, extracts the data and translates it to a PagedResponse.
*
* @param skip Number of elements to skip.
* @param context Context for the query.
*
* @return A Mono that completes with a paged response of subscriptions.
*/
private Mono<PagedResponse<SubscriptionProperties>> listSubscriptions(String topicName, int skip,
Context context) {
return managementClient.listSubscriptionsWithResponseAsync(topicName, skip, NUMBER_OF_ELEMENTS, context)
.onErrorMap(ServiceBusAdministrationAsyncClient::mapException)
.flatMap(response -> {
final Response<SubscriptionDescriptionFeed> feedResponse = deserialize(response,
SubscriptionDescriptionFeed.class);
final SubscriptionDescriptionFeed feed = feedResponse.getValue();
if (feed == null) {
logger.warning("Could not deserialize SubscriptionDescriptionFeed. skip {}, top: {}", skip,
NUMBER_OF_ELEMENTS);
return Mono.empty();
}
final List<SubscriptionProperties> entities = feed.getEntry().stream()
.filter(e -> e.getContent() != null && e.getContent().getSubscriptionDescription() != null)
.map(e -> {
final String subscriptionName = getTitleValue(e.getTitle());
final SubscriptionProperties description = EntityHelper.toModel(
e.getContent().getSubscriptionDescription());
EntityHelper.setTopicName(description, topicName);
EntityHelper.setSubscriptionName(description, subscriptionName);
return description;
})
.collect(Collectors.toList());
try {
return Mono.just(extractPage(feedResponse, entities, feed.getLink()));
} catch (MalformedURLException | UnsupportedEncodingException error) {
return Mono.error(new RuntimeException(
"Could not parse response into FeedPage<SubscriptionDescription>", error));
}
});
}
/**
* Helper method that invokes the service method, extracts the data and translates it to a PagedResponse.
*
* @param skip Number of elements to skip.
* @param context Context for the query.
*
* @return A Mono that completes with a paged response of topics.
*/
private Mono<PagedResponse<TopicProperties>> listTopics(int skip, Context context) {
return managementClient.listEntitiesWithResponseAsync(TOPICS_ENTITY_TYPE, skip, NUMBER_OF_ELEMENTS, context)
.onErrorMap(ServiceBusAdministrationAsyncClient::mapException)
.flatMap(response -> {
final Response<TopicDescriptionFeed> feedResponse = deserialize(response, TopicDescriptionFeed.class);
final TopicDescriptionFeed feed = feedResponse.getValue();
if (feed == null) {
logger.warning("Could not deserialize TopicDescriptionFeed. skip {}, top: {}", skip,
NUMBER_OF_ELEMENTS);
return Mono.empty();
}
final List<TopicProperties> entities = feed.getEntry().stream()
.filter(e -> e.getContent() != null && e.getContent().getTopicDescription() != null)
.map(e -> {
final String topicName = getTitleValue(e.getTitle());
final TopicProperties topicProperties = EntityHelper.toModel(
e.getContent().getTopicDescription());
EntityHelper.setTopicName(topicProperties, topicName);
return topicProperties;
})
.collect(Collectors.toList());
try {
return Mono.just(extractPage(feedResponse, entities, feed.getLink()));
} catch (MalformedURLException | UnsupportedEncodingException error) {
return Mono.error(new RuntimeException("Could not parse response into FeedPage<TopicDescription>",
error));
}
});
}
/**
* Given an XML title element, returns the XML text inside. Jackson deserializes Objects as LinkedHashMaps. XML text
* is represented as an entry with an empty string as the key.
*
* For example, the text returned from this {@code <title text="text/xml">QueueName</title>} is "QueueName".
*
* @param responseTitle XML title element.
*
* @return The XML text inside the title. {@code null} is returned if there is no value.
*/
@SuppressWarnings("unchecked")
private String getTitleValue(Object responseTitle) {
if (!(responseTitle instanceof Map)) {
return null;
}
final Map<String, String> map;
try {
map = (Map<String, String>) responseTitle;
return map.get("");
} catch (ClassCastException error) {
logger.warning("Unable to cast to Map<String,String>. Title: {}", responseTitle, error);
return null;
}
}
/**
* Maps an exception from the ATOM APIs to its associated {@link HttpResponseException}.
*
* @param exception Exception from the ATOM API.
*
* @return The corresponding {@link HttpResponseException} or {@code throwable} if it is not an instance of {@link
* ServiceBusManagementErrorException}.
*/
private static Throwable mapException(Throwable exception) {
if (!(exception instanceof ServiceBusManagementErrorException)) {
return exception;
}
final ServiceBusManagementErrorException managementError = ((ServiceBusManagementErrorException) exception);
final ServiceBusManagementError error = managementError.getValue();
final HttpResponse errorHttpResponse = managementError.getResponse();
final int statusCode = error != null && error.getCode() != null
? error.getCode()
: errorHttpResponse.getStatusCode();
final String errorDetail = error != null && error.getDetail() != null
? error.getDetail()
: managementError.getMessage();
switch (statusCode) {
case 401:
return new ClientAuthenticationException(errorDetail, managementError.getResponse(), exception);
case 404:
return new ResourceNotFoundException(errorDetail, managementError.getResponse(), exception);
case 409:
return new ResourceExistsException(errorDetail, managementError.getResponse(), exception);
case 412:
return new ResourceModifiedException(errorDetail, managementError.getResponse(), exception);
default:
return new HttpResponseException(errorDetail, managementError.getResponse(), exception);
}
}
/**
* A page of Service Bus entities.
*
* @param <T> The entity description from Service Bus.
*/
private static final class FeedPage<T> implements PagedResponse<T> {
private final int statusCode;
private final HttpHeaders header;
private final HttpRequest request;
private final IterableStream<T> entries;
private final String continuationToken;
/**
* Creates a page that does not have any more pages.
*
* @param entries Items in the page.
*/
private FeedPage(int statusCode, HttpHeaders header, HttpRequest request, List<T> entries) {
this.statusCode = statusCode;
this.header = header;
this.request = request;
this.entries = new IterableStream<>(entries);
this.continuationToken = null;
}
/**
* Creates an instance that has additional pages to fetch.
*
* @param entries Items in the page.
* @param skip Number of elements to "skip".
*/
private FeedPage(int statusCode, HttpHeaders header, HttpRequest request, List<T> entries, int skip) {
this.statusCode = statusCode;
this.header = header;
this.request = request;
this.entries = new IterableStream<>(entries);
this.continuationToken = String.valueOf(skip);
}
@Override
public IterableStream<T> getElements() {
return entries;
}
@Override
public String getContinuationToken() {
return continuationToken;
}
@Override
public int getStatusCode() {
return statusCode;
}
@Override
public HttpHeaders getHeaders() {
return header;
}
@Override
public HttpRequest getRequest() {
return request;
}
@Override
public void close() {
}
}
private static final class EntityNotFoundHttpResponse<T> extends HttpResponse {
private final int statusCode;
private final HttpHeaders headers;
private EntityNotFoundHttpResponse(Response<T> response) {
super(response.getRequest());
this.headers = response.getHeaders();
this.statusCode = response.getStatusCode();
}
@Override
public int getStatusCode() {
return statusCode;
}
@Override
public String getHeaderValue(String name) {
return headers.getValue(name);
}
@Override
public HttpHeaders getHeaders() {
return headers;
}
@Override
public Flux<ByteBuffer> getBody() {
return Flux.empty();
}
@Override
public Mono<byte[]> getBodyAsByteArray() {
return Mono.empty();
}
@Override
public Mono<String> getBodyAsString() {
return Mono.empty();
}
@Override
public Mono<String> getBodyAsString(Charset charset) {
return Mono.empty();
}
}
} | class ServiceBusAdministrationAsyncClient {
private static final String SERVICE_BUS_TRACING_NAMESPACE_VALUE = "Microsoft.ServiceBus";
private static final String CONTENT_TYPE = "application/xml";
private static final String QUEUES_ENTITY_TYPE = "queues";
private static final String TOPICS_ENTITY_TYPE = "topics";
private static final int NUMBER_OF_ELEMENTS = 100;
private final ServiceBusManagementClientImpl managementClient;
private final EntitiesImpl entityClient;
private final ClientLogger logger = new ClientLogger(ServiceBusAdministrationAsyncClient.class);
private final ServiceBusManagementSerializer serializer;
private final RulesImpl rulesClient;
/**
* Creates a new instance with the given management client and serializer.
*
* @param managementClient Client to make management calls.
* @param serializer Serializer to deserialize ATOM XML responses.
*/
ServiceBusAdministrationAsyncClient(ServiceBusManagementClientImpl managementClient,
ServiceBusManagementSerializer serializer) {
this.serializer = Objects.requireNonNull(serializer, "'serializer' cannot be null.");
this.managementClient = Objects.requireNonNull(managementClient, "'managementClient' cannot be null.");
this.entityClient = managementClient.getEntities();
this.rulesClient = managementClient.getRules();
}
/**
* Creates a queue with the given name.
*
* @param queueName Name of the queue to create.
*
* @return A Mono that completes with information about the created queue.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If the request body was invalid, the queue quota is exceeded, or an error
* occurred processing the request.
* @throws NullPointerException if {@code queueName} is null.
* @throws IllegalArgumentException if {@code queueName} is an empty string.
* @throws ResourceExistsException if a queue exists with the same {@code queueName}.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<QueueProperties> createQueue(String queueName) {
try {
return createQueue(queueName, new CreateQueueOptions());
} catch (RuntimeException e) {
return monoError(logger, e);
}
}
/**
* Creates a queue with the {@link CreateQueueOptions} and given queue name.
*
* @param queueName Name of the queue to create.
* @param queueOptions Options about the queue to create.
*
* @return A Mono that completes with information about the created queue.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If the request body was invalid, the queue quota is exceeded, or an error
* occurred processing the request.
* @throws IllegalArgumentException if {@code queueName} is an empty string.
* @throws NullPointerException if {@code queueName} or {@code queueOptions} is null.
* @throws ResourceExistsException if a queue exists with the same {@link QueueProperties
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<QueueProperties> createQueue(String queueName, CreateQueueOptions queueOptions) {
return createQueueWithResponse(queueName, queueOptions).map(Response::getValue);
}
/**
* Creates a queue and returns the created queue in addition to the HTTP response.
*
* @param queueName Name of the queue to create.
* @param queueOptions Options about the queue to create.
*
* @return A Mono that returns the created queue in addition to the HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If the request body was invalid, the queue quota is exceeded, or an error
* occurred processing the request.
* @throws IllegalArgumentException if {@code queueName} is an empty string.
* @throws NullPointerException if {@code queueName} or {@code queueOptions} is null.
* @throws ResourceExistsException if a queue exists with the same {@link QueueProperties
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<QueueProperties>> createQueueWithResponse(String queueName, CreateQueueOptions queueOptions) {
return withContext(context -> createQueueWithResponse(queueName, queueOptions, context));
}
/**
* Creates a rule under the given topic and subscription
*
* @param topicName Name of the topic associated with rule.
* @param subscriptionName Name of the subscription associated with the rule.
* @param ruleName Name of the rule.
*
* @return A Mono that completes with information about the created rule.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If the request body was invalid, the quota is exceeded, or an error occurred
* processing the request.
* @throws IllegalArgumentException if {@code topicName} or {@code ruleName} are are empty strings.
* @throws NullPointerException if {@code topicName} or {@code ruleName} are are null.
* @throws ResourceExistsException if a rule exists with the same topic, subscription, and rule name.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<RuleProperties> createRule(String topicName, String subscriptionName, String ruleName) {
try {
return createRule(topicName, subscriptionName, ruleName, new CreateRuleOptions());
} catch (RuntimeException e) {
return monoError(logger, e);
}
}
/**
* Creates a rule with the {@link CreateRuleOptions}.
*
* @param topicName Name of the topic associated with rule.
* @param subscriptionName Name of the subscription associated with the rule.
* @param ruleName Name of the rule.
* @param ruleOptions Information about the rule to create.
*
* @return A Mono that completes with information about the created rule.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If the request body was invalid, the quota is exceeded, or an error occurred
* processing the request.
* @throws IllegalArgumentException if {@code topicName} or {@code ruleName} are are empty strings.
* @throws NullPointerException if {@code topicName}, {@code ruleName}, or {@code ruleOptions}
* are are null.
* @throws ResourceExistsException if a rule exists with the same topic and rule name.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<RuleProperties> createRule(String topicName, String subscriptionName, String ruleName,
CreateRuleOptions ruleOptions) {
return createRuleWithResponse(topicName, subscriptionName, ruleName, ruleOptions)
.map(Response::getValue);
}
/**
* Creates a rule and returns the created rule in addition to the HTTP response.
*
* @param topicName Name of the topic associated with rule.
* @param subscriptionName Name of the subscription associated with the rule.
* @param ruleName Name of the rule.
* @param ruleOptions Information about the rule to create.
*
* @return A Mono that returns the created rule in addition to the HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If the request body was invalid, the quota is exceeded, or an error occurred
* processing the request.
* @throws IllegalArgumentException if {@code topicName} or {@code ruleName} are are empty strings.
* @throws NullPointerException if {@code topicName}, {@code ruleName}, or {@code ruleOptions}
* are are null.
* @throws ResourceExistsException if a rule exists with the same topic and rule name.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<RuleProperties>> createRuleWithResponse(String topicName, String subscriptionName,
String ruleName, CreateRuleOptions ruleOptions) {
return withContext(context -> createRuleWithResponse(topicName, subscriptionName, ruleName, ruleOptions,
context));
}
/**
* Creates a subscription with the given topic and subscription names.
*
* @param topicName Name of the topic associated with subscription.
* @param subscriptionName Name of the subscription.
*
* @return A Mono that completes with information about the created subscription.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If the request body was invalid, the quota is exceeded, or an error occurred
* processing the request.
* @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} are are empty strings.
* @throws NullPointerException if {@code topicName} or {@code subscriptionName} are are null.
* @throws ResourceExistsException if a subscription exists with the same topic and subscription name.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<SubscriptionProperties> createSubscription(String topicName, String subscriptionName) {
try {
return createSubscription(topicName, subscriptionName, new CreateSubscriptionOptions());
} catch (RuntimeException e) {
return monoError(logger, e);
}
}
/**
* Creates a subscription with the {@link CreateSubscriptionOptions}.
*
* @param topicName Name of the topic associated with subscription.
* @param subscriptionName Name of the subscription.
* @param subscriptionOptions Information about the subscription to create.
*
* @return A Mono that completes with information about the created subscription.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If the request body was invalid, the quota is exceeded, or an error occurred
* processing the request.
* @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} are are empty strings.
* @throws NullPointerException if {@code topicName}, {@code subscriptionName}, or {@code subscriptionOptions}
* are are null.
* @throws ResourceExistsException if a subscription exists with the same topic and subscription name.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<SubscriptionProperties> createSubscription(String topicName, String subscriptionName,
CreateSubscriptionOptions subscriptionOptions) {
return createSubscriptionWithResponse(topicName, subscriptionName, subscriptionOptions)
.map(Response::getValue);
}
/**
* Creates a subscription and returns the created subscription in addition to the HTTP response.
*
* @param topicName Name of the topic associated with subscription.
* @param subscriptionName Name of the subscription.
* @param subscriptionOptions Information about the subscription to create.
*
* @return A Mono that returns the created subscription in addition to the HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If the request body was invalid, the quota is exceeded, or an error occurred
* processing the request.
* @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} are are empty strings.
* @throws NullPointerException if {@code topicName}, {@code subscriptionName}, or {@code subscriptionOptions}
* are are null.
* @throws ResourceExistsException if a subscription exists with the same topic and subscription name.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<SubscriptionProperties>> createSubscriptionWithResponse(String topicName,
String subscriptionName, CreateSubscriptionOptions subscriptionOptions) {
return withContext(context -> createSubscriptionWithResponse(topicName, subscriptionName, subscriptionOptions,
context));
}
/**
* Creates a topic with the given name.
*
* @param topicName Name of the topic to create.
*
* @return A Mono that completes with information about the created topic.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If the request body was invalid, the topic quota is exceeded, or an error
* occurred processing the request.
* @throws NullPointerException if {@code topicName} is null.
* @throws IllegalArgumentException if {@code topicName} is an empty string.
* @throws ResourceExistsException if a topic exists with the same {@code topicName}.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<TopicProperties> createTopic(String topicName) {
try {
return createTopic(topicName, new CreateTopicOptions());
} catch (RuntimeException e) {
return monoError(logger, e);
}
}
/**
* Creates a topic with the {@link CreateTopicOptions}.
*
* @param topicName Name of the topic to create.
* @param topicOptions The options used to create the topic.
*
* @return A Mono that completes with information about the created topic.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If the request body was invalid, the topic quota is exceeded, or an error
* occurred processing the request.
* @throws IllegalArgumentException if {@code topicName} is an empty string.
* @throws NullPointerException if {@code topicName} or {@code topicOptions} is null.
* @throws ResourceExistsException if a topic exists with the same {@code topicName}.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<TopicProperties> createTopic(String topicName, CreateTopicOptions topicOptions) {
return createTopicWithResponse(topicName, topicOptions).map(Response::getValue);
}
/**
* Creates a topic and returns the created topic in addition to the HTTP response.
*
* @param topicName Name of the topic to create.
* @param topicOptions The options used to create the topic.
*
* @return A Mono that returns the created topic in addition to the HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If the request body was invalid, the topic quota is exceeded, or an error
* occurred processing the request.
* @throws IllegalArgumentException if {@link TopicProperties
* string.
* @throws NullPointerException if {@code topicName} or {@code topicOptions} is null.
* @throws ResourceExistsException if a topic exists with the same {@code topicName}.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<TopicProperties>> createTopicWithResponse(String topicName, CreateTopicOptions topicOptions) {
return withContext(context -> createTopicWithResponse(topicName, topicOptions, context));
}
/**
* Deletes a queue the matching {@code queueName}.
*
* @param queueName Name of queue to delete.
*
* @return A Mono that completes when the queue is deleted.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws NullPointerException if {@code queueName} is null.
* @throws IllegalArgumentException if {@code queueName} is an empty string.
* @throws ResourceNotFoundException if the {@code queueName} does not exist.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Void> deleteQueue(String queueName) {
return deleteQueueWithResponse(queueName).then();
}
/**
* Deletes a queue the matching {@code queueName} and returns the HTTP response.
*
* @param queueName Name of queue to delete.
*
* @return A Mono that completes when the queue is deleted and returns the HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws NullPointerException if {@code queueName} is null.
* @throws IllegalArgumentException if {@code queueName} is an empty string.
* @throws ResourceNotFoundException if the {@code queueName} does not exist.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Void>> deleteQueueWithResponse(String queueName) {
return withContext(context -> deleteQueueWithResponse(queueName, context));
}
/**
* Deletes a rule the matching {@code ruleName}.
*
* @param topicName Name of topic associated with rule to delete.
* @param subscriptionName Name of the subscription associated with the rule to delete.
* @param ruleName Name of rule to delete.
*
* @return A Mono that completes when the rule is deleted.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code topicName} or {@code ruleName} is an empty string.
* @throws NullPointerException if {@code topicName} or {@code ruleName} is null.
* @throws ResourceNotFoundException if the {@code ruleName} does not exist.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Void> deleteRule(String topicName, String subscriptionName, String ruleName) {
return deleteRuleWithResponse(topicName, subscriptionName, ruleName).then();
}
/**
* Deletes a rule the matching {@code ruleName} and returns the HTTP response.
*
* @param topicName Name of topic associated with rule to delete.
* @param subscriptionName Name of the subscription associated with the rule to delete.
* @param ruleName Name of rule to delete.
*
* @return A Mono that completes when the rule is deleted and returns the HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code topicName}, {@code subscriptionName}, or {@code ruleName} is an
* empty string.
* @throws NullPointerException if {@code topicName}, {@code subscriptionName}, or {@code ruleName} is null.
* @throws ResourceNotFoundException if the {@code ruleName} does not exist.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Void>> deleteRuleWithResponse(String topicName, String subscriptionName,
String ruleName) {
return withContext(context -> deleteRuleWithResponse(topicName, subscriptionName, ruleName, context));
}
/**
* Deletes a subscription the matching {@code subscriptionName}.
*
* @param topicName Name of topic associated with subscription to delete.
* @param subscriptionName Name of subscription to delete.
*
* @return A Mono that completes when the subscription is deleted.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} is an empty string.
* @throws NullPointerException if {@code topicName} or {@code subscriptionName} is null.
* @throws ResourceNotFoundException if the {@code subscriptionName} does not exist.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Void> deleteSubscription(String topicName, String subscriptionName) {
return deleteSubscriptionWithResponse(topicName, subscriptionName).then();
}
/**
* Deletes a subscription the matching {@code subscriptionName} and returns the HTTP response.
*
* @param topicName Name of topic associated with subscription to delete.
* @param subscriptionName Name of subscription to delete.
*
* @return A Mono that completes when the subscription is deleted and returns the HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} is an empty string.
* @throws NullPointerException if {@code topicName} or {@code subscriptionName} is null.
* @throws ResourceNotFoundException if the {@code subscriptionName} does not exist.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Void>> deleteSubscriptionWithResponse(String topicName, String subscriptionName) {
return withContext(context -> deleteSubscriptionWithResponse(topicName, subscriptionName, context));
}
/**
* Deletes a topic the matching {@code topicName}.
*
* @param topicName Name of topic to delete.
*
* @return A Mono that completes when the topic is deleted.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code topicName} is an empty string.
* @throws NullPointerException if {@code topicName} is null.
* @throws ResourceNotFoundException if the {@code topicName} does not exist.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Void> deleteTopic(String topicName) {
return deleteTopicWithResponse(topicName).then();
}
/**
* Deletes a topic the matching {@code topicName} and returns the HTTP response.
*
* @param topicName Name of topic to delete.
*
* @return A Mono that completes when the topic is deleted and returns the HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code topicName} is an empty string.
* @throws NullPointerException if {@code topicName} is null.
* @throws ResourceNotFoundException if the {@code topicName} does not exist.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Void>> deleteTopicWithResponse(String topicName) {
return withContext(context -> deleteTopicWithResponse(topicName, context));
}
/**
* Gets information about the queue.
*
* @param queueName Name of queue to get information about.
*
* @return A Mono that completes with information about the queue.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code queueName} is an empty string.
* @throws NullPointerException if {@code queueName} is null.
* @throws ResourceNotFoundException if the {@code queueName} does not exist.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<QueueProperties> getQueue(String queueName) {
return getQueueWithResponse(queueName).map(Response::getValue);
}
/**
* Gets information about the queue along with its HTTP response.
*
* @param queueName Name of queue to get information about.
*
* @return A Mono that completes with information about the queue and the associated HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code queueName} is an empty string.
* @throws NullPointerException if {@code queueName} is null.
* @throws ResourceNotFoundException if the {@code queueName} does not exist.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<QueueProperties>> getQueueWithResponse(String queueName) {
return withContext(context -> getQueueWithResponse(queueName, context, Function.identity()));
}
/**
* Gets whether or not a queue with {@code queueName} exists in the Service Bus namespace.
*
* @param queueName Name of the queue.
*
* @return A Mono that completes indicating whether or not the queue exists.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code queueName} is an empty string.
* @throws NullPointerException if {@code queueName} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Boolean> getQueueExists(String queueName) {
return getQueueExistsWithResponse(queueName).map(Response::getValue);
}
/**
* Gets whether or not a queue with {@code queueName} exists in the Service Bus namespace.
*
* @param queueName Name of the queue.
*
* @return A Mono that completes indicating whether or not the queue exists along with its HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code queueName} is an empty string.
* @throws NullPointerException if {@code queueName} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Boolean>> getQueueExistsWithResponse(String queueName) {
return getEntityExistsWithResponse(getQueueWithResponse(queueName));
}
/**
* Gets runtime properties about the queue.
*
* @param queueName Name of queue to get information about.
*
* @return A Mono that completes with runtime properties about the queue.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code queueName} is an empty string.
* @throws NullPointerException if {@code queueName} is null.
* @throws ResourceNotFoundException if the {@code queueName} does not exist.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<QueueRuntimeProperties> getQueueRuntimeProperties(String queueName) {
return getQueueRuntimePropertiesWithResponse(queueName).map(response -> response.getValue());
}
/**
* Gets runtime properties about the queue along with its HTTP response.
*
* @param queueName Name of queue to get information about.
*
* @return A Mono that completes with runtime properties about the queue and the associated HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code queueName} is an empty string.
* @throws NullPointerException if {@code queueName} is null.
* @throws ResourceNotFoundException if the {@code queueName} does not exist.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<QueueRuntimeProperties>> getQueueRuntimePropertiesWithResponse(String queueName) {
return withContext(context -> getQueueWithResponse(queueName, context, QueueRuntimeProperties::new));
}
/**
* Gets information about the Service Bus namespace.
*
* @return A Mono that completes with information about the Service Bus namespace.
* @throws ClientAuthenticationException if the client's credentials do not have access to the namespace.
* @throws HttpResponseException If error occurred processing the request.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<NamespaceProperties> getNamespaceProperties() {
return getNamespacePropertiesWithResponse().map(Response::getValue);
}
/**
* Gets information about the Service Bus namespace along with its HTTP response.
*
* @return A Mono that completes with information about the namespace and the associated HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<NamespaceProperties>> getNamespacePropertiesWithResponse() {
return withContext(this::getNamespacePropertiesWithResponse);
}
/**
* Gets a rule from the service namespace.
*
* Only following data types are deserialized in Filters and Action parameters - string, int, long, boolean, double,
* and OffsetDateTime. Other data types would return its string value.
*
* @param topicName The name of the topic relative to service bus namespace.
* @param subscriptionName The subscription name the rule belongs to.
* @param ruleName The name of the rule to retrieve.
*
* @return The associated rule.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<RuleProperties> getRule(String topicName, String subscriptionName, String ruleName) {
return getRuleWithResponse(topicName, subscriptionName, ruleName).map(response -> response.getValue());
}
/**
* Gets a rule from the service namespace.
*
* Only following data types are deserialized in Filters and Action parameters - string, int, long, bool, double,
* and OffsetDateTime. Other data types would return its string value.
*
* @param topicName The name of the topic relative to service bus namespace.
* @param subscriptionName The subscription name the rule belongs to.
* @param ruleName The name of the rule to retrieve.
*
* @return The associated rule with the corresponding HTTP response.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<RuleProperties>> getRuleWithResponse(String topicName, String subscriptionName,
String ruleName) {
return withContext(context -> getRuleWithResponse(topicName, subscriptionName, ruleName, context));
}
/**
* Gets information about the queue.
*
* @param topicName Name of topic associated with subscription.
* @param subscriptionName Name of subscription to get information about.
*
* @return A Mono that completes with information about the subscription.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} are empty strings.
* @throws NullPointerException if {@code topicName} or {@code subscriptionName} are null.
* @throws ResourceNotFoundException if the {@code subscriptionName} does not exist in the {@code topicName}.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<SubscriptionProperties> getSubscription(String topicName, String subscriptionName) {
return getSubscriptionWithResponse(topicName, subscriptionName).map(Response::getValue);
}
/**
* Gets information about the subscription along with its HTTP response.
*
* @param topicName Name of topic associated with subscription.
* @param subscriptionName Name of subscription to get information about.
*
* @return A Mono that completes with information about the subscription and the associated HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} are empty strings.
* @throws NullPointerException if {@code topicName} or {@code subscriptionName} are null.
* @throws ResourceNotFoundException if the {@code subscriptionName} does not exist.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<SubscriptionProperties>> getSubscriptionWithResponse(String topicName,
String subscriptionName) {
return withContext(context -> getSubscriptionWithResponse(topicName, subscriptionName, context,
Function.identity()));
}
/**
* Gets whether or not a subscription within a topic exists.
*
* @param topicName Name of topic associated with subscription.
* @param subscriptionName Name of the subscription.
*
* @return A Mono that completes indicating whether or not the subscription exists.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code subscriptionName} is an empty string.
* @throws NullPointerException if {@code subscriptionName} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Boolean> getSubscriptionExists(String topicName, String subscriptionName) {
return getSubscriptionExistsWithResponse(topicName, subscriptionName).map(Response::getValue);
}
/**
* Gets whether or not a subscription within a topic exists.
*
* @param topicName Name of topic associated with subscription.
* @param subscriptionName Name of the subscription.
*
* @return A Mono that completes indicating whether or not the subscription exists along with its HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code subscriptionName} is an empty string.
* @throws NullPointerException if {@code subscriptionName} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Boolean>> getSubscriptionExistsWithResponse(String topicName, String subscriptionName) {
return getEntityExistsWithResponse(getSubscriptionWithResponse(topicName, subscriptionName));
}
/**
* Gets runtime properties about the subscription.
*
* @param topicName Name of topic associated with subscription.
* @param subscriptionName Name of subscription to get information about.
*
* @return A Mono that completes with runtime properties about the subscription.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} are empty strings.
* @throws NullPointerException if {@code topicName} or {@code subscriptionName} are null.
* @throws ResourceNotFoundException if the {@code subscriptionName} does not exist.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<SubscriptionRuntimeProperties> getSubscriptionRuntimeProperties(
String topicName, String subscriptionName) {
return getSubscriptionRuntimePropertiesWithResponse(topicName, subscriptionName)
.map(response -> response.getValue());
}
/**
* Gets runtime properties about the subscription.
*
* @param topicName Name of topic associated with subscription.
* @param subscriptionName Name of subscription to get information about.
*
* @return A Mono that completes with runtime properties about the subscription.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code subscriptionName} is an empty string.
* @throws NullPointerException if {@code subscriptionName} is null.
* @throws ResourceNotFoundException if the {@code subscriptionName} does not exist.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<SubscriptionRuntimeProperties>> getSubscriptionRuntimePropertiesWithResponse(
String topicName, String subscriptionName) {
return withContext(context -> getSubscriptionWithResponse(topicName, subscriptionName, context,
SubscriptionRuntimeProperties::new));
}
/**
* Gets information about the topic.
*
* @param topicName Name of topic to get information about.
*
* @return A Mono that completes with information about the topic.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code topicName} is an empty string.
* @throws NullPointerException if {@code topicName} is null.
* @throws ResourceNotFoundException if the {@code topicName} does not exist.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<TopicProperties> getTopic(String topicName) {
return getTopicWithResponse(topicName).map(Response::getValue);
}
/**
* Gets information about the topic along with its HTTP response.
*
* @param topicName Name of topic to get information about.
*
* @return A Mono that completes with information about the topic and the associated HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code topicName} is an empty string.
* @throws NullPointerException if {@code topicName} is null.
* @throws ResourceNotFoundException if the {@code topicName} does not exist.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<TopicProperties>> getTopicWithResponse(String topicName) {
return withContext(context -> getTopicWithResponse(topicName, context, Function.identity()));
}
/**
* Gets whether or not a topic with {@code topicName} exists in the Service Bus namespace.
*
* @param topicName Name of the topic.
*
* @return A Mono that completes indicating whether or not the topic exists.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code topicName} is an empty string.
* @throws NullPointerException if {@code topicName} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Boolean> getTopicExists(String topicName) {
return getTopicExistsWithResponse(topicName).map(Response::getValue);
}
/**
* Gets whether or not a topic with {@code topicName} exists in the Service Bus namespace.
*
* @param topicName Name of the topic.
*
* @return A Mono that completes indicating whether or not the topic exists along with its HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code topicName} is an empty string.
* @throws NullPointerException if {@code topicName} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Boolean>> getTopicExistsWithResponse(String topicName) {
return getEntityExistsWithResponse(getTopicWithResponse(topicName));
}
/**
* Gets runtime properties about the topic.
*
* @param topicName Name of topic to get information about.
*
* @return A Mono that completes with runtime properties about the topic.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code topicName} is an empty string.
* @throws NullPointerException if {@code topicName} is null.
* @throws ResourceNotFoundException if the {@code topicName} does not exist.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<TopicRuntimeProperties> getTopicRuntimeProperties(String topicName) {
return getTopicRuntimePropertiesWithResponse(topicName).map(response -> response.getValue());
}
/**
* Gets runtime properties about the topic with its HTTP response.
*
* @param topicName Name of topic to get information about.
*
* @return A Mono that completes with runtime properties about the topic and the associated HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code topicName} is an empty string.
* @throws NullPointerException if {@code topicName} is null.
* @throws ResourceNotFoundException if the {@code topicName} does not exist.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<TopicRuntimeProperties>> getTopicRuntimePropertiesWithResponse(String topicName) {
return withContext(context -> getTopicWithResponse(topicName, context, TopicRuntimeProperties::new));
}
/**
* Fetches all the queues in the Service Bus namespace.
*
* @return A Flux of {@link QueueProperties queues} in the Service Bus namespace.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @see <a href="https:
* authorization rules</a>
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux<QueueProperties> listQueues() {
return new PagedFlux<>(
() -> withContext(context -> listQueuesFirstPage(context)),
token -> withContext(context -> listQueuesNextPage(token, context)));
}
/**
* Fetches all the rules for a topic and subscription.
*
* @param topicName The topic name under which all the rules need to be retrieved.
* @param subscriptionName The name of the subscription for which all rules need to be retrieved.
*
* @return A Flux of {@link RuleProperties rules} for the {@code topicName} and {@code subscriptionName}.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws NullPointerException if {@code topicName} or {@code subscriptionName} is null.
* @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} is an empty string.
* @see <a href="https:
* authorization rules</a>
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux<RuleProperties> listRules(String topicName, String subscriptionName) {
if (topicName == null) {
return pagedFluxError(logger, new NullPointerException("'topicName' cannot be null."));
} else if (topicName.isEmpty()) {
return pagedFluxError(logger, new IllegalArgumentException("'topicName' cannot be an empty string."));
}
return new PagedFlux<>(
() -> withContext(context -> listRulesFirstPage(topicName, subscriptionName, context)),
token -> withContext(context -> listRulesNextPage(topicName, subscriptionName, token, context)));
}
/**
* Fetches all the subscriptions for a topic.
*
* @param topicName The topic name under which all the subscriptions need to be retrieved.
*
* @return A Flux of {@link SubscriptionProperties subscriptions} for the {@code topicName}.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws NullPointerException if {@code topicName} is null.
* @throws IllegalArgumentException if {@code topicName} is an empty string.
* @see <a href="https:
* authorization rules</a>
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux<SubscriptionProperties> listSubscriptions(String topicName) {
if (topicName == null) {
return pagedFluxError(logger, new NullPointerException("'topicName' cannot be null."));
} else if (topicName.isEmpty()) {
return pagedFluxError(logger, new IllegalArgumentException("'topicName' cannot be an empty string."));
}
return new PagedFlux<>(
() -> withContext(context -> listSubscriptionsFirstPage(topicName, context)),
token -> withContext(context -> listSubscriptionsNextPage(topicName, token, context)));
}
/**
* Fetches all the topics in the Service Bus namespace.
*
* @return A Flux of {@link TopicProperties topics} in the Service Bus namespace.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @see <a href="https:
* authorization rules</a>
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux<TopicProperties> listTopics() {
return new PagedFlux<>(
() -> withContext(context -> listTopicsFirstPage(context)),
token -> withContext(context -> listTopicsNextPage(token, context)));
}
/**
* Updates a queue with the given {@link QueueProperties}. The {@link QueueProperties} must be fully populated as
* all of the properties are replaced. If a property is not set the service default value is used.
*
* The suggested flow is:
* <ol>
* <li>{@link
* <li>Update the required elements.</li>
* <li>Pass the updated description into this method.</li>
* </ol>
*
* <p>
* There are a subset of properties that can be updated. More information can be found in the links below. They are:
* <ul>
* <li>{@link QueueProperties
* <li>{@link QueueProperties
* <li>{@link QueueProperties
* </li>
* <li>{@link QueueProperties
* </ul>
*
* @param queue Information about the queue to update. You must provide all the property values that are desired
* on the updated entity. Any values not provided are set to the service default values.
*
* @return A Mono that completes with the updated queue.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If the request body was invalid, the queue quota is exceeded, or an error
* occurred processing the request.
* @throws NullPointerException if {@code queue} is null.
* @see <a href="https:
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<QueueProperties> updateQueue(QueueProperties queue) {
return updateQueueWithResponse(queue).map(Response::getValue);
}
/**
* Updates a queue with the given {@link QueueProperties}. The {@link QueueProperties} must be fully populated as
* all of the properties are replaced. If a property is not set the service default value is used.
*
* The suggested flow is:
* <ol>
* <li>{@link
* <li>Update the required elements.</li>
* <li>Pass the updated description into this method.</li>
* </ol>
*
* <p>
* There are a subset of properties that can be updated. More information can be found in the links below. They are:
* <ul>
* <li>{@link QueueProperties
* <li>{@link QueueProperties
* <li>{@link QueueProperties
* </li>
* <li>{@link QueueProperties
* </ul>
*
* @param queue Information about the queue to update. You must provide all the property values that are desired
* on the updated entity. Any values not provided are set to the service default values.
*
* @return A Mono that returns the updated queue in addition to the HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If the request body was invalid, the queue quota is exceeded, or an error
* occurred processing the request.
* @throws NullPointerException if {@code queue} is null.
* @see <a href="https:
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<QueueProperties>> updateQueueWithResponse(QueueProperties queue) {
return withContext(context -> updateQueueWithResponse(queue, context));
}
/**
* Updates a rule with the given {@link RuleProperties}. The {@link RuleProperties} must be fully populated as all
* of the properties are replaced. If a property is not set the service default value is used.
*
* The suggested flow is:
* <ol>
* <li>{@link
* <li>Update the required elements.</li>
* <li>Pass the updated description into this method.</li>
* </ol>
*
* @param topicName The topic name under which the rule is updated.
* @param subscriptionName The name of the subscription for which the rule is updated.
* @param rule Information about the rule to update. You must provide all the property values that are desired
* on the updated entity. Any values not provided are set to the service default values.
*
* @return A Mono that returns the updated rule.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If the request body was invalid, the rule quota is exceeded, or an error
* occurred processing the request.
* @throws IllegalArgumentException if {@link RuleProperties
* @throws NullPointerException if {@code rule} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<RuleProperties> updateRule(String topicName, String subscriptionName, RuleProperties rule) {
return updateRuleWithResponse(topicName, subscriptionName, rule).map(Response::getValue);
}
/**
* Updates a rule with the given {@link RuleProperties}. The {@link RuleProperties} must be fully populated as all
* of the properties are replaced. If a property is not set the service default value is used.
*
* The suggested flow is:
* <ol>
* <li>{@link
* <li>Update the required elements.</li>
* <li>Pass the updated description into this method.</li>
* </ol>
*
* @param topicName The topic name under which the rule is updated.
* @param subscriptionName The name of the subscription for which the rule is updated.
* @param rule Information about the rule to update. You must provide all the property values that are desired
* on the updated entity. Any values not provided are set to the service default values.
*
* @return A Mono that returns the updated rule in addition to the HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If the request body was invalid, the rule quota is exceeded, or an error
* occurred processing the request.
* @throws IllegalArgumentException if {@link RuleProperties
* @throws NullPointerException if {@code rule} is null.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<RuleProperties>> updateRuleWithResponse(String topicName, String subscriptionName,
RuleProperties rule) {
return withContext(context -> updateRuleWithResponse(topicName, subscriptionName, rule, context));
}
/**
* Updates a subscription with the given {@link SubscriptionProperties}. The {@link SubscriptionProperties} must be
* fully populated as all of the properties are replaced. If a property is not set the service default value is
* used.
*
* The suggested flow is:
* <ol>
* <li>{@link
* <li>Update the required elements.</li>
* <li>Pass the updated description into this method.</li>
* </ol>
*
* <p>
* There are a subset of properties that can be updated. More information can be found in the links below. They are:
* <ul>
* <li>{@link SubscriptionProperties
* <li>{@link SubscriptionProperties
* <li>{@link SubscriptionProperties
* </ul>
*
* @param subscription Information about the subscription to update. You must provide all the property values
* that are desired on the updated entity. Any values not provided are set to the service default values.
*
* @return A Mono that returns the updated subscription.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If the request body was invalid, the subscription quota is exceeded, or an
* error occurred processing the request.
* @throws IllegalArgumentException if {@link SubscriptionProperties
* SubscriptionProperties
* @throws NullPointerException if {@code subscription} is null.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<SubscriptionProperties> updateSubscription(SubscriptionProperties subscription) {
return updateSubscriptionWithResponse(subscription).map(Response::getValue);
}
/**
* Updates a subscription with the given {@link SubscriptionProperties}. The {@link SubscriptionProperties} must be
* fully populated as all of the properties are replaced. If a property is not set the service default value is
* used.
*
* The suggested flow is:
* <ol>
* <li>{@link
* <li>Update the required elements.</li>
* <li>Pass the updated description into this method.</li>
* </ol>
*
* <p>
* There are a subset of properties that can be updated. More information can be found in the links below. They are:
* <ul>
* <li>{@link SubscriptionProperties
* <li>{@link SubscriptionProperties
* <li>{@link SubscriptionProperties
* </ul>
*
* @param subscription Information about the subscription to update. You must provide all the property values
* that are desired on the updated entity. Any values not provided are set to the service default values.
*
* @return A Mono that returns the updated subscription in addition to the HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If the request body was invalid, the subscription quota is exceeded, or an
* error occurred processing the request.
* @throws IllegalArgumentException if {@link SubscriptionProperties
* SubscriptionProperties
* @throws NullPointerException if {@code subscription} is null.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<SubscriptionProperties>> updateSubscriptionWithResponse(
SubscriptionProperties subscription) {
return withContext(context -> updateSubscriptionWithResponse(subscription, context));
}
/**
* Updates a topic with the given {@link TopicProperties}. The {@link TopicProperties} must be fully populated as
* all of the properties are replaced. If a property is not set the service default value is used.
*
* The suggested flow is:
* <ol>
* <li>{@link
* <li>Update the required elements.</li>
* <li>Pass the updated description into this method.</li>
* </ol>
*
* <p>
* There are a subset of properties that can be updated. More information can be found in the links below. They are:
* <ul>
* <li>{@link TopicProperties
* <li>{@link TopicProperties
* </li>
* </ul>
*
* @param topic Information about the topic to update. You must provide all the property values that are desired
* on the updated entity. Any values not provided are set to the service default values.
*
* @return A Mono that completes with the updated topic.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If the request body was invalid, the topic quota is exceeded, or an error
* occurred processing the request.
* @throws IllegalArgumentException if {@link TopicProperties
* string.
* @throws NullPointerException if {@code topic} is null.
* @see <a href="https:
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<TopicProperties> updateTopic(TopicProperties topic) {
return updateTopicWithResponse(topic).map(Response::getValue);
}
/**
* Updates a topic with the given {@link TopicProperties}. The {@link TopicProperties} must be fully populated as
* all of the properties are replaced. If a property is not set the service default value is used.
*
* The suggested flow is:
* <ol>
* <li>{@link
* <li>Update the required elements.</li>
* <li>Pass the updated description into this method.</li>
* </ol>
*
* <p>
* There are a subset of properties that can be updated. More information can be found in the links below. They are:
* <ul>
* <li>{@link TopicProperties
* <li>{@link TopicProperties
* </li>
* </ul>
*
* @param topic Information about the topic to update. You must provide all the property values that are desired
* on the updated entity. Any values not provided are set to the service default values.
*
* @return A Mono that completes with the updated topic and its HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If the request body was invalid, the topic quota is exceeded, or an error
* occurred processing the request.
* @throws IllegalArgumentException if {@link TopicProperties
* string.
* @throws NullPointerException if {@code topic} is null.
* @see <a href="https:
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<TopicProperties>> updateTopicWithResponse(TopicProperties topic) {
return withContext(context -> updateTopicWithResponse(topic, context));
}
/**
* Creates a queue with its context.
*
* @param createQueueOptions Queue to create.
* @param context Context to pass into request.
*
* @return A Mono that completes with the created {@link QueueProperties}.
*/
Mono<Response<QueueProperties>> createQueueWithResponse(String queueName, CreateQueueOptions createQueueOptions,
Context context) {
if (queueName == null) {
return monoError(logger, new NullPointerException("'queueName' cannot be null."));
} else if (queueName.isEmpty()) {
return monoError(logger, new IllegalArgumentException("'queueName' cannot be empty."));
}
if (createQueueOptions == null) {
return monoError(logger, new NullPointerException("'createQueueOptions' cannot be null."));
} else if (context == null) {
return monoError(logger, new NullPointerException("'context' cannot be null."));
}
final QueueDescription description = EntityHelper.getQueueDescription(createQueueOptions);
final CreateQueueBodyContent content = new CreateQueueBodyContent()
.setType(CONTENT_TYPE)
.setQueueDescription(description);
final CreateQueueBody createEntity = new CreateQueueBody()
.setContent(content);
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
try {
return entityClient.putWithResponseAsync(queueName, createEntity, null, withTracing)
.onErrorMap(ServiceBusAdministrationAsyncClient::mapException)
.map(this::deserializeQueue);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Creates a rule with its context.
*
* @param ruleOptions Rule to create.
* @param context Context to pass into request.
*
* @return A Mono that completes with the created {@link RuleProperties}.
*/
Mono<Response<RuleProperties>> createRuleWithResponse(String topicName, String subscriptionName, String ruleName,
CreateRuleOptions ruleOptions, Context context) {
if (topicName == null) {
return monoError(logger, new NullPointerException("'topicName' cannot be null."));
} else if (topicName.isEmpty()) {
return monoError(logger, new IllegalArgumentException("'topicName' cannot be empty."));
}
if (subscriptionName == null) {
return monoError(logger, new NullPointerException("'subscriptionName' cannot be null."));
} else if (subscriptionName.isEmpty()) {
return monoError(logger, new IllegalArgumentException("'subscriptionName' cannot be empty."));
}
if (ruleName == null) {
return monoError(logger, new NullPointerException("'ruleName' cannot be null."));
} else if (ruleName.isEmpty()) {
return monoError(logger, new IllegalArgumentException("'ruleName' cannot be empty."));
}
if (ruleOptions == null) {
return monoError(logger, new NullPointerException("'rule' cannot be null."));
}
final RuleActionImpl action = ruleOptions.getAction() != null
? EntityHelper.toImplementation(ruleOptions.getAction())
: null;
final RuleFilterImpl filter = ruleOptions.getFilter() != null
? EntityHelper.toImplementation(ruleOptions.getFilter())
: null;
final RuleDescription rule = new RuleDescription()
.setAction(action)
.setFilter(filter)
.setName(ruleName);
final CreateRuleBodyContent content = new CreateRuleBodyContent()
.setType(CONTENT_TYPE)
.setRuleDescription(rule);
final CreateRuleBody createEntity = new CreateRuleBody().setContent(content);
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
try {
return managementClient.getRules().putWithResponseAsync(topicName, subscriptionName, ruleName, createEntity,
null, withTracing)
.onErrorMap(ServiceBusAdministrationAsyncClient::mapException)
.map(response -> deserializeRule(response));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Creates a subscription with its context.
*
* @param subscriptionOptions Subscription to create.
* @param context Context to pass into request.
*
* @return A Mono that completes with the created {@link SubscriptionProperties}.
*/
Mono<Response<SubscriptionProperties>> createSubscriptionWithResponse(String topicName, String subscriptionName,
CreateSubscriptionOptions subscriptionOptions, Context context) {
if (topicName == null) {
return monoError(logger, new NullPointerException("'topicName' cannot be null."));
} else if (topicName.isEmpty()) {
return monoError(logger, new IllegalArgumentException("'topicName' cannot be empty."));
}
if (subscriptionName == null) {
return monoError(logger, new NullPointerException("'subscriptionName' cannot be null."));
} else if (subscriptionName.isEmpty()) {
return monoError(logger, new IllegalArgumentException("'subscriptionName' cannot be empty."));
}
if (subscriptionOptions == null) {
return monoError(logger, new NullPointerException("'subscription' cannot be null."));
}
final SubscriptionDescription subscription = EntityHelper.getSubscriptionDescription(subscriptionOptions);
final CreateSubscriptionBodyContent content = new CreateSubscriptionBodyContent()
.setType(CONTENT_TYPE)
.setSubscriptionDescription(subscription);
final CreateSubscriptionBody createEntity = new CreateSubscriptionBody().setContent(content);
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
try {
return managementClient.getSubscriptions().putWithResponseAsync(topicName, subscriptionName, createEntity,
null, withTracing)
.onErrorMap(ServiceBusAdministrationAsyncClient::mapException)
.map(response -> deserializeSubscription(topicName, response));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Creates a topicOptions with its context.
*
* @param topicOptions Topic to create.
* @param context Context to pass into request.
*
* @return A Mono that completes with the created {@link TopicProperties}.
*/
Mono<Response<TopicProperties>> createTopicWithResponse(String topicName, CreateTopicOptions topicOptions,
Context context) {
if (topicName == null) {
return monoError(logger, new NullPointerException("'topicName' cannot be null."));
} else if (topicName.isEmpty()) {
return monoError(logger, new IllegalArgumentException("'topicName' cannot be empty."));
}
if (topicOptions == null) {
return monoError(logger, new NullPointerException("'topicOptions' cannot be null"));
} else if (context == null) {
return monoError(logger, new NullPointerException("'context' cannot be null."));
}
final TopicDescription topic = EntityHelper.getTopicDescription(topicOptions);
final CreateTopicBodyContent content = new CreateTopicBodyContent()
.setType(CONTENT_TYPE)
.setTopicDescription(topic);
final CreateTopicBody createEntity = new CreateTopicBody()
.setContent(content);
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
try {
return entityClient.putWithResponseAsync(topicName, createEntity, null, withTracing)
.onErrorMap(ServiceBusAdministrationAsyncClient::mapException)
.map(this::deserializeTopic);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Deletes a queue with its context.
*
* @param queueName Name of queue to delete.
* @param context Context to pass into request.
*
* @return A Mono that completes when the queue is deleted.
*/
Mono<Response<Void>> deleteQueueWithResponse(String queueName, Context context) {
if (queueName == null) {
return monoError(logger, new NullPointerException("'queueName' cannot be null"));
} else if (queueName.isEmpty()) {
return monoError(logger, new IllegalArgumentException("'queueName' cannot be an empty string."));
} else if (context == null) {
return monoError(logger, new NullPointerException("'context' cannot be null."));
}
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
try {
return entityClient.deleteWithResponseAsync(queueName, withTracing)
.onErrorMap(ServiceBusAdministrationAsyncClient::mapException)
.map(response -> {
return new SimpleResponse<>(response.getRequest(), response.getStatusCode(),
response.getHeaders(), null);
});
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Deletes a queue with its context.
*
* @param topicName Name of topic to delete.
* @param subscriptionName Name of the subscription for the rule.
* @param ruleName Name of the rule.
* @param context Context to pass into request.
*
* @return A Mono that completes with the created {@link QueueProperties}.
*/
Mono<Response<Void>> deleteRuleWithResponse(String topicName, String subscriptionName, String ruleName,
Context context) {
if (topicName == null) {
return monoError(logger, new NullPointerException("'topicName' cannot be null"));
} else if (topicName.isEmpty()) {
return monoError(logger, new IllegalArgumentException("'topicName' cannot be an empty string."));
} else if (subscriptionName == null) {
return monoError(logger, new NullPointerException("'subscriptionName' cannot be null"));
} else if (subscriptionName.isEmpty()) {
return monoError(logger, new IllegalArgumentException("'subscriptionName' cannot be an empty string."));
} else if (ruleName == null) {
return monoError(logger, new NullPointerException("'ruleName' cannot be null"));
} else if (ruleName.isEmpty()) {
return monoError(logger, new IllegalArgumentException("'ruleName' cannot be an empty string."));
} else if (context == null) {
return monoError(logger, new NullPointerException("'context' cannot be null."));
}
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
try {
return rulesClient.deleteWithResponseAsync(topicName, subscriptionName, ruleName, withTracing)
.onErrorMap(ServiceBusAdministrationAsyncClient::mapException)
.map(response -> new SimpleResponse<>(response.getRequest(), response.getStatusCode(),
response.getHeaders(), null));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Deletes a subscription with its context.
*
* @param topicName Name of topic associated with subscription to delete.
* @param subscriptionName Name of subscription to delete.
* @param context Context to pass into request.
*
* @return A Mono that completes with the created {@link SubscriptionProperties}.
*/
Mono<Response<Void>> deleteSubscriptionWithResponse(String topicName, String subscriptionName, Context context) {
if (subscriptionName == null) {
return monoError(logger, new NullPointerException("'subscriptionName' cannot be null"));
} else if (subscriptionName.isEmpty()) {
return monoError(logger, new IllegalArgumentException("'subscriptionName' cannot be an empty string."));
} else if (topicName == null) {
return monoError(logger, new NullPointerException("'topicName' cannot be null"));
} else if (topicName.isEmpty()) {
return monoError(logger, new IllegalArgumentException("'topicName' cannot be an empty string."));
} else if (context == null) {
return monoError(logger, new NullPointerException("'context' cannot be null."));
}
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
try {
return managementClient.getSubscriptions().deleteWithResponseAsync(topicName, subscriptionName,
withTracing)
.onErrorMap(ServiceBusAdministrationAsyncClient::mapException)
.map(response -> new SimpleResponse<>(response.getRequest(), response.getStatusCode(),
response.getHeaders(), null));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Deletes a topic with its context.
*
* @param topicName Name of topic to delete.
* @param context Context to pass into request.
*
* @return A Mono that completes with the created {@link TopicProperties}.
*/
Mono<Response<Void>> deleteTopicWithResponse(String topicName, Context context) {
if (topicName == null) {
return monoError(logger, new NullPointerException("'topicName' cannot be null"));
} else if (topicName.isEmpty()) {
return monoError(logger, new IllegalArgumentException("'topicName' cannot be an empty string."));
} else if (context == null) {
return monoError(logger, new NullPointerException("'context' cannot be null."));
}
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
try {
return entityClient.deleteWithResponseAsync(topicName, withTracing)
.onErrorMap(ServiceBusAdministrationAsyncClient::mapException)
.map(response -> new SimpleResponse<>(response.getRequest(), response.getStatusCode(),
response.getHeaders(), null));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Gets whether an entity exists.
*
* @param getEntityOperation Operation to get information about entity. If {@link ResourceNotFoundException} is
* thrown, then it is mapped to false.
* @param <T> Entity type.
*
* @return True if the entity exists, false otherwise.
*/
<T> Mono<Response<Boolean>> getEntityExistsWithResponse(Mono<Response<T>> getEntityOperation) {
return getEntityOperation.map(response -> {
final boolean exists = response.getValue() != null;
return (Response<Boolean>) new SimpleResponse<>(response.getRequest(), response.getStatusCode(),
response.getHeaders(), exists);
})
.onErrorResume(ResourceNotFoundException.class, exception -> {
final HttpResponse response = exception.getResponse();
final Response<Boolean> result = new SimpleResponse<>(response.getRequest(), response.getStatusCode(),
response.getHeaders(), false);
return Mono.just(result);
});
}
/**
* Gets a queue with its context.
*
* @param queueName Name of queue to fetch information for.
* @param context Context to pass into request.
*
* @return A Mono that completes with the {@link QueueProperties}.
*/
<T> Mono<Response<T>> getQueueWithResponse(String queueName, Context context,
Function<QueueProperties, T> mapper) {
if (queueName == null) {
return monoError(logger, new NullPointerException("'queueName' cannot be null"));
} else if (queueName.isEmpty()) {
return monoError(logger, new IllegalArgumentException("'queueName' cannot be empty."));
} else if (context == null) {
return monoError(logger, new NullPointerException("'context' cannot be null."));
}
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
try {
return entityClient.getWithResponseAsync(queueName, true, withTracing)
.onErrorMap(ServiceBusAdministrationAsyncClient::mapException)
.handle((response, sink) -> {
final Response<QueueProperties> deserialize = deserializeQueue(response);
if (deserialize.getValue() == null) {
final HttpResponse notFoundResponse = new EntityNotFoundHttpResponse<>(deserialize);
sink.error(new ResourceNotFoundException(String.format("Queue '%s' does not exist.", queueName),
notFoundResponse));
} else {
final T mapped = mapper.apply(deserialize.getValue());
sink.next(new SimpleResponse<>(response.getRequest(), response.getStatusCode(),
response.getHeaders(), mapped));
}
});
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<RuleProperties>> getRuleWithResponse(String topicName, String subscriptionName,
String ruleName, Context context) {
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
try {
return rulesClient.getWithResponseAsync(topicName, subscriptionName, ruleName, true, withTracing)
.onErrorMap(ServiceBusAdministrationAsyncClient::mapException)
.map(this::deserializeRule);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Gets a subscription with its context.
*
* @param topicName Name of the topic associated with the subscription.
* @param subscriptionName Name of subscription to fetch information for.
* @param context Context to pass into request.
*
* @return A Mono that completes with the {@link SubscriptionProperties}.
*/
<T> Mono<Response<T>> getSubscriptionWithResponse(String topicName, String subscriptionName, Context context,
Function<SubscriptionProperties, T> mapper) {
if (topicName == null) {
return monoError(logger, new NullPointerException("'topicName' cannot be null."));
} else if (topicName.isEmpty()) {
return monoError(logger, new IllegalArgumentException("'topicName' cannot be an empty string."));
} else if (subscriptionName == null) {
return monoError(logger, new NullPointerException("'subscriptionName' cannot be null."));
} else if (subscriptionName.isEmpty()) {
return monoError(logger, new IllegalArgumentException("'subscriptionName' cannot be an empty string."));
} else if (context == null) {
return monoError(logger, new NullPointerException("'context' cannot be null."));
}
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
try {
return managementClient.getSubscriptions().getWithResponseAsync(topicName, subscriptionName, true,
withTracing)
.onErrorMap(ServiceBusAdministrationAsyncClient::mapException)
.handle((response, sink) -> {
final Response<SubscriptionProperties> deserialize = deserializeSubscription(topicName, response);
if (deserialize.getValue() == null) {
final HttpResponse notFoundResponse = new EntityNotFoundHttpResponse<>(deserialize);
sink.error(new ResourceNotFoundException(String.format(
"Subscription '%s' in topic '%s' does not exist.", topicName, subscriptionName),
notFoundResponse));
} else {
final T mapped = mapper.apply(deserialize.getValue());
sink.next(new SimpleResponse<>(response.getRequest(), response.getStatusCode(),
response.getHeaders(), mapped));
}
});
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Gets the namespace properties with its context.
*
* @param context Context to pass into request.
*
* @return A Mono that completes with the {@link NamespaceProperties}.
*/
Mono<Response<NamespaceProperties>> getNamespacePropertiesWithResponse(Context context) {
return managementClient.getNamespaces().getWithResponseAsync(context).handle((response, sink) -> {
final NamespacePropertiesEntry entry = response.getValue();
if (entry == null || entry.getContent() == null) {
sink.error(new AzureException(
"There was no content inside namespace response. Entry: " + response));
return;
}
final NamespaceProperties namespaceProperties = entry.getContent().getNamespaceProperties();
final Response<NamespaceProperties> result = new SimpleResponse<>(response.getRequest(),
response.getStatusCode(), response.getHeaders(), namespaceProperties);
sink.next(result);
});
}
/**
* Gets a topic with its context.
*
* @param topicName Name of topic to fetch information for.
* @param context Context to pass into request.
*
* @return A Mono that completes with the {@link TopicProperties}.
*/
<T> Mono<Response<T>> getTopicWithResponse(String topicName, Context context,
Function<TopicProperties, T> mapper) {
if (topicName == null) {
return monoError(logger, new NullPointerException("'topicName' cannot be null"));
} else if (topicName.isEmpty()) {
return monoError(logger, new IllegalArgumentException("'topicName' cannot be empty."));
} else if (context == null) {
return monoError(logger, new NullPointerException("'context' cannot be null."));
}
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
try {
return entityClient.getWithResponseAsync(topicName, true, withTracing)
.onErrorMap(ServiceBusAdministrationAsyncClient::mapException)
.handle((response, sink) -> {
final Response<TopicProperties> deserialize = deserializeTopic(response);
if (deserialize.getValue() == null) {
final HttpResponse notFoundResponse = new EntityNotFoundHttpResponse<>(deserialize);
sink.error(new ResourceNotFoundException(String.format("Topic '%s' does not exist.", topicName),
notFoundResponse));
} else {
final T mapped = mapper.apply(deserialize.getValue());
sink.next(new SimpleResponse<>(response.getRequest(), response.getStatusCode(),
response.getHeaders(), mapped));
}
});
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Gets the first page of queues with context.
*
* @param context Context to pass into request.
*
* @return A Mono that completes with a page of queues.
*/
Mono<PagedResponse<QueueProperties>> listQueuesFirstPage(Context context) {
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
try {
return listQueues(0, withTracing);
} catch (RuntimeException e) {
return monoError(logger, e);
}
}
/**
* Gets the next page of queues with context.
*
* @param continuationToken Number of items to skip in feed.
* @param context Context to pass into request.
*
* @return A Mono that completes with a page of queues or empty if there are no items left.
*/
Mono<PagedResponse<QueueProperties>> listQueuesNextPage(String continuationToken, Context context) {
if (continuationToken == null || continuationToken.isEmpty()) {
return Mono.empty();
}
try {
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
final int skip = Integer.parseInt(continuationToken);
return listQueues(skip, withTracing);
} catch (RuntimeException e) {
return monoError(logger, e);
}
}
/**
* Gets the first page of rules with context.
*
* @param context Context to pass into request.
*
* @return A Mono that completes with a page of rules.
*/
Mono<PagedResponse<RuleProperties>> listRulesFirstPage(String topicName, String subscriptionName, Context context) {
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
try {
return listRules(topicName, subscriptionName, 0, withTracing);
} catch (RuntimeException e) {
return monoError(logger, e);
}
}
/**
* Gets the next page of rules with context.
*
* @param continuationToken Number of items to skip in feed.
* @param context Context to pass into request.
*
* @return A Mono that completes with a page of rules or empty if there are no items left.
*/
Mono<PagedResponse<RuleProperties>> listRulesNextPage(String topicName, String subscriptionName,
String continuationToken, Context context) {
if (continuationToken == null || continuationToken.isEmpty()) {
return Mono.empty();
}
try {
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
final int skip = Integer.parseInt(continuationToken);
return listRules(topicName, subscriptionName, skip, withTracing);
} catch (RuntimeException e) {
return monoError(logger, e);
}
}
/**
* Gets the first page of subscriptions with context.
*
* @param context Context to pass into request.
*
* @return A Mono that completes with a page of subscriptions.
*/
Mono<PagedResponse<SubscriptionProperties>> listSubscriptionsFirstPage(String topicName, Context context) {
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
try {
return listSubscriptions(topicName, 0, withTracing);
} catch (RuntimeException e) {
return monoError(logger, e);
}
}
/**
* Gets the next page of subscriptions with context.
*
* @param continuationToken Number of items to skip in feed.
* @param context Context to pass into request.
*
* @return A Mono that completes with a page of subscriptions or empty if there are no items left.
*/
Mono<PagedResponse<SubscriptionProperties>> listSubscriptionsNextPage(String topicName, String continuationToken,
Context context) {
if (continuationToken == null || continuationToken.isEmpty()) {
return Mono.empty();
}
try {
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
final int skip = Integer.parseInt(continuationToken);
return listSubscriptions(topicName, skip, withTracing);
} catch (RuntimeException e) {
return monoError(logger, e);
}
}
/**
* Gets the first page of topics with context.
*
* @param context Context to pass into request.
*
* @return A Mono that completes with a page of topics.
*/
Mono<PagedResponse<TopicProperties>> listTopicsFirstPage(Context context) {
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
try {
return listTopics(0, withTracing);
} catch (RuntimeException e) {
return monoError(logger, e);
}
}
/**
* Gets the next page of topics with context.
*
* @param continuationToken Number of items to skip in feed.
* @param context Context to pass into request.
*
* @return A Mono that completes with a page of topics or empty if there are no items left.
*/
Mono<PagedResponse<TopicProperties>> listTopicsNextPage(String continuationToken, Context context) {
if (continuationToken == null || continuationToken.isEmpty()) {
return Mono.empty();
}
try {
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
final int skip = Integer.parseInt(continuationToken);
return listTopics(skip, withTracing);
} catch (RuntimeException e) {
return monoError(logger, e);
}
}
/**
* Updates a queue with its context.
*
* @param queue Information about the queue to update. You must provide all the property values that are desired
* on the updated entity. Any values not provided are set to the service default values.
* @param context Context to pass into request.
*
* @return A Mono that completes with the updated {@link QueueProperties}.
*/
Mono<Response<QueueProperties>> updateQueueWithResponse(QueueProperties queue, Context context) {
if (queue == null) {
return monoError(logger, new NullPointerException("'queue' cannot be null"));
} else if (context == null) {
return monoError(logger, new NullPointerException("'context' cannot be null."));
}
final QueueDescription queueDescription = EntityHelper.toImplementation(queue);
final CreateQueueBodyContent content = new CreateQueueBodyContent()
.setType(CONTENT_TYPE)
.setQueueDescription(queueDescription);
final CreateQueueBody createEntity = new CreateQueueBody()
.setContent(content);
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
try {
return entityClient.putWithResponseAsync(queue.getName(), createEntity, "*", withTracing)
.onErrorMap(ServiceBusAdministrationAsyncClient::mapException)
.map(response -> deserializeQueue(response));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Updates a rule with its context.
*
* @param rule Information about the rule to update. You must provide all the property values that are desired
* on the updated entity. Any values not provided are set to the service default values.
* @param context Context to pass into request.
*
* @return A Mono that completes with the updated {@link RuleProperties}.
*/
Mono<Response<RuleProperties>> updateRuleWithResponse(String topicName, String subscriptionName,
RuleProperties rule, Context context) {
if (rule == null) {
return monoError(logger, new NullPointerException("'rule' cannot be null"));
} else if (context == null) {
return monoError(logger, new NullPointerException("'context' cannot be null."));
}
final RuleDescription implementation = EntityHelper.toImplementation(rule);
final CreateRuleBodyContent content = new CreateRuleBodyContent()
.setType(CONTENT_TYPE)
.setRuleDescription(implementation);
final CreateRuleBody ruleBody = new CreateRuleBody()
.setContent(content);
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
try {
return managementClient.getRules().putWithResponseAsync(topicName, subscriptionName, rule.getName(),
ruleBody, "*", withTracing)
.onErrorMap(ServiceBusAdministrationAsyncClient::mapException)
.map(response -> deserializeRule(response));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Updates a subscription with its context.
*
* @param subscription Information about the subscription to update. You must provide all the property values
* that are desired on the updated entity. Any values not provided are set to the service default values.
* @param context Context to pass into request.
*
* @return A Mono that completes with the updated {@link SubscriptionProperties}.
*/
Mono<Response<SubscriptionProperties>> updateSubscriptionWithResponse(SubscriptionProperties subscription,
Context context) {
if (subscription == null) {
return monoError(logger, new NullPointerException("'subscription' cannot be null"));
} else if (context == null) {
return monoError(logger, new NullPointerException("'context' cannot be null."));
}
final String topicName = subscription.getTopicName();
final String subscriptionName = subscription.getSubscriptionName();
final SubscriptionDescription implementation = EntityHelper.toImplementation(subscription);
final CreateSubscriptionBodyContent content = new CreateSubscriptionBodyContent()
.setType(CONTENT_TYPE)
.setSubscriptionDescription(implementation);
final CreateSubscriptionBody createEntity = new CreateSubscriptionBody()
.setContent(content);
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
try {
return managementClient.getSubscriptions().putWithResponseAsync(topicName, subscriptionName, createEntity,
"*", withTracing)
.onErrorMap(ServiceBusAdministrationAsyncClient::mapException)
.map(response -> deserializeSubscription(topicName, response));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Updates a topic with its context.
*
* @param topic Information about the topic to update. You must provide all the property values that are desired
* on the updated entity. Any values not provided are set to the service default values.
* @param context Context to pass into request.
*
* @return A Mono that completes with the updated {@link TopicProperties}.
*/
Mono<Response<TopicProperties>> updateTopicWithResponse(TopicProperties topic, Context context) {
if (topic == null) {
return monoError(logger, new NullPointerException("'topic' cannot be null"));
} else if (context == null) {
return monoError(logger, new NullPointerException("'context' cannot be null."));
}
final TopicDescription implementation = EntityHelper.toImplementation(topic);
final CreateTopicBodyContent content = new CreateTopicBodyContent()
.setType(CONTENT_TYPE)
.setTopicDescription(implementation);
final CreateTopicBody createEntity = new CreateTopicBody()
.setContent(content);
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
try {
return entityClient.putWithResponseAsync(topic.getName(), createEntity, "*", withTracing)
.onErrorMap(ServiceBusAdministrationAsyncClient::mapException)
.map(response -> deserializeTopic(response));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
private <T> T deserialize(Object object, Class<T> clazz) {
if (object == null) {
return null;
}
final String contents = String.valueOf(object);
if (contents.isEmpty()) {
return null;
}
try {
return serializer.deserialize(contents, clazz);
} catch (IOException e) {
throw logger.logExceptionAsError(new RuntimeException(String.format(
"Exception while deserializing. Body: [%s]. Class: %s", contents, clazz), e));
}
}
/**
* Given an HTTP response, will deserialize it into a strongly typed Response object.
*
* @param response HTTP response to deserialize response body from.
* @param clazz Class to deserialize response type into.
* @param <T> Class type to deserialize response into.
*
* @return A Response with a strongly typed response value.
*/
private <T> Response<T> deserialize(Response<Object> response, Class<T> clazz) {
final T deserialize = deserialize(response.getValue(), clazz);
return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(),
deserialize);
}
/**
* Converts a Response into its corresponding {@link QueueDescriptionEntry} then mapped into {@link
* QueueProperties}.
*
* @param response HTTP Response to deserialize.
*
* @return The corresponding HTTP response with convenience properties set.
*/
/**
* Converts a Response into its corresponding {@link RuleDescriptionEntry} then mapped into {@link RuleProperties}.
*
* @param response HTTP Response to deserialize.
*
* @return The corresponding HTTP response with convenience properties set.
*/
private Response<RuleProperties> deserializeRule(Response<Object> response) {
final RuleDescriptionEntry entry = deserialize(response.getValue(), RuleDescriptionEntry.class);
if (entry == null) {
return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null);
} else if (entry.getContent() == null) {
logger.info("entry.getContent() is null. The entity may not exist. {}", entry);
return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null);
}
final RuleDescription description = entry.getContent().getRuleDescription();
final RuleProperties result = EntityHelper.toModel(description);
return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), result);
}
/**
* Converts a Response into its corresponding {@link SubscriptionDescriptionEntry} then mapped into {@link
* SubscriptionProperties}.
*
* @param response HTTP Response to deserialize.
*
* @return The corresponding HTTP response with convenience properties set.
*/
private Response<SubscriptionProperties> deserializeSubscription(String topicName, Response<Object> response) {
final SubscriptionDescriptionEntry entry = deserialize(response.getValue(), SubscriptionDescriptionEntry.class);
if (entry == null) {
return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null);
} else if (entry.getContent() == null) {
logger.warning("entry.getContent() is null. There should have been content returned. Entry: {}", entry);
return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null);
}
final SubscriptionProperties subscription = EntityHelper.toModel(
entry.getContent().getSubscriptionDescription());
final String subscriptionName = getTitleValue(entry.getTitle());
EntityHelper.setSubscriptionName(subscription, subscriptionName);
EntityHelper.setTopicName(subscription, topicName);
return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(),
subscription);
}
/**
* Converts a Response into its corresponding {@link TopicDescriptionEntry} then mapped into {@link
* QueueProperties}.
*
* @param response HTTP Response to deserialize.
*
* @return The corresponding HTTP response with convenience properties set.
*/
private Response<TopicProperties> deserializeTopic(Response<Object> response) {
final TopicDescriptionEntry entry = deserialize(response.getValue(), TopicDescriptionEntry.class);
if (entry == null) {
return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null);
} else if (entry.getContent() == null) {
logger.warning("entry.getContent() is null. There should have been content returned. Entry: {}", entry);
return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null);
} else if (entry.getContent().getTopicDescription() == null) {
final QueueDescriptionEntry entryQueue = deserialize(response.getValue(), QueueDescriptionEntry.class);
if (entryQueue != null && entryQueue.getContent() != null && entryQueue.getContent().getQueueDescription() != null) {
logger.warning("'{}' is not a topic, it is a queue.", entryQueue.getTitle());
return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null);
}
}
final TopicProperties result = EntityHelper.toModel(entry.getContent().getTopicDescription());
final String topicName = getTitleValue(entry.getTitle());
EntityHelper.setTopicName(result, topicName);
return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), result);
}
/**
* Creates a {@link FeedPage} given the elements and a set of response links to get the next link from.
*
* @param entities Entities in the feed.
* @param responseLinks Links returned from the feed.
* @param <TResult> Type of Service Bus entities in page.
*
* @return A {@link FeedPage} indicating whether this can be continued or not.
* @throws MalformedURLException if the "next" page link does not contain a well-formed URL.
*/
private <TResult, TFeed> FeedPage<TResult> extractPage(Response<TFeed> response, List<TResult> entities,
List<ResponseLink> responseLinks)
throws MalformedURLException, UnsupportedEncodingException {
final Optional<ResponseLink> nextLink = responseLinks.stream()
.filter(link -> link.getRel().equalsIgnoreCase("next"))
.findFirst();
if (!nextLink.isPresent()) {
return new FeedPage<>(response.getStatusCode(), response.getHeaders(), response.getRequest(), entities);
}
final URL url = new URL(nextLink.get().getHref());
final String decode = URLDecoder.decode(url.getQuery(), StandardCharsets.UTF_8.name());
final Optional<Integer> skipParameter = Arrays.stream(decode.split("&|&"))
.map(part -> part.split("=", 2))
.filter(parts -> parts[0].equalsIgnoreCase("$skip") && parts.length == 2)
.map(parts -> Integer.valueOf(parts[1]))
.findFirst();
if (skipParameter.isPresent()) {
return new FeedPage<>(response.getStatusCode(), response.getHeaders(), response.getRequest(), entities,
skipParameter.get());
} else {
logger.warning("There should have been a skip parameter for the next page.");
return new FeedPage<>(response.getStatusCode(), response.getHeaders(), response.getRequest(), entities);
}
}
/**
* Helper method that invokes the service method, extracts the data and translates it to a PagedResponse.
*
* @param skip Number of elements to skip.
* @param context Context for the query.
*
* @return A Mono that completes with a paged response of queues.
*/
private Mono<PagedResponse<QueueProperties>> listQueues(int skip, Context context) {
return managementClient.listEntitiesWithResponseAsync(QUEUES_ENTITY_TYPE, skip, NUMBER_OF_ELEMENTS, context)
.onErrorMap(ServiceBusAdministrationAsyncClient::mapException)
.flatMap(response -> {
final Response<QueueDescriptionFeed> feedResponse = deserialize(response, QueueDescriptionFeed.class);
final QueueDescriptionFeed feed = feedResponse.getValue();
if (feed == null) {
logger.warning("Could not deserialize QueueDescriptionFeed. skip {}, top: {}", skip,
NUMBER_OF_ELEMENTS);
return Mono.empty();
}
final List<QueueProperties> entities = feed.getEntry().stream()
.filter(e -> e.getContent() != null && e.getContent().getQueueDescription() != null)
.map(e -> {
final String queueName = getTitleValue(e.getTitle());
final QueueProperties queueProperties = EntityHelper.toModel(
e.getContent().getQueueDescription());
EntityHelper.setQueueName(queueProperties, queueName);
return queueProperties;
})
.collect(Collectors.toList());
try {
return Mono.just(extractPage(feedResponse, entities, feed.getLink()));
} catch (MalformedURLException | UnsupportedEncodingException error) {
return Mono.error(new RuntimeException("Could not parse response into FeedPage<QueueDescription>",
error));
}
});
}
/**
* Helper method that invokes the service method, extracts the data and translates it to a PagedResponse.
*
* @param skip Number of elements to skip.
* @param context Context for the query.
*
* @return A Mono that completes with a paged response of rules.
*/
private Mono<PagedResponse<RuleProperties>> listRules(String topicName, String subscriptionName, int skip,
Context context) {
return managementClient.listRulesWithResponseAsync(topicName, subscriptionName, skip, NUMBER_OF_ELEMENTS,
context)
.onErrorMap(ServiceBusAdministrationAsyncClient::mapException)
.flatMap(response -> {
final Response<RuleDescriptionFeed> feedResponse = deserialize(response,
RuleDescriptionFeed.class);
final RuleDescriptionFeed feed = feedResponse.getValue();
if (feed == null) {
logger.warning("Could not deserialize RuleDescriptionFeed. skip {}, top: {}", skip,
NUMBER_OF_ELEMENTS);
return Mono.empty();
}
final List<RuleProperties> entities = feed.getEntry().stream()
.filter(e -> e.getContent() != null && e.getContent().getRuleDescription() != null)
.map(e -> {
return EntityHelper.toModel(e.getContent().getRuleDescription());
})
.collect(Collectors.toList());
try {
return Mono.just(extractPage(feedResponse, entities, feed.getLink()));
} catch (MalformedURLException | UnsupportedEncodingException error) {
return Mono.error(new RuntimeException(
"Could not parse response into FeedPage<RuleDescription>", error));
}
});
}
/**
* Helper method that invokes the service method, extracts the data and translates it to a PagedResponse.
*
* @param skip Number of elements to skip.
* @param context Context for the query.
*
* @return A Mono that completes with a paged response of subscriptions.
*/
private Mono<PagedResponse<SubscriptionProperties>> listSubscriptions(String topicName, int skip,
Context context) {
return managementClient.listSubscriptionsWithResponseAsync(topicName, skip, NUMBER_OF_ELEMENTS, context)
.onErrorMap(ServiceBusAdministrationAsyncClient::mapException)
.flatMap(response -> {
final Response<SubscriptionDescriptionFeed> feedResponse = deserialize(response,
SubscriptionDescriptionFeed.class);
final SubscriptionDescriptionFeed feed = feedResponse.getValue();
if (feed == null) {
logger.warning("Could not deserialize SubscriptionDescriptionFeed. skip {}, top: {}", skip,
NUMBER_OF_ELEMENTS);
return Mono.empty();
}
final List<SubscriptionProperties> entities = feed.getEntry().stream()
.filter(e -> e.getContent() != null && e.getContent().getSubscriptionDescription() != null)
.map(e -> {
final String subscriptionName = getTitleValue(e.getTitle());
final SubscriptionProperties description = EntityHelper.toModel(
e.getContent().getSubscriptionDescription());
EntityHelper.setTopicName(description, topicName);
EntityHelper.setSubscriptionName(description, subscriptionName);
return description;
})
.collect(Collectors.toList());
try {
return Mono.just(extractPage(feedResponse, entities, feed.getLink()));
} catch (MalformedURLException | UnsupportedEncodingException error) {
return Mono.error(new RuntimeException(
"Could not parse response into FeedPage<SubscriptionDescription>", error));
}
});
}
/**
* Helper method that invokes the service method, extracts the data and translates it to a PagedResponse.
*
* @param skip Number of elements to skip.
* @param context Context for the query.
*
* @return A Mono that completes with a paged response of topics.
*/
private Mono<PagedResponse<TopicProperties>> listTopics(int skip, Context context) {
return managementClient.listEntitiesWithResponseAsync(TOPICS_ENTITY_TYPE, skip, NUMBER_OF_ELEMENTS, context)
.onErrorMap(ServiceBusAdministrationAsyncClient::mapException)
.flatMap(response -> {
final Response<TopicDescriptionFeed> feedResponse = deserialize(response, TopicDescriptionFeed.class);
final TopicDescriptionFeed feed = feedResponse.getValue();
if (feed == null) {
logger.warning("Could not deserialize TopicDescriptionFeed. skip {}, top: {}", skip,
NUMBER_OF_ELEMENTS);
return Mono.empty();
}
final List<TopicProperties> entities = feed.getEntry().stream()
.filter(e -> e.getContent() != null && e.getContent().getTopicDescription() != null)
.map(e -> {
final String topicName = getTitleValue(e.getTitle());
final TopicProperties topicProperties = EntityHelper.toModel(
e.getContent().getTopicDescription());
EntityHelper.setTopicName(topicProperties, topicName);
return topicProperties;
})
.collect(Collectors.toList());
try {
return Mono.just(extractPage(feedResponse, entities, feed.getLink()));
} catch (MalformedURLException | UnsupportedEncodingException error) {
return Mono.error(new RuntimeException("Could not parse response into FeedPage<TopicDescription>",
error));
}
});
}
/**
* Given an XML title element, returns the XML text inside. Jackson deserializes Objects as LinkedHashMaps. XML text
* is represented as an entry with an empty string as the key.
*
* For example, the text returned from this {@code <title text="text/xml">QueueName</title>} is "QueueName".
*
* @param responseTitle XML title element.
*
* @return The XML text inside the title. {@code null} is returned if there is no value.
*/
@SuppressWarnings("unchecked")
private String getTitleValue(Object responseTitle) {
if (!(responseTitle instanceof Map)) {
return null;
}
final Map<String, String> map;
try {
map = (Map<String, String>) responseTitle;
return map.get("");
} catch (ClassCastException error) {
logger.warning("Unable to cast to Map<String,String>. Title: {}", responseTitle, error);
return null;
}
}
/**
* Maps an exception from the ATOM APIs to its associated {@link HttpResponseException}.
*
* @param exception Exception from the ATOM API.
*
* @return The corresponding {@link HttpResponseException} or {@code throwable} if it is not an instance of {@link
* ServiceBusManagementErrorException}.
*/
private static Throwable mapException(Throwable exception) {
if (!(exception instanceof ServiceBusManagementErrorException)) {
return exception;
}
final ServiceBusManagementErrorException managementError = ((ServiceBusManagementErrorException) exception);
final ServiceBusManagementError error = managementError.getValue();
final HttpResponse errorHttpResponse = managementError.getResponse();
final int statusCode = error != null && error.getCode() != null
? error.getCode()
: errorHttpResponse.getStatusCode();
final String errorDetail = error != null && error.getDetail() != null
? error.getDetail()
: managementError.getMessage();
switch (statusCode) {
case 401:
return new ClientAuthenticationException(errorDetail, managementError.getResponse(), exception);
case 404:
return new ResourceNotFoundException(errorDetail, managementError.getResponse(), exception);
case 409:
return new ResourceExistsException(errorDetail, managementError.getResponse(), exception);
case 412:
return new ResourceModifiedException(errorDetail, managementError.getResponse(), exception);
default:
return new HttpResponseException(errorDetail, managementError.getResponse(), exception);
}
}
/**
* A page of Service Bus entities.
*
* @param <T> The entity description from Service Bus.
*/
private static final class FeedPage<T> implements PagedResponse<T> {
private final int statusCode;
private final HttpHeaders header;
private final HttpRequest request;
private final IterableStream<T> entries;
private final String continuationToken;
/**
* Creates a page that does not have any more pages.
*
* @param entries Items in the page.
*/
private FeedPage(int statusCode, HttpHeaders header, HttpRequest request, List<T> entries) {
this.statusCode = statusCode;
this.header = header;
this.request = request;
this.entries = new IterableStream<>(entries);
this.continuationToken = null;
}
/**
* Creates an instance that has additional pages to fetch.
*
* @param entries Items in the page.
* @param skip Number of elements to "skip".
*/
private FeedPage(int statusCode, HttpHeaders header, HttpRequest request, List<T> entries, int skip) {
this.statusCode = statusCode;
this.header = header;
this.request = request;
this.entries = new IterableStream<>(entries);
this.continuationToken = String.valueOf(skip);
}
@Override
public IterableStream<T> getElements() {
return entries;
}
@Override
public String getContinuationToken() {
return continuationToken;
}
@Override
public int getStatusCode() {
return statusCode;
}
@Override
public HttpHeaders getHeaders() {
return header;
}
@Override
public HttpRequest getRequest() {
return request;
}
@Override
public void close() {
}
}
private static final class EntityNotFoundHttpResponse<T> extends HttpResponse {
private final int statusCode;
private final HttpHeaders headers;
private EntityNotFoundHttpResponse(Response<T> response) {
super(response.getRequest());
this.headers = response.getHeaders();
this.statusCode = response.getStatusCode();
}
@Override
public int getStatusCode() {
return statusCode;
}
@Override
public String getHeaderValue(String name) {
return headers.getValue(name);
}
@Override
public HttpHeaders getHeaders() {
return headers;
}
@Override
public Flux<ByteBuffer> getBody() {
return Flux.empty();
}
@Override
public Mono<byte[]> getBodyAsByteArray() {
return Mono.empty();
}
@Override
public Mono<String> getBodyAsString() {
return Mono.empty();
}
@Override
public Mono<String> getBodyAsString(Charset charset) {
return Mono.empty();
}
}
} |
The issue [19512](https://github.com/Azure/azure-sdk-for-java/issues/19512) occurs when a queue exists but the name is used for a topic **and vice versa**. Vice versa means that it occurs also when a topic exists but the name is used for a queue. Therefore I made the same fix for the queue deserialization ([here](https://github.com/Azure/azure-sdk-for-java/pull/19513/files/457d911af6e128fb7d963151f99d2d748e79e167#diff-8b1de19ce3e7548d62bea61e56b8d6dd9e11eeb8951f3afc1b5b09b9cf798e5cR2232)) and topic deserialization ([here](https://github.com/Azure/azure-sdk-for-java/pull/19513/files/457d911af6e128fb7d963151f99d2d748e79e167#diff-8b1de19ce3e7548d62bea61e56b8d6dd9e11eeb8951f3afc1b5b09b9cf798e5cR2317)). | private Response<QueueProperties> deserializeQueue(Response<Object> response) {
final QueueDescriptionEntry entry = deserialize(response.getValue(), QueueDescriptionEntry.class);
if (entry == null) {
return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null);
} else if (entry.getContent() == null) {
logger.info("entry.getContent() is null. The entity may not exist. {}", entry);
return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null);
} else if (entry.getContent().getQueueDescription() == null) {
final TopicDescriptionEntry entryTopic = deserialize(response.getValue(), TopicDescriptionEntry.class);
if (entryTopic != null && entryTopic.getContent() != null && entryTopic.getContent().getTopicDescription() != null) {
throw logger.logExceptionAsError(
new RuntimeException(String.format("'[%s]' is not a queue, it is a topic.", entryTopic.getTitle())));
}
}
final QueueProperties result = EntityHelper.toModel(entry.getContent().getQueueDescription());
final String queueName = getTitleValue(entry.getTitle());
EntityHelper.setQueueName(result, queueName);
return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), result);
} | } else if (entry.getContent().getQueueDescription() == null) { | private Response<QueueProperties> deserializeQueue(Response<Object> response) {
final QueueDescriptionEntry entry = deserialize(response.getValue(), QueueDescriptionEntry.class);
if (entry == null) {
return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null);
} else if (entry.getContent() == null) {
logger.info("entry.getContent() is null. The entity may not exist. {}", entry);
return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null);
} else if (entry.getContent().getQueueDescription() == null) {
final TopicDescriptionEntry entryTopic = deserialize(response.getValue(), TopicDescriptionEntry.class);
if (entryTopic != null && entryTopic.getContent() != null && entryTopic.getContent().getTopicDescription() != null) {
logger.warning("'{}' is not a queue, it is a topic.", entryTopic.getTitle());
return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null);
}
}
final QueueProperties result = EntityHelper.toModel(entry.getContent().getQueueDescription());
final String queueName = getTitleValue(entry.getTitle());
EntityHelper.setQueueName(result, queueName);
return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), result);
} | class ServiceBusAdministrationAsyncClient {
private static final String SERVICE_BUS_TRACING_NAMESPACE_VALUE = "Microsoft.ServiceBus";
private static final String CONTENT_TYPE = "application/xml";
private static final String QUEUES_ENTITY_TYPE = "queues";
private static final String TOPICS_ENTITY_TYPE = "topics";
private static final int NUMBER_OF_ELEMENTS = 100;
private final ServiceBusManagementClientImpl managementClient;
private final EntitiesImpl entityClient;
private final ClientLogger logger = new ClientLogger(ServiceBusAdministrationAsyncClient.class);
private final ServiceBusManagementSerializer serializer;
private final RulesImpl rulesClient;
/**
* Creates a new instance with the given management client and serializer.
*
* @param managementClient Client to make management calls.
* @param serializer Serializer to deserialize ATOM XML responses.
*/
ServiceBusAdministrationAsyncClient(ServiceBusManagementClientImpl managementClient,
ServiceBusManagementSerializer serializer) {
this.serializer = Objects.requireNonNull(serializer, "'serializer' cannot be null.");
this.managementClient = Objects.requireNonNull(managementClient, "'managementClient' cannot be null.");
this.entityClient = managementClient.getEntities();
this.rulesClient = managementClient.getRules();
}
/**
* Creates a queue with the given name.
*
* @param queueName Name of the queue to create.
*
* @return A Mono that completes with information about the created queue.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If the request body was invalid, the queue quota is exceeded, or an error
* occurred processing the request.
* @throws NullPointerException if {@code queueName} is null.
* @throws IllegalArgumentException if {@code queueName} is an empty string.
* @throws ResourceExistsException if a queue exists with the same {@code queueName}.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<QueueProperties> createQueue(String queueName) {
try {
return createQueue(queueName, new CreateQueueOptions());
} catch (RuntimeException e) {
return monoError(logger, e);
}
}
/**
* Creates a queue with the {@link CreateQueueOptions} and given queue name.
*
* @param queueName Name of the queue to create.
* @param queueOptions Options about the queue to create.
*
* @return A Mono that completes with information about the created queue.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If the request body was invalid, the queue quota is exceeded, or an error
* occurred processing the request.
* @throws IllegalArgumentException if {@code queueName} is an empty string.
* @throws NullPointerException if {@code queueName} or {@code queueOptions} is null.
* @throws ResourceExistsException if a queue exists with the same {@link QueueProperties
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<QueueProperties> createQueue(String queueName, CreateQueueOptions queueOptions) {
return createQueueWithResponse(queueName, queueOptions).map(Response::getValue);
}
/**
* Creates a queue and returns the created queue in addition to the HTTP response.
*
* @param queueName Name of the queue to create.
* @param queueOptions Options about the queue to create.
*
* @return A Mono that returns the created queue in addition to the HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If the request body was invalid, the queue quota is exceeded, or an error
* occurred processing the request.
* @throws IllegalArgumentException if {@code queueName} is an empty string.
* @throws NullPointerException if {@code queueName} or {@code queueOptions} is null.
* @throws ResourceExistsException if a queue exists with the same {@link QueueProperties
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<QueueProperties>> createQueueWithResponse(String queueName, CreateQueueOptions queueOptions) {
return withContext(context -> createQueueWithResponse(queueName, queueOptions, context));
}
/**
* Creates a rule under the given topic and subscription
*
* @param topicName Name of the topic associated with rule.
* @param subscriptionName Name of the subscription associated with the rule.
* @param ruleName Name of the rule.
*
* @return A Mono that completes with information about the created rule.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If the request body was invalid, the quota is exceeded, or an error occurred
* processing the request.
* @throws IllegalArgumentException if {@code topicName} or {@code ruleName} are are empty strings.
* @throws NullPointerException if {@code topicName} or {@code ruleName} are are null.
* @throws ResourceExistsException if a rule exists with the same topic, subscription, and rule name.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<RuleProperties> createRule(String topicName, String subscriptionName, String ruleName) {
try {
return createRule(topicName, subscriptionName, ruleName, new CreateRuleOptions());
} catch (RuntimeException e) {
return monoError(logger, e);
}
}
/**
* Creates a rule with the {@link CreateRuleOptions}.
*
* @param topicName Name of the topic associated with rule.
* @param subscriptionName Name of the subscription associated with the rule.
* @param ruleName Name of the rule.
* @param ruleOptions Information about the rule to create.
*
* @return A Mono that completes with information about the created rule.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If the request body was invalid, the quota is exceeded, or an error occurred
* processing the request.
* @throws IllegalArgumentException if {@code topicName} or {@code ruleName} are are empty strings.
* @throws NullPointerException if {@code topicName}, {@code ruleName}, or {@code ruleOptions}
* are are null.
* @throws ResourceExistsException if a rule exists with the same topic and rule name.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<RuleProperties> createRule(String topicName, String subscriptionName, String ruleName,
CreateRuleOptions ruleOptions) {
return createRuleWithResponse(topicName, subscriptionName, ruleName, ruleOptions)
.map(Response::getValue);
}
/**
* Creates a rule and returns the created rule in addition to the HTTP response.
*
* @param topicName Name of the topic associated with rule.
* @param subscriptionName Name of the subscription associated with the rule.
* @param ruleName Name of the rule.
* @param ruleOptions Information about the rule to create.
*
* @return A Mono that returns the created rule in addition to the HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If the request body was invalid, the quota is exceeded, or an error occurred
* processing the request.
* @throws IllegalArgumentException if {@code topicName} or {@code ruleName} are are empty strings.
* @throws NullPointerException if {@code topicName}, {@code ruleName}, or {@code ruleOptions}
* are are null.
* @throws ResourceExistsException if a rule exists with the same topic and rule name.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<RuleProperties>> createRuleWithResponse(String topicName, String subscriptionName,
String ruleName, CreateRuleOptions ruleOptions) {
return withContext(context -> createRuleWithResponse(topicName, subscriptionName, ruleName, ruleOptions,
context));
}
/**
* Creates a subscription with the given topic and subscription names.
*
* @param topicName Name of the topic associated with subscription.
* @param subscriptionName Name of the subscription.
*
* @return A Mono that completes with information about the created subscription.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If the request body was invalid, the quota is exceeded, or an error occurred
* processing the request.
* @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} are are empty strings.
* @throws NullPointerException if {@code topicName} or {@code subscriptionName} are are null.
* @throws ResourceExistsException if a subscription exists with the same topic and subscription name.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<SubscriptionProperties> createSubscription(String topicName, String subscriptionName) {
try {
return createSubscription(topicName, subscriptionName, new CreateSubscriptionOptions());
} catch (RuntimeException e) {
return monoError(logger, e);
}
}
/**
* Creates a subscription with the {@link CreateSubscriptionOptions}.
*
* @param topicName Name of the topic associated with subscription.
* @param subscriptionName Name of the subscription.
* @param subscriptionOptions Information about the subscription to create.
*
* @return A Mono that completes with information about the created subscription.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If the request body was invalid, the quota is exceeded, or an error occurred
* processing the request.
* @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} are are empty strings.
* @throws NullPointerException if {@code topicName}, {@code subscriptionName}, or {@code subscriptionOptions}
* are are null.
* @throws ResourceExistsException if a subscription exists with the same topic and subscription name.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<SubscriptionProperties> createSubscription(String topicName, String subscriptionName,
CreateSubscriptionOptions subscriptionOptions) {
return createSubscriptionWithResponse(topicName, subscriptionName, subscriptionOptions)
.map(Response::getValue);
}
/**
* Creates a subscription and returns the created subscription in addition to the HTTP response.
*
* @param topicName Name of the topic associated with subscription.
* @param subscriptionName Name of the subscription.
* @param subscriptionOptions Information about the subscription to create.
*
* @return A Mono that returns the created subscription in addition to the HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If the request body was invalid, the quota is exceeded, or an error occurred
* processing the request.
* @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} are are empty strings.
* @throws NullPointerException if {@code topicName}, {@code subscriptionName}, or {@code subscriptionOptions}
* are are null.
* @throws ResourceExistsException if a subscription exists with the same topic and subscription name.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<SubscriptionProperties>> createSubscriptionWithResponse(String topicName,
String subscriptionName, CreateSubscriptionOptions subscriptionOptions) {
return withContext(context -> createSubscriptionWithResponse(topicName, subscriptionName, subscriptionOptions,
context));
}
/**
* Creates a topic with the given name.
*
* @param topicName Name of the topic to create.
*
* @return A Mono that completes with information about the created topic.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If the request body was invalid, the topic quota is exceeded, or an error
* occurred processing the request.
* @throws NullPointerException if {@code topicName} is null.
* @throws IllegalArgumentException if {@code topicName} is an empty string.
* @throws ResourceExistsException if a topic exists with the same {@code topicName}.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<TopicProperties> createTopic(String topicName) {
try {
return createTopic(topicName, new CreateTopicOptions());
} catch (RuntimeException e) {
return monoError(logger, e);
}
}
/**
* Creates a topic with the {@link CreateTopicOptions}.
*
* @param topicName Name of the topic to create.
* @param topicOptions The options used to create the topic.
*
* @return A Mono that completes with information about the created topic.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If the request body was invalid, the topic quota is exceeded, or an error
* occurred processing the request.
* @throws IllegalArgumentException if {@code topicName} is an empty string.
* @throws NullPointerException if {@code topicName} or {@code topicOptions} is null.
* @throws ResourceExistsException if a topic exists with the same {@code topicName}.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<TopicProperties> createTopic(String topicName, CreateTopicOptions topicOptions) {
return createTopicWithResponse(topicName, topicOptions).map(Response::getValue);
}
/**
* Creates a topic and returns the created topic in addition to the HTTP response.
*
* @param topicName Name of the topic to create.
* @param topicOptions The options used to create the topic.
*
* @return A Mono that returns the created topic in addition to the HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If the request body was invalid, the topic quota is exceeded, or an error
* occurred processing the request.
* @throws IllegalArgumentException if {@link TopicProperties
* string.
* @throws NullPointerException if {@code topicName} or {@code topicOptions} is null.
* @throws ResourceExistsException if a topic exists with the same {@code topicName}.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<TopicProperties>> createTopicWithResponse(String topicName, CreateTopicOptions topicOptions) {
return withContext(context -> createTopicWithResponse(topicName, topicOptions, context));
}
/**
* Deletes a queue the matching {@code queueName}.
*
* @param queueName Name of queue to delete.
*
* @return A Mono that completes when the queue is deleted.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws NullPointerException if {@code queueName} is null.
* @throws IllegalArgumentException if {@code queueName} is an empty string.
* @throws ResourceNotFoundException if the {@code queueName} does not exist.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Void> deleteQueue(String queueName) {
return deleteQueueWithResponse(queueName).then();
}
/**
* Deletes a queue the matching {@code queueName} and returns the HTTP response.
*
* @param queueName Name of queue to delete.
*
* @return A Mono that completes when the queue is deleted and returns the HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws NullPointerException if {@code queueName} is null.
* @throws IllegalArgumentException if {@code queueName} is an empty string.
* @throws ResourceNotFoundException if the {@code queueName} does not exist.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Void>> deleteQueueWithResponse(String queueName) {
return withContext(context -> deleteQueueWithResponse(queueName, context));
}
/**
* Deletes a rule the matching {@code ruleName}.
*
* @param topicName Name of topic associated with rule to delete.
* @param subscriptionName Name of the subscription associated with the rule to delete.
* @param ruleName Name of rule to delete.
*
* @return A Mono that completes when the rule is deleted.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code topicName} or {@code ruleName} is an empty string.
* @throws NullPointerException if {@code topicName} or {@code ruleName} is null.
* @throws ResourceNotFoundException if the {@code ruleName} does not exist.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Void> deleteRule(String topicName, String subscriptionName, String ruleName) {
return deleteRuleWithResponse(topicName, subscriptionName, ruleName).then();
}
/**
* Deletes a rule the matching {@code ruleName} and returns the HTTP response.
*
* @param topicName Name of topic associated with rule to delete.
* @param subscriptionName Name of the subscription associated with the rule to delete.
* @param ruleName Name of rule to delete.
*
* @return A Mono that completes when the rule is deleted and returns the HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code topicName}, {@code subscriptionName}, or {@code ruleName} is an
* empty string.
* @throws NullPointerException if {@code topicName}, {@code subscriptionName}, or {@code ruleName} is null.
* @throws ResourceNotFoundException if the {@code ruleName} does not exist.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Void>> deleteRuleWithResponse(String topicName, String subscriptionName,
String ruleName) {
return withContext(context -> deleteRuleWithResponse(topicName, subscriptionName, ruleName, context));
}
/**
* Deletes a subscription the matching {@code subscriptionName}.
*
* @param topicName Name of topic associated with subscription to delete.
* @param subscriptionName Name of subscription to delete.
*
* @return A Mono that completes when the subscription is deleted.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} is an empty string.
* @throws NullPointerException if {@code topicName} or {@code subscriptionName} is null.
* @throws ResourceNotFoundException if the {@code subscriptionName} does not exist.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Void> deleteSubscription(String topicName, String subscriptionName) {
return deleteSubscriptionWithResponse(topicName, subscriptionName).then();
}
/**
* Deletes a subscription the matching {@code subscriptionName} and returns the HTTP response.
*
* @param topicName Name of topic associated with subscription to delete.
* @param subscriptionName Name of subscription to delete.
*
* @return A Mono that completes when the subscription is deleted and returns the HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} is an empty string.
* @throws NullPointerException if {@code topicName} or {@code subscriptionName} is null.
* @throws ResourceNotFoundException if the {@code subscriptionName} does not exist.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Void>> deleteSubscriptionWithResponse(String topicName, String subscriptionName) {
return withContext(context -> deleteSubscriptionWithResponse(topicName, subscriptionName, context));
}
/**
* Deletes a topic the matching {@code topicName}.
*
* @param topicName Name of topic to delete.
*
* @return A Mono that completes when the topic is deleted.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code topicName} is an empty string.
* @throws NullPointerException if {@code topicName} is null.
* @throws ResourceNotFoundException if the {@code topicName} does not exist.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Void> deleteTopic(String topicName) {
return deleteTopicWithResponse(topicName).then();
}
/**
* Deletes a topic the matching {@code topicName} and returns the HTTP response.
*
* @param topicName Name of topic to delete.
*
* @return A Mono that completes when the topic is deleted and returns the HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code topicName} is an empty string.
* @throws NullPointerException if {@code topicName} is null.
* @throws ResourceNotFoundException if the {@code topicName} does not exist.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Void>> deleteTopicWithResponse(String topicName) {
return withContext(context -> deleteTopicWithResponse(topicName, context));
}
/**
* Gets information about the queue.
*
* @param queueName Name of queue to get information about.
*
* @return A Mono that completes with information about the queue.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code queueName} is an empty string.
* @throws NullPointerException if {@code queueName} is null.
* @throws ResourceNotFoundException if the {@code queueName} does not exist.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<QueueProperties> getQueue(String queueName) {
return getQueueWithResponse(queueName).map(Response::getValue);
}
/**
* Gets information about the queue along with its HTTP response.
*
* @param queueName Name of queue to get information about.
*
* @return A Mono that completes with information about the queue and the associated HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code queueName} is an empty string.
* @throws NullPointerException if {@code queueName} is null.
* @throws ResourceNotFoundException if the {@code queueName} does not exist.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<QueueProperties>> getQueueWithResponse(String queueName) {
return withContext(context -> getQueueWithResponse(queueName, context, Function.identity()));
}
/**
* Gets whether or not a queue with {@code queueName} exists in the Service Bus namespace.
*
* @param queueName Name of the queue.
*
* @return A Mono that completes indicating whether or not the queue exists.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code queueName} is an empty string.
* @throws NullPointerException if {@code queueName} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Boolean> getQueueExists(String queueName) {
return getQueueExistsWithResponse(queueName).map(Response::getValue);
}
/**
* Gets whether or not a queue with {@code queueName} exists in the Service Bus namespace.
*
* @param queueName Name of the queue.
*
* @return A Mono that completes indicating whether or not the queue exists along with its HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code queueName} is an empty string.
* @throws NullPointerException if {@code queueName} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Boolean>> getQueueExistsWithResponse(String queueName) {
return getEntityExistsWithResponse(getQueueWithResponse(queueName));
}
/**
* Gets runtime properties about the queue.
*
* @param queueName Name of queue to get information about.
*
* @return A Mono that completes with runtime properties about the queue.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code queueName} is an empty string.
* @throws NullPointerException if {@code queueName} is null.
* @throws ResourceNotFoundException if the {@code queueName} does not exist.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<QueueRuntimeProperties> getQueueRuntimeProperties(String queueName) {
return getQueueRuntimePropertiesWithResponse(queueName).map(response -> response.getValue());
}
/**
* Gets runtime properties about the queue along with its HTTP response.
*
* @param queueName Name of queue to get information about.
*
* @return A Mono that completes with runtime properties about the queue and the associated HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code queueName} is an empty string.
* @throws NullPointerException if {@code queueName} is null.
* @throws ResourceNotFoundException if the {@code queueName} does not exist.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<QueueRuntimeProperties>> getQueueRuntimePropertiesWithResponse(String queueName) {
return withContext(context -> getQueueWithResponse(queueName, context, QueueRuntimeProperties::new));
}
/**
* Gets information about the Service Bus namespace.
*
* @return A Mono that completes with information about the Service Bus namespace.
* @throws ClientAuthenticationException if the client's credentials do not have access to the namespace.
* @throws HttpResponseException If error occurred processing the request.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<NamespaceProperties> getNamespaceProperties() {
return getNamespacePropertiesWithResponse().map(Response::getValue);
}
/**
* Gets information about the Service Bus namespace along with its HTTP response.
*
* @return A Mono that completes with information about the namespace and the associated HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<NamespaceProperties>> getNamespacePropertiesWithResponse() {
return withContext(this::getNamespacePropertiesWithResponse);
}
/**
* Gets a rule from the service namespace.
*
* Only following data types are deserialized in Filters and Action parameters - string, int, long, boolean, double,
* and OffsetDateTime. Other data types would return its string value.
*
* @param topicName The name of the topic relative to service bus namespace.
* @param subscriptionName The subscription name the rule belongs to.
* @param ruleName The name of the rule to retrieve.
*
* @return The associated rule.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<RuleProperties> getRule(String topicName, String subscriptionName, String ruleName) {
return getRuleWithResponse(topicName, subscriptionName, ruleName).map(response -> response.getValue());
}
/**
* Gets a rule from the service namespace.
*
* Only following data types are deserialized in Filters and Action parameters - string, int, long, bool, double,
* and OffsetDateTime. Other data types would return its string value.
*
* @param topicName The name of the topic relative to service bus namespace.
* @param subscriptionName The subscription name the rule belongs to.
* @param ruleName The name of the rule to retrieve.
*
* @return The associated rule with the corresponding HTTP response.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<RuleProperties>> getRuleWithResponse(String topicName, String subscriptionName,
String ruleName) {
return withContext(context -> getRuleWithResponse(topicName, subscriptionName, ruleName, context));
}
/**
* Gets information about the queue.
*
* @param topicName Name of topic associated with subscription.
* @param subscriptionName Name of subscription to get information about.
*
* @return A Mono that completes with information about the subscription.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} are empty strings.
* @throws NullPointerException if {@code topicName} or {@code subscriptionName} are null.
* @throws ResourceNotFoundException if the {@code subscriptionName} does not exist in the {@code topicName}.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<SubscriptionProperties> getSubscription(String topicName, String subscriptionName) {
return getSubscriptionWithResponse(topicName, subscriptionName).map(Response::getValue);
}
/**
* Gets information about the subscription along with its HTTP response.
*
* @param topicName Name of topic associated with subscription.
* @param subscriptionName Name of subscription to get information about.
*
* @return A Mono that completes with information about the subscription and the associated HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} are empty strings.
* @throws NullPointerException if {@code topicName} or {@code subscriptionName} are null.
* @throws ResourceNotFoundException if the {@code subscriptionName} does not exist.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<SubscriptionProperties>> getSubscriptionWithResponse(String topicName,
String subscriptionName) {
return withContext(context -> getSubscriptionWithResponse(topicName, subscriptionName, context,
Function.identity()));
}
/**
* Gets whether or not a subscription within a topic exists.
*
* @param topicName Name of topic associated with subscription.
* @param subscriptionName Name of the subscription.
*
* @return A Mono that completes indicating whether or not the subscription exists.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code subscriptionName} is an empty string.
* @throws NullPointerException if {@code subscriptionName} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Boolean> getSubscriptionExists(String topicName, String subscriptionName) {
return getSubscriptionExistsWithResponse(topicName, subscriptionName).map(Response::getValue);
}
/**
* Gets whether or not a subscription within a topic exists.
*
* @param topicName Name of topic associated with subscription.
* @param subscriptionName Name of the subscription.
*
* @return A Mono that completes indicating whether or not the subscription exists along with its HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code subscriptionName} is an empty string.
* @throws NullPointerException if {@code subscriptionName} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Boolean>> getSubscriptionExistsWithResponse(String topicName, String subscriptionName) {
return getEntityExistsWithResponse(getSubscriptionWithResponse(topicName, subscriptionName));
}
/**
* Gets runtime properties about the subscription.
*
* @param topicName Name of topic associated with subscription.
* @param subscriptionName Name of subscription to get information about.
*
* @return A Mono that completes with runtime properties about the subscription.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} are empty strings.
* @throws NullPointerException if {@code topicName} or {@code subscriptionName} are null.
* @throws ResourceNotFoundException if the {@code subscriptionName} does not exist.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<SubscriptionRuntimeProperties> getSubscriptionRuntimeProperties(
String topicName, String subscriptionName) {
return getSubscriptionRuntimePropertiesWithResponse(topicName, subscriptionName)
.map(response -> response.getValue());
}
/**
* Gets runtime properties about the subscription.
*
* @param topicName Name of topic associated with subscription.
* @param subscriptionName Name of subscription to get information about.
*
* @return A Mono that completes with runtime properties about the subscription.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code subscriptionName} is an empty string.
* @throws NullPointerException if {@code subscriptionName} is null.
* @throws ResourceNotFoundException if the {@code subscriptionName} does not exist.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<SubscriptionRuntimeProperties>> getSubscriptionRuntimePropertiesWithResponse(
String topicName, String subscriptionName) {
return withContext(context -> getSubscriptionWithResponse(topicName, subscriptionName, context,
SubscriptionRuntimeProperties::new));
}
/**
* Gets information about the topic.
*
* @param topicName Name of topic to get information about.
*
* @return A Mono that completes with information about the topic.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code topicName} is an empty string.
* @throws NullPointerException if {@code topicName} is null.
* @throws ResourceNotFoundException if the {@code topicName} does not exist.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<TopicProperties> getTopic(String topicName) {
return getTopicWithResponse(topicName).map(Response::getValue);
}
/**
* Gets information about the topic along with its HTTP response.
*
* @param topicName Name of topic to get information about.
*
* @return A Mono that completes with information about the topic and the associated HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code topicName} is an empty string.
* @throws NullPointerException if {@code topicName} is null.
* @throws ResourceNotFoundException if the {@code topicName} does not exist.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<TopicProperties>> getTopicWithResponse(String topicName) {
return withContext(context -> getTopicWithResponse(topicName, context, Function.identity()));
}
/**
* Gets whether or not a topic with {@code topicName} exists in the Service Bus namespace.
*
* @param topicName Name of the topic.
*
* @return A Mono that completes indicating whether or not the topic exists.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code topicName} is an empty string.
* @throws NullPointerException if {@code topicName} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Boolean> getTopicExists(String topicName) {
return getTopicExistsWithResponse(topicName).map(Response::getValue);
}
/**
* Gets whether or not a topic with {@code topicName} exists in the Service Bus namespace.
*
* @param topicName Name of the topic.
*
* @return A Mono that completes indicating whether or not the topic exists along with its HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code topicName} is an empty string.
* @throws NullPointerException if {@code topicName} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Boolean>> getTopicExistsWithResponse(String topicName) {
return getEntityExistsWithResponse(getTopicWithResponse(topicName));
}
/**
* Gets runtime properties about the topic.
*
* @param topicName Name of topic to get information about.
*
* @return A Mono that completes with runtime properties about the topic.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code topicName} is an empty string.
* @throws NullPointerException if {@code topicName} is null.
* @throws ResourceNotFoundException if the {@code topicName} does not exist.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<TopicRuntimeProperties> getTopicRuntimeProperties(String topicName) {
return getTopicRuntimePropertiesWithResponse(topicName).map(response -> response.getValue());
}
/**
* Gets runtime properties about the topic with its HTTP response.
*
* @param topicName Name of topic to get information about.
*
* @return A Mono that completes with runtime properties about the topic and the associated HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code topicName} is an empty string.
* @throws NullPointerException if {@code topicName} is null.
* @throws ResourceNotFoundException if the {@code topicName} does not exist.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<TopicRuntimeProperties>> getTopicRuntimePropertiesWithResponse(String topicName) {
return withContext(context -> getTopicWithResponse(topicName, context, TopicRuntimeProperties::new));
}
/**
* Fetches all the queues in the Service Bus namespace.
*
* @return A Flux of {@link QueueProperties queues} in the Service Bus namespace.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @see <a href="https:
* authorization rules</a>
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux<QueueProperties> listQueues() {
return new PagedFlux<>(
() -> withContext(context -> listQueuesFirstPage(context)),
token -> withContext(context -> listQueuesNextPage(token, context)));
}
/**
* Fetches all the rules for a topic and subscription.
*
* @param topicName The topic name under which all the rules need to be retrieved.
* @param subscriptionName The name of the subscription for which all rules need to be retrieved.
*
* @return A Flux of {@link RuleProperties rules} for the {@code topicName} and {@code subscriptionName}.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws NullPointerException if {@code topicName} or {@code subscriptionName} is null.
* @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} is an empty string.
* @see <a href="https:
* authorization rules</a>
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux<RuleProperties> listRules(String topicName, String subscriptionName) {
if (topicName == null) {
return pagedFluxError(logger, new NullPointerException("'topicName' cannot be null."));
} else if (topicName.isEmpty()) {
return pagedFluxError(logger, new IllegalArgumentException("'topicName' cannot be an empty string."));
}
return new PagedFlux<>(
() -> withContext(context -> listRulesFirstPage(topicName, subscriptionName, context)),
token -> withContext(context -> listRulesNextPage(topicName, subscriptionName, token, context)));
}
/**
* Fetches all the subscriptions for a topic.
*
* @param topicName The topic name under which all the subscriptions need to be retrieved.
*
* @return A Flux of {@link SubscriptionProperties subscriptions} for the {@code topicName}.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws NullPointerException if {@code topicName} is null.
* @throws IllegalArgumentException if {@code topicName} is an empty string.
* @see <a href="https:
* authorization rules</a>
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux<SubscriptionProperties> listSubscriptions(String topicName) {
if (topicName == null) {
return pagedFluxError(logger, new NullPointerException("'topicName' cannot be null."));
} else if (topicName.isEmpty()) {
return pagedFluxError(logger, new IllegalArgumentException("'topicName' cannot be an empty string."));
}
return new PagedFlux<>(
() -> withContext(context -> listSubscriptionsFirstPage(topicName, context)),
token -> withContext(context -> listSubscriptionsNextPage(topicName, token, context)));
}
/**
* Fetches all the topics in the Service Bus namespace.
*
* @return A Flux of {@link TopicProperties topics} in the Service Bus namespace.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @see <a href="https:
* authorization rules</a>
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux<TopicProperties> listTopics() {
return new PagedFlux<>(
() -> withContext(context -> listTopicsFirstPage(context)),
token -> withContext(context -> listTopicsNextPage(token, context)));
}
/**
* Updates a queue with the given {@link QueueProperties}. The {@link QueueProperties} must be fully populated as
* all of the properties are replaced. If a property is not set the service default value is used.
*
* The suggested flow is:
* <ol>
* <li>{@link
* <li>Update the required elements.</li>
* <li>Pass the updated description into this method.</li>
* </ol>
*
* <p>
* There are a subset of properties that can be updated. More information can be found in the links below. They are:
* <ul>
* <li>{@link QueueProperties
* <li>{@link QueueProperties
* <li>{@link QueueProperties
* </li>
* <li>{@link QueueProperties
* </ul>
*
* @param queue Information about the queue to update. You must provide all the property values that are desired
* on the updated entity. Any values not provided are set to the service default values.
*
* @return A Mono that completes with the updated queue.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If the request body was invalid, the queue quota is exceeded, or an error
* occurred processing the request.
* @throws NullPointerException if {@code queue} is null.
* @see <a href="https:
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<QueueProperties> updateQueue(QueueProperties queue) {
return updateQueueWithResponse(queue).map(Response::getValue);
}
/**
* Updates a queue with the given {@link QueueProperties}. The {@link QueueProperties} must be fully populated as
* all of the properties are replaced. If a property is not set the service default value is used.
*
* The suggested flow is:
* <ol>
* <li>{@link
* <li>Update the required elements.</li>
* <li>Pass the updated description into this method.</li>
* </ol>
*
* <p>
* There are a subset of properties that can be updated. More information can be found in the links below. They are:
* <ul>
* <li>{@link QueueProperties
* <li>{@link QueueProperties
* <li>{@link QueueProperties
* </li>
* <li>{@link QueueProperties
* </ul>
*
* @param queue Information about the queue to update. You must provide all the property values that are desired
* on the updated entity. Any values not provided are set to the service default values.
*
* @return A Mono that returns the updated queue in addition to the HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If the request body was invalid, the queue quota is exceeded, or an error
* occurred processing the request.
* @throws NullPointerException if {@code queue} is null.
* @see <a href="https:
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<QueueProperties>> updateQueueWithResponse(QueueProperties queue) {
return withContext(context -> updateQueueWithResponse(queue, context));
}
/**
* Updates a rule with the given {@link RuleProperties}. The {@link RuleProperties} must be fully populated as all
* of the properties are replaced. If a property is not set the service default value is used.
*
* The suggested flow is:
* <ol>
* <li>{@link
* <li>Update the required elements.</li>
* <li>Pass the updated description into this method.</li>
* </ol>
*
* @param topicName The topic name under which the rule is updated.
* @param subscriptionName The name of the subscription for which the rule is updated.
* @param rule Information about the rule to update. You must provide all the property values that are desired
* on the updated entity. Any values not provided are set to the service default values.
*
* @return A Mono that returns the updated rule.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If the request body was invalid, the rule quota is exceeded, or an error
* occurred processing the request.
* @throws IllegalArgumentException if {@link RuleProperties
* @throws NullPointerException if {@code rule} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<RuleProperties> updateRule(String topicName, String subscriptionName, RuleProperties rule) {
return updateRuleWithResponse(topicName, subscriptionName, rule).map(Response::getValue);
}
/**
* Updates a rule with the given {@link RuleProperties}. The {@link RuleProperties} must be fully populated as all
* of the properties are replaced. If a property is not set the service default value is used.
*
* The suggested flow is:
* <ol>
* <li>{@link
* <li>Update the required elements.</li>
* <li>Pass the updated description into this method.</li>
* </ol>
*
* @param topicName The topic name under which the rule is updated.
* @param subscriptionName The name of the subscription for which the rule is updated.
* @param rule Information about the rule to update. You must provide all the property values that are desired
* on the updated entity. Any values not provided are set to the service default values.
*
* @return A Mono that returns the updated rule in addition to the HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If the request body was invalid, the rule quota is exceeded, or an error
* occurred processing the request.
* @throws IllegalArgumentException if {@link RuleProperties
* @throws NullPointerException if {@code rule} is null.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<RuleProperties>> updateRuleWithResponse(String topicName, String subscriptionName,
RuleProperties rule) {
return withContext(context -> updateRuleWithResponse(topicName, subscriptionName, rule, context));
}
/**
* Updates a subscription with the given {@link SubscriptionProperties}. The {@link SubscriptionProperties} must be
* fully populated as all of the properties are replaced. If a property is not set the service default value is
* used.
*
* The suggested flow is:
* <ol>
* <li>{@link
* <li>Update the required elements.</li>
* <li>Pass the updated description into this method.</li>
* </ol>
*
* <p>
* There are a subset of properties that can be updated. More information can be found in the links below. They are:
* <ul>
* <li>{@link SubscriptionProperties
* <li>{@link SubscriptionProperties
* <li>{@link SubscriptionProperties
* </ul>
*
* @param subscription Information about the subscription to update. You must provide all the property values
* that are desired on the updated entity. Any values not provided are set to the service default values.
*
* @return A Mono that returns the updated subscription.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If the request body was invalid, the subscription quota is exceeded, or an
* error occurred processing the request.
* @throws IllegalArgumentException if {@link SubscriptionProperties
* SubscriptionProperties
* @throws NullPointerException if {@code subscription} is null.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<SubscriptionProperties> updateSubscription(SubscriptionProperties subscription) {
return updateSubscriptionWithResponse(subscription).map(Response::getValue);
}
/**
* Updates a subscription with the given {@link SubscriptionProperties}. The {@link SubscriptionProperties} must be
* fully populated as all of the properties are replaced. If a property is not set the service default value is
* used.
*
* The suggested flow is:
* <ol>
* <li>{@link
* <li>Update the required elements.</li>
* <li>Pass the updated description into this method.</li>
* </ol>
*
* <p>
* There are a subset of properties that can be updated. More information can be found in the links below. They are:
* <ul>
* <li>{@link SubscriptionProperties
* <li>{@link SubscriptionProperties
* <li>{@link SubscriptionProperties
* </ul>
*
* @param subscription Information about the subscription to update. You must provide all the property values
* that are desired on the updated entity. Any values not provided are set to the service default values.
*
* @return A Mono that returns the updated subscription in addition to the HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If the request body was invalid, the subscription quota is exceeded, or an
* error occurred processing the request.
* @throws IllegalArgumentException if {@link SubscriptionProperties
* SubscriptionProperties
* @throws NullPointerException if {@code subscription} is null.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<SubscriptionProperties>> updateSubscriptionWithResponse(
SubscriptionProperties subscription) {
return withContext(context -> updateSubscriptionWithResponse(subscription, context));
}
/**
* Updates a topic with the given {@link TopicProperties}. The {@link TopicProperties} must be fully populated as
* all of the properties are replaced. If a property is not set the service default value is used.
*
* The suggested flow is:
* <ol>
* <li>{@link
* <li>Update the required elements.</li>
* <li>Pass the updated description into this method.</li>
* </ol>
*
* <p>
* There are a subset of properties that can be updated. More information can be found in the links below. They are:
* <ul>
* <li>{@link TopicProperties
* <li>{@link TopicProperties
* </li>
* </ul>
*
* @param topic Information about the topic to update. You must provide all the property values that are desired
* on the updated entity. Any values not provided are set to the service default values.
*
* @return A Mono that completes with the updated topic.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If the request body was invalid, the topic quota is exceeded, or an error
* occurred processing the request.
* @throws IllegalArgumentException if {@link TopicProperties
* string.
* @throws NullPointerException if {@code topic} is null.
* @see <a href="https:
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<TopicProperties> updateTopic(TopicProperties topic) {
return updateTopicWithResponse(topic).map(Response::getValue);
}
/**
* Updates a topic with the given {@link TopicProperties}. The {@link TopicProperties} must be fully populated as
* all of the properties are replaced. If a property is not set the service default value is used.
*
* The suggested flow is:
* <ol>
* <li>{@link
* <li>Update the required elements.</li>
* <li>Pass the updated description into this method.</li>
* </ol>
*
* <p>
* There are a subset of properties that can be updated. More information can be found in the links below. They are:
* <ul>
* <li>{@link TopicProperties
* <li>{@link TopicProperties
* </li>
* </ul>
*
* @param topic Information about the topic to update. You must provide all the property values that are desired
* on the updated entity. Any values not provided are set to the service default values.
*
* @return A Mono that completes with the updated topic and its HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If the request body was invalid, the topic quota is exceeded, or an error
* occurred processing the request.
* @throws IllegalArgumentException if {@link TopicProperties
* string.
* @throws NullPointerException if {@code topic} is null.
* @see <a href="https:
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<TopicProperties>> updateTopicWithResponse(TopicProperties topic) {
return withContext(context -> updateTopicWithResponse(topic, context));
}
/**
* Creates a queue with its context.
*
* @param createQueueOptions Queue to create.
* @param context Context to pass into request.
*
* @return A Mono that completes with the created {@link QueueProperties}.
*/
Mono<Response<QueueProperties>> createQueueWithResponse(String queueName, CreateQueueOptions createQueueOptions,
Context context) {
if (queueName == null) {
return monoError(logger, new NullPointerException("'queueName' cannot be null."));
} else if (queueName.isEmpty()) {
return monoError(logger, new IllegalArgumentException("'queueName' cannot be empty."));
}
if (createQueueOptions == null) {
return monoError(logger, new NullPointerException("'createQueueOptions' cannot be null."));
} else if (context == null) {
return monoError(logger, new NullPointerException("'context' cannot be null."));
}
final QueueDescription description = EntityHelper.getQueueDescription(createQueueOptions);
final CreateQueueBodyContent content = new CreateQueueBodyContent()
.setType(CONTENT_TYPE)
.setQueueDescription(description);
final CreateQueueBody createEntity = new CreateQueueBody()
.setContent(content);
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
try {
return entityClient.putWithResponseAsync(queueName, createEntity, null, withTracing)
.onErrorMap(ServiceBusAdministrationAsyncClient::mapException)
.map(this::deserializeQueue);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Creates a rule with its context.
*
* @param ruleOptions Rule to create.
* @param context Context to pass into request.
*
* @return A Mono that completes with the created {@link RuleProperties}.
*/
Mono<Response<RuleProperties>> createRuleWithResponse(String topicName, String subscriptionName, String ruleName,
CreateRuleOptions ruleOptions, Context context) {
if (topicName == null) {
return monoError(logger, new NullPointerException("'topicName' cannot be null."));
} else if (topicName.isEmpty()) {
return monoError(logger, new IllegalArgumentException("'topicName' cannot be empty."));
}
if (subscriptionName == null) {
return monoError(logger, new NullPointerException("'subscriptionName' cannot be null."));
} else if (subscriptionName.isEmpty()) {
return monoError(logger, new IllegalArgumentException("'subscriptionName' cannot be empty."));
}
if (ruleName == null) {
return monoError(logger, new NullPointerException("'ruleName' cannot be null."));
} else if (ruleName.isEmpty()) {
return monoError(logger, new IllegalArgumentException("'ruleName' cannot be empty."));
}
if (ruleOptions == null) {
return monoError(logger, new NullPointerException("'rule' cannot be null."));
}
final RuleActionImpl action = ruleOptions.getAction() != null
? EntityHelper.toImplementation(ruleOptions.getAction())
: null;
final RuleFilterImpl filter = ruleOptions.getFilter() != null
? EntityHelper.toImplementation(ruleOptions.getFilter())
: null;
final RuleDescription rule = new RuleDescription()
.setAction(action)
.setFilter(filter)
.setName(ruleName);
final CreateRuleBodyContent content = new CreateRuleBodyContent()
.setType(CONTENT_TYPE)
.setRuleDescription(rule);
final CreateRuleBody createEntity = new CreateRuleBody().setContent(content);
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
try {
return managementClient.getRules().putWithResponseAsync(topicName, subscriptionName, ruleName, createEntity,
null, withTracing)
.onErrorMap(ServiceBusAdministrationAsyncClient::mapException)
.map(response -> deserializeRule(response));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Creates a subscription with its context.
*
* @param subscriptionOptions Subscription to create.
* @param context Context to pass into request.
*
* @return A Mono that completes with the created {@link SubscriptionProperties}.
*/
Mono<Response<SubscriptionProperties>> createSubscriptionWithResponse(String topicName, String subscriptionName,
CreateSubscriptionOptions subscriptionOptions, Context context) {
if (topicName == null) {
return monoError(logger, new NullPointerException("'topicName' cannot be null."));
} else if (topicName.isEmpty()) {
return monoError(logger, new IllegalArgumentException("'topicName' cannot be empty."));
}
if (subscriptionName == null) {
return monoError(logger, new NullPointerException("'subscriptionName' cannot be null."));
} else if (subscriptionName.isEmpty()) {
return monoError(logger, new IllegalArgumentException("'subscriptionName' cannot be empty."));
}
if (subscriptionOptions == null) {
return monoError(logger, new NullPointerException("'subscription' cannot be null."));
}
final SubscriptionDescription subscription = EntityHelper.getSubscriptionDescription(subscriptionOptions);
final CreateSubscriptionBodyContent content = new CreateSubscriptionBodyContent()
.setType(CONTENT_TYPE)
.setSubscriptionDescription(subscription);
final CreateSubscriptionBody createEntity = new CreateSubscriptionBody().setContent(content);
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
try {
return managementClient.getSubscriptions().putWithResponseAsync(topicName, subscriptionName, createEntity,
null, withTracing)
.onErrorMap(ServiceBusAdministrationAsyncClient::mapException)
.map(response -> deserializeSubscription(topicName, response));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Creates a topicOptions with its context.
*
* @param topicOptions Topic to create.
* @param context Context to pass into request.
*
* @return A Mono that completes with the created {@link TopicProperties}.
*/
Mono<Response<TopicProperties>> createTopicWithResponse(String topicName, CreateTopicOptions topicOptions,
Context context) {
if (topicName == null) {
return monoError(logger, new NullPointerException("'topicName' cannot be null."));
} else if (topicName.isEmpty()) {
return monoError(logger, new IllegalArgumentException("'topicName' cannot be empty."));
}
if (topicOptions == null) {
return monoError(logger, new NullPointerException("'topicOptions' cannot be null"));
} else if (context == null) {
return monoError(logger, new NullPointerException("'context' cannot be null."));
}
final TopicDescription topic = EntityHelper.getTopicDescription(topicOptions);
final CreateTopicBodyContent content = new CreateTopicBodyContent()
.setType(CONTENT_TYPE)
.setTopicDescription(topic);
final CreateTopicBody createEntity = new CreateTopicBody()
.setContent(content);
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
try {
return entityClient.putWithResponseAsync(topicName, createEntity, null, withTracing)
.onErrorMap(ServiceBusAdministrationAsyncClient::mapException)
.map(this::deserializeTopic);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Deletes a queue with its context.
*
* @param queueName Name of queue to delete.
* @param context Context to pass into request.
*
* @return A Mono that completes when the queue is deleted.
*/
Mono<Response<Void>> deleteQueueWithResponse(String queueName, Context context) {
if (queueName == null) {
return monoError(logger, new NullPointerException("'queueName' cannot be null"));
} else if (queueName.isEmpty()) {
return monoError(logger, new IllegalArgumentException("'queueName' cannot be an empty string."));
} else if (context == null) {
return monoError(logger, new NullPointerException("'context' cannot be null."));
}
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
try {
return entityClient.deleteWithResponseAsync(queueName, withTracing)
.onErrorMap(ServiceBusAdministrationAsyncClient::mapException)
.map(response -> {
return new SimpleResponse<>(response.getRequest(), response.getStatusCode(),
response.getHeaders(), null);
});
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Deletes a queue with its context.
*
* @param topicName Name of topic to delete.
* @param subscriptionName Name of the subscription for the rule.
* @param ruleName Name of the rule.
* @param context Context to pass into request.
*
* @return A Mono that completes with the created {@link QueueProperties}.
*/
Mono<Response<Void>> deleteRuleWithResponse(String topicName, String subscriptionName, String ruleName,
Context context) {
if (topicName == null) {
return monoError(logger, new NullPointerException("'topicName' cannot be null"));
} else if (topicName.isEmpty()) {
return monoError(logger, new IllegalArgumentException("'topicName' cannot be an empty string."));
} else if (subscriptionName == null) {
return monoError(logger, new NullPointerException("'subscriptionName' cannot be null"));
} else if (subscriptionName.isEmpty()) {
return monoError(logger, new IllegalArgumentException("'subscriptionName' cannot be an empty string."));
} else if (ruleName == null) {
return monoError(logger, new NullPointerException("'ruleName' cannot be null"));
} else if (ruleName.isEmpty()) {
return monoError(logger, new IllegalArgumentException("'ruleName' cannot be an empty string."));
} else if (context == null) {
return monoError(logger, new NullPointerException("'context' cannot be null."));
}
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
try {
return rulesClient.deleteWithResponseAsync(topicName, subscriptionName, ruleName, withTracing)
.onErrorMap(ServiceBusAdministrationAsyncClient::mapException)
.map(response -> new SimpleResponse<>(response.getRequest(), response.getStatusCode(),
response.getHeaders(), null));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Deletes a subscription with its context.
*
* @param topicName Name of topic associated with subscription to delete.
* @param subscriptionName Name of subscription to delete.
* @param context Context to pass into request.
*
* @return A Mono that completes with the created {@link SubscriptionProperties}.
*/
Mono<Response<Void>> deleteSubscriptionWithResponse(String topicName, String subscriptionName, Context context) {
if (subscriptionName == null) {
return monoError(logger, new NullPointerException("'subscriptionName' cannot be null"));
} else if (subscriptionName.isEmpty()) {
return monoError(logger, new IllegalArgumentException("'subscriptionName' cannot be an empty string."));
} else if (topicName == null) {
return monoError(logger, new NullPointerException("'topicName' cannot be null"));
} else if (topicName.isEmpty()) {
return monoError(logger, new IllegalArgumentException("'topicName' cannot be an empty string."));
} else if (context == null) {
return monoError(logger, new NullPointerException("'context' cannot be null."));
}
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
try {
return managementClient.getSubscriptions().deleteWithResponseAsync(topicName, subscriptionName,
withTracing)
.onErrorMap(ServiceBusAdministrationAsyncClient::mapException)
.map(response -> new SimpleResponse<>(response.getRequest(), response.getStatusCode(),
response.getHeaders(), null));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Deletes a topic with its context.
*
* @param topicName Name of topic to delete.
* @param context Context to pass into request.
*
* @return A Mono that completes with the created {@link TopicProperties}.
*/
Mono<Response<Void>> deleteTopicWithResponse(String topicName, Context context) {
if (topicName == null) {
return monoError(logger, new NullPointerException("'topicName' cannot be null"));
} else if (topicName.isEmpty()) {
return monoError(logger, new IllegalArgumentException("'topicName' cannot be an empty string."));
} else if (context == null) {
return monoError(logger, new NullPointerException("'context' cannot be null."));
}
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
try {
return entityClient.deleteWithResponseAsync(topicName, withTracing)
.onErrorMap(ServiceBusAdministrationAsyncClient::mapException)
.map(response -> new SimpleResponse<>(response.getRequest(), response.getStatusCode(),
response.getHeaders(), null));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Gets whether an entity exists.
*
* @param getEntityOperation Operation to get information about entity. If {@link ResourceNotFoundException} is
* thrown, then it is mapped to false.
* @param <T> Entity type.
*
* @return True if the entity exists, false otherwise.
*/
<T> Mono<Response<Boolean>> getEntityExistsWithResponse(Mono<Response<T>> getEntityOperation) {
return getEntityOperation.map(response -> {
final boolean exists = response.getValue() != null;
return (Response<Boolean>) new SimpleResponse<>(response.getRequest(), response.getStatusCode(),
response.getHeaders(), exists);
})
.onErrorResume(ResourceNotFoundException.class, exception -> {
final HttpResponse response = exception.getResponse();
final Response<Boolean> result = new SimpleResponse<>(response.getRequest(), response.getStatusCode(),
response.getHeaders(), false);
return Mono.just(result);
});
}
/**
* Gets a queue with its context.
*
* @param queueName Name of queue to fetch information for.
* @param context Context to pass into request.
*
* @return A Mono that completes with the {@link QueueProperties}.
*/
<T> Mono<Response<T>> getQueueWithResponse(String queueName, Context context,
Function<QueueProperties, T> mapper) {
if (queueName == null) {
return monoError(logger, new NullPointerException("'queueName' cannot be null"));
} else if (queueName.isEmpty()) {
return monoError(logger, new IllegalArgumentException("'queueName' cannot be empty."));
} else if (context == null) {
return monoError(logger, new NullPointerException("'context' cannot be null."));
}
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
try {
return entityClient.getWithResponseAsync(queueName, true, withTracing)
.onErrorMap(ServiceBusAdministrationAsyncClient::mapException)
.handle((response, sink) -> {
final Response<QueueProperties> deserialize = deserializeQueue(response);
if (deserialize.getValue() == null) {
final HttpResponse notFoundResponse = new EntityNotFoundHttpResponse<>(deserialize);
sink.error(new ResourceNotFoundException(String.format("Queue '%s' does not exist.", queueName),
notFoundResponse));
} else {
final T mapped = mapper.apply(deserialize.getValue());
sink.next(new SimpleResponse<>(response.getRequest(), response.getStatusCode(),
response.getHeaders(), mapped));
}
});
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<RuleProperties>> getRuleWithResponse(String topicName, String subscriptionName,
String ruleName, Context context) {
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
try {
return rulesClient.getWithResponseAsync(topicName, subscriptionName, ruleName, true, withTracing)
.onErrorMap(ServiceBusAdministrationAsyncClient::mapException)
.map(this::deserializeRule);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Gets a subscription with its context.
*
* @param topicName Name of the topic associated with the subscription.
* @param subscriptionName Name of subscription to fetch information for.
* @param context Context to pass into request.
*
* @return A Mono that completes with the {@link SubscriptionProperties}.
*/
<T> Mono<Response<T>> getSubscriptionWithResponse(String topicName, String subscriptionName, Context context,
Function<SubscriptionProperties, T> mapper) {
if (topicName == null) {
return monoError(logger, new NullPointerException("'topicName' cannot be null."));
} else if (topicName.isEmpty()) {
return monoError(logger, new IllegalArgumentException("'topicName' cannot be an empty string."));
} else if (subscriptionName == null) {
return monoError(logger, new NullPointerException("'subscriptionName' cannot be null."));
} else if (subscriptionName.isEmpty()) {
return monoError(logger, new IllegalArgumentException("'subscriptionName' cannot be an empty string."));
} else if (context == null) {
return monoError(logger, new NullPointerException("'context' cannot be null."));
}
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
try {
return managementClient.getSubscriptions().getWithResponseAsync(topicName, subscriptionName, true,
withTracing)
.onErrorMap(ServiceBusAdministrationAsyncClient::mapException)
.handle((response, sink) -> {
final Response<SubscriptionProperties> deserialize = deserializeSubscription(topicName, response);
if (deserialize.getValue() == null) {
final HttpResponse notFoundResponse = new EntityNotFoundHttpResponse<>(deserialize);
sink.error(new ResourceNotFoundException(String.format(
"Subscription '%s' in topic '%s' does not exist.", topicName, subscriptionName),
notFoundResponse));
} else {
final T mapped = mapper.apply(deserialize.getValue());
sink.next(new SimpleResponse<>(response.getRequest(), response.getStatusCode(),
response.getHeaders(), mapped));
}
});
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Gets the namespace properties with its context.
*
* @param context Context to pass into request.
*
* @return A Mono that completes with the {@link NamespaceProperties}.
*/
Mono<Response<NamespaceProperties>> getNamespacePropertiesWithResponse(Context context) {
return managementClient.getNamespaces().getWithResponseAsync(context).handle((response, sink) -> {
final NamespacePropertiesEntry entry = response.getValue();
if (entry == null || entry.getContent() == null) {
sink.error(new AzureException(
"There was no content inside namespace response. Entry: " + response));
return;
}
final NamespaceProperties namespaceProperties = entry.getContent().getNamespaceProperties();
final Response<NamespaceProperties> result = new SimpleResponse<>(response.getRequest(),
response.getStatusCode(), response.getHeaders(), namespaceProperties);
sink.next(result);
});
}
/**
* Gets a topic with its context.
*
* @param topicName Name of topic to fetch information for.
* @param context Context to pass into request.
*
* @return A Mono that completes with the {@link TopicProperties}.
*/
<T> Mono<Response<T>> getTopicWithResponse(String topicName, Context context,
Function<TopicProperties, T> mapper) {
if (topicName == null) {
return monoError(logger, new NullPointerException("'topicName' cannot be null"));
} else if (topicName.isEmpty()) {
return monoError(logger, new IllegalArgumentException("'topicName' cannot be empty."));
} else if (context == null) {
return monoError(logger, new NullPointerException("'context' cannot be null."));
}
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
try {
return entityClient.getWithResponseAsync(topicName, true, withTracing)
.onErrorMap(ServiceBusAdministrationAsyncClient::mapException)
.handle((response, sink) -> {
final Response<TopicProperties> deserialize = deserializeTopic(response);
if (deserialize.getValue() == null) {
final HttpResponse notFoundResponse = new EntityNotFoundHttpResponse<>(deserialize);
sink.error(new ResourceNotFoundException(String.format("Topic '%s' does not exist.", topicName),
notFoundResponse));
} else {
final T mapped = mapper.apply(deserialize.getValue());
sink.next(new SimpleResponse<>(response.getRequest(), response.getStatusCode(),
response.getHeaders(), mapped));
}
});
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Gets the first page of queues with context.
*
* @param context Context to pass into request.
*
* @return A Mono that completes with a page of queues.
*/
Mono<PagedResponse<QueueProperties>> listQueuesFirstPage(Context context) {
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
try {
return listQueues(0, withTracing);
} catch (RuntimeException e) {
return monoError(logger, e);
}
}
/**
* Gets the next page of queues with context.
*
* @param continuationToken Number of items to skip in feed.
* @param context Context to pass into request.
*
* @return A Mono that completes with a page of queues or empty if there are no items left.
*/
Mono<PagedResponse<QueueProperties>> listQueuesNextPage(String continuationToken, Context context) {
if (continuationToken == null || continuationToken.isEmpty()) {
return Mono.empty();
}
try {
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
final int skip = Integer.parseInt(continuationToken);
return listQueues(skip, withTracing);
} catch (RuntimeException e) {
return monoError(logger, e);
}
}
/**
* Gets the first page of rules with context.
*
* @param context Context to pass into request.
*
* @return A Mono that completes with a page of rules.
*/
Mono<PagedResponse<RuleProperties>> listRulesFirstPage(String topicName, String subscriptionName, Context context) {
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
try {
return listRules(topicName, subscriptionName, 0, withTracing);
} catch (RuntimeException e) {
return monoError(logger, e);
}
}
/**
* Gets the next page of rules with context.
*
* @param continuationToken Number of items to skip in feed.
* @param context Context to pass into request.
*
* @return A Mono that completes with a page of rules or empty if there are no items left.
*/
Mono<PagedResponse<RuleProperties>> listRulesNextPage(String topicName, String subscriptionName,
String continuationToken, Context context) {
if (continuationToken == null || continuationToken.isEmpty()) {
return Mono.empty();
}
try {
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
final int skip = Integer.parseInt(continuationToken);
return listRules(topicName, subscriptionName, skip, withTracing);
} catch (RuntimeException e) {
return monoError(logger, e);
}
}
/**
* Gets the first page of subscriptions with context.
*
* @param context Context to pass into request.
*
* @return A Mono that completes with a page of subscriptions.
*/
Mono<PagedResponse<SubscriptionProperties>> listSubscriptionsFirstPage(String topicName, Context context) {
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
try {
return listSubscriptions(topicName, 0, withTracing);
} catch (RuntimeException e) {
return monoError(logger, e);
}
}
/**
* Gets the next page of subscriptions with context.
*
* @param continuationToken Number of items to skip in feed.
* @param context Context to pass into request.
*
* @return A Mono that completes with a page of subscriptions or empty if there are no items left.
*/
Mono<PagedResponse<SubscriptionProperties>> listSubscriptionsNextPage(String topicName, String continuationToken,
Context context) {
if (continuationToken == null || continuationToken.isEmpty()) {
return Mono.empty();
}
try {
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
final int skip = Integer.parseInt(continuationToken);
return listSubscriptions(topicName, skip, withTracing);
} catch (RuntimeException e) {
return monoError(logger, e);
}
}
/**
* Gets the first page of topics with context.
*
* @param context Context to pass into request.
*
* @return A Mono that completes with a page of topics.
*/
Mono<PagedResponse<TopicProperties>> listTopicsFirstPage(Context context) {
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
try {
return listTopics(0, withTracing);
} catch (RuntimeException e) {
return monoError(logger, e);
}
}
/**
* Gets the next page of topics with context.
*
* @param continuationToken Number of items to skip in feed.
* @param context Context to pass into request.
*
* @return A Mono that completes with a page of topics or empty if there are no items left.
*/
Mono<PagedResponse<TopicProperties>> listTopicsNextPage(String continuationToken, Context context) {
if (continuationToken == null || continuationToken.isEmpty()) {
return Mono.empty();
}
try {
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
final int skip = Integer.parseInt(continuationToken);
return listTopics(skip, withTracing);
} catch (RuntimeException e) {
return monoError(logger, e);
}
}
/**
* Updates a queue with its context.
*
* @param queue Information about the queue to update. You must provide all the property values that are desired
* on the updated entity. Any values not provided are set to the service default values.
* @param context Context to pass into request.
*
* @return A Mono that completes with the updated {@link QueueProperties}.
*/
Mono<Response<QueueProperties>> updateQueueWithResponse(QueueProperties queue, Context context) {
if (queue == null) {
return monoError(logger, new NullPointerException("'queue' cannot be null"));
} else if (context == null) {
return monoError(logger, new NullPointerException("'context' cannot be null."));
}
final QueueDescription queueDescription = EntityHelper.toImplementation(queue);
final CreateQueueBodyContent content = new CreateQueueBodyContent()
.setType(CONTENT_TYPE)
.setQueueDescription(queueDescription);
final CreateQueueBody createEntity = new CreateQueueBody()
.setContent(content);
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
try {
return entityClient.putWithResponseAsync(queue.getName(), createEntity, "*", withTracing)
.onErrorMap(ServiceBusAdministrationAsyncClient::mapException)
.map(response -> deserializeQueue(response));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Updates a rule with its context.
*
* @param rule Information about the rule to update. You must provide all the property values that are desired
* on the updated entity. Any values not provided are set to the service default values.
* @param context Context to pass into request.
*
* @return A Mono that completes with the updated {@link RuleProperties}.
*/
Mono<Response<RuleProperties>> updateRuleWithResponse(String topicName, String subscriptionName,
RuleProperties rule, Context context) {
if (rule == null) {
return monoError(logger, new NullPointerException("'rule' cannot be null"));
} else if (context == null) {
return monoError(logger, new NullPointerException("'context' cannot be null."));
}
final RuleDescription implementation = EntityHelper.toImplementation(rule);
final CreateRuleBodyContent content = new CreateRuleBodyContent()
.setType(CONTENT_TYPE)
.setRuleDescription(implementation);
final CreateRuleBody ruleBody = new CreateRuleBody()
.setContent(content);
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
try {
return managementClient.getRules().putWithResponseAsync(topicName, subscriptionName, rule.getName(),
ruleBody, "*", withTracing)
.onErrorMap(ServiceBusAdministrationAsyncClient::mapException)
.map(response -> deserializeRule(response));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Updates a subscription with its context.
*
* @param subscription Information about the subscription to update. You must provide all the property values
* that are desired on the updated entity. Any values not provided are set to the service default values.
* @param context Context to pass into request.
*
* @return A Mono that completes with the updated {@link SubscriptionProperties}.
*/
Mono<Response<SubscriptionProperties>> updateSubscriptionWithResponse(SubscriptionProperties subscription,
Context context) {
if (subscription == null) {
return monoError(logger, new NullPointerException("'subscription' cannot be null"));
} else if (context == null) {
return monoError(logger, new NullPointerException("'context' cannot be null."));
}
final String topicName = subscription.getTopicName();
final String subscriptionName = subscription.getSubscriptionName();
final SubscriptionDescription implementation = EntityHelper.toImplementation(subscription);
final CreateSubscriptionBodyContent content = new CreateSubscriptionBodyContent()
.setType(CONTENT_TYPE)
.setSubscriptionDescription(implementation);
final CreateSubscriptionBody createEntity = new CreateSubscriptionBody()
.setContent(content);
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
try {
return managementClient.getSubscriptions().putWithResponseAsync(topicName, subscriptionName, createEntity,
"*", withTracing)
.onErrorMap(ServiceBusAdministrationAsyncClient::mapException)
.map(response -> deserializeSubscription(topicName, response));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Updates a topic with its context.
*
* @param topic Information about the topic to update. You must provide all the property values that are desired
* on the updated entity. Any values not provided are set to the service default values.
* @param context Context to pass into request.
*
* @return A Mono that completes with the updated {@link TopicProperties}.
*/
Mono<Response<TopicProperties>> updateTopicWithResponse(TopicProperties topic, Context context) {
if (topic == null) {
return monoError(logger, new NullPointerException("'topic' cannot be null"));
} else if (context == null) {
return monoError(logger, new NullPointerException("'context' cannot be null."));
}
final TopicDescription implementation = EntityHelper.toImplementation(topic);
final CreateTopicBodyContent content = new CreateTopicBodyContent()
.setType(CONTENT_TYPE)
.setTopicDescription(implementation);
final CreateTopicBody createEntity = new CreateTopicBody()
.setContent(content);
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
try {
return entityClient.putWithResponseAsync(topic.getName(), createEntity, "*", withTracing)
.onErrorMap(ServiceBusAdministrationAsyncClient::mapException)
.map(response -> deserializeTopic(response));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
private <T> T deserialize(Object object, Class<T> clazz) {
if (object == null) {
return null;
}
final String contents = String.valueOf(object);
if (contents.isEmpty()) {
return null;
}
try {
return serializer.deserialize(contents, clazz);
} catch (IOException e) {
throw logger.logExceptionAsError(new RuntimeException(String.format(
"Exception while deserializing. Body: [%s]. Class: %s", contents, clazz), e));
}
}
/**
* Given an HTTP response, will deserialize it into a strongly typed Response object.
*
* @param response HTTP response to deserialize response body from.
* @param clazz Class to deserialize response type into.
* @param <T> Class type to deserialize response into.
*
* @return A Response with a strongly typed response value.
*/
private <T> Response<T> deserialize(Response<Object> response, Class<T> clazz) {
final T deserialize = deserialize(response.getValue(), clazz);
return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(),
deserialize);
}
/**
* Converts a Response into its corresponding {@link QueueDescriptionEntry} then mapped into {@link
* QueueProperties}.
*
* @param response HTTP Response to deserialize.
*
* @return The corresponding HTTP response with convenience properties set.
*/
/**
* Converts a Response into its corresponding {@link RuleDescriptionEntry} then mapped into {@link RuleProperties}.
*
* @param response HTTP Response to deserialize.
*
* @return The corresponding HTTP response with convenience properties set.
*/
private Response<RuleProperties> deserializeRule(Response<Object> response) {
final RuleDescriptionEntry entry = deserialize(response.getValue(), RuleDescriptionEntry.class);
if (entry == null) {
return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null);
} else if (entry.getContent() == null) {
logger.info("entry.getContent() is null. The entity may not exist. {}", entry);
return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null);
}
final RuleDescription description = entry.getContent().getRuleDescription();
final RuleProperties result = EntityHelper.toModel(description);
return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), result);
}
/**
* Converts a Response into its corresponding {@link SubscriptionDescriptionEntry} then mapped into {@link
* SubscriptionProperties}.
*
* @param response HTTP Response to deserialize.
*
* @return The corresponding HTTP response with convenience properties set.
*/
private Response<SubscriptionProperties> deserializeSubscription(String topicName, Response<Object> response) {
final SubscriptionDescriptionEntry entry = deserialize(response.getValue(), SubscriptionDescriptionEntry.class);
if (entry == null) {
return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null);
} else if (entry.getContent() == null) {
logger.warning("entry.getContent() is null. There should have been content returned. Entry: {}", entry);
return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null);
}
final SubscriptionProperties subscription = EntityHelper.toModel(
entry.getContent().getSubscriptionDescription());
final String subscriptionName = getTitleValue(entry.getTitle());
EntityHelper.setSubscriptionName(subscription, subscriptionName);
EntityHelper.setTopicName(subscription, topicName);
return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(),
subscription);
}
/**
* Converts a Response into its corresponding {@link TopicDescriptionEntry} then mapped into {@link
* QueueProperties}.
*
* @param response HTTP Response to deserialize.
*
* @return The corresponding HTTP response with convenience properties set.
*/
private Response<TopicProperties> deserializeTopic(Response<Object> response) {
final TopicDescriptionEntry entry = deserialize(response.getValue(), TopicDescriptionEntry.class);
if (entry == null) {
return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null);
} else if (entry.getContent() == null) {
logger.warning("entry.getContent() is null. There should have been content returned. Entry: {}", entry);
return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null);
} else if (entry.getContent().getTopicDescription() == null) {
final QueueDescriptionEntry entryTopic = deserialize(response.getValue(), QueueDescriptionEntry.class);
if (entryTopic != null && entryTopic.getContent() != null && entryTopic.getContent().getQueueDescription() != null) {
throw logger.logExceptionAsError(
new RuntimeException(String.format("'[%s]' is not a topic, it is a queue.", entryTopic.getTitle())));
}
}
final TopicProperties result = EntityHelper.toModel(entry.getContent().getTopicDescription());
final String topicName = getTitleValue(entry.getTitle());
EntityHelper.setTopicName(result, topicName);
return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), result);
}
/**
* Creates a {@link FeedPage} given the elements and a set of response links to get the next link from.
*
* @param entities Entities in the feed.
* @param responseLinks Links returned from the feed.
* @param <TResult> Type of Service Bus entities in page.
*
* @return A {@link FeedPage} indicating whether this can be continued or not.
* @throws MalformedURLException if the "next" page link does not contain a well-formed URL.
*/
private <TResult, TFeed> FeedPage<TResult> extractPage(Response<TFeed> response, List<TResult> entities,
List<ResponseLink> responseLinks)
throws MalformedURLException, UnsupportedEncodingException {
final Optional<ResponseLink> nextLink = responseLinks.stream()
.filter(link -> link.getRel().equalsIgnoreCase("next"))
.findFirst();
if (!nextLink.isPresent()) {
return new FeedPage<>(response.getStatusCode(), response.getHeaders(), response.getRequest(), entities);
}
final URL url = new URL(nextLink.get().getHref());
final String decode = URLDecoder.decode(url.getQuery(), StandardCharsets.UTF_8.name());
final Optional<Integer> skipParameter = Arrays.stream(decode.split("&|&"))
.map(part -> part.split("=", 2))
.filter(parts -> parts[0].equalsIgnoreCase("$skip") && parts.length == 2)
.map(parts -> Integer.valueOf(parts[1]))
.findFirst();
if (skipParameter.isPresent()) {
return new FeedPage<>(response.getStatusCode(), response.getHeaders(), response.getRequest(), entities,
skipParameter.get());
} else {
logger.warning("There should have been a skip parameter for the next page.");
return new FeedPage<>(response.getStatusCode(), response.getHeaders(), response.getRequest(), entities);
}
}
/**
* Helper method that invokes the service method, extracts the data and translates it to a PagedResponse.
*
* @param skip Number of elements to skip.
* @param context Context for the query.
*
* @return A Mono that completes with a paged response of queues.
*/
private Mono<PagedResponse<QueueProperties>> listQueues(int skip, Context context) {
return managementClient.listEntitiesWithResponseAsync(QUEUES_ENTITY_TYPE, skip, NUMBER_OF_ELEMENTS, context)
.onErrorMap(ServiceBusAdministrationAsyncClient::mapException)
.flatMap(response -> {
final Response<QueueDescriptionFeed> feedResponse = deserialize(response, QueueDescriptionFeed.class);
final QueueDescriptionFeed feed = feedResponse.getValue();
if (feed == null) {
logger.warning("Could not deserialize QueueDescriptionFeed. skip {}, top: {}", skip,
NUMBER_OF_ELEMENTS);
return Mono.empty();
}
final List<QueueProperties> entities = feed.getEntry().stream()
.filter(e -> e.getContent() != null && e.getContent().getQueueDescription() != null)
.map(e -> {
final String queueName = getTitleValue(e.getTitle());
final QueueProperties queueProperties = EntityHelper.toModel(
e.getContent().getQueueDescription());
EntityHelper.setQueueName(queueProperties, queueName);
return queueProperties;
})
.collect(Collectors.toList());
try {
return Mono.just(extractPage(feedResponse, entities, feed.getLink()));
} catch (MalformedURLException | UnsupportedEncodingException error) {
return Mono.error(new RuntimeException("Could not parse response into FeedPage<QueueDescription>",
error));
}
});
}
/**
* Helper method that invokes the service method, extracts the data and translates it to a PagedResponse.
*
* @param skip Number of elements to skip.
* @param context Context for the query.
*
* @return A Mono that completes with a paged response of rules.
*/
private Mono<PagedResponse<RuleProperties>> listRules(String topicName, String subscriptionName, int skip,
Context context) {
return managementClient.listRulesWithResponseAsync(topicName, subscriptionName, skip, NUMBER_OF_ELEMENTS,
context)
.onErrorMap(ServiceBusAdministrationAsyncClient::mapException)
.flatMap(response -> {
final Response<RuleDescriptionFeed> feedResponse = deserialize(response,
RuleDescriptionFeed.class);
final RuleDescriptionFeed feed = feedResponse.getValue();
if (feed == null) {
logger.warning("Could not deserialize RuleDescriptionFeed. skip {}, top: {}", skip,
NUMBER_OF_ELEMENTS);
return Mono.empty();
}
final List<RuleProperties> entities = feed.getEntry().stream()
.filter(e -> e.getContent() != null && e.getContent().getRuleDescription() != null)
.map(e -> {
return EntityHelper.toModel(e.getContent().getRuleDescription());
})
.collect(Collectors.toList());
try {
return Mono.just(extractPage(feedResponse, entities, feed.getLink()));
} catch (MalformedURLException | UnsupportedEncodingException error) {
return Mono.error(new RuntimeException(
"Could not parse response into FeedPage<RuleDescription>", error));
}
});
}
/**
* Helper method that invokes the service method, extracts the data and translates it to a PagedResponse.
*
* @param skip Number of elements to skip.
* @param context Context for the query.
*
* @return A Mono that completes with a paged response of subscriptions.
*/
private Mono<PagedResponse<SubscriptionProperties>> listSubscriptions(String topicName, int skip,
Context context) {
return managementClient.listSubscriptionsWithResponseAsync(topicName, skip, NUMBER_OF_ELEMENTS, context)
.onErrorMap(ServiceBusAdministrationAsyncClient::mapException)
.flatMap(response -> {
final Response<SubscriptionDescriptionFeed> feedResponse = deserialize(response,
SubscriptionDescriptionFeed.class);
final SubscriptionDescriptionFeed feed = feedResponse.getValue();
if (feed == null) {
logger.warning("Could not deserialize SubscriptionDescriptionFeed. skip {}, top: {}", skip,
NUMBER_OF_ELEMENTS);
return Mono.empty();
}
final List<SubscriptionProperties> entities = feed.getEntry().stream()
.filter(e -> e.getContent() != null && e.getContent().getSubscriptionDescription() != null)
.map(e -> {
final String subscriptionName = getTitleValue(e.getTitle());
final SubscriptionProperties description = EntityHelper.toModel(
e.getContent().getSubscriptionDescription());
EntityHelper.setTopicName(description, topicName);
EntityHelper.setSubscriptionName(description, subscriptionName);
return description;
})
.collect(Collectors.toList());
try {
return Mono.just(extractPage(feedResponse, entities, feed.getLink()));
} catch (MalformedURLException | UnsupportedEncodingException error) {
return Mono.error(new RuntimeException(
"Could not parse response into FeedPage<SubscriptionDescription>", error));
}
});
}
/**
* Helper method that invokes the service method, extracts the data and translates it to a PagedResponse.
*
* @param skip Number of elements to skip.
* @param context Context for the query.
*
* @return A Mono that completes with a paged response of topics.
*/
private Mono<PagedResponse<TopicProperties>> listTopics(int skip, Context context) {
return managementClient.listEntitiesWithResponseAsync(TOPICS_ENTITY_TYPE, skip, NUMBER_OF_ELEMENTS, context)
.onErrorMap(ServiceBusAdministrationAsyncClient::mapException)
.flatMap(response -> {
final Response<TopicDescriptionFeed> feedResponse = deserialize(response, TopicDescriptionFeed.class);
final TopicDescriptionFeed feed = feedResponse.getValue();
if (feed == null) {
logger.warning("Could not deserialize TopicDescriptionFeed. skip {}, top: {}", skip,
NUMBER_OF_ELEMENTS);
return Mono.empty();
}
final List<TopicProperties> entities = feed.getEntry().stream()
.filter(e -> e.getContent() != null && e.getContent().getTopicDescription() != null)
.map(e -> {
final String topicName = getTitleValue(e.getTitle());
final TopicProperties topicProperties = EntityHelper.toModel(
e.getContent().getTopicDescription());
EntityHelper.setTopicName(topicProperties, topicName);
return topicProperties;
})
.collect(Collectors.toList());
try {
return Mono.just(extractPage(feedResponse, entities, feed.getLink()));
} catch (MalformedURLException | UnsupportedEncodingException error) {
return Mono.error(new RuntimeException("Could not parse response into FeedPage<TopicDescription>",
error));
}
});
}
/**
* Given an XML title element, returns the XML text inside. Jackson deserializes Objects as LinkedHashMaps. XML text
* is represented as an entry with an empty string as the key.
*
* For example, the text returned from this {@code <title text="text/xml">QueueName</title>} is "QueueName".
*
* @param responseTitle XML title element.
*
* @return The XML text inside the title. {@code null} is returned if there is no value.
*/
@SuppressWarnings("unchecked")
private String getTitleValue(Object responseTitle) {
if (!(responseTitle instanceof Map)) {
return null;
}
final Map<String, String> map;
try {
map = (Map<String, String>) responseTitle;
return map.get("");
} catch (ClassCastException error) {
logger.warning("Unable to cast to Map<String,String>. Title: {}", responseTitle, error);
return null;
}
}
/**
* Maps an exception from the ATOM APIs to its associated {@link HttpResponseException}.
*
* @param exception Exception from the ATOM API.
*
* @return The corresponding {@link HttpResponseException} or {@code throwable} if it is not an instance of {@link
* ServiceBusManagementErrorException}.
*/
private static Throwable mapException(Throwable exception) {
if (!(exception instanceof ServiceBusManagementErrorException)) {
return exception;
}
final ServiceBusManagementErrorException managementError = ((ServiceBusManagementErrorException) exception);
final ServiceBusManagementError error = managementError.getValue();
final HttpResponse errorHttpResponse = managementError.getResponse();
final int statusCode = error != null && error.getCode() != null
? error.getCode()
: errorHttpResponse.getStatusCode();
final String errorDetail = error != null && error.getDetail() != null
? error.getDetail()
: managementError.getMessage();
switch (statusCode) {
case 401:
return new ClientAuthenticationException(errorDetail, managementError.getResponse(), exception);
case 404:
return new ResourceNotFoundException(errorDetail, managementError.getResponse(), exception);
case 409:
return new ResourceExistsException(errorDetail, managementError.getResponse(), exception);
case 412:
return new ResourceModifiedException(errorDetail, managementError.getResponse(), exception);
default:
return new HttpResponseException(errorDetail, managementError.getResponse(), exception);
}
}
/**
* A page of Service Bus entities.
*
* @param <T> The entity description from Service Bus.
*/
private static final class FeedPage<T> implements PagedResponse<T> {
private final int statusCode;
private final HttpHeaders header;
private final HttpRequest request;
private final IterableStream<T> entries;
private final String continuationToken;
/**
* Creates a page that does not have any more pages.
*
* @param entries Items in the page.
*/
private FeedPage(int statusCode, HttpHeaders header, HttpRequest request, List<T> entries) {
this.statusCode = statusCode;
this.header = header;
this.request = request;
this.entries = new IterableStream<>(entries);
this.continuationToken = null;
}
/**
* Creates an instance that has additional pages to fetch.
*
* @param entries Items in the page.
* @param skip Number of elements to "skip".
*/
private FeedPage(int statusCode, HttpHeaders header, HttpRequest request, List<T> entries, int skip) {
this.statusCode = statusCode;
this.header = header;
this.request = request;
this.entries = new IterableStream<>(entries);
this.continuationToken = String.valueOf(skip);
}
@Override
public IterableStream<T> getElements() {
return entries;
}
@Override
public String getContinuationToken() {
return continuationToken;
}
@Override
public int getStatusCode() {
return statusCode;
}
@Override
public HttpHeaders getHeaders() {
return header;
}
@Override
public HttpRequest getRequest() {
return request;
}
@Override
public void close() {
}
}
private static final class EntityNotFoundHttpResponse<T> extends HttpResponse {
private final int statusCode;
private final HttpHeaders headers;
private EntityNotFoundHttpResponse(Response<T> response) {
super(response.getRequest());
this.headers = response.getHeaders();
this.statusCode = response.getStatusCode();
}
@Override
public int getStatusCode() {
return statusCode;
}
@Override
public String getHeaderValue(String name) {
return headers.getValue(name);
}
@Override
public HttpHeaders getHeaders() {
return headers;
}
@Override
public Flux<ByteBuffer> getBody() {
return Flux.empty();
}
@Override
public Mono<byte[]> getBodyAsByteArray() {
return Mono.empty();
}
@Override
public Mono<String> getBodyAsString() {
return Mono.empty();
}
@Override
public Mono<String> getBodyAsString(Charset charset) {
return Mono.empty();
}
}
} | class ServiceBusAdministrationAsyncClient {
private static final String SERVICE_BUS_TRACING_NAMESPACE_VALUE = "Microsoft.ServiceBus";
private static final String CONTENT_TYPE = "application/xml";
private static final String QUEUES_ENTITY_TYPE = "queues";
private static final String TOPICS_ENTITY_TYPE = "topics";
private static final int NUMBER_OF_ELEMENTS = 100;
private final ServiceBusManagementClientImpl managementClient;
private final EntitiesImpl entityClient;
private final ClientLogger logger = new ClientLogger(ServiceBusAdministrationAsyncClient.class);
private final ServiceBusManagementSerializer serializer;
private final RulesImpl rulesClient;
/**
* Creates a new instance with the given management client and serializer.
*
* @param managementClient Client to make management calls.
* @param serializer Serializer to deserialize ATOM XML responses.
*/
ServiceBusAdministrationAsyncClient(ServiceBusManagementClientImpl managementClient,
ServiceBusManagementSerializer serializer) {
this.serializer = Objects.requireNonNull(serializer, "'serializer' cannot be null.");
this.managementClient = Objects.requireNonNull(managementClient, "'managementClient' cannot be null.");
this.entityClient = managementClient.getEntities();
this.rulesClient = managementClient.getRules();
}
/**
* Creates a queue with the given name.
*
* @param queueName Name of the queue to create.
*
* @return A Mono that completes with information about the created queue.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If the request body was invalid, the queue quota is exceeded, or an error
* occurred processing the request.
* @throws NullPointerException if {@code queueName} is null.
* @throws IllegalArgumentException if {@code queueName} is an empty string.
* @throws ResourceExistsException if a queue exists with the same {@code queueName}.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<QueueProperties> createQueue(String queueName) {
try {
return createQueue(queueName, new CreateQueueOptions());
} catch (RuntimeException e) {
return monoError(logger, e);
}
}
/**
* Creates a queue with the {@link CreateQueueOptions} and given queue name.
*
* @param queueName Name of the queue to create.
* @param queueOptions Options about the queue to create.
*
* @return A Mono that completes with information about the created queue.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If the request body was invalid, the queue quota is exceeded, or an error
* occurred processing the request.
* @throws IllegalArgumentException if {@code queueName} is an empty string.
* @throws NullPointerException if {@code queueName} or {@code queueOptions} is null.
* @throws ResourceExistsException if a queue exists with the same {@link QueueProperties
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<QueueProperties> createQueue(String queueName, CreateQueueOptions queueOptions) {
return createQueueWithResponse(queueName, queueOptions).map(Response::getValue);
}
/**
* Creates a queue and returns the created queue in addition to the HTTP response.
*
* @param queueName Name of the queue to create.
* @param queueOptions Options about the queue to create.
*
* @return A Mono that returns the created queue in addition to the HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If the request body was invalid, the queue quota is exceeded, or an error
* occurred processing the request.
* @throws IllegalArgumentException if {@code queueName} is an empty string.
* @throws NullPointerException if {@code queueName} or {@code queueOptions} is null.
* @throws ResourceExistsException if a queue exists with the same {@link QueueProperties
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<QueueProperties>> createQueueWithResponse(String queueName, CreateQueueOptions queueOptions) {
return withContext(context -> createQueueWithResponse(queueName, queueOptions, context));
}
/**
* Creates a rule under the given topic and subscription
*
* @param topicName Name of the topic associated with rule.
* @param subscriptionName Name of the subscription associated with the rule.
* @param ruleName Name of the rule.
*
* @return A Mono that completes with information about the created rule.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If the request body was invalid, the quota is exceeded, or an error occurred
* processing the request.
* @throws IllegalArgumentException if {@code topicName} or {@code ruleName} are are empty strings.
* @throws NullPointerException if {@code topicName} or {@code ruleName} are are null.
* @throws ResourceExistsException if a rule exists with the same topic, subscription, and rule name.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<RuleProperties> createRule(String topicName, String subscriptionName, String ruleName) {
try {
return createRule(topicName, subscriptionName, ruleName, new CreateRuleOptions());
} catch (RuntimeException e) {
return monoError(logger, e);
}
}
/**
* Creates a rule with the {@link CreateRuleOptions}.
*
* @param topicName Name of the topic associated with rule.
* @param subscriptionName Name of the subscription associated with the rule.
* @param ruleName Name of the rule.
* @param ruleOptions Information about the rule to create.
*
* @return A Mono that completes with information about the created rule.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If the request body was invalid, the quota is exceeded, or an error occurred
* processing the request.
* @throws IllegalArgumentException if {@code topicName} or {@code ruleName} are are empty strings.
* @throws NullPointerException if {@code topicName}, {@code ruleName}, or {@code ruleOptions}
* are are null.
* @throws ResourceExistsException if a rule exists with the same topic and rule name.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<RuleProperties> createRule(String topicName, String subscriptionName, String ruleName,
CreateRuleOptions ruleOptions) {
return createRuleWithResponse(topicName, subscriptionName, ruleName, ruleOptions)
.map(Response::getValue);
}
/**
* Creates a rule and returns the created rule in addition to the HTTP response.
*
* @param topicName Name of the topic associated with rule.
* @param subscriptionName Name of the subscription associated with the rule.
* @param ruleName Name of the rule.
* @param ruleOptions Information about the rule to create.
*
* @return A Mono that returns the created rule in addition to the HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If the request body was invalid, the quota is exceeded, or an error occurred
* processing the request.
* @throws IllegalArgumentException if {@code topicName} or {@code ruleName} are are empty strings.
* @throws NullPointerException if {@code topicName}, {@code ruleName}, or {@code ruleOptions}
* are are null.
* @throws ResourceExistsException if a rule exists with the same topic and rule name.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<RuleProperties>> createRuleWithResponse(String topicName, String subscriptionName,
String ruleName, CreateRuleOptions ruleOptions) {
return withContext(context -> createRuleWithResponse(topicName, subscriptionName, ruleName, ruleOptions,
context));
}
/**
* Creates a subscription with the given topic and subscription names.
*
* @param topicName Name of the topic associated with subscription.
* @param subscriptionName Name of the subscription.
*
* @return A Mono that completes with information about the created subscription.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If the request body was invalid, the quota is exceeded, or an error occurred
* processing the request.
* @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} are are empty strings.
* @throws NullPointerException if {@code topicName} or {@code subscriptionName} are are null.
* @throws ResourceExistsException if a subscription exists with the same topic and subscription name.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<SubscriptionProperties> createSubscription(String topicName, String subscriptionName) {
try {
return createSubscription(topicName, subscriptionName, new CreateSubscriptionOptions());
} catch (RuntimeException e) {
return monoError(logger, e);
}
}
/**
* Creates a subscription with the {@link CreateSubscriptionOptions}.
*
* @param topicName Name of the topic associated with subscription.
* @param subscriptionName Name of the subscription.
* @param subscriptionOptions Information about the subscription to create.
*
* @return A Mono that completes with information about the created subscription.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If the request body was invalid, the quota is exceeded, or an error occurred
* processing the request.
* @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} are are empty strings.
* @throws NullPointerException if {@code topicName}, {@code subscriptionName}, or {@code subscriptionOptions}
* are are null.
* @throws ResourceExistsException if a subscription exists with the same topic and subscription name.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<SubscriptionProperties> createSubscription(String topicName, String subscriptionName,
CreateSubscriptionOptions subscriptionOptions) {
return createSubscriptionWithResponse(topicName, subscriptionName, subscriptionOptions)
.map(Response::getValue);
}
/**
* Creates a subscription and returns the created subscription in addition to the HTTP response.
*
* @param topicName Name of the topic associated with subscription.
* @param subscriptionName Name of the subscription.
* @param subscriptionOptions Information about the subscription to create.
*
* @return A Mono that returns the created subscription in addition to the HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If the request body was invalid, the quota is exceeded, or an error occurred
* processing the request.
* @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} are are empty strings.
* @throws NullPointerException if {@code topicName}, {@code subscriptionName}, or {@code subscriptionOptions}
* are are null.
* @throws ResourceExistsException if a subscription exists with the same topic and subscription name.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<SubscriptionProperties>> createSubscriptionWithResponse(String topicName,
String subscriptionName, CreateSubscriptionOptions subscriptionOptions) {
return withContext(context -> createSubscriptionWithResponse(topicName, subscriptionName, subscriptionOptions,
context));
}
/**
* Creates a topic with the given name.
*
* @param topicName Name of the topic to create.
*
* @return A Mono that completes with information about the created topic.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If the request body was invalid, the topic quota is exceeded, or an error
* occurred processing the request.
* @throws NullPointerException if {@code topicName} is null.
* @throws IllegalArgumentException if {@code topicName} is an empty string.
* @throws ResourceExistsException if a topic exists with the same {@code topicName}.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<TopicProperties> createTopic(String topicName) {
try {
return createTopic(topicName, new CreateTopicOptions());
} catch (RuntimeException e) {
return monoError(logger, e);
}
}
/**
* Creates a topic with the {@link CreateTopicOptions}.
*
* @param topicName Name of the topic to create.
* @param topicOptions The options used to create the topic.
*
* @return A Mono that completes with information about the created topic.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If the request body was invalid, the topic quota is exceeded, or an error
* occurred processing the request.
* @throws IllegalArgumentException if {@code topicName} is an empty string.
* @throws NullPointerException if {@code topicName} or {@code topicOptions} is null.
* @throws ResourceExistsException if a topic exists with the same {@code topicName}.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<TopicProperties> createTopic(String topicName, CreateTopicOptions topicOptions) {
return createTopicWithResponse(topicName, topicOptions).map(Response::getValue);
}
/**
* Creates a topic and returns the created topic in addition to the HTTP response.
*
* @param topicName Name of the topic to create.
* @param topicOptions The options used to create the topic.
*
* @return A Mono that returns the created topic in addition to the HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If the request body was invalid, the topic quota is exceeded, or an error
* occurred processing the request.
* @throws IllegalArgumentException if {@link TopicProperties
* string.
* @throws NullPointerException if {@code topicName} or {@code topicOptions} is null.
* @throws ResourceExistsException if a topic exists with the same {@code topicName}.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<TopicProperties>> createTopicWithResponse(String topicName, CreateTopicOptions topicOptions) {
return withContext(context -> createTopicWithResponse(topicName, topicOptions, context));
}
/**
* Deletes a queue the matching {@code queueName}.
*
* @param queueName Name of queue to delete.
*
* @return A Mono that completes when the queue is deleted.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws NullPointerException if {@code queueName} is null.
* @throws IllegalArgumentException if {@code queueName} is an empty string.
* @throws ResourceNotFoundException if the {@code queueName} does not exist.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Void> deleteQueue(String queueName) {
return deleteQueueWithResponse(queueName).then();
}
/**
* Deletes a queue the matching {@code queueName} and returns the HTTP response.
*
* @param queueName Name of queue to delete.
*
* @return A Mono that completes when the queue is deleted and returns the HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws NullPointerException if {@code queueName} is null.
* @throws IllegalArgumentException if {@code queueName} is an empty string.
* @throws ResourceNotFoundException if the {@code queueName} does not exist.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Void>> deleteQueueWithResponse(String queueName) {
return withContext(context -> deleteQueueWithResponse(queueName, context));
}
/**
* Deletes a rule the matching {@code ruleName}.
*
* @param topicName Name of topic associated with rule to delete.
* @param subscriptionName Name of the subscription associated with the rule to delete.
* @param ruleName Name of rule to delete.
*
* @return A Mono that completes when the rule is deleted.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code topicName} or {@code ruleName} is an empty string.
* @throws NullPointerException if {@code topicName} or {@code ruleName} is null.
* @throws ResourceNotFoundException if the {@code ruleName} does not exist.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Void> deleteRule(String topicName, String subscriptionName, String ruleName) {
return deleteRuleWithResponse(topicName, subscriptionName, ruleName).then();
}
/**
* Deletes a rule the matching {@code ruleName} and returns the HTTP response.
*
* @param topicName Name of topic associated with rule to delete.
* @param subscriptionName Name of the subscription associated with the rule to delete.
* @param ruleName Name of rule to delete.
*
* @return A Mono that completes when the rule is deleted and returns the HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code topicName}, {@code subscriptionName}, or {@code ruleName} is an
* empty string.
* @throws NullPointerException if {@code topicName}, {@code subscriptionName}, or {@code ruleName} is null.
* @throws ResourceNotFoundException if the {@code ruleName} does not exist.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Void>> deleteRuleWithResponse(String topicName, String subscriptionName,
String ruleName) {
return withContext(context -> deleteRuleWithResponse(topicName, subscriptionName, ruleName, context));
}
/**
* Deletes a subscription the matching {@code subscriptionName}.
*
* @param topicName Name of topic associated with subscription to delete.
* @param subscriptionName Name of subscription to delete.
*
* @return A Mono that completes when the subscription is deleted.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} is an empty string.
* @throws NullPointerException if {@code topicName} or {@code subscriptionName} is null.
* @throws ResourceNotFoundException if the {@code subscriptionName} does not exist.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Void> deleteSubscription(String topicName, String subscriptionName) {
return deleteSubscriptionWithResponse(topicName, subscriptionName).then();
}
/**
* Deletes a subscription the matching {@code subscriptionName} and returns the HTTP response.
*
* @param topicName Name of topic associated with subscription to delete.
* @param subscriptionName Name of subscription to delete.
*
* @return A Mono that completes when the subscription is deleted and returns the HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} is an empty string.
* @throws NullPointerException if {@code topicName} or {@code subscriptionName} is null.
* @throws ResourceNotFoundException if the {@code subscriptionName} does not exist.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Void>> deleteSubscriptionWithResponse(String topicName, String subscriptionName) {
return withContext(context -> deleteSubscriptionWithResponse(topicName, subscriptionName, context));
}
/**
* Deletes a topic the matching {@code topicName}.
*
* @param topicName Name of topic to delete.
*
* @return A Mono that completes when the topic is deleted.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code topicName} is an empty string.
* @throws NullPointerException if {@code topicName} is null.
* @throws ResourceNotFoundException if the {@code topicName} does not exist.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Void> deleteTopic(String topicName) {
return deleteTopicWithResponse(topicName).then();
}
/**
* Deletes a topic the matching {@code topicName} and returns the HTTP response.
*
* @param topicName Name of topic to delete.
*
* @return A Mono that completes when the topic is deleted and returns the HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code topicName} is an empty string.
* @throws NullPointerException if {@code topicName} is null.
* @throws ResourceNotFoundException if the {@code topicName} does not exist.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Void>> deleteTopicWithResponse(String topicName) {
return withContext(context -> deleteTopicWithResponse(topicName, context));
}
/**
* Gets information about the queue.
*
* @param queueName Name of queue to get information about.
*
* @return A Mono that completes with information about the queue.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code queueName} is an empty string.
* @throws NullPointerException if {@code queueName} is null.
* @throws ResourceNotFoundException if the {@code queueName} does not exist.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<QueueProperties> getQueue(String queueName) {
return getQueueWithResponse(queueName).map(Response::getValue);
}
/**
* Gets information about the queue along with its HTTP response.
*
* @param queueName Name of queue to get information about.
*
* @return A Mono that completes with information about the queue and the associated HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code queueName} is an empty string.
* @throws NullPointerException if {@code queueName} is null.
* @throws ResourceNotFoundException if the {@code queueName} does not exist.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<QueueProperties>> getQueueWithResponse(String queueName) {
return withContext(context -> getQueueWithResponse(queueName, context, Function.identity()));
}
/**
* Gets whether or not a queue with {@code queueName} exists in the Service Bus namespace.
*
* @param queueName Name of the queue.
*
* @return A Mono that completes indicating whether or not the queue exists.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code queueName} is an empty string.
* @throws NullPointerException if {@code queueName} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Boolean> getQueueExists(String queueName) {
return getQueueExistsWithResponse(queueName).map(Response::getValue);
}
/**
* Gets whether or not a queue with {@code queueName} exists in the Service Bus namespace.
*
* @param queueName Name of the queue.
*
* @return A Mono that completes indicating whether or not the queue exists along with its HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code queueName} is an empty string.
* @throws NullPointerException if {@code queueName} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Boolean>> getQueueExistsWithResponse(String queueName) {
return getEntityExistsWithResponse(getQueueWithResponse(queueName));
}
/**
* Gets runtime properties about the queue.
*
* @param queueName Name of queue to get information about.
*
* @return A Mono that completes with runtime properties about the queue.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code queueName} is an empty string.
* @throws NullPointerException if {@code queueName} is null.
* @throws ResourceNotFoundException if the {@code queueName} does not exist.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<QueueRuntimeProperties> getQueueRuntimeProperties(String queueName) {
return getQueueRuntimePropertiesWithResponse(queueName).map(response -> response.getValue());
}
/**
* Gets runtime properties about the queue along with its HTTP response.
*
* @param queueName Name of queue to get information about.
*
* @return A Mono that completes with runtime properties about the queue and the associated HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code queueName} is an empty string.
* @throws NullPointerException if {@code queueName} is null.
* @throws ResourceNotFoundException if the {@code queueName} does not exist.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<QueueRuntimeProperties>> getQueueRuntimePropertiesWithResponse(String queueName) {
return withContext(context -> getQueueWithResponse(queueName, context, QueueRuntimeProperties::new));
}
/**
* Gets information about the Service Bus namespace.
*
* @return A Mono that completes with information about the Service Bus namespace.
* @throws ClientAuthenticationException if the client's credentials do not have access to the namespace.
* @throws HttpResponseException If error occurred processing the request.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<NamespaceProperties> getNamespaceProperties() {
return getNamespacePropertiesWithResponse().map(Response::getValue);
}
/**
* Gets information about the Service Bus namespace along with its HTTP response.
*
* @return A Mono that completes with information about the namespace and the associated HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<NamespaceProperties>> getNamespacePropertiesWithResponse() {
return withContext(this::getNamespacePropertiesWithResponse);
}
/**
* Gets a rule from the service namespace.
*
* Only following data types are deserialized in Filters and Action parameters - string, int, long, boolean, double,
* and OffsetDateTime. Other data types would return its string value.
*
* @param topicName The name of the topic relative to service bus namespace.
* @param subscriptionName The subscription name the rule belongs to.
* @param ruleName The name of the rule to retrieve.
*
* @return The associated rule.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<RuleProperties> getRule(String topicName, String subscriptionName, String ruleName) {
return getRuleWithResponse(topicName, subscriptionName, ruleName).map(response -> response.getValue());
}
/**
* Gets a rule from the service namespace.
*
* Only following data types are deserialized in Filters and Action parameters - string, int, long, bool, double,
* and OffsetDateTime. Other data types would return its string value.
*
* @param topicName The name of the topic relative to service bus namespace.
* @param subscriptionName The subscription name the rule belongs to.
* @param ruleName The name of the rule to retrieve.
*
* @return The associated rule with the corresponding HTTP response.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<RuleProperties>> getRuleWithResponse(String topicName, String subscriptionName,
String ruleName) {
return withContext(context -> getRuleWithResponse(topicName, subscriptionName, ruleName, context));
}
/**
* Gets information about the queue.
*
* @param topicName Name of topic associated with subscription.
* @param subscriptionName Name of subscription to get information about.
*
* @return A Mono that completes with information about the subscription.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} are empty strings.
* @throws NullPointerException if {@code topicName} or {@code subscriptionName} are null.
* @throws ResourceNotFoundException if the {@code subscriptionName} does not exist in the {@code topicName}.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<SubscriptionProperties> getSubscription(String topicName, String subscriptionName) {
return getSubscriptionWithResponse(topicName, subscriptionName).map(Response::getValue);
}
/**
* Gets information about the subscription along with its HTTP response.
*
* @param topicName Name of topic associated with subscription.
* @param subscriptionName Name of subscription to get information about.
*
* @return A Mono that completes with information about the subscription and the associated HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} are empty strings.
* @throws NullPointerException if {@code topicName} or {@code subscriptionName} are null.
* @throws ResourceNotFoundException if the {@code subscriptionName} does not exist.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<SubscriptionProperties>> getSubscriptionWithResponse(String topicName,
String subscriptionName) {
return withContext(context -> getSubscriptionWithResponse(topicName, subscriptionName, context,
Function.identity()));
}
/**
* Gets whether or not a subscription within a topic exists.
*
* @param topicName Name of topic associated with subscription.
* @param subscriptionName Name of the subscription.
*
* @return A Mono that completes indicating whether or not the subscription exists.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code subscriptionName} is an empty string.
* @throws NullPointerException if {@code subscriptionName} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Boolean> getSubscriptionExists(String topicName, String subscriptionName) {
return getSubscriptionExistsWithResponse(topicName, subscriptionName).map(Response::getValue);
}
/**
* Gets whether or not a subscription within a topic exists.
*
* @param topicName Name of topic associated with subscription.
* @param subscriptionName Name of the subscription.
*
* @return A Mono that completes indicating whether or not the subscription exists along with its HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code subscriptionName} is an empty string.
* @throws NullPointerException if {@code subscriptionName} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Boolean>> getSubscriptionExistsWithResponse(String topicName, String subscriptionName) {
return getEntityExistsWithResponse(getSubscriptionWithResponse(topicName, subscriptionName));
}
/**
* Gets runtime properties about the subscription.
*
* @param topicName Name of topic associated with subscription.
* @param subscriptionName Name of subscription to get information about.
*
* @return A Mono that completes with runtime properties about the subscription.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} are empty strings.
* @throws NullPointerException if {@code topicName} or {@code subscriptionName} are null.
* @throws ResourceNotFoundException if the {@code subscriptionName} does not exist.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<SubscriptionRuntimeProperties> getSubscriptionRuntimeProperties(
String topicName, String subscriptionName) {
return getSubscriptionRuntimePropertiesWithResponse(topicName, subscriptionName)
.map(response -> response.getValue());
}
/**
* Gets runtime properties about the subscription.
*
* @param topicName Name of topic associated with subscription.
* @param subscriptionName Name of subscription to get information about.
*
* @return A Mono that completes with runtime properties about the subscription.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code subscriptionName} is an empty string.
* @throws NullPointerException if {@code subscriptionName} is null.
* @throws ResourceNotFoundException if the {@code subscriptionName} does not exist.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<SubscriptionRuntimeProperties>> getSubscriptionRuntimePropertiesWithResponse(
String topicName, String subscriptionName) {
return withContext(context -> getSubscriptionWithResponse(topicName, subscriptionName, context,
SubscriptionRuntimeProperties::new));
}
/**
* Gets information about the topic.
*
* @param topicName Name of topic to get information about.
*
* @return A Mono that completes with information about the topic.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code topicName} is an empty string.
* @throws NullPointerException if {@code topicName} is null.
* @throws ResourceNotFoundException if the {@code topicName} does not exist.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<TopicProperties> getTopic(String topicName) {
return getTopicWithResponse(topicName).map(Response::getValue);
}
/**
* Gets information about the topic along with its HTTP response.
*
* @param topicName Name of topic to get information about.
*
* @return A Mono that completes with information about the topic and the associated HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code topicName} is an empty string.
* @throws NullPointerException if {@code topicName} is null.
* @throws ResourceNotFoundException if the {@code topicName} does not exist.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<TopicProperties>> getTopicWithResponse(String topicName) {
return withContext(context -> getTopicWithResponse(topicName, context, Function.identity()));
}
/**
* Gets whether or not a topic with {@code topicName} exists in the Service Bus namespace.
*
* @param topicName Name of the topic.
*
* @return A Mono that completes indicating whether or not the topic exists.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code topicName} is an empty string.
* @throws NullPointerException if {@code topicName} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Boolean> getTopicExists(String topicName) {
return getTopicExistsWithResponse(topicName).map(Response::getValue);
}
/**
* Gets whether or not a topic with {@code topicName} exists in the Service Bus namespace.
*
* @param topicName Name of the topic.
*
* @return A Mono that completes indicating whether or not the topic exists along with its HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code topicName} is an empty string.
* @throws NullPointerException if {@code topicName} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Boolean>> getTopicExistsWithResponse(String topicName) {
return getEntityExistsWithResponse(getTopicWithResponse(topicName));
}
/**
* Gets runtime properties about the topic.
*
* @param topicName Name of topic to get information about.
*
* @return A Mono that completes with runtime properties about the topic.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code topicName} is an empty string.
* @throws NullPointerException if {@code topicName} is null.
* @throws ResourceNotFoundException if the {@code topicName} does not exist.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<TopicRuntimeProperties> getTopicRuntimeProperties(String topicName) {
return getTopicRuntimePropertiesWithResponse(topicName).map(response -> response.getValue());
}
/**
* Gets runtime properties about the topic with its HTTP response.
*
* @param topicName Name of topic to get information about.
*
* @return A Mono that completes with runtime properties about the topic and the associated HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code topicName} is an empty string.
* @throws NullPointerException if {@code topicName} is null.
* @throws ResourceNotFoundException if the {@code topicName} does not exist.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<TopicRuntimeProperties>> getTopicRuntimePropertiesWithResponse(String topicName) {
return withContext(context -> getTopicWithResponse(topicName, context, TopicRuntimeProperties::new));
}
/**
* Fetches all the queues in the Service Bus namespace.
*
* @return A Flux of {@link QueueProperties queues} in the Service Bus namespace.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @see <a href="https:
* authorization rules</a>
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux<QueueProperties> listQueues() {
return new PagedFlux<>(
() -> withContext(context -> listQueuesFirstPage(context)),
token -> withContext(context -> listQueuesNextPage(token, context)));
}
/**
* Fetches all the rules for a topic and subscription.
*
* @param topicName The topic name under which all the rules need to be retrieved.
* @param subscriptionName The name of the subscription for which all rules need to be retrieved.
*
* @return A Flux of {@link RuleProperties rules} for the {@code topicName} and {@code subscriptionName}.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws NullPointerException if {@code topicName} or {@code subscriptionName} is null.
* @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} is an empty string.
* @see <a href="https:
* authorization rules</a>
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux<RuleProperties> listRules(String topicName, String subscriptionName) {
if (topicName == null) {
return pagedFluxError(logger, new NullPointerException("'topicName' cannot be null."));
} else if (topicName.isEmpty()) {
return pagedFluxError(logger, new IllegalArgumentException("'topicName' cannot be an empty string."));
}
return new PagedFlux<>(
() -> withContext(context -> listRulesFirstPage(topicName, subscriptionName, context)),
token -> withContext(context -> listRulesNextPage(topicName, subscriptionName, token, context)));
}
/**
* Fetches all the subscriptions for a topic.
*
* @param topicName The topic name under which all the subscriptions need to be retrieved.
*
* @return A Flux of {@link SubscriptionProperties subscriptions} for the {@code topicName}.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws NullPointerException if {@code topicName} is null.
* @throws IllegalArgumentException if {@code topicName} is an empty string.
* @see <a href="https:
* authorization rules</a>
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux<SubscriptionProperties> listSubscriptions(String topicName) {
if (topicName == null) {
return pagedFluxError(logger, new NullPointerException("'topicName' cannot be null."));
} else if (topicName.isEmpty()) {
return pagedFluxError(logger, new IllegalArgumentException("'topicName' cannot be an empty string."));
}
return new PagedFlux<>(
() -> withContext(context -> listSubscriptionsFirstPage(topicName, context)),
token -> withContext(context -> listSubscriptionsNextPage(topicName, token, context)));
}
/**
* Fetches all the topics in the Service Bus namespace.
*
* @return A Flux of {@link TopicProperties topics} in the Service Bus namespace.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @see <a href="https:
* authorization rules</a>
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux<TopicProperties> listTopics() {
return new PagedFlux<>(
() -> withContext(context -> listTopicsFirstPage(context)),
token -> withContext(context -> listTopicsNextPage(token, context)));
}
/**
* Updates a queue with the given {@link QueueProperties}. The {@link QueueProperties} must be fully populated as
* all of the properties are replaced. If a property is not set the service default value is used.
*
* The suggested flow is:
* <ol>
* <li>{@link
* <li>Update the required elements.</li>
* <li>Pass the updated description into this method.</li>
* </ol>
*
* <p>
* There are a subset of properties that can be updated. More information can be found in the links below. They are:
* <ul>
* <li>{@link QueueProperties
* <li>{@link QueueProperties
* <li>{@link QueueProperties
* </li>
* <li>{@link QueueProperties
* </ul>
*
* @param queue Information about the queue to update. You must provide all the property values that are desired
* on the updated entity. Any values not provided are set to the service default values.
*
* @return A Mono that completes with the updated queue.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If the request body was invalid, the queue quota is exceeded, or an error
* occurred processing the request.
* @throws NullPointerException if {@code queue} is null.
* @see <a href="https:
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<QueueProperties> updateQueue(QueueProperties queue) {
return updateQueueWithResponse(queue).map(Response::getValue);
}
/**
* Updates a queue with the given {@link QueueProperties}. The {@link QueueProperties} must be fully populated as
* all of the properties are replaced. If a property is not set the service default value is used.
*
* The suggested flow is:
* <ol>
* <li>{@link
* <li>Update the required elements.</li>
* <li>Pass the updated description into this method.</li>
* </ol>
*
* <p>
* There are a subset of properties that can be updated. More information can be found in the links below. They are:
* <ul>
* <li>{@link QueueProperties
* <li>{@link QueueProperties
* <li>{@link QueueProperties
* </li>
* <li>{@link QueueProperties
* </ul>
*
* @param queue Information about the queue to update. You must provide all the property values that are desired
* on the updated entity. Any values not provided are set to the service default values.
*
* @return A Mono that returns the updated queue in addition to the HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If the request body was invalid, the queue quota is exceeded, or an error
* occurred processing the request.
* @throws NullPointerException if {@code queue} is null.
* @see <a href="https:
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<QueueProperties>> updateQueueWithResponse(QueueProperties queue) {
return withContext(context -> updateQueueWithResponse(queue, context));
}
/**
* Updates a rule with the given {@link RuleProperties}. The {@link RuleProperties} must be fully populated as all
* of the properties are replaced. If a property is not set the service default value is used.
*
* The suggested flow is:
* <ol>
* <li>{@link
* <li>Update the required elements.</li>
* <li>Pass the updated description into this method.</li>
* </ol>
*
* @param topicName The topic name under which the rule is updated.
* @param subscriptionName The name of the subscription for which the rule is updated.
* @param rule Information about the rule to update. You must provide all the property values that are desired
* on the updated entity. Any values not provided are set to the service default values.
*
* @return A Mono that returns the updated rule.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If the request body was invalid, the rule quota is exceeded, or an error
* occurred processing the request.
* @throws IllegalArgumentException if {@link RuleProperties
* @throws NullPointerException if {@code rule} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<RuleProperties> updateRule(String topicName, String subscriptionName, RuleProperties rule) {
return updateRuleWithResponse(topicName, subscriptionName, rule).map(Response::getValue);
}
/**
* Updates a rule with the given {@link RuleProperties}. The {@link RuleProperties} must be fully populated as all
* of the properties are replaced. If a property is not set the service default value is used.
*
* The suggested flow is:
* <ol>
* <li>{@link
* <li>Update the required elements.</li>
* <li>Pass the updated description into this method.</li>
* </ol>
*
* @param topicName The topic name under which the rule is updated.
* @param subscriptionName The name of the subscription for which the rule is updated.
* @param rule Information about the rule to update. You must provide all the property values that are desired
* on the updated entity. Any values not provided are set to the service default values.
*
* @return A Mono that returns the updated rule in addition to the HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If the request body was invalid, the rule quota is exceeded, or an error
* occurred processing the request.
* @throws IllegalArgumentException if {@link RuleProperties
* @throws NullPointerException if {@code rule} is null.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<RuleProperties>> updateRuleWithResponse(String topicName, String subscriptionName,
RuleProperties rule) {
return withContext(context -> updateRuleWithResponse(topicName, subscriptionName, rule, context));
}
/**
* Updates a subscription with the given {@link SubscriptionProperties}. The {@link SubscriptionProperties} must be
* fully populated as all of the properties are replaced. If a property is not set the service default value is
* used.
*
* The suggested flow is:
* <ol>
* <li>{@link
* <li>Update the required elements.</li>
* <li>Pass the updated description into this method.</li>
* </ol>
*
* <p>
* There are a subset of properties that can be updated. More information can be found in the links below. They are:
* <ul>
* <li>{@link SubscriptionProperties
* <li>{@link SubscriptionProperties
* <li>{@link SubscriptionProperties
* </ul>
*
* @param subscription Information about the subscription to update. You must provide all the property values
* that are desired on the updated entity. Any values not provided are set to the service default values.
*
* @return A Mono that returns the updated subscription.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If the request body was invalid, the subscription quota is exceeded, or an
* error occurred processing the request.
* @throws IllegalArgumentException if {@link SubscriptionProperties
* SubscriptionProperties
* @throws NullPointerException if {@code subscription} is null.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<SubscriptionProperties> updateSubscription(SubscriptionProperties subscription) {
return updateSubscriptionWithResponse(subscription).map(Response::getValue);
}
/**
* Updates a subscription with the given {@link SubscriptionProperties}. The {@link SubscriptionProperties} must be
* fully populated as all of the properties are replaced. If a property is not set the service default value is
* used.
*
* The suggested flow is:
* <ol>
* <li>{@link
* <li>Update the required elements.</li>
* <li>Pass the updated description into this method.</li>
* </ol>
*
* <p>
* There are a subset of properties that can be updated. More information can be found in the links below. They are:
* <ul>
* <li>{@link SubscriptionProperties
* <li>{@link SubscriptionProperties
* <li>{@link SubscriptionProperties
* </ul>
*
* @param subscription Information about the subscription to update. You must provide all the property values
* that are desired on the updated entity. Any values not provided are set to the service default values.
*
* @return A Mono that returns the updated subscription in addition to the HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If the request body was invalid, the subscription quota is exceeded, or an
* error occurred processing the request.
* @throws IllegalArgumentException if {@link SubscriptionProperties
* SubscriptionProperties
* @throws NullPointerException if {@code subscription} is null.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<SubscriptionProperties>> updateSubscriptionWithResponse(
SubscriptionProperties subscription) {
return withContext(context -> updateSubscriptionWithResponse(subscription, context));
}
/**
* Updates a topic with the given {@link TopicProperties}. The {@link TopicProperties} must be fully populated as
* all of the properties are replaced. If a property is not set the service default value is used.
*
* The suggested flow is:
* <ol>
* <li>{@link
* <li>Update the required elements.</li>
* <li>Pass the updated description into this method.</li>
* </ol>
*
* <p>
* There are a subset of properties that can be updated. More information can be found in the links below. They are:
* <ul>
* <li>{@link TopicProperties
* <li>{@link TopicProperties
* </li>
* </ul>
*
* @param topic Information about the topic to update. You must provide all the property values that are desired
* on the updated entity. Any values not provided are set to the service default values.
*
* @return A Mono that completes with the updated topic.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If the request body was invalid, the topic quota is exceeded, or an error
* occurred processing the request.
* @throws IllegalArgumentException if {@link TopicProperties
* string.
* @throws NullPointerException if {@code topic} is null.
* @see <a href="https:
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<TopicProperties> updateTopic(TopicProperties topic) {
return updateTopicWithResponse(topic).map(Response::getValue);
}
/**
* Updates a topic with the given {@link TopicProperties}. The {@link TopicProperties} must be fully populated as
* all of the properties are replaced. If a property is not set the service default value is used.
*
* The suggested flow is:
* <ol>
* <li>{@link
* <li>Update the required elements.</li>
* <li>Pass the updated description into this method.</li>
* </ol>
*
* <p>
* There are a subset of properties that can be updated. More information can be found in the links below. They are:
* <ul>
* <li>{@link TopicProperties
* <li>{@link TopicProperties
* </li>
* </ul>
*
* @param topic Information about the topic to update. You must provide all the property values that are desired
* on the updated entity. Any values not provided are set to the service default values.
*
* @return A Mono that completes with the updated topic and its HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If the request body was invalid, the topic quota is exceeded, or an error
* occurred processing the request.
* @throws IllegalArgumentException if {@link TopicProperties
* string.
* @throws NullPointerException if {@code topic} is null.
* @see <a href="https:
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<TopicProperties>> updateTopicWithResponse(TopicProperties topic) {
return withContext(context -> updateTopicWithResponse(topic, context));
}
/**
* Creates a queue with its context.
*
* @param createQueueOptions Queue to create.
* @param context Context to pass into request.
*
* @return A Mono that completes with the created {@link QueueProperties}.
*/
Mono<Response<QueueProperties>> createQueueWithResponse(String queueName, CreateQueueOptions createQueueOptions,
Context context) {
if (queueName == null) {
return monoError(logger, new NullPointerException("'queueName' cannot be null."));
} else if (queueName.isEmpty()) {
return monoError(logger, new IllegalArgumentException("'queueName' cannot be empty."));
}
if (createQueueOptions == null) {
return monoError(logger, new NullPointerException("'createQueueOptions' cannot be null."));
} else if (context == null) {
return monoError(logger, new NullPointerException("'context' cannot be null."));
}
final QueueDescription description = EntityHelper.getQueueDescription(createQueueOptions);
final CreateQueueBodyContent content = new CreateQueueBodyContent()
.setType(CONTENT_TYPE)
.setQueueDescription(description);
final CreateQueueBody createEntity = new CreateQueueBody()
.setContent(content);
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
try {
return entityClient.putWithResponseAsync(queueName, createEntity, null, withTracing)
.onErrorMap(ServiceBusAdministrationAsyncClient::mapException)
.map(this::deserializeQueue);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Creates a rule with its context.
*
* @param ruleOptions Rule to create.
* @param context Context to pass into request.
*
* @return A Mono that completes with the created {@link RuleProperties}.
*/
Mono<Response<RuleProperties>> createRuleWithResponse(String topicName, String subscriptionName, String ruleName,
CreateRuleOptions ruleOptions, Context context) {
if (topicName == null) {
return monoError(logger, new NullPointerException("'topicName' cannot be null."));
} else if (topicName.isEmpty()) {
return monoError(logger, new IllegalArgumentException("'topicName' cannot be empty."));
}
if (subscriptionName == null) {
return monoError(logger, new NullPointerException("'subscriptionName' cannot be null."));
} else if (subscriptionName.isEmpty()) {
return monoError(logger, new IllegalArgumentException("'subscriptionName' cannot be empty."));
}
if (ruleName == null) {
return monoError(logger, new NullPointerException("'ruleName' cannot be null."));
} else if (ruleName.isEmpty()) {
return monoError(logger, new IllegalArgumentException("'ruleName' cannot be empty."));
}
if (ruleOptions == null) {
return monoError(logger, new NullPointerException("'rule' cannot be null."));
}
final RuleActionImpl action = ruleOptions.getAction() != null
? EntityHelper.toImplementation(ruleOptions.getAction())
: null;
final RuleFilterImpl filter = ruleOptions.getFilter() != null
? EntityHelper.toImplementation(ruleOptions.getFilter())
: null;
final RuleDescription rule = new RuleDescription()
.setAction(action)
.setFilter(filter)
.setName(ruleName);
final CreateRuleBodyContent content = new CreateRuleBodyContent()
.setType(CONTENT_TYPE)
.setRuleDescription(rule);
final CreateRuleBody createEntity = new CreateRuleBody().setContent(content);
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
try {
return managementClient.getRules().putWithResponseAsync(topicName, subscriptionName, ruleName, createEntity,
null, withTracing)
.onErrorMap(ServiceBusAdministrationAsyncClient::mapException)
.map(response -> deserializeRule(response));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Creates a subscription with its context.
*
* @param subscriptionOptions Subscription to create.
* @param context Context to pass into request.
*
* @return A Mono that completes with the created {@link SubscriptionProperties}.
*/
Mono<Response<SubscriptionProperties>> createSubscriptionWithResponse(String topicName, String subscriptionName,
CreateSubscriptionOptions subscriptionOptions, Context context) {
if (topicName == null) {
return monoError(logger, new NullPointerException("'topicName' cannot be null."));
} else if (topicName.isEmpty()) {
return monoError(logger, new IllegalArgumentException("'topicName' cannot be empty."));
}
if (subscriptionName == null) {
return monoError(logger, new NullPointerException("'subscriptionName' cannot be null."));
} else if (subscriptionName.isEmpty()) {
return monoError(logger, new IllegalArgumentException("'subscriptionName' cannot be empty."));
}
if (subscriptionOptions == null) {
return monoError(logger, new NullPointerException("'subscription' cannot be null."));
}
final SubscriptionDescription subscription = EntityHelper.getSubscriptionDescription(subscriptionOptions);
final CreateSubscriptionBodyContent content = new CreateSubscriptionBodyContent()
.setType(CONTENT_TYPE)
.setSubscriptionDescription(subscription);
final CreateSubscriptionBody createEntity = new CreateSubscriptionBody().setContent(content);
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
try {
return managementClient.getSubscriptions().putWithResponseAsync(topicName, subscriptionName, createEntity,
null, withTracing)
.onErrorMap(ServiceBusAdministrationAsyncClient::mapException)
.map(response -> deserializeSubscription(topicName, response));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Creates a topicOptions with its context.
*
* @param topicOptions Topic to create.
* @param context Context to pass into request.
*
* @return A Mono that completes with the created {@link TopicProperties}.
*/
Mono<Response<TopicProperties>> createTopicWithResponse(String topicName, CreateTopicOptions topicOptions,
Context context) {
if (topicName == null) {
return monoError(logger, new NullPointerException("'topicName' cannot be null."));
} else if (topicName.isEmpty()) {
return monoError(logger, new IllegalArgumentException("'topicName' cannot be empty."));
}
if (topicOptions == null) {
return monoError(logger, new NullPointerException("'topicOptions' cannot be null"));
} else if (context == null) {
return monoError(logger, new NullPointerException("'context' cannot be null."));
}
final TopicDescription topic = EntityHelper.getTopicDescription(topicOptions);
final CreateTopicBodyContent content = new CreateTopicBodyContent()
.setType(CONTENT_TYPE)
.setTopicDescription(topic);
final CreateTopicBody createEntity = new CreateTopicBody()
.setContent(content);
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
try {
return entityClient.putWithResponseAsync(topicName, createEntity, null, withTracing)
.onErrorMap(ServiceBusAdministrationAsyncClient::mapException)
.map(this::deserializeTopic);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Deletes a queue with its context.
*
* @param queueName Name of queue to delete.
* @param context Context to pass into request.
*
* @return A Mono that completes when the queue is deleted.
*/
Mono<Response<Void>> deleteQueueWithResponse(String queueName, Context context) {
if (queueName == null) {
return monoError(logger, new NullPointerException("'queueName' cannot be null"));
} else if (queueName.isEmpty()) {
return monoError(logger, new IllegalArgumentException("'queueName' cannot be an empty string."));
} else if (context == null) {
return monoError(logger, new NullPointerException("'context' cannot be null."));
}
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
try {
return entityClient.deleteWithResponseAsync(queueName, withTracing)
.onErrorMap(ServiceBusAdministrationAsyncClient::mapException)
.map(response -> {
return new SimpleResponse<>(response.getRequest(), response.getStatusCode(),
response.getHeaders(), null);
});
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Deletes a queue with its context.
*
* @param topicName Name of topic to delete.
* @param subscriptionName Name of the subscription for the rule.
* @param ruleName Name of the rule.
* @param context Context to pass into request.
*
* @return A Mono that completes with the created {@link QueueProperties}.
*/
Mono<Response<Void>> deleteRuleWithResponse(String topicName, String subscriptionName, String ruleName,
Context context) {
if (topicName == null) {
return monoError(logger, new NullPointerException("'topicName' cannot be null"));
} else if (topicName.isEmpty()) {
return monoError(logger, new IllegalArgumentException("'topicName' cannot be an empty string."));
} else if (subscriptionName == null) {
return monoError(logger, new NullPointerException("'subscriptionName' cannot be null"));
} else if (subscriptionName.isEmpty()) {
return monoError(logger, new IllegalArgumentException("'subscriptionName' cannot be an empty string."));
} else if (ruleName == null) {
return monoError(logger, new NullPointerException("'ruleName' cannot be null"));
} else if (ruleName.isEmpty()) {
return monoError(logger, new IllegalArgumentException("'ruleName' cannot be an empty string."));
} else if (context == null) {
return monoError(logger, new NullPointerException("'context' cannot be null."));
}
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
try {
return rulesClient.deleteWithResponseAsync(topicName, subscriptionName, ruleName, withTracing)
.onErrorMap(ServiceBusAdministrationAsyncClient::mapException)
.map(response -> new SimpleResponse<>(response.getRequest(), response.getStatusCode(),
response.getHeaders(), null));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Deletes a subscription with its context.
*
* @param topicName Name of topic associated with subscription to delete.
* @param subscriptionName Name of subscription to delete.
* @param context Context to pass into request.
*
* @return A Mono that completes with the created {@link SubscriptionProperties}.
*/
Mono<Response<Void>> deleteSubscriptionWithResponse(String topicName, String subscriptionName, Context context) {
if (subscriptionName == null) {
return monoError(logger, new NullPointerException("'subscriptionName' cannot be null"));
} else if (subscriptionName.isEmpty()) {
return monoError(logger, new IllegalArgumentException("'subscriptionName' cannot be an empty string."));
} else if (topicName == null) {
return monoError(logger, new NullPointerException("'topicName' cannot be null"));
} else if (topicName.isEmpty()) {
return monoError(logger, new IllegalArgumentException("'topicName' cannot be an empty string."));
} else if (context == null) {
return monoError(logger, new NullPointerException("'context' cannot be null."));
}
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
try {
return managementClient.getSubscriptions().deleteWithResponseAsync(topicName, subscriptionName,
withTracing)
.onErrorMap(ServiceBusAdministrationAsyncClient::mapException)
.map(response -> new SimpleResponse<>(response.getRequest(), response.getStatusCode(),
response.getHeaders(), null));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Deletes a topic with its context.
*
* @param topicName Name of topic to delete.
* @param context Context to pass into request.
*
* @return A Mono that completes with the created {@link TopicProperties}.
*/
Mono<Response<Void>> deleteTopicWithResponse(String topicName, Context context) {
if (topicName == null) {
return monoError(logger, new NullPointerException("'topicName' cannot be null"));
} else if (topicName.isEmpty()) {
return monoError(logger, new IllegalArgumentException("'topicName' cannot be an empty string."));
} else if (context == null) {
return monoError(logger, new NullPointerException("'context' cannot be null."));
}
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
try {
return entityClient.deleteWithResponseAsync(topicName, withTracing)
.onErrorMap(ServiceBusAdministrationAsyncClient::mapException)
.map(response -> new SimpleResponse<>(response.getRequest(), response.getStatusCode(),
response.getHeaders(), null));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Gets whether an entity exists.
*
* @param getEntityOperation Operation to get information about entity. If {@link ResourceNotFoundException} is
* thrown, then it is mapped to false.
* @param <T> Entity type.
*
* @return True if the entity exists, false otherwise.
*/
<T> Mono<Response<Boolean>> getEntityExistsWithResponse(Mono<Response<T>> getEntityOperation) {
return getEntityOperation.map(response -> {
final boolean exists = response.getValue() != null;
return (Response<Boolean>) new SimpleResponse<>(response.getRequest(), response.getStatusCode(),
response.getHeaders(), exists);
})
.onErrorResume(ResourceNotFoundException.class, exception -> {
final HttpResponse response = exception.getResponse();
final Response<Boolean> result = new SimpleResponse<>(response.getRequest(), response.getStatusCode(),
response.getHeaders(), false);
return Mono.just(result);
});
}
/**
* Gets a queue with its context.
*
* @param queueName Name of queue to fetch information for.
* @param context Context to pass into request.
*
* @return A Mono that completes with the {@link QueueProperties}.
*/
<T> Mono<Response<T>> getQueueWithResponse(String queueName, Context context,
Function<QueueProperties, T> mapper) {
if (queueName == null) {
return monoError(logger, new NullPointerException("'queueName' cannot be null"));
} else if (queueName.isEmpty()) {
return monoError(logger, new IllegalArgumentException("'queueName' cannot be empty."));
} else if (context == null) {
return monoError(logger, new NullPointerException("'context' cannot be null."));
}
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
try {
return entityClient.getWithResponseAsync(queueName, true, withTracing)
.onErrorMap(ServiceBusAdministrationAsyncClient::mapException)
.handle((response, sink) -> {
final Response<QueueProperties> deserialize = deserializeQueue(response);
if (deserialize.getValue() == null) {
final HttpResponse notFoundResponse = new EntityNotFoundHttpResponse<>(deserialize);
sink.error(new ResourceNotFoundException(String.format("Queue '%s' does not exist.", queueName),
notFoundResponse));
} else {
final T mapped = mapper.apply(deserialize.getValue());
sink.next(new SimpleResponse<>(response.getRequest(), response.getStatusCode(),
response.getHeaders(), mapped));
}
});
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<RuleProperties>> getRuleWithResponse(String topicName, String subscriptionName,
String ruleName, Context context) {
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
try {
return rulesClient.getWithResponseAsync(topicName, subscriptionName, ruleName, true, withTracing)
.onErrorMap(ServiceBusAdministrationAsyncClient::mapException)
.map(this::deserializeRule);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Gets a subscription with its context.
*
* @param topicName Name of the topic associated with the subscription.
* @param subscriptionName Name of subscription to fetch information for.
* @param context Context to pass into request.
*
* @return A Mono that completes with the {@link SubscriptionProperties}.
*/
<T> Mono<Response<T>> getSubscriptionWithResponse(String topicName, String subscriptionName, Context context,
Function<SubscriptionProperties, T> mapper) {
if (topicName == null) {
return monoError(logger, new NullPointerException("'topicName' cannot be null."));
} else if (topicName.isEmpty()) {
return monoError(logger, new IllegalArgumentException("'topicName' cannot be an empty string."));
} else if (subscriptionName == null) {
return monoError(logger, new NullPointerException("'subscriptionName' cannot be null."));
} else if (subscriptionName.isEmpty()) {
return monoError(logger, new IllegalArgumentException("'subscriptionName' cannot be an empty string."));
} else if (context == null) {
return monoError(logger, new NullPointerException("'context' cannot be null."));
}
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
try {
return managementClient.getSubscriptions().getWithResponseAsync(topicName, subscriptionName, true,
withTracing)
.onErrorMap(ServiceBusAdministrationAsyncClient::mapException)
.handle((response, sink) -> {
final Response<SubscriptionProperties> deserialize = deserializeSubscription(topicName, response);
if (deserialize.getValue() == null) {
final HttpResponse notFoundResponse = new EntityNotFoundHttpResponse<>(deserialize);
sink.error(new ResourceNotFoundException(String.format(
"Subscription '%s' in topic '%s' does not exist.", topicName, subscriptionName),
notFoundResponse));
} else {
final T mapped = mapper.apply(deserialize.getValue());
sink.next(new SimpleResponse<>(response.getRequest(), response.getStatusCode(),
response.getHeaders(), mapped));
}
});
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Gets the namespace properties with its context.
*
* @param context Context to pass into request.
*
* @return A Mono that completes with the {@link NamespaceProperties}.
*/
Mono<Response<NamespaceProperties>> getNamespacePropertiesWithResponse(Context context) {
return managementClient.getNamespaces().getWithResponseAsync(context).handle((response, sink) -> {
final NamespacePropertiesEntry entry = response.getValue();
if (entry == null || entry.getContent() == null) {
sink.error(new AzureException(
"There was no content inside namespace response. Entry: " + response));
return;
}
final NamespaceProperties namespaceProperties = entry.getContent().getNamespaceProperties();
final Response<NamespaceProperties> result = new SimpleResponse<>(response.getRequest(),
response.getStatusCode(), response.getHeaders(), namespaceProperties);
sink.next(result);
});
}
/**
* Gets a topic with its context.
*
* @param topicName Name of topic to fetch information for.
* @param context Context to pass into request.
*
* @return A Mono that completes with the {@link TopicProperties}.
*/
<T> Mono<Response<T>> getTopicWithResponse(String topicName, Context context,
Function<TopicProperties, T> mapper) {
if (topicName == null) {
return monoError(logger, new NullPointerException("'topicName' cannot be null"));
} else if (topicName.isEmpty()) {
return monoError(logger, new IllegalArgumentException("'topicName' cannot be empty."));
} else if (context == null) {
return monoError(logger, new NullPointerException("'context' cannot be null."));
}
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
try {
return entityClient.getWithResponseAsync(topicName, true, withTracing)
.onErrorMap(ServiceBusAdministrationAsyncClient::mapException)
.handle((response, sink) -> {
final Response<TopicProperties> deserialize = deserializeTopic(response);
if (deserialize.getValue() == null) {
final HttpResponse notFoundResponse = new EntityNotFoundHttpResponse<>(deserialize);
sink.error(new ResourceNotFoundException(String.format("Topic '%s' does not exist.", topicName),
notFoundResponse));
} else {
final T mapped = mapper.apply(deserialize.getValue());
sink.next(new SimpleResponse<>(response.getRequest(), response.getStatusCode(),
response.getHeaders(), mapped));
}
});
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Gets the first page of queues with context.
*
* @param context Context to pass into request.
*
* @return A Mono that completes with a page of queues.
*/
Mono<PagedResponse<QueueProperties>> listQueuesFirstPage(Context context) {
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
try {
return listQueues(0, withTracing);
} catch (RuntimeException e) {
return monoError(logger, e);
}
}
/**
* Gets the next page of queues with context.
*
* @param continuationToken Number of items to skip in feed.
* @param context Context to pass into request.
*
* @return A Mono that completes with a page of queues or empty if there are no items left.
*/
Mono<PagedResponse<QueueProperties>> listQueuesNextPage(String continuationToken, Context context) {
if (continuationToken == null || continuationToken.isEmpty()) {
return Mono.empty();
}
try {
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
final int skip = Integer.parseInt(continuationToken);
return listQueues(skip, withTracing);
} catch (RuntimeException e) {
return monoError(logger, e);
}
}
/**
* Gets the first page of rules with context.
*
* @param context Context to pass into request.
*
* @return A Mono that completes with a page of rules.
*/
Mono<PagedResponse<RuleProperties>> listRulesFirstPage(String topicName, String subscriptionName, Context context) {
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
try {
return listRules(topicName, subscriptionName, 0, withTracing);
} catch (RuntimeException e) {
return monoError(logger, e);
}
}
/**
* Gets the next page of rules with context.
*
* @param continuationToken Number of items to skip in feed.
* @param context Context to pass into request.
*
* @return A Mono that completes with a page of rules or empty if there are no items left.
*/
Mono<PagedResponse<RuleProperties>> listRulesNextPage(String topicName, String subscriptionName,
String continuationToken, Context context) {
if (continuationToken == null || continuationToken.isEmpty()) {
return Mono.empty();
}
try {
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
final int skip = Integer.parseInt(continuationToken);
return listRules(topicName, subscriptionName, skip, withTracing);
} catch (RuntimeException e) {
return monoError(logger, e);
}
}
/**
* Gets the first page of subscriptions with context.
*
* @param context Context to pass into request.
*
* @return A Mono that completes with a page of subscriptions.
*/
Mono<PagedResponse<SubscriptionProperties>> listSubscriptionsFirstPage(String topicName, Context context) {
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
try {
return listSubscriptions(topicName, 0, withTracing);
} catch (RuntimeException e) {
return monoError(logger, e);
}
}
/**
* Gets the next page of subscriptions with context.
*
* @param continuationToken Number of items to skip in feed.
* @param context Context to pass into request.
*
* @return A Mono that completes with a page of subscriptions or empty if there are no items left.
*/
Mono<PagedResponse<SubscriptionProperties>> listSubscriptionsNextPage(String topicName, String continuationToken,
Context context) {
if (continuationToken == null || continuationToken.isEmpty()) {
return Mono.empty();
}
try {
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
final int skip = Integer.parseInt(continuationToken);
return listSubscriptions(topicName, skip, withTracing);
} catch (RuntimeException e) {
return monoError(logger, e);
}
}
/**
* Gets the first page of topics with context.
*
* @param context Context to pass into request.
*
* @return A Mono that completes with a page of topics.
*/
Mono<PagedResponse<TopicProperties>> listTopicsFirstPage(Context context) {
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
try {
return listTopics(0, withTracing);
} catch (RuntimeException e) {
return monoError(logger, e);
}
}
/**
* Gets the next page of topics with context.
*
* @param continuationToken Number of items to skip in feed.
* @param context Context to pass into request.
*
* @return A Mono that completes with a page of topics or empty if there are no items left.
*/
Mono<PagedResponse<TopicProperties>> listTopicsNextPage(String continuationToken, Context context) {
if (continuationToken == null || continuationToken.isEmpty()) {
return Mono.empty();
}
try {
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
final int skip = Integer.parseInt(continuationToken);
return listTopics(skip, withTracing);
} catch (RuntimeException e) {
return monoError(logger, e);
}
}
/**
* Updates a queue with its context.
*
* @param queue Information about the queue to update. You must provide all the property values that are desired
* on the updated entity. Any values not provided are set to the service default values.
* @param context Context to pass into request.
*
* @return A Mono that completes with the updated {@link QueueProperties}.
*/
Mono<Response<QueueProperties>> updateQueueWithResponse(QueueProperties queue, Context context) {
if (queue == null) {
return monoError(logger, new NullPointerException("'queue' cannot be null"));
} else if (context == null) {
return monoError(logger, new NullPointerException("'context' cannot be null."));
}
final QueueDescription queueDescription = EntityHelper.toImplementation(queue);
final CreateQueueBodyContent content = new CreateQueueBodyContent()
.setType(CONTENT_TYPE)
.setQueueDescription(queueDescription);
final CreateQueueBody createEntity = new CreateQueueBody()
.setContent(content);
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
try {
return entityClient.putWithResponseAsync(queue.getName(), createEntity, "*", withTracing)
.onErrorMap(ServiceBusAdministrationAsyncClient::mapException)
.map(response -> deserializeQueue(response));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Updates a rule with its context.
*
* @param rule Information about the rule to update. You must provide all the property values that are desired
* on the updated entity. Any values not provided are set to the service default values.
* @param context Context to pass into request.
*
* @return A Mono that completes with the updated {@link RuleProperties}.
*/
Mono<Response<RuleProperties>> updateRuleWithResponse(String topicName, String subscriptionName,
RuleProperties rule, Context context) {
if (rule == null) {
return monoError(logger, new NullPointerException("'rule' cannot be null"));
} else if (context == null) {
return monoError(logger, new NullPointerException("'context' cannot be null."));
}
final RuleDescription implementation = EntityHelper.toImplementation(rule);
final CreateRuleBodyContent content = new CreateRuleBodyContent()
.setType(CONTENT_TYPE)
.setRuleDescription(implementation);
final CreateRuleBody ruleBody = new CreateRuleBody()
.setContent(content);
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
try {
return managementClient.getRules().putWithResponseAsync(topicName, subscriptionName, rule.getName(),
ruleBody, "*", withTracing)
.onErrorMap(ServiceBusAdministrationAsyncClient::mapException)
.map(response -> deserializeRule(response));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Updates a subscription with its context.
*
* @param subscription Information about the subscription to update. You must provide all the property values
* that are desired on the updated entity. Any values not provided are set to the service default values.
* @param context Context to pass into request.
*
* @return A Mono that completes with the updated {@link SubscriptionProperties}.
*/
Mono<Response<SubscriptionProperties>> updateSubscriptionWithResponse(SubscriptionProperties subscription,
Context context) {
if (subscription == null) {
return monoError(logger, new NullPointerException("'subscription' cannot be null"));
} else if (context == null) {
return monoError(logger, new NullPointerException("'context' cannot be null."));
}
final String topicName = subscription.getTopicName();
final String subscriptionName = subscription.getSubscriptionName();
final SubscriptionDescription implementation = EntityHelper.toImplementation(subscription);
final CreateSubscriptionBodyContent content = new CreateSubscriptionBodyContent()
.setType(CONTENT_TYPE)
.setSubscriptionDescription(implementation);
final CreateSubscriptionBody createEntity = new CreateSubscriptionBody()
.setContent(content);
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
try {
return managementClient.getSubscriptions().putWithResponseAsync(topicName, subscriptionName, createEntity,
"*", withTracing)
.onErrorMap(ServiceBusAdministrationAsyncClient::mapException)
.map(response -> deserializeSubscription(topicName, response));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Updates a topic with its context.
*
* @param topic Information about the topic to update. You must provide all the property values that are desired
* on the updated entity. Any values not provided are set to the service default values.
* @param context Context to pass into request.
*
* @return A Mono that completes with the updated {@link TopicProperties}.
*/
Mono<Response<TopicProperties>> updateTopicWithResponse(TopicProperties topic, Context context) {
if (topic == null) {
return monoError(logger, new NullPointerException("'topic' cannot be null"));
} else if (context == null) {
return monoError(logger, new NullPointerException("'context' cannot be null."));
}
final TopicDescription implementation = EntityHelper.toImplementation(topic);
final CreateTopicBodyContent content = new CreateTopicBodyContent()
.setType(CONTENT_TYPE)
.setTopicDescription(implementation);
final CreateTopicBody createEntity = new CreateTopicBody()
.setContent(content);
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
try {
return entityClient.putWithResponseAsync(topic.getName(), createEntity, "*", withTracing)
.onErrorMap(ServiceBusAdministrationAsyncClient::mapException)
.map(response -> deserializeTopic(response));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
private <T> T deserialize(Object object, Class<T> clazz) {
if (object == null) {
return null;
}
final String contents = String.valueOf(object);
if (contents.isEmpty()) {
return null;
}
try {
return serializer.deserialize(contents, clazz);
} catch (IOException e) {
throw logger.logExceptionAsError(new RuntimeException(String.format(
"Exception while deserializing. Body: [%s]. Class: %s", contents, clazz), e));
}
}
/**
* Given an HTTP response, will deserialize it into a strongly typed Response object.
*
* @param response HTTP response to deserialize response body from.
* @param clazz Class to deserialize response type into.
* @param <T> Class type to deserialize response into.
*
* @return A Response with a strongly typed response value.
*/
private <T> Response<T> deserialize(Response<Object> response, Class<T> clazz) {
final T deserialize = deserialize(response.getValue(), clazz);
return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(),
deserialize);
}
/**
* Converts a Response into its corresponding {@link QueueDescriptionEntry} then mapped into {@link
* QueueProperties}.
*
* @param response HTTP Response to deserialize.
*
* @return The corresponding HTTP response with convenience properties set.
*/
/**
* Converts a Response into its corresponding {@link RuleDescriptionEntry} then mapped into {@link RuleProperties}.
*
* @param response HTTP Response to deserialize.
*
* @return The corresponding HTTP response with convenience properties set.
*/
private Response<RuleProperties> deserializeRule(Response<Object> response) {
final RuleDescriptionEntry entry = deserialize(response.getValue(), RuleDescriptionEntry.class);
if (entry == null) {
return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null);
} else if (entry.getContent() == null) {
logger.info("entry.getContent() is null. The entity may not exist. {}", entry);
return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null);
}
final RuleDescription description = entry.getContent().getRuleDescription();
final RuleProperties result = EntityHelper.toModel(description);
return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), result);
}
/**
* Converts a Response into its corresponding {@link SubscriptionDescriptionEntry} then mapped into {@link
* SubscriptionProperties}.
*
* @param response HTTP Response to deserialize.
*
* @return The corresponding HTTP response with convenience properties set.
*/
private Response<SubscriptionProperties> deserializeSubscription(String topicName, Response<Object> response) {
final SubscriptionDescriptionEntry entry = deserialize(response.getValue(), SubscriptionDescriptionEntry.class);
if (entry == null) {
return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null);
} else if (entry.getContent() == null) {
logger.warning("entry.getContent() is null. There should have been content returned. Entry: {}", entry);
return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null);
}
final SubscriptionProperties subscription = EntityHelper.toModel(
entry.getContent().getSubscriptionDescription());
final String subscriptionName = getTitleValue(entry.getTitle());
EntityHelper.setSubscriptionName(subscription, subscriptionName);
EntityHelper.setTopicName(subscription, topicName);
return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(),
subscription);
}
/**
* Converts a Response into its corresponding {@link TopicDescriptionEntry} then mapped into {@link
* QueueProperties}.
*
* @param response HTTP Response to deserialize.
*
* @return The corresponding HTTP response with convenience properties set.
*/
private Response<TopicProperties> deserializeTopic(Response<Object> response) {
final TopicDescriptionEntry entry = deserialize(response.getValue(), TopicDescriptionEntry.class);
if (entry == null) {
return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null);
} else if (entry.getContent() == null) {
logger.warning("entry.getContent() is null. There should have been content returned. Entry: {}", entry);
return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null);
} else if (entry.getContent().getTopicDescription() == null) {
final QueueDescriptionEntry entryQueue = deserialize(response.getValue(), QueueDescriptionEntry.class);
if (entryQueue != null && entryQueue.getContent() != null && entryQueue.getContent().getQueueDescription() != null) {
logger.warning("'{}' is not a topic, it is a queue.", entryQueue.getTitle());
return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null);
}
}
final TopicProperties result = EntityHelper.toModel(entry.getContent().getTopicDescription());
final String topicName = getTitleValue(entry.getTitle());
EntityHelper.setTopicName(result, topicName);
return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), result);
}
/**
* Creates a {@link FeedPage} given the elements and a set of response links to get the next link from.
*
* @param entities Entities in the feed.
* @param responseLinks Links returned from the feed.
* @param <TResult> Type of Service Bus entities in page.
*
* @return A {@link FeedPage} indicating whether this can be continued or not.
* @throws MalformedURLException if the "next" page link does not contain a well-formed URL.
*/
private <TResult, TFeed> FeedPage<TResult> extractPage(Response<TFeed> response, List<TResult> entities,
List<ResponseLink> responseLinks)
throws MalformedURLException, UnsupportedEncodingException {
final Optional<ResponseLink> nextLink = responseLinks.stream()
.filter(link -> link.getRel().equalsIgnoreCase("next"))
.findFirst();
if (!nextLink.isPresent()) {
return new FeedPage<>(response.getStatusCode(), response.getHeaders(), response.getRequest(), entities);
}
final URL url = new URL(nextLink.get().getHref());
final String decode = URLDecoder.decode(url.getQuery(), StandardCharsets.UTF_8.name());
final Optional<Integer> skipParameter = Arrays.stream(decode.split("&|&"))
.map(part -> part.split("=", 2))
.filter(parts -> parts[0].equalsIgnoreCase("$skip") && parts.length == 2)
.map(parts -> Integer.valueOf(parts[1]))
.findFirst();
if (skipParameter.isPresent()) {
return new FeedPage<>(response.getStatusCode(), response.getHeaders(), response.getRequest(), entities,
skipParameter.get());
} else {
logger.warning("There should have been a skip parameter for the next page.");
return new FeedPage<>(response.getStatusCode(), response.getHeaders(), response.getRequest(), entities);
}
}
/**
* Helper method that invokes the service method, extracts the data and translates it to a PagedResponse.
*
* @param skip Number of elements to skip.
* @param context Context for the query.
*
* @return A Mono that completes with a paged response of queues.
*/
private Mono<PagedResponse<QueueProperties>> listQueues(int skip, Context context) {
return managementClient.listEntitiesWithResponseAsync(QUEUES_ENTITY_TYPE, skip, NUMBER_OF_ELEMENTS, context)
.onErrorMap(ServiceBusAdministrationAsyncClient::mapException)
.flatMap(response -> {
final Response<QueueDescriptionFeed> feedResponse = deserialize(response, QueueDescriptionFeed.class);
final QueueDescriptionFeed feed = feedResponse.getValue();
if (feed == null) {
logger.warning("Could not deserialize QueueDescriptionFeed. skip {}, top: {}", skip,
NUMBER_OF_ELEMENTS);
return Mono.empty();
}
final List<QueueProperties> entities = feed.getEntry().stream()
.filter(e -> e.getContent() != null && e.getContent().getQueueDescription() != null)
.map(e -> {
final String queueName = getTitleValue(e.getTitle());
final QueueProperties queueProperties = EntityHelper.toModel(
e.getContent().getQueueDescription());
EntityHelper.setQueueName(queueProperties, queueName);
return queueProperties;
})
.collect(Collectors.toList());
try {
return Mono.just(extractPage(feedResponse, entities, feed.getLink()));
} catch (MalformedURLException | UnsupportedEncodingException error) {
return Mono.error(new RuntimeException("Could not parse response into FeedPage<QueueDescription>",
error));
}
});
}
/**
* Helper method that invokes the service method, extracts the data and translates it to a PagedResponse.
*
* @param skip Number of elements to skip.
* @param context Context for the query.
*
* @return A Mono that completes with a paged response of rules.
*/
private Mono<PagedResponse<RuleProperties>> listRules(String topicName, String subscriptionName, int skip,
Context context) {
return managementClient.listRulesWithResponseAsync(topicName, subscriptionName, skip, NUMBER_OF_ELEMENTS,
context)
.onErrorMap(ServiceBusAdministrationAsyncClient::mapException)
.flatMap(response -> {
final Response<RuleDescriptionFeed> feedResponse = deserialize(response,
RuleDescriptionFeed.class);
final RuleDescriptionFeed feed = feedResponse.getValue();
if (feed == null) {
logger.warning("Could not deserialize RuleDescriptionFeed. skip {}, top: {}", skip,
NUMBER_OF_ELEMENTS);
return Mono.empty();
}
final List<RuleProperties> entities = feed.getEntry().stream()
.filter(e -> e.getContent() != null && e.getContent().getRuleDescription() != null)
.map(e -> {
return EntityHelper.toModel(e.getContent().getRuleDescription());
})
.collect(Collectors.toList());
try {
return Mono.just(extractPage(feedResponse, entities, feed.getLink()));
} catch (MalformedURLException | UnsupportedEncodingException error) {
return Mono.error(new RuntimeException(
"Could not parse response into FeedPage<RuleDescription>", error));
}
});
}
/**
* Helper method that invokes the service method, extracts the data and translates it to a PagedResponse.
*
* @param skip Number of elements to skip.
* @param context Context for the query.
*
* @return A Mono that completes with a paged response of subscriptions.
*/
private Mono<PagedResponse<SubscriptionProperties>> listSubscriptions(String topicName, int skip,
Context context) {
return managementClient.listSubscriptionsWithResponseAsync(topicName, skip, NUMBER_OF_ELEMENTS, context)
.onErrorMap(ServiceBusAdministrationAsyncClient::mapException)
.flatMap(response -> {
final Response<SubscriptionDescriptionFeed> feedResponse = deserialize(response,
SubscriptionDescriptionFeed.class);
final SubscriptionDescriptionFeed feed = feedResponse.getValue();
if (feed == null) {
logger.warning("Could not deserialize SubscriptionDescriptionFeed. skip {}, top: {}", skip,
NUMBER_OF_ELEMENTS);
return Mono.empty();
}
final List<SubscriptionProperties> entities = feed.getEntry().stream()
.filter(e -> e.getContent() != null && e.getContent().getSubscriptionDescription() != null)
.map(e -> {
final String subscriptionName = getTitleValue(e.getTitle());
final SubscriptionProperties description = EntityHelper.toModel(
e.getContent().getSubscriptionDescription());
EntityHelper.setTopicName(description, topicName);
EntityHelper.setSubscriptionName(description, subscriptionName);
return description;
})
.collect(Collectors.toList());
try {
return Mono.just(extractPage(feedResponse, entities, feed.getLink()));
} catch (MalformedURLException | UnsupportedEncodingException error) {
return Mono.error(new RuntimeException(
"Could not parse response into FeedPage<SubscriptionDescription>", error));
}
});
}
/**
* Helper method that invokes the service method, extracts the data and translates it to a PagedResponse.
*
* @param skip Number of elements to skip.
* @param context Context for the query.
*
* @return A Mono that completes with a paged response of topics.
*/
private Mono<PagedResponse<TopicProperties>> listTopics(int skip, Context context) {
return managementClient.listEntitiesWithResponseAsync(TOPICS_ENTITY_TYPE, skip, NUMBER_OF_ELEMENTS, context)
.onErrorMap(ServiceBusAdministrationAsyncClient::mapException)
.flatMap(response -> {
final Response<TopicDescriptionFeed> feedResponse = deserialize(response, TopicDescriptionFeed.class);
final TopicDescriptionFeed feed = feedResponse.getValue();
if (feed == null) {
logger.warning("Could not deserialize TopicDescriptionFeed. skip {}, top: {}", skip,
NUMBER_OF_ELEMENTS);
return Mono.empty();
}
final List<TopicProperties> entities = feed.getEntry().stream()
.filter(e -> e.getContent() != null && e.getContent().getTopicDescription() != null)
.map(e -> {
final String topicName = getTitleValue(e.getTitle());
final TopicProperties topicProperties = EntityHelper.toModel(
e.getContent().getTopicDescription());
EntityHelper.setTopicName(topicProperties, topicName);
return topicProperties;
})
.collect(Collectors.toList());
try {
return Mono.just(extractPage(feedResponse, entities, feed.getLink()));
} catch (MalformedURLException | UnsupportedEncodingException error) {
return Mono.error(new RuntimeException("Could not parse response into FeedPage<TopicDescription>",
error));
}
});
}
/**
* Given an XML title element, returns the XML text inside. Jackson deserializes Objects as LinkedHashMaps. XML text
* is represented as an entry with an empty string as the key.
*
* For example, the text returned from this {@code <title text="text/xml">QueueName</title>} is "QueueName".
*
* @param responseTitle XML title element.
*
* @return The XML text inside the title. {@code null} is returned if there is no value.
*/
@SuppressWarnings("unchecked")
private String getTitleValue(Object responseTitle) {
if (!(responseTitle instanceof Map)) {
return null;
}
final Map<String, String> map;
try {
map = (Map<String, String>) responseTitle;
return map.get("");
} catch (ClassCastException error) {
logger.warning("Unable to cast to Map<String,String>. Title: {}", responseTitle, error);
return null;
}
}
/**
* Maps an exception from the ATOM APIs to its associated {@link HttpResponseException}.
*
* @param exception Exception from the ATOM API.
*
* @return The corresponding {@link HttpResponseException} or {@code throwable} if it is not an instance of {@link
* ServiceBusManagementErrorException}.
*/
private static Throwable mapException(Throwable exception) {
if (!(exception instanceof ServiceBusManagementErrorException)) {
return exception;
}
final ServiceBusManagementErrorException managementError = ((ServiceBusManagementErrorException) exception);
final ServiceBusManagementError error = managementError.getValue();
final HttpResponse errorHttpResponse = managementError.getResponse();
final int statusCode = error != null && error.getCode() != null
? error.getCode()
: errorHttpResponse.getStatusCode();
final String errorDetail = error != null && error.getDetail() != null
? error.getDetail()
: managementError.getMessage();
switch (statusCode) {
case 401:
return new ClientAuthenticationException(errorDetail, managementError.getResponse(), exception);
case 404:
return new ResourceNotFoundException(errorDetail, managementError.getResponse(), exception);
case 409:
return new ResourceExistsException(errorDetail, managementError.getResponse(), exception);
case 412:
return new ResourceModifiedException(errorDetail, managementError.getResponse(), exception);
default:
return new HttpResponseException(errorDetail, managementError.getResponse(), exception);
}
}
/**
* A page of Service Bus entities.
*
* @param <T> The entity description from Service Bus.
*/
private static final class FeedPage<T> implements PagedResponse<T> {
private final int statusCode;
private final HttpHeaders header;
private final HttpRequest request;
private final IterableStream<T> entries;
private final String continuationToken;
/**
* Creates a page that does not have any more pages.
*
* @param entries Items in the page.
*/
private FeedPage(int statusCode, HttpHeaders header, HttpRequest request, List<T> entries) {
this.statusCode = statusCode;
this.header = header;
this.request = request;
this.entries = new IterableStream<>(entries);
this.continuationToken = null;
}
/**
* Creates an instance that has additional pages to fetch.
*
* @param entries Items in the page.
* @param skip Number of elements to "skip".
*/
private FeedPage(int statusCode, HttpHeaders header, HttpRequest request, List<T> entries, int skip) {
this.statusCode = statusCode;
this.header = header;
this.request = request;
this.entries = new IterableStream<>(entries);
this.continuationToken = String.valueOf(skip);
}
@Override
public IterableStream<T> getElements() {
return entries;
}
@Override
public String getContinuationToken() {
return continuationToken;
}
@Override
public int getStatusCode() {
return statusCode;
}
@Override
public HttpHeaders getHeaders() {
return header;
}
@Override
public HttpRequest getRequest() {
return request;
}
@Override
public void close() {
}
}
private static final class EntityNotFoundHttpResponse<T> extends HttpResponse {
private final int statusCode;
private final HttpHeaders headers;
private EntityNotFoundHttpResponse(Response<T> response) {
super(response.getRequest());
this.headers = response.getHeaders();
this.statusCode = response.getStatusCode();
}
@Override
public int getStatusCode() {
return statusCode;
}
@Override
public String getHeaderValue(String name) {
return headers.getValue(name);
}
@Override
public HttpHeaders getHeaders() {
return headers;
}
@Override
public Flux<ByteBuffer> getBody() {
return Flux.empty();
}
@Override
public Mono<byte[]> getBodyAsByteArray() {
return Mono.empty();
}
@Override
public Mono<String> getBodyAsString() {
return Mono.empty();
}
@Override
public Mono<String> getBodyAsString(Charset charset) {
return Mono.empty();
}
}
} |
Rather than a generic RuntimeException, can we throw HttpResponseException? The javadocs `@throws` needs to reflect this change. | private Response<QueueProperties> deserializeQueue(Response<Object> response) {
final QueueDescriptionEntry entry = deserialize(response.getValue(), QueueDescriptionEntry.class);
if (entry == null) {
return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null);
} else if (entry.getContent() == null) {
logger.info("entry.getContent() is null. The entity may not exist. {}", entry);
return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null);
} else if (entry.getContent().getQueueDescription() == null) {
final TopicDescriptionEntry entryTopic = deserialize(response.getValue(), TopicDescriptionEntry.class);
if (entryTopic != null && entryTopic.getContent() != null && entryTopic.getContent().getTopicDescription() != null) {
throw logger.logExceptionAsError(
new RuntimeException(String.format("'[%s]' is not a queue, it is a topic.", entryTopic.getTitle())));
}
}
final QueueProperties result = EntityHelper.toModel(entry.getContent().getQueueDescription());
final String queueName = getTitleValue(entry.getTitle());
EntityHelper.setQueueName(result, queueName);
return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), result);
} | new RuntimeException(String.format("'[%s]' is not a queue, it is a topic.", entryTopic.getTitle()))); | private Response<QueueProperties> deserializeQueue(Response<Object> response) {
final QueueDescriptionEntry entry = deserialize(response.getValue(), QueueDescriptionEntry.class);
if (entry == null) {
return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null);
} else if (entry.getContent() == null) {
logger.info("entry.getContent() is null. The entity may not exist. {}", entry);
return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null);
} else if (entry.getContent().getQueueDescription() == null) {
final TopicDescriptionEntry entryTopic = deserialize(response.getValue(), TopicDescriptionEntry.class);
if (entryTopic != null && entryTopic.getContent() != null && entryTopic.getContent().getTopicDescription() != null) {
logger.warning("'{}' is not a queue, it is a topic.", entryTopic.getTitle());
return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null);
}
}
final QueueProperties result = EntityHelper.toModel(entry.getContent().getQueueDescription());
final String queueName = getTitleValue(entry.getTitle());
EntityHelper.setQueueName(result, queueName);
return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), result);
} | class ServiceBusAdministrationAsyncClient {
private static final String SERVICE_BUS_TRACING_NAMESPACE_VALUE = "Microsoft.ServiceBus";
private static final String CONTENT_TYPE = "application/xml";
private static final String QUEUES_ENTITY_TYPE = "queues";
private static final String TOPICS_ENTITY_TYPE = "topics";
private static final int NUMBER_OF_ELEMENTS = 100;
private final ServiceBusManagementClientImpl managementClient;
private final EntitiesImpl entityClient;
private final ClientLogger logger = new ClientLogger(ServiceBusAdministrationAsyncClient.class);
private final ServiceBusManagementSerializer serializer;
private final RulesImpl rulesClient;
/**
* Creates a new instance with the given management client and serializer.
*
* @param managementClient Client to make management calls.
* @param serializer Serializer to deserialize ATOM XML responses.
*/
ServiceBusAdministrationAsyncClient(ServiceBusManagementClientImpl managementClient,
ServiceBusManagementSerializer serializer) {
this.serializer = Objects.requireNonNull(serializer, "'serializer' cannot be null.");
this.managementClient = Objects.requireNonNull(managementClient, "'managementClient' cannot be null.");
this.entityClient = managementClient.getEntities();
this.rulesClient = managementClient.getRules();
}
/**
* Creates a queue with the given name.
*
* @param queueName Name of the queue to create.
*
* @return A Mono that completes with information about the created queue.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If the request body was invalid, the queue quota is exceeded, or an error
* occurred processing the request.
* @throws NullPointerException if {@code queueName} is null.
* @throws IllegalArgumentException if {@code queueName} is an empty string.
* @throws ResourceExistsException if a queue exists with the same {@code queueName}.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<QueueProperties> createQueue(String queueName) {
try {
return createQueue(queueName, new CreateQueueOptions());
} catch (RuntimeException e) {
return monoError(logger, e);
}
}
/**
* Creates a queue with the {@link CreateQueueOptions} and given queue name.
*
* @param queueName Name of the queue to create.
* @param queueOptions Options about the queue to create.
*
* @return A Mono that completes with information about the created queue.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If the request body was invalid, the queue quota is exceeded, or an error
* occurred processing the request.
* @throws IllegalArgumentException if {@code queueName} is an empty string.
* @throws NullPointerException if {@code queueName} or {@code queueOptions} is null.
* @throws ResourceExistsException if a queue exists with the same {@link QueueProperties
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<QueueProperties> createQueue(String queueName, CreateQueueOptions queueOptions) {
return createQueueWithResponse(queueName, queueOptions).map(Response::getValue);
}
/**
* Creates a queue and returns the created queue in addition to the HTTP response.
*
* @param queueName Name of the queue to create.
* @param queueOptions Options about the queue to create.
*
* @return A Mono that returns the created queue in addition to the HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If the request body was invalid, the queue quota is exceeded, or an error
* occurred processing the request.
* @throws IllegalArgumentException if {@code queueName} is an empty string.
* @throws NullPointerException if {@code queueName} or {@code queueOptions} is null.
* @throws ResourceExistsException if a queue exists with the same {@link QueueProperties
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<QueueProperties>> createQueueWithResponse(String queueName, CreateQueueOptions queueOptions) {
return withContext(context -> createQueueWithResponse(queueName, queueOptions, context));
}
/**
* Creates a rule under the given topic and subscription
*
* @param topicName Name of the topic associated with rule.
* @param subscriptionName Name of the subscription associated with the rule.
* @param ruleName Name of the rule.
*
* @return A Mono that completes with information about the created rule.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If the request body was invalid, the quota is exceeded, or an error occurred
* processing the request.
* @throws IllegalArgumentException if {@code topicName} or {@code ruleName} are are empty strings.
* @throws NullPointerException if {@code topicName} or {@code ruleName} are are null.
* @throws ResourceExistsException if a rule exists with the same topic, subscription, and rule name.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<RuleProperties> createRule(String topicName, String subscriptionName, String ruleName) {
try {
return createRule(topicName, subscriptionName, ruleName, new CreateRuleOptions());
} catch (RuntimeException e) {
return monoError(logger, e);
}
}
/**
* Creates a rule with the {@link CreateRuleOptions}.
*
* @param topicName Name of the topic associated with rule.
* @param subscriptionName Name of the subscription associated with the rule.
* @param ruleName Name of the rule.
* @param ruleOptions Information about the rule to create.
*
* @return A Mono that completes with information about the created rule.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If the request body was invalid, the quota is exceeded, or an error occurred
* processing the request.
* @throws IllegalArgumentException if {@code topicName} or {@code ruleName} are are empty strings.
* @throws NullPointerException if {@code topicName}, {@code ruleName}, or {@code ruleOptions}
* are are null.
* @throws ResourceExistsException if a rule exists with the same topic and rule name.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<RuleProperties> createRule(String topicName, String subscriptionName, String ruleName,
CreateRuleOptions ruleOptions) {
return createRuleWithResponse(topicName, subscriptionName, ruleName, ruleOptions)
.map(Response::getValue);
}
/**
* Creates a rule and returns the created rule in addition to the HTTP response.
*
* @param topicName Name of the topic associated with rule.
* @param subscriptionName Name of the subscription associated with the rule.
* @param ruleName Name of the rule.
* @param ruleOptions Information about the rule to create.
*
* @return A Mono that returns the created rule in addition to the HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If the request body was invalid, the quota is exceeded, or an error occurred
* processing the request.
* @throws IllegalArgumentException if {@code topicName} or {@code ruleName} are are empty strings.
* @throws NullPointerException if {@code topicName}, {@code ruleName}, or {@code ruleOptions}
* are are null.
* @throws ResourceExistsException if a rule exists with the same topic and rule name.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<RuleProperties>> createRuleWithResponse(String topicName, String subscriptionName,
String ruleName, CreateRuleOptions ruleOptions) {
return withContext(context -> createRuleWithResponse(topicName, subscriptionName, ruleName, ruleOptions,
context));
}
/**
* Creates a subscription with the given topic and subscription names.
*
* @param topicName Name of the topic associated with subscription.
* @param subscriptionName Name of the subscription.
*
* @return A Mono that completes with information about the created subscription.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If the request body was invalid, the quota is exceeded, or an error occurred
* processing the request.
* @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} are are empty strings.
* @throws NullPointerException if {@code topicName} or {@code subscriptionName} are are null.
* @throws ResourceExistsException if a subscription exists with the same topic and subscription name.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<SubscriptionProperties> createSubscription(String topicName, String subscriptionName) {
try {
return createSubscription(topicName, subscriptionName, new CreateSubscriptionOptions());
} catch (RuntimeException e) {
return monoError(logger, e);
}
}
/**
* Creates a subscription with the {@link CreateSubscriptionOptions}.
*
* @param topicName Name of the topic associated with subscription.
* @param subscriptionName Name of the subscription.
* @param subscriptionOptions Information about the subscription to create.
*
* @return A Mono that completes with information about the created subscription.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If the request body was invalid, the quota is exceeded, or an error occurred
* processing the request.
* @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} are are empty strings.
* @throws NullPointerException if {@code topicName}, {@code subscriptionName}, or {@code subscriptionOptions}
* are are null.
* @throws ResourceExistsException if a subscription exists with the same topic and subscription name.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<SubscriptionProperties> createSubscription(String topicName, String subscriptionName,
CreateSubscriptionOptions subscriptionOptions) {
return createSubscriptionWithResponse(topicName, subscriptionName, subscriptionOptions)
.map(Response::getValue);
}
/**
* Creates a subscription and returns the created subscription in addition to the HTTP response.
*
* @param topicName Name of the topic associated with subscription.
* @param subscriptionName Name of the subscription.
* @param subscriptionOptions Information about the subscription to create.
*
* @return A Mono that returns the created subscription in addition to the HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If the request body was invalid, the quota is exceeded, or an error occurred
* processing the request.
* @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} are are empty strings.
* @throws NullPointerException if {@code topicName}, {@code subscriptionName}, or {@code subscriptionOptions}
* are are null.
* @throws ResourceExistsException if a subscription exists with the same topic and subscription name.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<SubscriptionProperties>> createSubscriptionWithResponse(String topicName,
String subscriptionName, CreateSubscriptionOptions subscriptionOptions) {
return withContext(context -> createSubscriptionWithResponse(topicName, subscriptionName, subscriptionOptions,
context));
}
/**
* Creates a topic with the given name.
*
* @param topicName Name of the topic to create.
*
* @return A Mono that completes with information about the created topic.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If the request body was invalid, the topic quota is exceeded, or an error
* occurred processing the request.
* @throws NullPointerException if {@code topicName} is null.
* @throws IllegalArgumentException if {@code topicName} is an empty string.
* @throws ResourceExistsException if a topic exists with the same {@code topicName}.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<TopicProperties> createTopic(String topicName) {
try {
return createTopic(topicName, new CreateTopicOptions());
} catch (RuntimeException e) {
return monoError(logger, e);
}
}
/**
* Creates a topic with the {@link CreateTopicOptions}.
*
* @param topicName Name of the topic to create.
* @param topicOptions The options used to create the topic.
*
* @return A Mono that completes with information about the created topic.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If the request body was invalid, the topic quota is exceeded, or an error
* occurred processing the request.
* @throws IllegalArgumentException if {@code topicName} is an empty string.
* @throws NullPointerException if {@code topicName} or {@code topicOptions} is null.
* @throws ResourceExistsException if a topic exists with the same {@code topicName}.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<TopicProperties> createTopic(String topicName, CreateTopicOptions topicOptions) {
return createTopicWithResponse(topicName, topicOptions).map(Response::getValue);
}
/**
* Creates a topic and returns the created topic in addition to the HTTP response.
*
* @param topicName Name of the topic to create.
* @param topicOptions The options used to create the topic.
*
* @return A Mono that returns the created topic in addition to the HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If the request body was invalid, the topic quota is exceeded, or an error
* occurred processing the request.
* @throws IllegalArgumentException if {@link TopicProperties
* string.
* @throws NullPointerException if {@code topicName} or {@code topicOptions} is null.
* @throws ResourceExistsException if a topic exists with the same {@code topicName}.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<TopicProperties>> createTopicWithResponse(String topicName, CreateTopicOptions topicOptions) {
return withContext(context -> createTopicWithResponse(topicName, topicOptions, context));
}
/**
* Deletes a queue the matching {@code queueName}.
*
* @param queueName Name of queue to delete.
*
* @return A Mono that completes when the queue is deleted.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws NullPointerException if {@code queueName} is null.
* @throws IllegalArgumentException if {@code queueName} is an empty string.
* @throws ResourceNotFoundException if the {@code queueName} does not exist.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Void> deleteQueue(String queueName) {
return deleteQueueWithResponse(queueName).then();
}
/**
* Deletes a queue the matching {@code queueName} and returns the HTTP response.
*
* @param queueName Name of queue to delete.
*
* @return A Mono that completes when the queue is deleted and returns the HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws NullPointerException if {@code queueName} is null.
* @throws IllegalArgumentException if {@code queueName} is an empty string.
* @throws ResourceNotFoundException if the {@code queueName} does not exist.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Void>> deleteQueueWithResponse(String queueName) {
return withContext(context -> deleteQueueWithResponse(queueName, context));
}
/**
* Deletes a rule the matching {@code ruleName}.
*
* @param topicName Name of topic associated with rule to delete.
* @param subscriptionName Name of the subscription associated with the rule to delete.
* @param ruleName Name of rule to delete.
*
* @return A Mono that completes when the rule is deleted.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code topicName} or {@code ruleName} is an empty string.
* @throws NullPointerException if {@code topicName} or {@code ruleName} is null.
* @throws ResourceNotFoundException if the {@code ruleName} does not exist.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Void> deleteRule(String topicName, String subscriptionName, String ruleName) {
return deleteRuleWithResponse(topicName, subscriptionName, ruleName).then();
}
/**
* Deletes a rule the matching {@code ruleName} and returns the HTTP response.
*
* @param topicName Name of topic associated with rule to delete.
* @param subscriptionName Name of the subscription associated with the rule to delete.
* @param ruleName Name of rule to delete.
*
* @return A Mono that completes when the rule is deleted and returns the HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code topicName}, {@code subscriptionName}, or {@code ruleName} is an
* empty string.
* @throws NullPointerException if {@code topicName}, {@code subscriptionName}, or {@code ruleName} is null.
* @throws ResourceNotFoundException if the {@code ruleName} does not exist.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Void>> deleteRuleWithResponse(String topicName, String subscriptionName,
String ruleName) {
return withContext(context -> deleteRuleWithResponse(topicName, subscriptionName, ruleName, context));
}
/**
* Deletes a subscription the matching {@code subscriptionName}.
*
* @param topicName Name of topic associated with subscription to delete.
* @param subscriptionName Name of subscription to delete.
*
* @return A Mono that completes when the subscription is deleted.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} is an empty string.
* @throws NullPointerException if {@code topicName} or {@code subscriptionName} is null.
* @throws ResourceNotFoundException if the {@code subscriptionName} does not exist.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Void> deleteSubscription(String topicName, String subscriptionName) {
return deleteSubscriptionWithResponse(topicName, subscriptionName).then();
}
/**
* Deletes a subscription the matching {@code subscriptionName} and returns the HTTP response.
*
* @param topicName Name of topic associated with subscription to delete.
* @param subscriptionName Name of subscription to delete.
*
* @return A Mono that completes when the subscription is deleted and returns the HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} is an empty string.
* @throws NullPointerException if {@code topicName} or {@code subscriptionName} is null.
* @throws ResourceNotFoundException if the {@code subscriptionName} does not exist.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Void>> deleteSubscriptionWithResponse(String topicName, String subscriptionName) {
return withContext(context -> deleteSubscriptionWithResponse(topicName, subscriptionName, context));
}
/**
* Deletes a topic the matching {@code topicName}.
*
* @param topicName Name of topic to delete.
*
* @return A Mono that completes when the topic is deleted.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code topicName} is an empty string.
* @throws NullPointerException if {@code topicName} is null.
* @throws ResourceNotFoundException if the {@code topicName} does not exist.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Void> deleteTopic(String topicName) {
return deleteTopicWithResponse(topicName).then();
}
/**
* Deletes a topic the matching {@code topicName} and returns the HTTP response.
*
* @param topicName Name of topic to delete.
*
* @return A Mono that completes when the topic is deleted and returns the HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code topicName} is an empty string.
* @throws NullPointerException if {@code topicName} is null.
* @throws ResourceNotFoundException if the {@code topicName} does not exist.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Void>> deleteTopicWithResponse(String topicName) {
return withContext(context -> deleteTopicWithResponse(topicName, context));
}
/**
* Gets information about the queue.
*
* @param queueName Name of queue to get information about.
*
* @return A Mono that completes with information about the queue.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code queueName} is an empty string.
* @throws NullPointerException if {@code queueName} is null.
* @throws ResourceNotFoundException if the {@code queueName} does not exist.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<QueueProperties> getQueue(String queueName) {
return getQueueWithResponse(queueName).map(Response::getValue);
}
/**
* Gets information about the queue along with its HTTP response.
*
* @param queueName Name of queue to get information about.
*
* @return A Mono that completes with information about the queue and the associated HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code queueName} is an empty string.
* @throws NullPointerException if {@code queueName} is null.
* @throws ResourceNotFoundException if the {@code queueName} does not exist.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<QueueProperties>> getQueueWithResponse(String queueName) {
return withContext(context -> getQueueWithResponse(queueName, context, Function.identity()));
}
/**
* Gets whether or not a queue with {@code queueName} exists in the Service Bus namespace.
*
* @param queueName Name of the queue.
*
* @return A Mono that completes indicating whether or not the queue exists.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code queueName} is an empty string.
* @throws NullPointerException if {@code queueName} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Boolean> getQueueExists(String queueName) {
return getQueueExistsWithResponse(queueName).map(Response::getValue);
}
/**
* Gets whether or not a queue with {@code queueName} exists in the Service Bus namespace.
*
* @param queueName Name of the queue.
*
* @return A Mono that completes indicating whether or not the queue exists along with its HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code queueName} is an empty string.
* @throws NullPointerException if {@code queueName} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Boolean>> getQueueExistsWithResponse(String queueName) {
return getEntityExistsWithResponse(getQueueWithResponse(queueName));
}
/**
* Gets runtime properties about the queue.
*
* @param queueName Name of queue to get information about.
*
* @return A Mono that completes with runtime properties about the queue.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code queueName} is an empty string.
* @throws NullPointerException if {@code queueName} is null.
* @throws ResourceNotFoundException if the {@code queueName} does not exist.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<QueueRuntimeProperties> getQueueRuntimeProperties(String queueName) {
return getQueueRuntimePropertiesWithResponse(queueName).map(response -> response.getValue());
}
/**
* Gets runtime properties about the queue along with its HTTP response.
*
* @param queueName Name of queue to get information about.
*
* @return A Mono that completes with runtime properties about the queue and the associated HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code queueName} is an empty string.
* @throws NullPointerException if {@code queueName} is null.
* @throws ResourceNotFoundException if the {@code queueName} does not exist.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<QueueRuntimeProperties>> getQueueRuntimePropertiesWithResponse(String queueName) {
return withContext(context -> getQueueWithResponse(queueName, context, QueueRuntimeProperties::new));
}
/**
* Gets information about the Service Bus namespace.
*
* @return A Mono that completes with information about the Service Bus namespace.
* @throws ClientAuthenticationException if the client's credentials do not have access to the namespace.
* @throws HttpResponseException If error occurred processing the request.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<NamespaceProperties> getNamespaceProperties() {
return getNamespacePropertiesWithResponse().map(Response::getValue);
}
/**
* Gets information about the Service Bus namespace along with its HTTP response.
*
* @return A Mono that completes with information about the namespace and the associated HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<NamespaceProperties>> getNamespacePropertiesWithResponse() {
return withContext(this::getNamespacePropertiesWithResponse);
}
/**
* Gets a rule from the service namespace.
*
* Only following data types are deserialized in Filters and Action parameters - string, int, long, boolean, double,
* and OffsetDateTime. Other data types would return its string value.
*
* @param topicName The name of the topic relative to service bus namespace.
* @param subscriptionName The subscription name the rule belongs to.
* @param ruleName The name of the rule to retrieve.
*
* @return The associated rule.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<RuleProperties> getRule(String topicName, String subscriptionName, String ruleName) {
return getRuleWithResponse(topicName, subscriptionName, ruleName).map(response -> response.getValue());
}
/**
* Gets a rule from the service namespace.
*
* Only following data types are deserialized in Filters and Action parameters - string, int, long, bool, double,
* and OffsetDateTime. Other data types would return its string value.
*
* @param topicName The name of the topic relative to service bus namespace.
* @param subscriptionName The subscription name the rule belongs to.
* @param ruleName The name of the rule to retrieve.
*
* @return The associated rule with the corresponding HTTP response.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<RuleProperties>> getRuleWithResponse(String topicName, String subscriptionName,
String ruleName) {
return withContext(context -> getRuleWithResponse(topicName, subscriptionName, ruleName, context));
}
/**
* Gets information about the queue.
*
* @param topicName Name of topic associated with subscription.
* @param subscriptionName Name of subscription to get information about.
*
* @return A Mono that completes with information about the subscription.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} are empty strings.
* @throws NullPointerException if {@code topicName} or {@code subscriptionName} are null.
* @throws ResourceNotFoundException if the {@code subscriptionName} does not exist in the {@code topicName}.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<SubscriptionProperties> getSubscription(String topicName, String subscriptionName) {
return getSubscriptionWithResponse(topicName, subscriptionName).map(Response::getValue);
}
/**
* Gets information about the subscription along with its HTTP response.
*
* @param topicName Name of topic associated with subscription.
* @param subscriptionName Name of subscription to get information about.
*
* @return A Mono that completes with information about the subscription and the associated HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} are empty strings.
* @throws NullPointerException if {@code topicName} or {@code subscriptionName} are null.
* @throws ResourceNotFoundException if the {@code subscriptionName} does not exist.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<SubscriptionProperties>> getSubscriptionWithResponse(String topicName,
String subscriptionName) {
return withContext(context -> getSubscriptionWithResponse(topicName, subscriptionName, context,
Function.identity()));
}
/**
* Gets whether or not a subscription within a topic exists.
*
* @param topicName Name of topic associated with subscription.
* @param subscriptionName Name of the subscription.
*
* @return A Mono that completes indicating whether or not the subscription exists.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code subscriptionName} is an empty string.
* @throws NullPointerException if {@code subscriptionName} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Boolean> getSubscriptionExists(String topicName, String subscriptionName) {
return getSubscriptionExistsWithResponse(topicName, subscriptionName).map(Response::getValue);
}
/**
* Gets whether or not a subscription within a topic exists.
*
* @param topicName Name of topic associated with subscription.
* @param subscriptionName Name of the subscription.
*
* @return A Mono that completes indicating whether or not the subscription exists along with its HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code subscriptionName} is an empty string.
* @throws NullPointerException if {@code subscriptionName} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Boolean>> getSubscriptionExistsWithResponse(String topicName, String subscriptionName) {
return getEntityExistsWithResponse(getSubscriptionWithResponse(topicName, subscriptionName));
}
/**
* Gets runtime properties about the subscription.
*
* @param topicName Name of topic associated with subscription.
* @param subscriptionName Name of subscription to get information about.
*
* @return A Mono that completes with runtime properties about the subscription.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} are empty strings.
* @throws NullPointerException if {@code topicName} or {@code subscriptionName} are null.
* @throws ResourceNotFoundException if the {@code subscriptionName} does not exist.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<SubscriptionRuntimeProperties> getSubscriptionRuntimeProperties(
String topicName, String subscriptionName) {
return getSubscriptionRuntimePropertiesWithResponse(topicName, subscriptionName)
.map(response -> response.getValue());
}
/**
* Gets runtime properties about the subscription.
*
* @param topicName Name of topic associated with subscription.
* @param subscriptionName Name of subscription to get information about.
*
* @return A Mono that completes with runtime properties about the subscription.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code subscriptionName} is an empty string.
* @throws NullPointerException if {@code subscriptionName} is null.
* @throws ResourceNotFoundException if the {@code subscriptionName} does not exist.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<SubscriptionRuntimeProperties>> getSubscriptionRuntimePropertiesWithResponse(
String topicName, String subscriptionName) {
return withContext(context -> getSubscriptionWithResponse(topicName, subscriptionName, context,
SubscriptionRuntimeProperties::new));
}
/**
* Gets information about the topic.
*
* @param topicName Name of topic to get information about.
*
* @return A Mono that completes with information about the topic.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code topicName} is an empty string.
* @throws NullPointerException if {@code topicName} is null.
* @throws ResourceNotFoundException if the {@code topicName} does not exist.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<TopicProperties> getTopic(String topicName) {
return getTopicWithResponse(topicName).map(Response::getValue);
}
/**
* Gets information about the topic along with its HTTP response.
*
* @param topicName Name of topic to get information about.
*
* @return A Mono that completes with information about the topic and the associated HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code topicName} is an empty string.
* @throws NullPointerException if {@code topicName} is null.
* @throws ResourceNotFoundException if the {@code topicName} does not exist.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<TopicProperties>> getTopicWithResponse(String topicName) {
return withContext(context -> getTopicWithResponse(topicName, context, Function.identity()));
}
/**
* Gets whether or not a topic with {@code topicName} exists in the Service Bus namespace.
*
* @param topicName Name of the topic.
*
* @return A Mono that completes indicating whether or not the topic exists.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code topicName} is an empty string.
* @throws NullPointerException if {@code topicName} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Boolean> getTopicExists(String topicName) {
return getTopicExistsWithResponse(topicName).map(Response::getValue);
}
/**
* Gets whether or not a topic with {@code topicName} exists in the Service Bus namespace.
*
* @param topicName Name of the topic.
*
* @return A Mono that completes indicating whether or not the topic exists along with its HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code topicName} is an empty string.
* @throws NullPointerException if {@code topicName} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Boolean>> getTopicExistsWithResponse(String topicName) {
return getEntityExistsWithResponse(getTopicWithResponse(topicName));
}
/**
* Gets runtime properties about the topic.
*
* @param topicName Name of topic to get information about.
*
* @return A Mono that completes with runtime properties about the topic.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code topicName} is an empty string.
* @throws NullPointerException if {@code topicName} is null.
* @throws ResourceNotFoundException if the {@code topicName} does not exist.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<TopicRuntimeProperties> getTopicRuntimeProperties(String topicName) {
return getTopicRuntimePropertiesWithResponse(topicName).map(response -> response.getValue());
}
/**
* Gets runtime properties about the topic with its HTTP response.
*
* @param topicName Name of topic to get information about.
*
* @return A Mono that completes with runtime properties about the topic and the associated HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code topicName} is an empty string.
* @throws NullPointerException if {@code topicName} is null.
* @throws ResourceNotFoundException if the {@code topicName} does not exist.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<TopicRuntimeProperties>> getTopicRuntimePropertiesWithResponse(String topicName) {
return withContext(context -> getTopicWithResponse(topicName, context, TopicRuntimeProperties::new));
}
/**
* Fetches all the queues in the Service Bus namespace.
*
* @return A Flux of {@link QueueProperties queues} in the Service Bus namespace.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @see <a href="https:
* authorization rules</a>
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux<QueueProperties> listQueues() {
return new PagedFlux<>(
() -> withContext(context -> listQueuesFirstPage(context)),
token -> withContext(context -> listQueuesNextPage(token, context)));
}
/**
* Fetches all the rules for a topic and subscription.
*
* @param topicName The topic name under which all the rules need to be retrieved.
* @param subscriptionName The name of the subscription for which all rules need to be retrieved.
*
* @return A Flux of {@link RuleProperties rules} for the {@code topicName} and {@code subscriptionName}.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws NullPointerException if {@code topicName} or {@code subscriptionName} is null.
* @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} is an empty string.
* @see <a href="https:
* authorization rules</a>
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux<RuleProperties> listRules(String topicName, String subscriptionName) {
if (topicName == null) {
return pagedFluxError(logger, new NullPointerException("'topicName' cannot be null."));
} else if (topicName.isEmpty()) {
return pagedFluxError(logger, new IllegalArgumentException("'topicName' cannot be an empty string."));
}
return new PagedFlux<>(
() -> withContext(context -> listRulesFirstPage(topicName, subscriptionName, context)),
token -> withContext(context -> listRulesNextPage(topicName, subscriptionName, token, context)));
}
/**
* Fetches all the subscriptions for a topic.
*
* @param topicName The topic name under which all the subscriptions need to be retrieved.
*
* @return A Flux of {@link SubscriptionProperties subscriptions} for the {@code topicName}.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws NullPointerException if {@code topicName} is null.
* @throws IllegalArgumentException if {@code topicName} is an empty string.
* @see <a href="https:
* authorization rules</a>
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux<SubscriptionProperties> listSubscriptions(String topicName) {
if (topicName == null) {
return pagedFluxError(logger, new NullPointerException("'topicName' cannot be null."));
} else if (topicName.isEmpty()) {
return pagedFluxError(logger, new IllegalArgumentException("'topicName' cannot be an empty string."));
}
return new PagedFlux<>(
() -> withContext(context -> listSubscriptionsFirstPage(topicName, context)),
token -> withContext(context -> listSubscriptionsNextPage(topicName, token, context)));
}
/**
* Fetches all the topics in the Service Bus namespace.
*
* @return A Flux of {@link TopicProperties topics} in the Service Bus namespace.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @see <a href="https:
* authorization rules</a>
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux<TopicProperties> listTopics() {
return new PagedFlux<>(
() -> withContext(context -> listTopicsFirstPage(context)),
token -> withContext(context -> listTopicsNextPage(token, context)));
}
/**
* Updates a queue with the given {@link QueueProperties}. The {@link QueueProperties} must be fully populated as
* all of the properties are replaced. If a property is not set the service default value is used.
*
* The suggested flow is:
* <ol>
* <li>{@link
* <li>Update the required elements.</li>
* <li>Pass the updated description into this method.</li>
* </ol>
*
* <p>
* There are a subset of properties that can be updated. More information can be found in the links below. They are:
* <ul>
* <li>{@link QueueProperties
* <li>{@link QueueProperties
* <li>{@link QueueProperties
* </li>
* <li>{@link QueueProperties
* </ul>
*
* @param queue Information about the queue to update. You must provide all the property values that are desired
* on the updated entity. Any values not provided are set to the service default values.
*
* @return A Mono that completes with the updated queue.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If the request body was invalid, the queue quota is exceeded, or an error
* occurred processing the request.
* @throws NullPointerException if {@code queue} is null.
* @see <a href="https:
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<QueueProperties> updateQueue(QueueProperties queue) {
return updateQueueWithResponse(queue).map(Response::getValue);
}
/**
* Updates a queue with the given {@link QueueProperties}. The {@link QueueProperties} must be fully populated as
* all of the properties are replaced. If a property is not set the service default value is used.
*
* The suggested flow is:
* <ol>
* <li>{@link
* <li>Update the required elements.</li>
* <li>Pass the updated description into this method.</li>
* </ol>
*
* <p>
* There are a subset of properties that can be updated. More information can be found in the links below. They are:
* <ul>
* <li>{@link QueueProperties
* <li>{@link QueueProperties
* <li>{@link QueueProperties
* </li>
* <li>{@link QueueProperties
* </ul>
*
* @param queue Information about the queue to update. You must provide all the property values that are desired
* on the updated entity. Any values not provided are set to the service default values.
*
* @return A Mono that returns the updated queue in addition to the HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If the request body was invalid, the queue quota is exceeded, or an error
* occurred processing the request.
* @throws NullPointerException if {@code queue} is null.
* @see <a href="https:
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<QueueProperties>> updateQueueWithResponse(QueueProperties queue) {
return withContext(context -> updateQueueWithResponse(queue, context));
}
/**
* Updates a rule with the given {@link RuleProperties}. The {@link RuleProperties} must be fully populated as all
* of the properties are replaced. If a property is not set the service default value is used.
*
* The suggested flow is:
* <ol>
* <li>{@link
* <li>Update the required elements.</li>
* <li>Pass the updated description into this method.</li>
* </ol>
*
* @param topicName The topic name under which the rule is updated.
* @param subscriptionName The name of the subscription for which the rule is updated.
* @param rule Information about the rule to update. You must provide all the property values that are desired
* on the updated entity. Any values not provided are set to the service default values.
*
* @return A Mono that returns the updated rule.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If the request body was invalid, the rule quota is exceeded, or an error
* occurred processing the request.
* @throws IllegalArgumentException if {@link RuleProperties
* @throws NullPointerException if {@code rule} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<RuleProperties> updateRule(String topicName, String subscriptionName, RuleProperties rule) {
return updateRuleWithResponse(topicName, subscriptionName, rule).map(Response::getValue);
}
/**
* Updates a rule with the given {@link RuleProperties}. The {@link RuleProperties} must be fully populated as all
* of the properties are replaced. If a property is not set the service default value is used.
*
* The suggested flow is:
* <ol>
* <li>{@link
* <li>Update the required elements.</li>
* <li>Pass the updated description into this method.</li>
* </ol>
*
* @param topicName The topic name under which the rule is updated.
* @param subscriptionName The name of the subscription for which the rule is updated.
* @param rule Information about the rule to update. You must provide all the property values that are desired
* on the updated entity. Any values not provided are set to the service default values.
*
* @return A Mono that returns the updated rule in addition to the HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If the request body was invalid, the rule quota is exceeded, or an error
* occurred processing the request.
* @throws IllegalArgumentException if {@link RuleProperties
* @throws NullPointerException if {@code rule} is null.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<RuleProperties>> updateRuleWithResponse(String topicName, String subscriptionName,
RuleProperties rule) {
return withContext(context -> updateRuleWithResponse(topicName, subscriptionName, rule, context));
}
/**
* Updates a subscription with the given {@link SubscriptionProperties}. The {@link SubscriptionProperties} must be
* fully populated as all of the properties are replaced. If a property is not set the service default value is
* used.
*
* The suggested flow is:
* <ol>
* <li>{@link
* <li>Update the required elements.</li>
* <li>Pass the updated description into this method.</li>
* </ol>
*
* <p>
* There are a subset of properties that can be updated. More information can be found in the links below. They are:
* <ul>
* <li>{@link SubscriptionProperties
* <li>{@link SubscriptionProperties
* <li>{@link SubscriptionProperties
* </ul>
*
* @param subscription Information about the subscription to update. You must provide all the property values
* that are desired on the updated entity. Any values not provided are set to the service default values.
*
* @return A Mono that returns the updated subscription.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If the request body was invalid, the subscription quota is exceeded, or an
* error occurred processing the request.
* @throws IllegalArgumentException if {@link SubscriptionProperties
* SubscriptionProperties
* @throws NullPointerException if {@code subscription} is null.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<SubscriptionProperties> updateSubscription(SubscriptionProperties subscription) {
return updateSubscriptionWithResponse(subscription).map(Response::getValue);
}
/**
* Updates a subscription with the given {@link SubscriptionProperties}. The {@link SubscriptionProperties} must be
* fully populated as all of the properties are replaced. If a property is not set the service default value is
* used.
*
* The suggested flow is:
* <ol>
* <li>{@link
* <li>Update the required elements.</li>
* <li>Pass the updated description into this method.</li>
* </ol>
*
* <p>
* There are a subset of properties that can be updated. More information can be found in the links below. They are:
* <ul>
* <li>{@link SubscriptionProperties
* <li>{@link SubscriptionProperties
* <li>{@link SubscriptionProperties
* </ul>
*
* @param subscription Information about the subscription to update. You must provide all the property values
* that are desired on the updated entity. Any values not provided are set to the service default values.
*
* @return A Mono that returns the updated subscription in addition to the HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If the request body was invalid, the subscription quota is exceeded, or an
* error occurred processing the request.
* @throws IllegalArgumentException if {@link SubscriptionProperties
* SubscriptionProperties
* @throws NullPointerException if {@code subscription} is null.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<SubscriptionProperties>> updateSubscriptionWithResponse(
SubscriptionProperties subscription) {
return withContext(context -> updateSubscriptionWithResponse(subscription, context));
}
/**
* Updates a topic with the given {@link TopicProperties}. The {@link TopicProperties} must be fully populated as
* all of the properties are replaced. If a property is not set the service default value is used.
*
* The suggested flow is:
* <ol>
* <li>{@link
* <li>Update the required elements.</li>
* <li>Pass the updated description into this method.</li>
* </ol>
*
* <p>
* There are a subset of properties that can be updated. More information can be found in the links below. They are:
* <ul>
* <li>{@link TopicProperties
* <li>{@link TopicProperties
* </li>
* </ul>
*
* @param topic Information about the topic to update. You must provide all the property values that are desired
* on the updated entity. Any values not provided are set to the service default values.
*
* @return A Mono that completes with the updated topic.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If the request body was invalid, the topic quota is exceeded, or an error
* occurred processing the request.
* @throws IllegalArgumentException if {@link TopicProperties
* string.
* @throws NullPointerException if {@code topic} is null.
* @see <a href="https:
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<TopicProperties> updateTopic(TopicProperties topic) {
return updateTopicWithResponse(topic).map(Response::getValue);
}
/**
* Updates a topic with the given {@link TopicProperties}. The {@link TopicProperties} must be fully populated as
* all of the properties are replaced. If a property is not set the service default value is used.
*
* The suggested flow is:
* <ol>
* <li>{@link
* <li>Update the required elements.</li>
* <li>Pass the updated description into this method.</li>
* </ol>
*
* <p>
* There are a subset of properties that can be updated. More information can be found in the links below. They are:
* <ul>
* <li>{@link TopicProperties
* <li>{@link TopicProperties
* </li>
* </ul>
*
* @param topic Information about the topic to update. You must provide all the property values that are desired
* on the updated entity. Any values not provided are set to the service default values.
*
* @return A Mono that completes with the updated topic and its HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If the request body was invalid, the topic quota is exceeded, or an error
* occurred processing the request.
* @throws IllegalArgumentException if {@link TopicProperties
* string.
* @throws NullPointerException if {@code topic} is null.
* @see <a href="https:
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<TopicProperties>> updateTopicWithResponse(TopicProperties topic) {
return withContext(context -> updateTopicWithResponse(topic, context));
}
/**
* Creates a queue with its context.
*
* @param createQueueOptions Queue to create.
* @param context Context to pass into request.
*
* @return A Mono that completes with the created {@link QueueProperties}.
*/
Mono<Response<QueueProperties>> createQueueWithResponse(String queueName, CreateQueueOptions createQueueOptions,
Context context) {
if (queueName == null) {
return monoError(logger, new NullPointerException("'queueName' cannot be null."));
} else if (queueName.isEmpty()) {
return monoError(logger, new IllegalArgumentException("'queueName' cannot be empty."));
}
if (createQueueOptions == null) {
return monoError(logger, new NullPointerException("'createQueueOptions' cannot be null."));
} else if (context == null) {
return monoError(logger, new NullPointerException("'context' cannot be null."));
}
final QueueDescription description = EntityHelper.getQueueDescription(createQueueOptions);
final CreateQueueBodyContent content = new CreateQueueBodyContent()
.setType(CONTENT_TYPE)
.setQueueDescription(description);
final CreateQueueBody createEntity = new CreateQueueBody()
.setContent(content);
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
try {
return entityClient.putWithResponseAsync(queueName, createEntity, null, withTracing)
.onErrorMap(ServiceBusAdministrationAsyncClient::mapException)
.map(this::deserializeQueue);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Creates a rule with its context.
*
* @param ruleOptions Rule to create.
* @param context Context to pass into request.
*
* @return A Mono that completes with the created {@link RuleProperties}.
*/
Mono<Response<RuleProperties>> createRuleWithResponse(String topicName, String subscriptionName, String ruleName,
CreateRuleOptions ruleOptions, Context context) {
if (topicName == null) {
return monoError(logger, new NullPointerException("'topicName' cannot be null."));
} else if (topicName.isEmpty()) {
return monoError(logger, new IllegalArgumentException("'topicName' cannot be empty."));
}
if (subscriptionName == null) {
return monoError(logger, new NullPointerException("'subscriptionName' cannot be null."));
} else if (subscriptionName.isEmpty()) {
return monoError(logger, new IllegalArgumentException("'subscriptionName' cannot be empty."));
}
if (ruleName == null) {
return monoError(logger, new NullPointerException("'ruleName' cannot be null."));
} else if (ruleName.isEmpty()) {
return monoError(logger, new IllegalArgumentException("'ruleName' cannot be empty."));
}
if (ruleOptions == null) {
return monoError(logger, new NullPointerException("'rule' cannot be null."));
}
final RuleActionImpl action = ruleOptions.getAction() != null
? EntityHelper.toImplementation(ruleOptions.getAction())
: null;
final RuleFilterImpl filter = ruleOptions.getFilter() != null
? EntityHelper.toImplementation(ruleOptions.getFilter())
: null;
final RuleDescription rule = new RuleDescription()
.setAction(action)
.setFilter(filter)
.setName(ruleName);
final CreateRuleBodyContent content = new CreateRuleBodyContent()
.setType(CONTENT_TYPE)
.setRuleDescription(rule);
final CreateRuleBody createEntity = new CreateRuleBody().setContent(content);
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
try {
return managementClient.getRules().putWithResponseAsync(topicName, subscriptionName, ruleName, createEntity,
null, withTracing)
.onErrorMap(ServiceBusAdministrationAsyncClient::mapException)
.map(response -> deserializeRule(response));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Creates a subscription with its context.
*
* @param subscriptionOptions Subscription to create.
* @param context Context to pass into request.
*
* @return A Mono that completes with the created {@link SubscriptionProperties}.
*/
Mono<Response<SubscriptionProperties>> createSubscriptionWithResponse(String topicName, String subscriptionName,
CreateSubscriptionOptions subscriptionOptions, Context context) {
if (topicName == null) {
return monoError(logger, new NullPointerException("'topicName' cannot be null."));
} else if (topicName.isEmpty()) {
return monoError(logger, new IllegalArgumentException("'topicName' cannot be empty."));
}
if (subscriptionName == null) {
return monoError(logger, new NullPointerException("'subscriptionName' cannot be null."));
} else if (subscriptionName.isEmpty()) {
return monoError(logger, new IllegalArgumentException("'subscriptionName' cannot be empty."));
}
if (subscriptionOptions == null) {
return monoError(logger, new NullPointerException("'subscription' cannot be null."));
}
final SubscriptionDescription subscription = EntityHelper.getSubscriptionDescription(subscriptionOptions);
final CreateSubscriptionBodyContent content = new CreateSubscriptionBodyContent()
.setType(CONTENT_TYPE)
.setSubscriptionDescription(subscription);
final CreateSubscriptionBody createEntity = new CreateSubscriptionBody().setContent(content);
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
try {
return managementClient.getSubscriptions().putWithResponseAsync(topicName, subscriptionName, createEntity,
null, withTracing)
.onErrorMap(ServiceBusAdministrationAsyncClient::mapException)
.map(response -> deserializeSubscription(topicName, response));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Creates a topicOptions with its context.
*
* @param topicOptions Topic to create.
* @param context Context to pass into request.
*
* @return A Mono that completes with the created {@link TopicProperties}.
*/
Mono<Response<TopicProperties>> createTopicWithResponse(String topicName, CreateTopicOptions topicOptions,
Context context) {
if (topicName == null) {
return monoError(logger, new NullPointerException("'topicName' cannot be null."));
} else if (topicName.isEmpty()) {
return monoError(logger, new IllegalArgumentException("'topicName' cannot be empty."));
}
if (topicOptions == null) {
return monoError(logger, new NullPointerException("'topicOptions' cannot be null"));
} else if (context == null) {
return monoError(logger, new NullPointerException("'context' cannot be null."));
}
final TopicDescription topic = EntityHelper.getTopicDescription(topicOptions);
final CreateTopicBodyContent content = new CreateTopicBodyContent()
.setType(CONTENT_TYPE)
.setTopicDescription(topic);
final CreateTopicBody createEntity = new CreateTopicBody()
.setContent(content);
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
try {
return entityClient.putWithResponseAsync(topicName, createEntity, null, withTracing)
.onErrorMap(ServiceBusAdministrationAsyncClient::mapException)
.map(this::deserializeTopic);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Deletes a queue with its context.
*
* @param queueName Name of queue to delete.
* @param context Context to pass into request.
*
* @return A Mono that completes when the queue is deleted.
*/
Mono<Response<Void>> deleteQueueWithResponse(String queueName, Context context) {
if (queueName == null) {
return monoError(logger, new NullPointerException("'queueName' cannot be null"));
} else if (queueName.isEmpty()) {
return monoError(logger, new IllegalArgumentException("'queueName' cannot be an empty string."));
} else if (context == null) {
return monoError(logger, new NullPointerException("'context' cannot be null."));
}
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
try {
return entityClient.deleteWithResponseAsync(queueName, withTracing)
.onErrorMap(ServiceBusAdministrationAsyncClient::mapException)
.map(response -> {
return new SimpleResponse<>(response.getRequest(), response.getStatusCode(),
response.getHeaders(), null);
});
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Deletes a queue with its context.
*
* @param topicName Name of topic to delete.
* @param subscriptionName Name of the subscription for the rule.
* @param ruleName Name of the rule.
* @param context Context to pass into request.
*
* @return A Mono that completes with the created {@link QueueProperties}.
*/
Mono<Response<Void>> deleteRuleWithResponse(String topicName, String subscriptionName, String ruleName,
Context context) {
if (topicName == null) {
return monoError(logger, new NullPointerException("'topicName' cannot be null"));
} else if (topicName.isEmpty()) {
return monoError(logger, new IllegalArgumentException("'topicName' cannot be an empty string."));
} else if (subscriptionName == null) {
return monoError(logger, new NullPointerException("'subscriptionName' cannot be null"));
} else if (subscriptionName.isEmpty()) {
return monoError(logger, new IllegalArgumentException("'subscriptionName' cannot be an empty string."));
} else if (ruleName == null) {
return monoError(logger, new NullPointerException("'ruleName' cannot be null"));
} else if (ruleName.isEmpty()) {
return monoError(logger, new IllegalArgumentException("'ruleName' cannot be an empty string."));
} else if (context == null) {
return monoError(logger, new NullPointerException("'context' cannot be null."));
}
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
try {
return rulesClient.deleteWithResponseAsync(topicName, subscriptionName, ruleName, withTracing)
.onErrorMap(ServiceBusAdministrationAsyncClient::mapException)
.map(response -> new SimpleResponse<>(response.getRequest(), response.getStatusCode(),
response.getHeaders(), null));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Deletes a subscription with its context.
*
* @param topicName Name of topic associated with subscription to delete.
* @param subscriptionName Name of subscription to delete.
* @param context Context to pass into request.
*
* @return A Mono that completes with the created {@link SubscriptionProperties}.
*/
Mono<Response<Void>> deleteSubscriptionWithResponse(String topicName, String subscriptionName, Context context) {
if (subscriptionName == null) {
return monoError(logger, new NullPointerException("'subscriptionName' cannot be null"));
} else if (subscriptionName.isEmpty()) {
return monoError(logger, new IllegalArgumentException("'subscriptionName' cannot be an empty string."));
} else if (topicName == null) {
return monoError(logger, new NullPointerException("'topicName' cannot be null"));
} else if (topicName.isEmpty()) {
return monoError(logger, new IllegalArgumentException("'topicName' cannot be an empty string."));
} else if (context == null) {
return monoError(logger, new NullPointerException("'context' cannot be null."));
}
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
try {
return managementClient.getSubscriptions().deleteWithResponseAsync(topicName, subscriptionName,
withTracing)
.onErrorMap(ServiceBusAdministrationAsyncClient::mapException)
.map(response -> new SimpleResponse<>(response.getRequest(), response.getStatusCode(),
response.getHeaders(), null));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Deletes a topic with its context.
*
* @param topicName Name of topic to delete.
* @param context Context to pass into request.
*
* @return A Mono that completes with the created {@link TopicProperties}.
*/
Mono<Response<Void>> deleteTopicWithResponse(String topicName, Context context) {
if (topicName == null) {
return monoError(logger, new NullPointerException("'topicName' cannot be null"));
} else if (topicName.isEmpty()) {
return monoError(logger, new IllegalArgumentException("'topicName' cannot be an empty string."));
} else if (context == null) {
return monoError(logger, new NullPointerException("'context' cannot be null."));
}
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
try {
return entityClient.deleteWithResponseAsync(topicName, withTracing)
.onErrorMap(ServiceBusAdministrationAsyncClient::mapException)
.map(response -> new SimpleResponse<>(response.getRequest(), response.getStatusCode(),
response.getHeaders(), null));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Gets whether an entity exists.
*
* @param getEntityOperation Operation to get information about entity. If {@link ResourceNotFoundException} is
* thrown, then it is mapped to false.
* @param <T> Entity type.
*
* @return True if the entity exists, false otherwise.
*/
<T> Mono<Response<Boolean>> getEntityExistsWithResponse(Mono<Response<T>> getEntityOperation) {
return getEntityOperation.map(response -> {
final boolean exists = response.getValue() != null;
return (Response<Boolean>) new SimpleResponse<>(response.getRequest(), response.getStatusCode(),
response.getHeaders(), exists);
})
.onErrorResume(ResourceNotFoundException.class, exception -> {
final HttpResponse response = exception.getResponse();
final Response<Boolean> result = new SimpleResponse<>(response.getRequest(), response.getStatusCode(),
response.getHeaders(), false);
return Mono.just(result);
});
}
/**
* Gets a queue with its context.
*
* @param queueName Name of queue to fetch information for.
* @param context Context to pass into request.
*
* @return A Mono that completes with the {@link QueueProperties}.
*/
<T> Mono<Response<T>> getQueueWithResponse(String queueName, Context context,
Function<QueueProperties, T> mapper) {
if (queueName == null) {
return monoError(logger, new NullPointerException("'queueName' cannot be null"));
} else if (queueName.isEmpty()) {
return monoError(logger, new IllegalArgumentException("'queueName' cannot be empty."));
} else if (context == null) {
return monoError(logger, new NullPointerException("'context' cannot be null."));
}
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
try {
return entityClient.getWithResponseAsync(queueName, true, withTracing)
.onErrorMap(ServiceBusAdministrationAsyncClient::mapException)
.handle((response, sink) -> {
final Response<QueueProperties> deserialize = deserializeQueue(response);
if (deserialize.getValue() == null) {
final HttpResponse notFoundResponse = new EntityNotFoundHttpResponse<>(deserialize);
sink.error(new ResourceNotFoundException(String.format("Queue '%s' does not exist.", queueName),
notFoundResponse));
} else {
final T mapped = mapper.apply(deserialize.getValue());
sink.next(new SimpleResponse<>(response.getRequest(), response.getStatusCode(),
response.getHeaders(), mapped));
}
});
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<RuleProperties>> getRuleWithResponse(String topicName, String subscriptionName,
String ruleName, Context context) {
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
try {
return rulesClient.getWithResponseAsync(topicName, subscriptionName, ruleName, true, withTracing)
.onErrorMap(ServiceBusAdministrationAsyncClient::mapException)
.map(this::deserializeRule);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Gets a subscription with its context.
*
* @param topicName Name of the topic associated with the subscription.
* @param subscriptionName Name of subscription to fetch information for.
* @param context Context to pass into request.
*
* @return A Mono that completes with the {@link SubscriptionProperties}.
*/
<T> Mono<Response<T>> getSubscriptionWithResponse(String topicName, String subscriptionName, Context context,
Function<SubscriptionProperties, T> mapper) {
if (topicName == null) {
return monoError(logger, new NullPointerException("'topicName' cannot be null."));
} else if (topicName.isEmpty()) {
return monoError(logger, new IllegalArgumentException("'topicName' cannot be an empty string."));
} else if (subscriptionName == null) {
return monoError(logger, new NullPointerException("'subscriptionName' cannot be null."));
} else if (subscriptionName.isEmpty()) {
return monoError(logger, new IllegalArgumentException("'subscriptionName' cannot be an empty string."));
} else if (context == null) {
return monoError(logger, new NullPointerException("'context' cannot be null."));
}
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
try {
return managementClient.getSubscriptions().getWithResponseAsync(topicName, subscriptionName, true,
withTracing)
.onErrorMap(ServiceBusAdministrationAsyncClient::mapException)
.handle((response, sink) -> {
final Response<SubscriptionProperties> deserialize = deserializeSubscription(topicName, response);
if (deserialize.getValue() == null) {
final HttpResponse notFoundResponse = new EntityNotFoundHttpResponse<>(deserialize);
sink.error(new ResourceNotFoundException(String.format(
"Subscription '%s' in topic '%s' does not exist.", topicName, subscriptionName),
notFoundResponse));
} else {
final T mapped = mapper.apply(deserialize.getValue());
sink.next(new SimpleResponse<>(response.getRequest(), response.getStatusCode(),
response.getHeaders(), mapped));
}
});
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Gets the namespace properties with its context.
*
* @param context Context to pass into request.
*
* @return A Mono that completes with the {@link NamespaceProperties}.
*/
Mono<Response<NamespaceProperties>> getNamespacePropertiesWithResponse(Context context) {
return managementClient.getNamespaces().getWithResponseAsync(context).handle((response, sink) -> {
final NamespacePropertiesEntry entry = response.getValue();
if (entry == null || entry.getContent() == null) {
sink.error(new AzureException(
"There was no content inside namespace response. Entry: " + response));
return;
}
final NamespaceProperties namespaceProperties = entry.getContent().getNamespaceProperties();
final Response<NamespaceProperties> result = new SimpleResponse<>(response.getRequest(),
response.getStatusCode(), response.getHeaders(), namespaceProperties);
sink.next(result);
});
}
/**
* Gets a topic with its context.
*
* @param topicName Name of topic to fetch information for.
* @param context Context to pass into request.
*
* @return A Mono that completes with the {@link TopicProperties}.
*/
<T> Mono<Response<T>> getTopicWithResponse(String topicName, Context context,
Function<TopicProperties, T> mapper) {
if (topicName == null) {
return monoError(logger, new NullPointerException("'topicName' cannot be null"));
} else if (topicName.isEmpty()) {
return monoError(logger, new IllegalArgumentException("'topicName' cannot be empty."));
} else if (context == null) {
return monoError(logger, new NullPointerException("'context' cannot be null."));
}
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
try {
return entityClient.getWithResponseAsync(topicName, true, withTracing)
.onErrorMap(ServiceBusAdministrationAsyncClient::mapException)
.handle((response, sink) -> {
final Response<TopicProperties> deserialize = deserializeTopic(response);
if (deserialize.getValue() == null) {
final HttpResponse notFoundResponse = new EntityNotFoundHttpResponse<>(deserialize);
sink.error(new ResourceNotFoundException(String.format("Topic '%s' does not exist.", topicName),
notFoundResponse));
} else {
final T mapped = mapper.apply(deserialize.getValue());
sink.next(new SimpleResponse<>(response.getRequest(), response.getStatusCode(),
response.getHeaders(), mapped));
}
});
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Gets the first page of queues with context.
*
* @param context Context to pass into request.
*
* @return A Mono that completes with a page of queues.
*/
Mono<PagedResponse<QueueProperties>> listQueuesFirstPage(Context context) {
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
try {
return listQueues(0, withTracing);
} catch (RuntimeException e) {
return monoError(logger, e);
}
}
/**
* Gets the next page of queues with context.
*
* @param continuationToken Number of items to skip in feed.
* @param context Context to pass into request.
*
* @return A Mono that completes with a page of queues or empty if there are no items left.
*/
Mono<PagedResponse<QueueProperties>> listQueuesNextPage(String continuationToken, Context context) {
if (continuationToken == null || continuationToken.isEmpty()) {
return Mono.empty();
}
try {
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
final int skip = Integer.parseInt(continuationToken);
return listQueues(skip, withTracing);
} catch (RuntimeException e) {
return monoError(logger, e);
}
}
/**
* Gets the first page of rules with context.
*
* @param context Context to pass into request.
*
* @return A Mono that completes with a page of rules.
*/
Mono<PagedResponse<RuleProperties>> listRulesFirstPage(String topicName, String subscriptionName, Context context) {
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
try {
return listRules(topicName, subscriptionName, 0, withTracing);
} catch (RuntimeException e) {
return monoError(logger, e);
}
}
/**
* Gets the next page of rules with context.
*
* @param continuationToken Number of items to skip in feed.
* @param context Context to pass into request.
*
* @return A Mono that completes with a page of rules or empty if there are no items left.
*/
Mono<PagedResponse<RuleProperties>> listRulesNextPage(String topicName, String subscriptionName,
String continuationToken, Context context) {
if (continuationToken == null || continuationToken.isEmpty()) {
return Mono.empty();
}
try {
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
final int skip = Integer.parseInt(continuationToken);
return listRules(topicName, subscriptionName, skip, withTracing);
} catch (RuntimeException e) {
return monoError(logger, e);
}
}
/**
* Gets the first page of subscriptions with context.
*
* @param context Context to pass into request.
*
* @return A Mono that completes with a page of subscriptions.
*/
Mono<PagedResponse<SubscriptionProperties>> listSubscriptionsFirstPage(String topicName, Context context) {
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
try {
return listSubscriptions(topicName, 0, withTracing);
} catch (RuntimeException e) {
return monoError(logger, e);
}
}
/**
* Gets the next page of subscriptions with context.
*
* @param continuationToken Number of items to skip in feed.
* @param context Context to pass into request.
*
* @return A Mono that completes with a page of subscriptions or empty if there are no items left.
*/
Mono<PagedResponse<SubscriptionProperties>> listSubscriptionsNextPage(String topicName, String continuationToken,
Context context) {
if (continuationToken == null || continuationToken.isEmpty()) {
return Mono.empty();
}
try {
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
final int skip = Integer.parseInt(continuationToken);
return listSubscriptions(topicName, skip, withTracing);
} catch (RuntimeException e) {
return monoError(logger, e);
}
}
/**
* Gets the first page of topics with context.
*
* @param context Context to pass into request.
*
* @return A Mono that completes with a page of topics.
*/
Mono<PagedResponse<TopicProperties>> listTopicsFirstPage(Context context) {
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
try {
return listTopics(0, withTracing);
} catch (RuntimeException e) {
return monoError(logger, e);
}
}
/**
* Gets the next page of topics with context.
*
* @param continuationToken Number of items to skip in feed.
* @param context Context to pass into request.
*
* @return A Mono that completes with a page of topics or empty if there are no items left.
*/
Mono<PagedResponse<TopicProperties>> listTopicsNextPage(String continuationToken, Context context) {
if (continuationToken == null || continuationToken.isEmpty()) {
return Mono.empty();
}
try {
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
final int skip = Integer.parseInt(continuationToken);
return listTopics(skip, withTracing);
} catch (RuntimeException e) {
return monoError(logger, e);
}
}
/**
* Updates a queue with its context.
*
* @param queue Information about the queue to update. You must provide all the property values that are desired
* on the updated entity. Any values not provided are set to the service default values.
* @param context Context to pass into request.
*
* @return A Mono that completes with the updated {@link QueueProperties}.
*/
Mono<Response<QueueProperties>> updateQueueWithResponse(QueueProperties queue, Context context) {
if (queue == null) {
return monoError(logger, new NullPointerException("'queue' cannot be null"));
} else if (context == null) {
return monoError(logger, new NullPointerException("'context' cannot be null."));
}
final QueueDescription queueDescription = EntityHelper.toImplementation(queue);
final CreateQueueBodyContent content = new CreateQueueBodyContent()
.setType(CONTENT_TYPE)
.setQueueDescription(queueDescription);
final CreateQueueBody createEntity = new CreateQueueBody()
.setContent(content);
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
try {
return entityClient.putWithResponseAsync(queue.getName(), createEntity, "*", withTracing)
.onErrorMap(ServiceBusAdministrationAsyncClient::mapException)
.map(response -> deserializeQueue(response));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Updates a rule with its context.
*
* @param rule Information about the rule to update. You must provide all the property values that are desired
* on the updated entity. Any values not provided are set to the service default values.
* @param context Context to pass into request.
*
* @return A Mono that completes with the updated {@link RuleProperties}.
*/
Mono<Response<RuleProperties>> updateRuleWithResponse(String topicName, String subscriptionName,
RuleProperties rule, Context context) {
if (rule == null) {
return monoError(logger, new NullPointerException("'rule' cannot be null"));
} else if (context == null) {
return monoError(logger, new NullPointerException("'context' cannot be null."));
}
final RuleDescription implementation = EntityHelper.toImplementation(rule);
final CreateRuleBodyContent content = new CreateRuleBodyContent()
.setType(CONTENT_TYPE)
.setRuleDescription(implementation);
final CreateRuleBody ruleBody = new CreateRuleBody()
.setContent(content);
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
try {
return managementClient.getRules().putWithResponseAsync(topicName, subscriptionName, rule.getName(),
ruleBody, "*", withTracing)
.onErrorMap(ServiceBusAdministrationAsyncClient::mapException)
.map(response -> deserializeRule(response));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Updates a subscription with its context.
*
* @param subscription Information about the subscription to update. You must provide all the property values
* that are desired on the updated entity. Any values not provided are set to the service default values.
* @param context Context to pass into request.
*
* @return A Mono that completes with the updated {@link SubscriptionProperties}.
*/
Mono<Response<SubscriptionProperties>> updateSubscriptionWithResponse(SubscriptionProperties subscription,
Context context) {
if (subscription == null) {
return monoError(logger, new NullPointerException("'subscription' cannot be null"));
} else if (context == null) {
return monoError(logger, new NullPointerException("'context' cannot be null."));
}
final String topicName = subscription.getTopicName();
final String subscriptionName = subscription.getSubscriptionName();
final SubscriptionDescription implementation = EntityHelper.toImplementation(subscription);
final CreateSubscriptionBodyContent content = new CreateSubscriptionBodyContent()
.setType(CONTENT_TYPE)
.setSubscriptionDescription(implementation);
final CreateSubscriptionBody createEntity = new CreateSubscriptionBody()
.setContent(content);
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
try {
return managementClient.getSubscriptions().putWithResponseAsync(topicName, subscriptionName, createEntity,
"*", withTracing)
.onErrorMap(ServiceBusAdministrationAsyncClient::mapException)
.map(response -> deserializeSubscription(topicName, response));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Updates a topic with its context.
*
* @param topic Information about the topic to update. You must provide all the property values that are desired
* on the updated entity. Any values not provided are set to the service default values.
* @param context Context to pass into request.
*
* @return A Mono that completes with the updated {@link TopicProperties}.
*/
Mono<Response<TopicProperties>> updateTopicWithResponse(TopicProperties topic, Context context) {
if (topic == null) {
return monoError(logger, new NullPointerException("'topic' cannot be null"));
} else if (context == null) {
return monoError(logger, new NullPointerException("'context' cannot be null."));
}
final TopicDescription implementation = EntityHelper.toImplementation(topic);
final CreateTopicBodyContent content = new CreateTopicBodyContent()
.setType(CONTENT_TYPE)
.setTopicDescription(implementation);
final CreateTopicBody createEntity = new CreateTopicBody()
.setContent(content);
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
try {
return entityClient.putWithResponseAsync(topic.getName(), createEntity, "*", withTracing)
.onErrorMap(ServiceBusAdministrationAsyncClient::mapException)
.map(response -> deserializeTopic(response));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
private <T> T deserialize(Object object, Class<T> clazz) {
if (object == null) {
return null;
}
final String contents = String.valueOf(object);
if (contents.isEmpty()) {
return null;
}
try {
return serializer.deserialize(contents, clazz);
} catch (IOException e) {
throw logger.logExceptionAsError(new RuntimeException(String.format(
"Exception while deserializing. Body: [%s]. Class: %s", contents, clazz), e));
}
}
/**
* Given an HTTP response, will deserialize it into a strongly typed Response object.
*
* @param response HTTP response to deserialize response body from.
* @param clazz Class to deserialize response type into.
* @param <T> Class type to deserialize response into.
*
* @return A Response with a strongly typed response value.
*/
private <T> Response<T> deserialize(Response<Object> response, Class<T> clazz) {
final T deserialize = deserialize(response.getValue(), clazz);
return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(),
deserialize);
}
/**
* Converts a Response into its corresponding {@link QueueDescriptionEntry} then mapped into {@link
* QueueProperties}.
*
* @param response HTTP Response to deserialize.
*
* @return The corresponding HTTP response with convenience properties set.
*/
/**
* Converts a Response into its corresponding {@link RuleDescriptionEntry} then mapped into {@link RuleProperties}.
*
* @param response HTTP Response to deserialize.
*
* @return The corresponding HTTP response with convenience properties set.
*/
private Response<RuleProperties> deserializeRule(Response<Object> response) {
final RuleDescriptionEntry entry = deserialize(response.getValue(), RuleDescriptionEntry.class);
if (entry == null) {
return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null);
} else if (entry.getContent() == null) {
logger.info("entry.getContent() is null. The entity may not exist. {}", entry);
return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null);
}
final RuleDescription description = entry.getContent().getRuleDescription();
final RuleProperties result = EntityHelper.toModel(description);
return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), result);
}
/**
* Converts a Response into its corresponding {@link SubscriptionDescriptionEntry} then mapped into {@link
* SubscriptionProperties}.
*
* @param response HTTP Response to deserialize.
*
* @return The corresponding HTTP response with convenience properties set.
*/
private Response<SubscriptionProperties> deserializeSubscription(String topicName, Response<Object> response) {
final SubscriptionDescriptionEntry entry = deserialize(response.getValue(), SubscriptionDescriptionEntry.class);
if (entry == null) {
return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null);
} else if (entry.getContent() == null) {
logger.warning("entry.getContent() is null. There should have been content returned. Entry: {}", entry);
return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null);
}
final SubscriptionProperties subscription = EntityHelper.toModel(
entry.getContent().getSubscriptionDescription());
final String subscriptionName = getTitleValue(entry.getTitle());
EntityHelper.setSubscriptionName(subscription, subscriptionName);
EntityHelper.setTopicName(subscription, topicName);
return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(),
subscription);
}
/**
* Converts a Response into its corresponding {@link TopicDescriptionEntry} then mapped into {@link
* QueueProperties}.
*
* @param response HTTP Response to deserialize.
*
* @return The corresponding HTTP response with convenience properties set.
*/
private Response<TopicProperties> deserializeTopic(Response<Object> response) {
final TopicDescriptionEntry entry = deserialize(response.getValue(), TopicDescriptionEntry.class);
if (entry == null) {
return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null);
} else if (entry.getContent() == null) {
logger.warning("entry.getContent() is null. There should have been content returned. Entry: {}", entry);
return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null);
} else if (entry.getContent().getTopicDescription() == null) {
final QueueDescriptionEntry entryTopic = deserialize(response.getValue(), QueueDescriptionEntry.class);
if (entryTopic != null && entryTopic.getContent() != null && entryTopic.getContent().getQueueDescription() != null) {
throw logger.logExceptionAsError(
new RuntimeException(String.format("'[%s]' is not a topic, it is a queue.", entryTopic.getTitle())));
}
}
final TopicProperties result = EntityHelper.toModel(entry.getContent().getTopicDescription());
final String topicName = getTitleValue(entry.getTitle());
EntityHelper.setTopicName(result, topicName);
return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), result);
}
/**
* Creates a {@link FeedPage} given the elements and a set of response links to get the next link from.
*
* @param entities Entities in the feed.
* @param responseLinks Links returned from the feed.
* @param <TResult> Type of Service Bus entities in page.
*
* @return A {@link FeedPage} indicating whether this can be continued or not.
* @throws MalformedURLException if the "next" page link does not contain a well-formed URL.
*/
private <TResult, TFeed> FeedPage<TResult> extractPage(Response<TFeed> response, List<TResult> entities,
List<ResponseLink> responseLinks)
throws MalformedURLException, UnsupportedEncodingException {
final Optional<ResponseLink> nextLink = responseLinks.stream()
.filter(link -> link.getRel().equalsIgnoreCase("next"))
.findFirst();
if (!nextLink.isPresent()) {
return new FeedPage<>(response.getStatusCode(), response.getHeaders(), response.getRequest(), entities);
}
final URL url = new URL(nextLink.get().getHref());
final String decode = URLDecoder.decode(url.getQuery(), StandardCharsets.UTF_8.name());
final Optional<Integer> skipParameter = Arrays.stream(decode.split("&|&"))
.map(part -> part.split("=", 2))
.filter(parts -> parts[0].equalsIgnoreCase("$skip") && parts.length == 2)
.map(parts -> Integer.valueOf(parts[1]))
.findFirst();
if (skipParameter.isPresent()) {
return new FeedPage<>(response.getStatusCode(), response.getHeaders(), response.getRequest(), entities,
skipParameter.get());
} else {
logger.warning("There should have been a skip parameter for the next page.");
return new FeedPage<>(response.getStatusCode(), response.getHeaders(), response.getRequest(), entities);
}
}
/**
* Helper method that invokes the service method, extracts the data and translates it to a PagedResponse.
*
* @param skip Number of elements to skip.
* @param context Context for the query.
*
* @return A Mono that completes with a paged response of queues.
*/
private Mono<PagedResponse<QueueProperties>> listQueues(int skip, Context context) {
return managementClient.listEntitiesWithResponseAsync(QUEUES_ENTITY_TYPE, skip, NUMBER_OF_ELEMENTS, context)
.onErrorMap(ServiceBusAdministrationAsyncClient::mapException)
.flatMap(response -> {
final Response<QueueDescriptionFeed> feedResponse = deserialize(response, QueueDescriptionFeed.class);
final QueueDescriptionFeed feed = feedResponse.getValue();
if (feed == null) {
logger.warning("Could not deserialize QueueDescriptionFeed. skip {}, top: {}", skip,
NUMBER_OF_ELEMENTS);
return Mono.empty();
}
final List<QueueProperties> entities = feed.getEntry().stream()
.filter(e -> e.getContent() != null && e.getContent().getQueueDescription() != null)
.map(e -> {
final String queueName = getTitleValue(e.getTitle());
final QueueProperties queueProperties = EntityHelper.toModel(
e.getContent().getQueueDescription());
EntityHelper.setQueueName(queueProperties, queueName);
return queueProperties;
})
.collect(Collectors.toList());
try {
return Mono.just(extractPage(feedResponse, entities, feed.getLink()));
} catch (MalformedURLException | UnsupportedEncodingException error) {
return Mono.error(new RuntimeException("Could not parse response into FeedPage<QueueDescription>",
error));
}
});
}
/**
* Helper method that invokes the service method, extracts the data and translates it to a PagedResponse.
*
* @param skip Number of elements to skip.
* @param context Context for the query.
*
* @return A Mono that completes with a paged response of rules.
*/
private Mono<PagedResponse<RuleProperties>> listRules(String topicName, String subscriptionName, int skip,
Context context) {
return managementClient.listRulesWithResponseAsync(topicName, subscriptionName, skip, NUMBER_OF_ELEMENTS,
context)
.onErrorMap(ServiceBusAdministrationAsyncClient::mapException)
.flatMap(response -> {
final Response<RuleDescriptionFeed> feedResponse = deserialize(response,
RuleDescriptionFeed.class);
final RuleDescriptionFeed feed = feedResponse.getValue();
if (feed == null) {
logger.warning("Could not deserialize RuleDescriptionFeed. skip {}, top: {}", skip,
NUMBER_OF_ELEMENTS);
return Mono.empty();
}
final List<RuleProperties> entities = feed.getEntry().stream()
.filter(e -> e.getContent() != null && e.getContent().getRuleDescription() != null)
.map(e -> {
return EntityHelper.toModel(e.getContent().getRuleDescription());
})
.collect(Collectors.toList());
try {
return Mono.just(extractPage(feedResponse, entities, feed.getLink()));
} catch (MalformedURLException | UnsupportedEncodingException error) {
return Mono.error(new RuntimeException(
"Could not parse response into FeedPage<RuleDescription>", error));
}
});
}
/**
* Helper method that invokes the service method, extracts the data and translates it to a PagedResponse.
*
* @param skip Number of elements to skip.
* @param context Context for the query.
*
* @return A Mono that completes with a paged response of subscriptions.
*/
private Mono<PagedResponse<SubscriptionProperties>> listSubscriptions(String topicName, int skip,
Context context) {
return managementClient.listSubscriptionsWithResponseAsync(topicName, skip, NUMBER_OF_ELEMENTS, context)
.onErrorMap(ServiceBusAdministrationAsyncClient::mapException)
.flatMap(response -> {
final Response<SubscriptionDescriptionFeed> feedResponse = deserialize(response,
SubscriptionDescriptionFeed.class);
final SubscriptionDescriptionFeed feed = feedResponse.getValue();
if (feed == null) {
logger.warning("Could not deserialize SubscriptionDescriptionFeed. skip {}, top: {}", skip,
NUMBER_OF_ELEMENTS);
return Mono.empty();
}
final List<SubscriptionProperties> entities = feed.getEntry().stream()
.filter(e -> e.getContent() != null && e.getContent().getSubscriptionDescription() != null)
.map(e -> {
final String subscriptionName = getTitleValue(e.getTitle());
final SubscriptionProperties description = EntityHelper.toModel(
e.getContent().getSubscriptionDescription());
EntityHelper.setTopicName(description, topicName);
EntityHelper.setSubscriptionName(description, subscriptionName);
return description;
})
.collect(Collectors.toList());
try {
return Mono.just(extractPage(feedResponse, entities, feed.getLink()));
} catch (MalformedURLException | UnsupportedEncodingException error) {
return Mono.error(new RuntimeException(
"Could not parse response into FeedPage<SubscriptionDescription>", error));
}
});
}
/**
* Helper method that invokes the service method, extracts the data and translates it to a PagedResponse.
*
* @param skip Number of elements to skip.
* @param context Context for the query.
*
* @return A Mono that completes with a paged response of topics.
*/
private Mono<PagedResponse<TopicProperties>> listTopics(int skip, Context context) {
return managementClient.listEntitiesWithResponseAsync(TOPICS_ENTITY_TYPE, skip, NUMBER_OF_ELEMENTS, context)
.onErrorMap(ServiceBusAdministrationAsyncClient::mapException)
.flatMap(response -> {
final Response<TopicDescriptionFeed> feedResponse = deserialize(response, TopicDescriptionFeed.class);
final TopicDescriptionFeed feed = feedResponse.getValue();
if (feed == null) {
logger.warning("Could not deserialize TopicDescriptionFeed. skip {}, top: {}", skip,
NUMBER_OF_ELEMENTS);
return Mono.empty();
}
final List<TopicProperties> entities = feed.getEntry().stream()
.filter(e -> e.getContent() != null && e.getContent().getTopicDescription() != null)
.map(e -> {
final String topicName = getTitleValue(e.getTitle());
final TopicProperties topicProperties = EntityHelper.toModel(
e.getContent().getTopicDescription());
EntityHelper.setTopicName(topicProperties, topicName);
return topicProperties;
})
.collect(Collectors.toList());
try {
return Mono.just(extractPage(feedResponse, entities, feed.getLink()));
} catch (MalformedURLException | UnsupportedEncodingException error) {
return Mono.error(new RuntimeException("Could not parse response into FeedPage<TopicDescription>",
error));
}
});
}
/**
* Given an XML title element, returns the XML text inside. Jackson deserializes Objects as LinkedHashMaps. XML text
* is represented as an entry with an empty string as the key.
*
* For example, the text returned from this {@code <title text="text/xml">QueueName</title>} is "QueueName".
*
* @param responseTitle XML title element.
*
* @return The XML text inside the title. {@code null} is returned if there is no value.
*/
@SuppressWarnings("unchecked")
private String getTitleValue(Object responseTitle) {
if (!(responseTitle instanceof Map)) {
return null;
}
final Map<String, String> map;
try {
map = (Map<String, String>) responseTitle;
return map.get("");
} catch (ClassCastException error) {
logger.warning("Unable to cast to Map<String,String>. Title: {}", responseTitle, error);
return null;
}
}
/**
* Maps an exception from the ATOM APIs to its associated {@link HttpResponseException}.
*
* @param exception Exception from the ATOM API.
*
* @return The corresponding {@link HttpResponseException} or {@code throwable} if it is not an instance of {@link
* ServiceBusManagementErrorException}.
*/
private static Throwable mapException(Throwable exception) {
if (!(exception instanceof ServiceBusManagementErrorException)) {
return exception;
}
final ServiceBusManagementErrorException managementError = ((ServiceBusManagementErrorException) exception);
final ServiceBusManagementError error = managementError.getValue();
final HttpResponse errorHttpResponse = managementError.getResponse();
final int statusCode = error != null && error.getCode() != null
? error.getCode()
: errorHttpResponse.getStatusCode();
final String errorDetail = error != null && error.getDetail() != null
? error.getDetail()
: managementError.getMessage();
switch (statusCode) {
case 401:
return new ClientAuthenticationException(errorDetail, managementError.getResponse(), exception);
case 404:
return new ResourceNotFoundException(errorDetail, managementError.getResponse(), exception);
case 409:
return new ResourceExistsException(errorDetail, managementError.getResponse(), exception);
case 412:
return new ResourceModifiedException(errorDetail, managementError.getResponse(), exception);
default:
return new HttpResponseException(errorDetail, managementError.getResponse(), exception);
}
}
/**
* A page of Service Bus entities.
*
* @param <T> The entity description from Service Bus.
*/
private static final class FeedPage<T> implements PagedResponse<T> {
private final int statusCode;
private final HttpHeaders header;
private final HttpRequest request;
private final IterableStream<T> entries;
private final String continuationToken;
/**
* Creates a page that does not have any more pages.
*
* @param entries Items in the page.
*/
private FeedPage(int statusCode, HttpHeaders header, HttpRequest request, List<T> entries) {
this.statusCode = statusCode;
this.header = header;
this.request = request;
this.entries = new IterableStream<>(entries);
this.continuationToken = null;
}
/**
* Creates an instance that has additional pages to fetch.
*
* @param entries Items in the page.
* @param skip Number of elements to "skip".
*/
private FeedPage(int statusCode, HttpHeaders header, HttpRequest request, List<T> entries, int skip) {
this.statusCode = statusCode;
this.header = header;
this.request = request;
this.entries = new IterableStream<>(entries);
this.continuationToken = String.valueOf(skip);
}
@Override
public IterableStream<T> getElements() {
return entries;
}
@Override
public String getContinuationToken() {
return continuationToken;
}
@Override
public int getStatusCode() {
return statusCode;
}
@Override
public HttpHeaders getHeaders() {
return header;
}
@Override
public HttpRequest getRequest() {
return request;
}
@Override
public void close() {
}
}
private static final class EntityNotFoundHttpResponse<T> extends HttpResponse {
private final int statusCode;
private final HttpHeaders headers;
private EntityNotFoundHttpResponse(Response<T> response) {
super(response.getRequest());
this.headers = response.getHeaders();
this.statusCode = response.getStatusCode();
}
@Override
public int getStatusCode() {
return statusCode;
}
@Override
public String getHeaderValue(String name) {
return headers.getValue(name);
}
@Override
public HttpHeaders getHeaders() {
return headers;
}
@Override
public Flux<ByteBuffer> getBody() {
return Flux.empty();
}
@Override
public Mono<byte[]> getBodyAsByteArray() {
return Mono.empty();
}
@Override
public Mono<String> getBodyAsString() {
return Mono.empty();
}
@Override
public Mono<String> getBodyAsString(Charset charset) {
return Mono.empty();
}
}
} | class ServiceBusAdministrationAsyncClient {
private static final String SERVICE_BUS_TRACING_NAMESPACE_VALUE = "Microsoft.ServiceBus";
private static final String CONTENT_TYPE = "application/xml";
private static final String QUEUES_ENTITY_TYPE = "queues";
private static final String TOPICS_ENTITY_TYPE = "topics";
private static final int NUMBER_OF_ELEMENTS = 100;
private final ServiceBusManagementClientImpl managementClient;
private final EntitiesImpl entityClient;
private final ClientLogger logger = new ClientLogger(ServiceBusAdministrationAsyncClient.class);
private final ServiceBusManagementSerializer serializer;
private final RulesImpl rulesClient;
/**
* Creates a new instance with the given management client and serializer.
*
* @param managementClient Client to make management calls.
* @param serializer Serializer to deserialize ATOM XML responses.
*/
ServiceBusAdministrationAsyncClient(ServiceBusManagementClientImpl managementClient,
ServiceBusManagementSerializer serializer) {
this.serializer = Objects.requireNonNull(serializer, "'serializer' cannot be null.");
this.managementClient = Objects.requireNonNull(managementClient, "'managementClient' cannot be null.");
this.entityClient = managementClient.getEntities();
this.rulesClient = managementClient.getRules();
}
/**
* Creates a queue with the given name.
*
* @param queueName Name of the queue to create.
*
* @return A Mono that completes with information about the created queue.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If the request body was invalid, the queue quota is exceeded, or an error
* occurred processing the request.
* @throws NullPointerException if {@code queueName} is null.
* @throws IllegalArgumentException if {@code queueName} is an empty string.
* @throws ResourceExistsException if a queue exists with the same {@code queueName}.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<QueueProperties> createQueue(String queueName) {
try {
return createQueue(queueName, new CreateQueueOptions());
} catch (RuntimeException e) {
return monoError(logger, e);
}
}
/**
* Creates a queue with the {@link CreateQueueOptions} and given queue name.
*
* @param queueName Name of the queue to create.
* @param queueOptions Options about the queue to create.
*
* @return A Mono that completes with information about the created queue.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If the request body was invalid, the queue quota is exceeded, or an error
* occurred processing the request.
* @throws IllegalArgumentException if {@code queueName} is an empty string.
* @throws NullPointerException if {@code queueName} or {@code queueOptions} is null.
* @throws ResourceExistsException if a queue exists with the same {@link QueueProperties
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<QueueProperties> createQueue(String queueName, CreateQueueOptions queueOptions) {
return createQueueWithResponse(queueName, queueOptions).map(Response::getValue);
}
/**
* Creates a queue and returns the created queue in addition to the HTTP response.
*
* @param queueName Name of the queue to create.
* @param queueOptions Options about the queue to create.
*
* @return A Mono that returns the created queue in addition to the HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If the request body was invalid, the queue quota is exceeded, or an error
* occurred processing the request.
* @throws IllegalArgumentException if {@code queueName} is an empty string.
* @throws NullPointerException if {@code queueName} or {@code queueOptions} is null.
* @throws ResourceExistsException if a queue exists with the same {@link QueueProperties
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<QueueProperties>> createQueueWithResponse(String queueName, CreateQueueOptions queueOptions) {
return withContext(context -> createQueueWithResponse(queueName, queueOptions, context));
}
/**
* Creates a rule under the given topic and subscription
*
* @param topicName Name of the topic associated with rule.
* @param subscriptionName Name of the subscription associated with the rule.
* @param ruleName Name of the rule.
*
* @return A Mono that completes with information about the created rule.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If the request body was invalid, the quota is exceeded, or an error occurred
* processing the request.
* @throws IllegalArgumentException if {@code topicName} or {@code ruleName} are are empty strings.
* @throws NullPointerException if {@code topicName} or {@code ruleName} are are null.
* @throws ResourceExistsException if a rule exists with the same topic, subscription, and rule name.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<RuleProperties> createRule(String topicName, String subscriptionName, String ruleName) {
try {
return createRule(topicName, subscriptionName, ruleName, new CreateRuleOptions());
} catch (RuntimeException e) {
return monoError(logger, e);
}
}
/**
* Creates a rule with the {@link CreateRuleOptions}.
*
* @param topicName Name of the topic associated with rule.
* @param subscriptionName Name of the subscription associated with the rule.
* @param ruleName Name of the rule.
* @param ruleOptions Information about the rule to create.
*
* @return A Mono that completes with information about the created rule.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If the request body was invalid, the quota is exceeded, or an error occurred
* processing the request.
* @throws IllegalArgumentException if {@code topicName} or {@code ruleName} are are empty strings.
* @throws NullPointerException if {@code topicName}, {@code ruleName}, or {@code ruleOptions}
* are are null.
* @throws ResourceExistsException if a rule exists with the same topic and rule name.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<RuleProperties> createRule(String topicName, String subscriptionName, String ruleName,
CreateRuleOptions ruleOptions) {
return createRuleWithResponse(topicName, subscriptionName, ruleName, ruleOptions)
.map(Response::getValue);
}
/**
* Creates a rule and returns the created rule in addition to the HTTP response.
*
* @param topicName Name of the topic associated with rule.
* @param subscriptionName Name of the subscription associated with the rule.
* @param ruleName Name of the rule.
* @param ruleOptions Information about the rule to create.
*
* @return A Mono that returns the created rule in addition to the HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If the request body was invalid, the quota is exceeded, or an error occurred
* processing the request.
* @throws IllegalArgumentException if {@code topicName} or {@code ruleName} are are empty strings.
* @throws NullPointerException if {@code topicName}, {@code ruleName}, or {@code ruleOptions}
* are are null.
* @throws ResourceExistsException if a rule exists with the same topic and rule name.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<RuleProperties>> createRuleWithResponse(String topicName, String subscriptionName,
String ruleName, CreateRuleOptions ruleOptions) {
return withContext(context -> createRuleWithResponse(topicName, subscriptionName, ruleName, ruleOptions,
context));
}
/**
* Creates a subscription with the given topic and subscription names.
*
* @param topicName Name of the topic associated with subscription.
* @param subscriptionName Name of the subscription.
*
* @return A Mono that completes with information about the created subscription.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If the request body was invalid, the quota is exceeded, or an error occurred
* processing the request.
* @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} are are empty strings.
* @throws NullPointerException if {@code topicName} or {@code subscriptionName} are are null.
* @throws ResourceExistsException if a subscription exists with the same topic and subscription name.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<SubscriptionProperties> createSubscription(String topicName, String subscriptionName) {
try {
return createSubscription(topicName, subscriptionName, new CreateSubscriptionOptions());
} catch (RuntimeException e) {
return monoError(logger, e);
}
}
/**
* Creates a subscription with the {@link CreateSubscriptionOptions}.
*
* @param topicName Name of the topic associated with subscription.
* @param subscriptionName Name of the subscription.
* @param subscriptionOptions Information about the subscription to create.
*
* @return A Mono that completes with information about the created subscription.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If the request body was invalid, the quota is exceeded, or an error occurred
* processing the request.
* @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} are are empty strings.
* @throws NullPointerException if {@code topicName}, {@code subscriptionName}, or {@code subscriptionOptions}
* are are null.
* @throws ResourceExistsException if a subscription exists with the same topic and subscription name.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<SubscriptionProperties> createSubscription(String topicName, String subscriptionName,
CreateSubscriptionOptions subscriptionOptions) {
return createSubscriptionWithResponse(topicName, subscriptionName, subscriptionOptions)
.map(Response::getValue);
}
/**
* Creates a subscription and returns the created subscription in addition to the HTTP response.
*
* @param topicName Name of the topic associated with subscription.
* @param subscriptionName Name of the subscription.
* @param subscriptionOptions Information about the subscription to create.
*
* @return A Mono that returns the created subscription in addition to the HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If the request body was invalid, the quota is exceeded, or an error occurred
* processing the request.
* @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} are are empty strings.
* @throws NullPointerException if {@code topicName}, {@code subscriptionName}, or {@code subscriptionOptions}
* are are null.
* @throws ResourceExistsException if a subscription exists with the same topic and subscription name.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<SubscriptionProperties>> createSubscriptionWithResponse(String topicName,
String subscriptionName, CreateSubscriptionOptions subscriptionOptions) {
return withContext(context -> createSubscriptionWithResponse(topicName, subscriptionName, subscriptionOptions,
context));
}
/**
* Creates a topic with the given name.
*
* @param topicName Name of the topic to create.
*
* @return A Mono that completes with information about the created topic.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If the request body was invalid, the topic quota is exceeded, or an error
* occurred processing the request.
* @throws NullPointerException if {@code topicName} is null.
* @throws IllegalArgumentException if {@code topicName} is an empty string.
* @throws ResourceExistsException if a topic exists with the same {@code topicName}.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<TopicProperties> createTopic(String topicName) {
try {
return createTopic(topicName, new CreateTopicOptions());
} catch (RuntimeException e) {
return monoError(logger, e);
}
}
/**
* Creates a topic with the {@link CreateTopicOptions}.
*
* @param topicName Name of the topic to create.
* @param topicOptions The options used to create the topic.
*
* @return A Mono that completes with information about the created topic.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If the request body was invalid, the topic quota is exceeded, or an error
* occurred processing the request.
* @throws IllegalArgumentException if {@code topicName} is an empty string.
* @throws NullPointerException if {@code topicName} or {@code topicOptions} is null.
* @throws ResourceExistsException if a topic exists with the same {@code topicName}.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<TopicProperties> createTopic(String topicName, CreateTopicOptions topicOptions) {
return createTopicWithResponse(topicName, topicOptions).map(Response::getValue);
}
/**
* Creates a topic and returns the created topic in addition to the HTTP response.
*
* @param topicName Name of the topic to create.
* @param topicOptions The options used to create the topic.
*
* @return A Mono that returns the created topic in addition to the HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If the request body was invalid, the topic quota is exceeded, or an error
* occurred processing the request.
* @throws IllegalArgumentException if {@link TopicProperties
* string.
* @throws NullPointerException if {@code topicName} or {@code topicOptions} is null.
* @throws ResourceExistsException if a topic exists with the same {@code topicName}.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<TopicProperties>> createTopicWithResponse(String topicName, CreateTopicOptions topicOptions) {
return withContext(context -> createTopicWithResponse(topicName, topicOptions, context));
}
/**
* Deletes a queue the matching {@code queueName}.
*
* @param queueName Name of queue to delete.
*
* @return A Mono that completes when the queue is deleted.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws NullPointerException if {@code queueName} is null.
* @throws IllegalArgumentException if {@code queueName} is an empty string.
* @throws ResourceNotFoundException if the {@code queueName} does not exist.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Void> deleteQueue(String queueName) {
return deleteQueueWithResponse(queueName).then();
}
/**
* Deletes a queue the matching {@code queueName} and returns the HTTP response.
*
* @param queueName Name of queue to delete.
*
* @return A Mono that completes when the queue is deleted and returns the HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws NullPointerException if {@code queueName} is null.
* @throws IllegalArgumentException if {@code queueName} is an empty string.
* @throws ResourceNotFoundException if the {@code queueName} does not exist.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Void>> deleteQueueWithResponse(String queueName) {
return withContext(context -> deleteQueueWithResponse(queueName, context));
}
/**
* Deletes a rule the matching {@code ruleName}.
*
* @param topicName Name of topic associated with rule to delete.
* @param subscriptionName Name of the subscription associated with the rule to delete.
* @param ruleName Name of rule to delete.
*
* @return A Mono that completes when the rule is deleted.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code topicName} or {@code ruleName} is an empty string.
* @throws NullPointerException if {@code topicName} or {@code ruleName} is null.
* @throws ResourceNotFoundException if the {@code ruleName} does not exist.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Void> deleteRule(String topicName, String subscriptionName, String ruleName) {
return deleteRuleWithResponse(topicName, subscriptionName, ruleName).then();
}
/**
* Deletes a rule the matching {@code ruleName} and returns the HTTP response.
*
* @param topicName Name of topic associated with rule to delete.
* @param subscriptionName Name of the subscription associated with the rule to delete.
* @param ruleName Name of rule to delete.
*
* @return A Mono that completes when the rule is deleted and returns the HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code topicName}, {@code subscriptionName}, or {@code ruleName} is an
* empty string.
* @throws NullPointerException if {@code topicName}, {@code subscriptionName}, or {@code ruleName} is null.
* @throws ResourceNotFoundException if the {@code ruleName} does not exist.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Void>> deleteRuleWithResponse(String topicName, String subscriptionName,
String ruleName) {
return withContext(context -> deleteRuleWithResponse(topicName, subscriptionName, ruleName, context));
}
/**
* Deletes a subscription the matching {@code subscriptionName}.
*
* @param topicName Name of topic associated with subscription to delete.
* @param subscriptionName Name of subscription to delete.
*
* @return A Mono that completes when the subscription is deleted.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} is an empty string.
* @throws NullPointerException if {@code topicName} or {@code subscriptionName} is null.
* @throws ResourceNotFoundException if the {@code subscriptionName} does not exist.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Void> deleteSubscription(String topicName, String subscriptionName) {
return deleteSubscriptionWithResponse(topicName, subscriptionName).then();
}
/**
* Deletes a subscription the matching {@code subscriptionName} and returns the HTTP response.
*
* @param topicName Name of topic associated with subscription to delete.
* @param subscriptionName Name of subscription to delete.
*
* @return A Mono that completes when the subscription is deleted and returns the HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} is an empty string.
* @throws NullPointerException if {@code topicName} or {@code subscriptionName} is null.
* @throws ResourceNotFoundException if the {@code subscriptionName} does not exist.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Void>> deleteSubscriptionWithResponse(String topicName, String subscriptionName) {
return withContext(context -> deleteSubscriptionWithResponse(topicName, subscriptionName, context));
}
/**
* Deletes a topic the matching {@code topicName}.
*
* @param topicName Name of topic to delete.
*
* @return A Mono that completes when the topic is deleted.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code topicName} is an empty string.
* @throws NullPointerException if {@code topicName} is null.
* @throws ResourceNotFoundException if the {@code topicName} does not exist.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Void> deleteTopic(String topicName) {
return deleteTopicWithResponse(topicName).then();
}
/**
* Deletes a topic the matching {@code topicName} and returns the HTTP response.
*
* @param topicName Name of topic to delete.
*
* @return A Mono that completes when the topic is deleted and returns the HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code topicName} is an empty string.
* @throws NullPointerException if {@code topicName} is null.
* @throws ResourceNotFoundException if the {@code topicName} does not exist.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Void>> deleteTopicWithResponse(String topicName) {
return withContext(context -> deleteTopicWithResponse(topicName, context));
}
/**
* Gets information about the queue.
*
* @param queueName Name of queue to get information about.
*
* @return A Mono that completes with information about the queue.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code queueName} is an empty string.
* @throws NullPointerException if {@code queueName} is null.
* @throws ResourceNotFoundException if the {@code queueName} does not exist.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<QueueProperties> getQueue(String queueName) {
return getQueueWithResponse(queueName).map(Response::getValue);
}
/**
* Gets information about the queue along with its HTTP response.
*
* @param queueName Name of queue to get information about.
*
* @return A Mono that completes with information about the queue and the associated HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code queueName} is an empty string.
* @throws NullPointerException if {@code queueName} is null.
* @throws ResourceNotFoundException if the {@code queueName} does not exist.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<QueueProperties>> getQueueWithResponse(String queueName) {
return withContext(context -> getQueueWithResponse(queueName, context, Function.identity()));
}
/**
* Gets whether or not a queue with {@code queueName} exists in the Service Bus namespace.
*
* @param queueName Name of the queue.
*
* @return A Mono that completes indicating whether or not the queue exists.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code queueName} is an empty string.
* @throws NullPointerException if {@code queueName} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Boolean> getQueueExists(String queueName) {
return getQueueExistsWithResponse(queueName).map(Response::getValue);
}
/**
* Gets whether or not a queue with {@code queueName} exists in the Service Bus namespace.
*
* @param queueName Name of the queue.
*
* @return A Mono that completes indicating whether or not the queue exists along with its HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code queueName} is an empty string.
* @throws NullPointerException if {@code queueName} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Boolean>> getQueueExistsWithResponse(String queueName) {
return getEntityExistsWithResponse(getQueueWithResponse(queueName));
}
/**
* Gets runtime properties about the queue.
*
* @param queueName Name of queue to get information about.
*
* @return A Mono that completes with runtime properties about the queue.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code queueName} is an empty string.
* @throws NullPointerException if {@code queueName} is null.
* @throws ResourceNotFoundException if the {@code queueName} does not exist.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<QueueRuntimeProperties> getQueueRuntimeProperties(String queueName) {
return getQueueRuntimePropertiesWithResponse(queueName).map(response -> response.getValue());
}
/**
* Gets runtime properties about the queue along with its HTTP response.
*
* @param queueName Name of queue to get information about.
*
* @return A Mono that completes with runtime properties about the queue and the associated HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code queueName} is an empty string.
* @throws NullPointerException if {@code queueName} is null.
* @throws ResourceNotFoundException if the {@code queueName} does not exist.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<QueueRuntimeProperties>> getQueueRuntimePropertiesWithResponse(String queueName) {
return withContext(context -> getQueueWithResponse(queueName, context, QueueRuntimeProperties::new));
}
/**
* Gets information about the Service Bus namespace.
*
* @return A Mono that completes with information about the Service Bus namespace.
* @throws ClientAuthenticationException if the client's credentials do not have access to the namespace.
* @throws HttpResponseException If error occurred processing the request.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<NamespaceProperties> getNamespaceProperties() {
return getNamespacePropertiesWithResponse().map(Response::getValue);
}
/**
* Gets information about the Service Bus namespace along with its HTTP response.
*
* @return A Mono that completes with information about the namespace and the associated HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<NamespaceProperties>> getNamespacePropertiesWithResponse() {
return withContext(this::getNamespacePropertiesWithResponse);
}
/**
* Gets a rule from the service namespace.
*
* Only following data types are deserialized in Filters and Action parameters - string, int, long, boolean, double,
* and OffsetDateTime. Other data types would return its string value.
*
* @param topicName The name of the topic relative to service bus namespace.
* @param subscriptionName The subscription name the rule belongs to.
* @param ruleName The name of the rule to retrieve.
*
* @return The associated rule.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<RuleProperties> getRule(String topicName, String subscriptionName, String ruleName) {
return getRuleWithResponse(topicName, subscriptionName, ruleName).map(response -> response.getValue());
}
/**
* Gets a rule from the service namespace.
*
* Only following data types are deserialized in Filters and Action parameters - string, int, long, bool, double,
* and OffsetDateTime. Other data types would return its string value.
*
* @param topicName The name of the topic relative to service bus namespace.
* @param subscriptionName The subscription name the rule belongs to.
* @param ruleName The name of the rule to retrieve.
*
* @return The associated rule with the corresponding HTTP response.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<RuleProperties>> getRuleWithResponse(String topicName, String subscriptionName,
String ruleName) {
return withContext(context -> getRuleWithResponse(topicName, subscriptionName, ruleName, context));
}
/**
* Gets information about the queue.
*
* @param topicName Name of topic associated with subscription.
* @param subscriptionName Name of subscription to get information about.
*
* @return A Mono that completes with information about the subscription.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} are empty strings.
* @throws NullPointerException if {@code topicName} or {@code subscriptionName} are null.
* @throws ResourceNotFoundException if the {@code subscriptionName} does not exist in the {@code topicName}.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<SubscriptionProperties> getSubscription(String topicName, String subscriptionName) {
return getSubscriptionWithResponse(topicName, subscriptionName).map(Response::getValue);
}
/**
* Gets information about the subscription along with its HTTP response.
*
* @param topicName Name of topic associated with subscription.
* @param subscriptionName Name of subscription to get information about.
*
* @return A Mono that completes with information about the subscription and the associated HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} are empty strings.
* @throws NullPointerException if {@code topicName} or {@code subscriptionName} are null.
* @throws ResourceNotFoundException if the {@code subscriptionName} does not exist.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<SubscriptionProperties>> getSubscriptionWithResponse(String topicName,
String subscriptionName) {
return withContext(context -> getSubscriptionWithResponse(topicName, subscriptionName, context,
Function.identity()));
}
/**
* Gets whether or not a subscription within a topic exists.
*
* @param topicName Name of topic associated with subscription.
* @param subscriptionName Name of the subscription.
*
* @return A Mono that completes indicating whether or not the subscription exists.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code subscriptionName} is an empty string.
* @throws NullPointerException if {@code subscriptionName} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Boolean> getSubscriptionExists(String topicName, String subscriptionName) {
return getSubscriptionExistsWithResponse(topicName, subscriptionName).map(Response::getValue);
}
/**
* Gets whether or not a subscription within a topic exists.
*
* @param topicName Name of topic associated with subscription.
* @param subscriptionName Name of the subscription.
*
* @return A Mono that completes indicating whether or not the subscription exists along with its HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code subscriptionName} is an empty string.
* @throws NullPointerException if {@code subscriptionName} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Boolean>> getSubscriptionExistsWithResponse(String topicName, String subscriptionName) {
return getEntityExistsWithResponse(getSubscriptionWithResponse(topicName, subscriptionName));
}
/**
* Gets runtime properties about the subscription.
*
* @param topicName Name of topic associated with subscription.
* @param subscriptionName Name of subscription to get information about.
*
* @return A Mono that completes with runtime properties about the subscription.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} are empty strings.
* @throws NullPointerException if {@code topicName} or {@code subscriptionName} are null.
* @throws ResourceNotFoundException if the {@code subscriptionName} does not exist.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<SubscriptionRuntimeProperties> getSubscriptionRuntimeProperties(
String topicName, String subscriptionName) {
return getSubscriptionRuntimePropertiesWithResponse(topicName, subscriptionName)
.map(response -> response.getValue());
}
/**
* Gets runtime properties about the subscription.
*
* @param topicName Name of topic associated with subscription.
* @param subscriptionName Name of subscription to get information about.
*
* @return A Mono that completes with runtime properties about the subscription.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code subscriptionName} is an empty string.
* @throws NullPointerException if {@code subscriptionName} is null.
* @throws ResourceNotFoundException if the {@code subscriptionName} does not exist.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<SubscriptionRuntimeProperties>> getSubscriptionRuntimePropertiesWithResponse(
String topicName, String subscriptionName) {
return withContext(context -> getSubscriptionWithResponse(topicName, subscriptionName, context,
SubscriptionRuntimeProperties::new));
}
/**
* Gets information about the topic.
*
* @param topicName Name of topic to get information about.
*
* @return A Mono that completes with information about the topic.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code topicName} is an empty string.
* @throws NullPointerException if {@code topicName} is null.
* @throws ResourceNotFoundException if the {@code topicName} does not exist.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<TopicProperties> getTopic(String topicName) {
return getTopicWithResponse(topicName).map(Response::getValue);
}
/**
* Gets information about the topic along with its HTTP response.
*
* @param topicName Name of topic to get information about.
*
* @return A Mono that completes with information about the topic and the associated HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code topicName} is an empty string.
* @throws NullPointerException if {@code topicName} is null.
* @throws ResourceNotFoundException if the {@code topicName} does not exist.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<TopicProperties>> getTopicWithResponse(String topicName) {
return withContext(context -> getTopicWithResponse(topicName, context, Function.identity()));
}
/**
* Gets whether or not a topic with {@code topicName} exists in the Service Bus namespace.
*
* @param topicName Name of the topic.
*
* @return A Mono that completes indicating whether or not the topic exists.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code topicName} is an empty string.
* @throws NullPointerException if {@code topicName} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Boolean> getTopicExists(String topicName) {
return getTopicExistsWithResponse(topicName).map(Response::getValue);
}
/**
* Gets whether or not a topic with {@code topicName} exists in the Service Bus namespace.
*
* @param topicName Name of the topic.
*
* @return A Mono that completes indicating whether or not the topic exists along with its HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code topicName} is an empty string.
* @throws NullPointerException if {@code topicName} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Boolean>> getTopicExistsWithResponse(String topicName) {
return getEntityExistsWithResponse(getTopicWithResponse(topicName));
}
/**
* Gets runtime properties about the topic.
*
* @param topicName Name of topic to get information about.
*
* @return A Mono that completes with runtime properties about the topic.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code topicName} is an empty string.
* @throws NullPointerException if {@code topicName} is null.
* @throws ResourceNotFoundException if the {@code topicName} does not exist.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<TopicRuntimeProperties> getTopicRuntimeProperties(String topicName) {
return getTopicRuntimePropertiesWithResponse(topicName).map(response -> response.getValue());
}
/**
* Gets runtime properties about the topic with its HTTP response.
*
* @param topicName Name of topic to get information about.
*
* @return A Mono that completes with runtime properties about the topic and the associated HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code topicName} is an empty string.
* @throws NullPointerException if {@code topicName} is null.
* @throws ResourceNotFoundException if the {@code topicName} does not exist.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<TopicRuntimeProperties>> getTopicRuntimePropertiesWithResponse(String topicName) {
return withContext(context -> getTopicWithResponse(topicName, context, TopicRuntimeProperties::new));
}
/**
* Fetches all the queues in the Service Bus namespace.
*
* @return A Flux of {@link QueueProperties queues} in the Service Bus namespace.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @see <a href="https:
* authorization rules</a>
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux<QueueProperties> listQueues() {
return new PagedFlux<>(
() -> withContext(context -> listQueuesFirstPage(context)),
token -> withContext(context -> listQueuesNextPage(token, context)));
}
/**
* Fetches all the rules for a topic and subscription.
*
* @param topicName The topic name under which all the rules need to be retrieved.
* @param subscriptionName The name of the subscription for which all rules need to be retrieved.
*
* @return A Flux of {@link RuleProperties rules} for the {@code topicName} and {@code subscriptionName}.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws NullPointerException if {@code topicName} or {@code subscriptionName} is null.
* @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} is an empty string.
* @see <a href="https:
* authorization rules</a>
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux<RuleProperties> listRules(String topicName, String subscriptionName) {
if (topicName == null) {
return pagedFluxError(logger, new NullPointerException("'topicName' cannot be null."));
} else if (topicName.isEmpty()) {
return pagedFluxError(logger, new IllegalArgumentException("'topicName' cannot be an empty string."));
}
return new PagedFlux<>(
() -> withContext(context -> listRulesFirstPage(topicName, subscriptionName, context)),
token -> withContext(context -> listRulesNextPage(topicName, subscriptionName, token, context)));
}
/**
* Fetches all the subscriptions for a topic.
*
* @param topicName The topic name under which all the subscriptions need to be retrieved.
*
* @return A Flux of {@link SubscriptionProperties subscriptions} for the {@code topicName}.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws NullPointerException if {@code topicName} is null.
* @throws IllegalArgumentException if {@code topicName} is an empty string.
* @see <a href="https:
* authorization rules</a>
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux<SubscriptionProperties> listSubscriptions(String topicName) {
if (topicName == null) {
return pagedFluxError(logger, new NullPointerException("'topicName' cannot be null."));
} else if (topicName.isEmpty()) {
return pagedFluxError(logger, new IllegalArgumentException("'topicName' cannot be an empty string."));
}
return new PagedFlux<>(
() -> withContext(context -> listSubscriptionsFirstPage(topicName, context)),
token -> withContext(context -> listSubscriptionsNextPage(topicName, token, context)));
}
/**
* Fetches all the topics in the Service Bus namespace.
*
* @return A Flux of {@link TopicProperties topics} in the Service Bus namespace.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @see <a href="https:
* authorization rules</a>
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux<TopicProperties> listTopics() {
return new PagedFlux<>(
() -> withContext(context -> listTopicsFirstPage(context)),
token -> withContext(context -> listTopicsNextPage(token, context)));
}
/**
* Updates a queue with the given {@link QueueProperties}. The {@link QueueProperties} must be fully populated as
* all of the properties are replaced. If a property is not set the service default value is used.
*
* The suggested flow is:
* <ol>
* <li>{@link
* <li>Update the required elements.</li>
* <li>Pass the updated description into this method.</li>
* </ol>
*
* <p>
* There are a subset of properties that can be updated. More information can be found in the links below. They are:
* <ul>
* <li>{@link QueueProperties
* <li>{@link QueueProperties
* <li>{@link QueueProperties
* </li>
* <li>{@link QueueProperties
* </ul>
*
* @param queue Information about the queue to update. You must provide all the property values that are desired
* on the updated entity. Any values not provided are set to the service default values.
*
* @return A Mono that completes with the updated queue.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If the request body was invalid, the queue quota is exceeded, or an error
* occurred processing the request.
* @throws NullPointerException if {@code queue} is null.
* @see <a href="https:
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<QueueProperties> updateQueue(QueueProperties queue) {
return updateQueueWithResponse(queue).map(Response::getValue);
}
/**
* Updates a queue with the given {@link QueueProperties}. The {@link QueueProperties} must be fully populated as
* all of the properties are replaced. If a property is not set the service default value is used.
*
* The suggested flow is:
* <ol>
* <li>{@link
* <li>Update the required elements.</li>
* <li>Pass the updated description into this method.</li>
* </ol>
*
* <p>
* There are a subset of properties that can be updated. More information can be found in the links below. They are:
* <ul>
* <li>{@link QueueProperties
* <li>{@link QueueProperties
* <li>{@link QueueProperties
* </li>
* <li>{@link QueueProperties
* </ul>
*
* @param queue Information about the queue to update. You must provide all the property values that are desired
* on the updated entity. Any values not provided are set to the service default values.
*
* @return A Mono that returns the updated queue in addition to the HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If the request body was invalid, the queue quota is exceeded, or an error
* occurred processing the request.
* @throws NullPointerException if {@code queue} is null.
* @see <a href="https:
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<QueueProperties>> updateQueueWithResponse(QueueProperties queue) {
return withContext(context -> updateQueueWithResponse(queue, context));
}
/**
* Updates a rule with the given {@link RuleProperties}. The {@link RuleProperties} must be fully populated as all
* of the properties are replaced. If a property is not set the service default value is used.
*
* The suggested flow is:
* <ol>
* <li>{@link
* <li>Update the required elements.</li>
* <li>Pass the updated description into this method.</li>
* </ol>
*
* @param topicName The topic name under which the rule is updated.
* @param subscriptionName The name of the subscription for which the rule is updated.
* @param rule Information about the rule to update. You must provide all the property values that are desired
* on the updated entity. Any values not provided are set to the service default values.
*
* @return A Mono that returns the updated rule.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If the request body was invalid, the rule quota is exceeded, or an error
* occurred processing the request.
* @throws IllegalArgumentException if {@link RuleProperties
* @throws NullPointerException if {@code rule} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<RuleProperties> updateRule(String topicName, String subscriptionName, RuleProperties rule) {
return updateRuleWithResponse(topicName, subscriptionName, rule).map(Response::getValue);
}
/**
* Updates a rule with the given {@link RuleProperties}. The {@link RuleProperties} must be fully populated as all
* of the properties are replaced. If a property is not set the service default value is used.
*
* The suggested flow is:
* <ol>
* <li>{@link
* <li>Update the required elements.</li>
* <li>Pass the updated description into this method.</li>
* </ol>
*
* @param topicName The topic name under which the rule is updated.
* @param subscriptionName The name of the subscription for which the rule is updated.
* @param rule Information about the rule to update. You must provide all the property values that are desired
* on the updated entity. Any values not provided are set to the service default values.
*
* @return A Mono that returns the updated rule in addition to the HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If the request body was invalid, the rule quota is exceeded, or an error
* occurred processing the request.
* @throws IllegalArgumentException if {@link RuleProperties
* @throws NullPointerException if {@code rule} is null.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<RuleProperties>> updateRuleWithResponse(String topicName, String subscriptionName,
RuleProperties rule) {
return withContext(context -> updateRuleWithResponse(topicName, subscriptionName, rule, context));
}
/**
* Updates a subscription with the given {@link SubscriptionProperties}. The {@link SubscriptionProperties} must be
* fully populated as all of the properties are replaced. If a property is not set the service default value is
* used.
*
* The suggested flow is:
* <ol>
* <li>{@link
* <li>Update the required elements.</li>
* <li>Pass the updated description into this method.</li>
* </ol>
*
* <p>
* There are a subset of properties that can be updated. More information can be found in the links below. They are:
* <ul>
* <li>{@link SubscriptionProperties
* <li>{@link SubscriptionProperties
* <li>{@link SubscriptionProperties
* </ul>
*
* @param subscription Information about the subscription to update. You must provide all the property values
* that are desired on the updated entity. Any values not provided are set to the service default values.
*
* @return A Mono that returns the updated subscription.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If the request body was invalid, the subscription quota is exceeded, or an
* error occurred processing the request.
* @throws IllegalArgumentException if {@link SubscriptionProperties
* SubscriptionProperties
* @throws NullPointerException if {@code subscription} is null.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<SubscriptionProperties> updateSubscription(SubscriptionProperties subscription) {
return updateSubscriptionWithResponse(subscription).map(Response::getValue);
}
/**
* Updates a subscription with the given {@link SubscriptionProperties}. The {@link SubscriptionProperties} must be
* fully populated as all of the properties are replaced. If a property is not set the service default value is
* used.
*
* The suggested flow is:
* <ol>
* <li>{@link
* <li>Update the required elements.</li>
* <li>Pass the updated description into this method.</li>
* </ol>
*
* <p>
* There are a subset of properties that can be updated. More information can be found in the links below. They are:
* <ul>
* <li>{@link SubscriptionProperties
* <li>{@link SubscriptionProperties
* <li>{@link SubscriptionProperties
* </ul>
*
* @param subscription Information about the subscription to update. You must provide all the property values
* that are desired on the updated entity. Any values not provided are set to the service default values.
*
* @return A Mono that returns the updated subscription in addition to the HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If the request body was invalid, the subscription quota is exceeded, or an
* error occurred processing the request.
* @throws IllegalArgumentException if {@link SubscriptionProperties
* SubscriptionProperties
* @throws NullPointerException if {@code subscription} is null.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<SubscriptionProperties>> updateSubscriptionWithResponse(
SubscriptionProperties subscription) {
return withContext(context -> updateSubscriptionWithResponse(subscription, context));
}
/**
* Updates a topic with the given {@link TopicProperties}. The {@link TopicProperties} must be fully populated as
* all of the properties are replaced. If a property is not set the service default value is used.
*
* The suggested flow is:
* <ol>
* <li>{@link
* <li>Update the required elements.</li>
* <li>Pass the updated description into this method.</li>
* </ol>
*
* <p>
* There are a subset of properties that can be updated. More information can be found in the links below. They are:
* <ul>
* <li>{@link TopicProperties
* <li>{@link TopicProperties
* </li>
* </ul>
*
* @param topic Information about the topic to update. You must provide all the property values that are desired
* on the updated entity. Any values not provided are set to the service default values.
*
* @return A Mono that completes with the updated topic.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If the request body was invalid, the topic quota is exceeded, or an error
* occurred processing the request.
* @throws IllegalArgumentException if {@link TopicProperties
* string.
* @throws NullPointerException if {@code topic} is null.
* @see <a href="https:
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<TopicProperties> updateTopic(TopicProperties topic) {
return updateTopicWithResponse(topic).map(Response::getValue);
}
/**
* Updates a topic with the given {@link TopicProperties}. The {@link TopicProperties} must be fully populated as
* all of the properties are replaced. If a property is not set the service default value is used.
*
* The suggested flow is:
* <ol>
* <li>{@link
* <li>Update the required elements.</li>
* <li>Pass the updated description into this method.</li>
* </ol>
*
* <p>
* There are a subset of properties that can be updated. More information can be found in the links below. They are:
* <ul>
* <li>{@link TopicProperties
* <li>{@link TopicProperties
* </li>
* </ul>
*
* @param topic Information about the topic to update. You must provide all the property values that are desired
* on the updated entity. Any values not provided are set to the service default values.
*
* @return A Mono that completes with the updated topic and its HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If the request body was invalid, the topic quota is exceeded, or an error
* occurred processing the request.
* @throws IllegalArgumentException if {@link TopicProperties
* string.
* @throws NullPointerException if {@code topic} is null.
* @see <a href="https:
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<TopicProperties>> updateTopicWithResponse(TopicProperties topic) {
return withContext(context -> updateTopicWithResponse(topic, context));
}
/**
* Creates a queue with its context.
*
* @param createQueueOptions Queue to create.
* @param context Context to pass into request.
*
* @return A Mono that completes with the created {@link QueueProperties}.
*/
Mono<Response<QueueProperties>> createQueueWithResponse(String queueName, CreateQueueOptions createQueueOptions,
Context context) {
if (queueName == null) {
return monoError(logger, new NullPointerException("'queueName' cannot be null."));
} else if (queueName.isEmpty()) {
return monoError(logger, new IllegalArgumentException("'queueName' cannot be empty."));
}
if (createQueueOptions == null) {
return monoError(logger, new NullPointerException("'createQueueOptions' cannot be null."));
} else if (context == null) {
return monoError(logger, new NullPointerException("'context' cannot be null."));
}
final QueueDescription description = EntityHelper.getQueueDescription(createQueueOptions);
final CreateQueueBodyContent content = new CreateQueueBodyContent()
.setType(CONTENT_TYPE)
.setQueueDescription(description);
final CreateQueueBody createEntity = new CreateQueueBody()
.setContent(content);
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
try {
return entityClient.putWithResponseAsync(queueName, createEntity, null, withTracing)
.onErrorMap(ServiceBusAdministrationAsyncClient::mapException)
.map(this::deserializeQueue);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Creates a rule with its context.
*
* @param ruleOptions Rule to create.
* @param context Context to pass into request.
*
* @return A Mono that completes with the created {@link RuleProperties}.
*/
Mono<Response<RuleProperties>> createRuleWithResponse(String topicName, String subscriptionName, String ruleName,
CreateRuleOptions ruleOptions, Context context) {
if (topicName == null) {
return monoError(logger, new NullPointerException("'topicName' cannot be null."));
} else if (topicName.isEmpty()) {
return monoError(logger, new IllegalArgumentException("'topicName' cannot be empty."));
}
if (subscriptionName == null) {
return monoError(logger, new NullPointerException("'subscriptionName' cannot be null."));
} else if (subscriptionName.isEmpty()) {
return monoError(logger, new IllegalArgumentException("'subscriptionName' cannot be empty."));
}
if (ruleName == null) {
return monoError(logger, new NullPointerException("'ruleName' cannot be null."));
} else if (ruleName.isEmpty()) {
return monoError(logger, new IllegalArgumentException("'ruleName' cannot be empty."));
}
if (ruleOptions == null) {
return monoError(logger, new NullPointerException("'rule' cannot be null."));
}
final RuleActionImpl action = ruleOptions.getAction() != null
? EntityHelper.toImplementation(ruleOptions.getAction())
: null;
final RuleFilterImpl filter = ruleOptions.getFilter() != null
? EntityHelper.toImplementation(ruleOptions.getFilter())
: null;
final RuleDescription rule = new RuleDescription()
.setAction(action)
.setFilter(filter)
.setName(ruleName);
final CreateRuleBodyContent content = new CreateRuleBodyContent()
.setType(CONTENT_TYPE)
.setRuleDescription(rule);
final CreateRuleBody createEntity = new CreateRuleBody().setContent(content);
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
try {
return managementClient.getRules().putWithResponseAsync(topicName, subscriptionName, ruleName, createEntity,
null, withTracing)
.onErrorMap(ServiceBusAdministrationAsyncClient::mapException)
.map(response -> deserializeRule(response));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Creates a subscription with its context.
*
* @param subscriptionOptions Subscription to create.
* @param context Context to pass into request.
*
* @return A Mono that completes with the created {@link SubscriptionProperties}.
*/
Mono<Response<SubscriptionProperties>> createSubscriptionWithResponse(String topicName, String subscriptionName,
CreateSubscriptionOptions subscriptionOptions, Context context) {
if (topicName == null) {
return monoError(logger, new NullPointerException("'topicName' cannot be null."));
} else if (topicName.isEmpty()) {
return monoError(logger, new IllegalArgumentException("'topicName' cannot be empty."));
}
if (subscriptionName == null) {
return monoError(logger, new NullPointerException("'subscriptionName' cannot be null."));
} else if (subscriptionName.isEmpty()) {
return monoError(logger, new IllegalArgumentException("'subscriptionName' cannot be empty."));
}
if (subscriptionOptions == null) {
return monoError(logger, new NullPointerException("'subscription' cannot be null."));
}
final SubscriptionDescription subscription = EntityHelper.getSubscriptionDescription(subscriptionOptions);
final CreateSubscriptionBodyContent content = new CreateSubscriptionBodyContent()
.setType(CONTENT_TYPE)
.setSubscriptionDescription(subscription);
final CreateSubscriptionBody createEntity = new CreateSubscriptionBody().setContent(content);
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
try {
return managementClient.getSubscriptions().putWithResponseAsync(topicName, subscriptionName, createEntity,
null, withTracing)
.onErrorMap(ServiceBusAdministrationAsyncClient::mapException)
.map(response -> deserializeSubscription(topicName, response));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Creates a topicOptions with its context.
*
* @param topicOptions Topic to create.
* @param context Context to pass into request.
*
* @return A Mono that completes with the created {@link TopicProperties}.
*/
Mono<Response<TopicProperties>> createTopicWithResponse(String topicName, CreateTopicOptions topicOptions,
Context context) {
if (topicName == null) {
return monoError(logger, new NullPointerException("'topicName' cannot be null."));
} else if (topicName.isEmpty()) {
return monoError(logger, new IllegalArgumentException("'topicName' cannot be empty."));
}
if (topicOptions == null) {
return monoError(logger, new NullPointerException("'topicOptions' cannot be null"));
} else if (context == null) {
return monoError(logger, new NullPointerException("'context' cannot be null."));
}
final TopicDescription topic = EntityHelper.getTopicDescription(topicOptions);
final CreateTopicBodyContent content = new CreateTopicBodyContent()
.setType(CONTENT_TYPE)
.setTopicDescription(topic);
final CreateTopicBody createEntity = new CreateTopicBody()
.setContent(content);
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
try {
return entityClient.putWithResponseAsync(topicName, createEntity, null, withTracing)
.onErrorMap(ServiceBusAdministrationAsyncClient::mapException)
.map(this::deserializeTopic);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Deletes a queue with its context.
*
* @param queueName Name of queue to delete.
* @param context Context to pass into request.
*
* @return A Mono that completes when the queue is deleted.
*/
Mono<Response<Void>> deleteQueueWithResponse(String queueName, Context context) {
if (queueName == null) {
return monoError(logger, new NullPointerException("'queueName' cannot be null"));
} else if (queueName.isEmpty()) {
return monoError(logger, new IllegalArgumentException("'queueName' cannot be an empty string."));
} else if (context == null) {
return monoError(logger, new NullPointerException("'context' cannot be null."));
}
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
try {
return entityClient.deleteWithResponseAsync(queueName, withTracing)
.onErrorMap(ServiceBusAdministrationAsyncClient::mapException)
.map(response -> {
return new SimpleResponse<>(response.getRequest(), response.getStatusCode(),
response.getHeaders(), null);
});
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Deletes a queue with its context.
*
* @param topicName Name of topic to delete.
* @param subscriptionName Name of the subscription for the rule.
* @param ruleName Name of the rule.
* @param context Context to pass into request.
*
* @return A Mono that completes with the created {@link QueueProperties}.
*/
Mono<Response<Void>> deleteRuleWithResponse(String topicName, String subscriptionName, String ruleName,
Context context) {
if (topicName == null) {
return monoError(logger, new NullPointerException("'topicName' cannot be null"));
} else if (topicName.isEmpty()) {
return monoError(logger, new IllegalArgumentException("'topicName' cannot be an empty string."));
} else if (subscriptionName == null) {
return monoError(logger, new NullPointerException("'subscriptionName' cannot be null"));
} else if (subscriptionName.isEmpty()) {
return monoError(logger, new IllegalArgumentException("'subscriptionName' cannot be an empty string."));
} else if (ruleName == null) {
return monoError(logger, new NullPointerException("'ruleName' cannot be null"));
} else if (ruleName.isEmpty()) {
return monoError(logger, new IllegalArgumentException("'ruleName' cannot be an empty string."));
} else if (context == null) {
return monoError(logger, new NullPointerException("'context' cannot be null."));
}
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
try {
return rulesClient.deleteWithResponseAsync(topicName, subscriptionName, ruleName, withTracing)
.onErrorMap(ServiceBusAdministrationAsyncClient::mapException)
.map(response -> new SimpleResponse<>(response.getRequest(), response.getStatusCode(),
response.getHeaders(), null));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Deletes a subscription with its context.
*
* @param topicName Name of topic associated with subscription to delete.
* @param subscriptionName Name of subscription to delete.
* @param context Context to pass into request.
*
* @return A Mono that completes with the created {@link SubscriptionProperties}.
*/
Mono<Response<Void>> deleteSubscriptionWithResponse(String topicName, String subscriptionName, Context context) {
if (subscriptionName == null) {
return monoError(logger, new NullPointerException("'subscriptionName' cannot be null"));
} else if (subscriptionName.isEmpty()) {
return monoError(logger, new IllegalArgumentException("'subscriptionName' cannot be an empty string."));
} else if (topicName == null) {
return monoError(logger, new NullPointerException("'topicName' cannot be null"));
} else if (topicName.isEmpty()) {
return monoError(logger, new IllegalArgumentException("'topicName' cannot be an empty string."));
} else if (context == null) {
return monoError(logger, new NullPointerException("'context' cannot be null."));
}
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
try {
return managementClient.getSubscriptions().deleteWithResponseAsync(topicName, subscriptionName,
withTracing)
.onErrorMap(ServiceBusAdministrationAsyncClient::mapException)
.map(response -> new SimpleResponse<>(response.getRequest(), response.getStatusCode(),
response.getHeaders(), null));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Deletes a topic with its context.
*
* @param topicName Name of topic to delete.
* @param context Context to pass into request.
*
* @return A Mono that completes with the created {@link TopicProperties}.
*/
Mono<Response<Void>> deleteTopicWithResponse(String topicName, Context context) {
if (topicName == null) {
return monoError(logger, new NullPointerException("'topicName' cannot be null"));
} else if (topicName.isEmpty()) {
return monoError(logger, new IllegalArgumentException("'topicName' cannot be an empty string."));
} else if (context == null) {
return monoError(logger, new NullPointerException("'context' cannot be null."));
}
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
try {
return entityClient.deleteWithResponseAsync(topicName, withTracing)
.onErrorMap(ServiceBusAdministrationAsyncClient::mapException)
.map(response -> new SimpleResponse<>(response.getRequest(), response.getStatusCode(),
response.getHeaders(), null));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Gets whether an entity exists.
*
* @param getEntityOperation Operation to get information about entity. If {@link ResourceNotFoundException} is
* thrown, then it is mapped to false.
* @param <T> Entity type.
*
* @return True if the entity exists, false otherwise.
*/
<T> Mono<Response<Boolean>> getEntityExistsWithResponse(Mono<Response<T>> getEntityOperation) {
return getEntityOperation.map(response -> {
final boolean exists = response.getValue() != null;
return (Response<Boolean>) new SimpleResponse<>(response.getRequest(), response.getStatusCode(),
response.getHeaders(), exists);
})
.onErrorResume(ResourceNotFoundException.class, exception -> {
final HttpResponse response = exception.getResponse();
final Response<Boolean> result = new SimpleResponse<>(response.getRequest(), response.getStatusCode(),
response.getHeaders(), false);
return Mono.just(result);
});
}
/**
* Gets a queue with its context.
*
* @param queueName Name of queue to fetch information for.
* @param context Context to pass into request.
*
* @return A Mono that completes with the {@link QueueProperties}.
*/
<T> Mono<Response<T>> getQueueWithResponse(String queueName, Context context,
Function<QueueProperties, T> mapper) {
if (queueName == null) {
return monoError(logger, new NullPointerException("'queueName' cannot be null"));
} else if (queueName.isEmpty()) {
return monoError(logger, new IllegalArgumentException("'queueName' cannot be empty."));
} else if (context == null) {
return monoError(logger, new NullPointerException("'context' cannot be null."));
}
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
try {
return entityClient.getWithResponseAsync(queueName, true, withTracing)
.onErrorMap(ServiceBusAdministrationAsyncClient::mapException)
.handle((response, sink) -> {
final Response<QueueProperties> deserialize = deserializeQueue(response);
if (deserialize.getValue() == null) {
final HttpResponse notFoundResponse = new EntityNotFoundHttpResponse<>(deserialize);
sink.error(new ResourceNotFoundException(String.format("Queue '%s' does not exist.", queueName),
notFoundResponse));
} else {
final T mapped = mapper.apply(deserialize.getValue());
sink.next(new SimpleResponse<>(response.getRequest(), response.getStatusCode(),
response.getHeaders(), mapped));
}
});
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<RuleProperties>> getRuleWithResponse(String topicName, String subscriptionName,
String ruleName, Context context) {
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
try {
return rulesClient.getWithResponseAsync(topicName, subscriptionName, ruleName, true, withTracing)
.onErrorMap(ServiceBusAdministrationAsyncClient::mapException)
.map(this::deserializeRule);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Gets a subscription with its context.
*
* @param topicName Name of the topic associated with the subscription.
* @param subscriptionName Name of subscription to fetch information for.
* @param context Context to pass into request.
*
* @return A Mono that completes with the {@link SubscriptionProperties}.
*/
<T> Mono<Response<T>> getSubscriptionWithResponse(String topicName, String subscriptionName, Context context,
Function<SubscriptionProperties, T> mapper) {
if (topicName == null) {
return monoError(logger, new NullPointerException("'topicName' cannot be null."));
} else if (topicName.isEmpty()) {
return monoError(logger, new IllegalArgumentException("'topicName' cannot be an empty string."));
} else if (subscriptionName == null) {
return monoError(logger, new NullPointerException("'subscriptionName' cannot be null."));
} else if (subscriptionName.isEmpty()) {
return monoError(logger, new IllegalArgumentException("'subscriptionName' cannot be an empty string."));
} else if (context == null) {
return monoError(logger, new NullPointerException("'context' cannot be null."));
}
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
try {
return managementClient.getSubscriptions().getWithResponseAsync(topicName, subscriptionName, true,
withTracing)
.onErrorMap(ServiceBusAdministrationAsyncClient::mapException)
.handle((response, sink) -> {
final Response<SubscriptionProperties> deserialize = deserializeSubscription(topicName, response);
if (deserialize.getValue() == null) {
final HttpResponse notFoundResponse = new EntityNotFoundHttpResponse<>(deserialize);
sink.error(new ResourceNotFoundException(String.format(
"Subscription '%s' in topic '%s' does not exist.", topicName, subscriptionName),
notFoundResponse));
} else {
final T mapped = mapper.apply(deserialize.getValue());
sink.next(new SimpleResponse<>(response.getRequest(), response.getStatusCode(),
response.getHeaders(), mapped));
}
});
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Gets the namespace properties with its context.
*
* @param context Context to pass into request.
*
* @return A Mono that completes with the {@link NamespaceProperties}.
*/
Mono<Response<NamespaceProperties>> getNamespacePropertiesWithResponse(Context context) {
return managementClient.getNamespaces().getWithResponseAsync(context).handle((response, sink) -> {
final NamespacePropertiesEntry entry = response.getValue();
if (entry == null || entry.getContent() == null) {
sink.error(new AzureException(
"There was no content inside namespace response. Entry: " + response));
return;
}
final NamespaceProperties namespaceProperties = entry.getContent().getNamespaceProperties();
final Response<NamespaceProperties> result = new SimpleResponse<>(response.getRequest(),
response.getStatusCode(), response.getHeaders(), namespaceProperties);
sink.next(result);
});
}
/**
* Gets a topic with its context.
*
* @param topicName Name of topic to fetch information for.
* @param context Context to pass into request.
*
* @return A Mono that completes with the {@link TopicProperties}.
*/
<T> Mono<Response<T>> getTopicWithResponse(String topicName, Context context,
Function<TopicProperties, T> mapper) {
if (topicName == null) {
return monoError(logger, new NullPointerException("'topicName' cannot be null"));
} else if (topicName.isEmpty()) {
return monoError(logger, new IllegalArgumentException("'topicName' cannot be empty."));
} else if (context == null) {
return monoError(logger, new NullPointerException("'context' cannot be null."));
}
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
try {
return entityClient.getWithResponseAsync(topicName, true, withTracing)
.onErrorMap(ServiceBusAdministrationAsyncClient::mapException)
.handle((response, sink) -> {
final Response<TopicProperties> deserialize = deserializeTopic(response);
if (deserialize.getValue() == null) {
final HttpResponse notFoundResponse = new EntityNotFoundHttpResponse<>(deserialize);
sink.error(new ResourceNotFoundException(String.format("Topic '%s' does not exist.", topicName),
notFoundResponse));
} else {
final T mapped = mapper.apply(deserialize.getValue());
sink.next(new SimpleResponse<>(response.getRequest(), response.getStatusCode(),
response.getHeaders(), mapped));
}
});
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Gets the first page of queues with context.
*
* @param context Context to pass into request.
*
* @return A Mono that completes with a page of queues.
*/
Mono<PagedResponse<QueueProperties>> listQueuesFirstPage(Context context) {
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
try {
return listQueues(0, withTracing);
} catch (RuntimeException e) {
return monoError(logger, e);
}
}
/**
* Gets the next page of queues with context.
*
* @param continuationToken Number of items to skip in feed.
* @param context Context to pass into request.
*
* @return A Mono that completes with a page of queues or empty if there are no items left.
*/
Mono<PagedResponse<QueueProperties>> listQueuesNextPage(String continuationToken, Context context) {
if (continuationToken == null || continuationToken.isEmpty()) {
return Mono.empty();
}
try {
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
final int skip = Integer.parseInt(continuationToken);
return listQueues(skip, withTracing);
} catch (RuntimeException e) {
return monoError(logger, e);
}
}
/**
* Gets the first page of rules with context.
*
* @param context Context to pass into request.
*
* @return A Mono that completes with a page of rules.
*/
Mono<PagedResponse<RuleProperties>> listRulesFirstPage(String topicName, String subscriptionName, Context context) {
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
try {
return listRules(topicName, subscriptionName, 0, withTracing);
} catch (RuntimeException e) {
return monoError(logger, e);
}
}
/**
* Gets the next page of rules with context.
*
* @param continuationToken Number of items to skip in feed.
* @param context Context to pass into request.
*
* @return A Mono that completes with a page of rules or empty if there are no items left.
*/
Mono<PagedResponse<RuleProperties>> listRulesNextPage(String topicName, String subscriptionName,
String continuationToken, Context context) {
if (continuationToken == null || continuationToken.isEmpty()) {
return Mono.empty();
}
try {
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
final int skip = Integer.parseInt(continuationToken);
return listRules(topicName, subscriptionName, skip, withTracing);
} catch (RuntimeException e) {
return monoError(logger, e);
}
}
/**
* Gets the first page of subscriptions with context.
*
* @param context Context to pass into request.
*
* @return A Mono that completes with a page of subscriptions.
*/
Mono<PagedResponse<SubscriptionProperties>> listSubscriptionsFirstPage(String topicName, Context context) {
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
try {
return listSubscriptions(topicName, 0, withTracing);
} catch (RuntimeException e) {
return monoError(logger, e);
}
}
/**
* Gets the next page of subscriptions with context.
*
* @param continuationToken Number of items to skip in feed.
* @param context Context to pass into request.
*
* @return A Mono that completes with a page of subscriptions or empty if there are no items left.
*/
Mono<PagedResponse<SubscriptionProperties>> listSubscriptionsNextPage(String topicName, String continuationToken,
Context context) {
if (continuationToken == null || continuationToken.isEmpty()) {
return Mono.empty();
}
try {
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
final int skip = Integer.parseInt(continuationToken);
return listSubscriptions(topicName, skip, withTracing);
} catch (RuntimeException e) {
return monoError(logger, e);
}
}
/**
* Gets the first page of topics with context.
*
* @param context Context to pass into request.
*
* @return A Mono that completes with a page of topics.
*/
Mono<PagedResponse<TopicProperties>> listTopicsFirstPage(Context context) {
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
try {
return listTopics(0, withTracing);
} catch (RuntimeException e) {
return monoError(logger, e);
}
}
/**
* Gets the next page of topics with context.
*
* @param continuationToken Number of items to skip in feed.
* @param context Context to pass into request.
*
* @return A Mono that completes with a page of topics or empty if there are no items left.
*/
Mono<PagedResponse<TopicProperties>> listTopicsNextPage(String continuationToken, Context context) {
if (continuationToken == null || continuationToken.isEmpty()) {
return Mono.empty();
}
try {
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
final int skip = Integer.parseInt(continuationToken);
return listTopics(skip, withTracing);
} catch (RuntimeException e) {
return monoError(logger, e);
}
}
/**
* Updates a queue with its context.
*
* @param queue Information about the queue to update. You must provide all the property values that are desired
* on the updated entity. Any values not provided are set to the service default values.
* @param context Context to pass into request.
*
* @return A Mono that completes with the updated {@link QueueProperties}.
*/
Mono<Response<QueueProperties>> updateQueueWithResponse(QueueProperties queue, Context context) {
if (queue == null) {
return monoError(logger, new NullPointerException("'queue' cannot be null"));
} else if (context == null) {
return monoError(logger, new NullPointerException("'context' cannot be null."));
}
final QueueDescription queueDescription = EntityHelper.toImplementation(queue);
final CreateQueueBodyContent content = new CreateQueueBodyContent()
.setType(CONTENT_TYPE)
.setQueueDescription(queueDescription);
final CreateQueueBody createEntity = new CreateQueueBody()
.setContent(content);
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
try {
return entityClient.putWithResponseAsync(queue.getName(), createEntity, "*", withTracing)
.onErrorMap(ServiceBusAdministrationAsyncClient::mapException)
.map(response -> deserializeQueue(response));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Updates a rule with its context.
*
* @param rule Information about the rule to update. You must provide all the property values that are desired
* on the updated entity. Any values not provided are set to the service default values.
* @param context Context to pass into request.
*
* @return A Mono that completes with the updated {@link RuleProperties}.
*/
Mono<Response<RuleProperties>> updateRuleWithResponse(String topicName, String subscriptionName,
RuleProperties rule, Context context) {
if (rule == null) {
return monoError(logger, new NullPointerException("'rule' cannot be null"));
} else if (context == null) {
return monoError(logger, new NullPointerException("'context' cannot be null."));
}
final RuleDescription implementation = EntityHelper.toImplementation(rule);
final CreateRuleBodyContent content = new CreateRuleBodyContent()
.setType(CONTENT_TYPE)
.setRuleDescription(implementation);
final CreateRuleBody ruleBody = new CreateRuleBody()
.setContent(content);
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
try {
return managementClient.getRules().putWithResponseAsync(topicName, subscriptionName, rule.getName(),
ruleBody, "*", withTracing)
.onErrorMap(ServiceBusAdministrationAsyncClient::mapException)
.map(response -> deserializeRule(response));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Updates a subscription with its context.
*
* @param subscription Information about the subscription to update. You must provide all the property values
* that are desired on the updated entity. Any values not provided are set to the service default values.
* @param context Context to pass into request.
*
* @return A Mono that completes with the updated {@link SubscriptionProperties}.
*/
Mono<Response<SubscriptionProperties>> updateSubscriptionWithResponse(SubscriptionProperties subscription,
Context context) {
if (subscription == null) {
return monoError(logger, new NullPointerException("'subscription' cannot be null"));
} else if (context == null) {
return monoError(logger, new NullPointerException("'context' cannot be null."));
}
final String topicName = subscription.getTopicName();
final String subscriptionName = subscription.getSubscriptionName();
final SubscriptionDescription implementation = EntityHelper.toImplementation(subscription);
final CreateSubscriptionBodyContent content = new CreateSubscriptionBodyContent()
.setType(CONTENT_TYPE)
.setSubscriptionDescription(implementation);
final CreateSubscriptionBody createEntity = new CreateSubscriptionBody()
.setContent(content);
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
try {
return managementClient.getSubscriptions().putWithResponseAsync(topicName, subscriptionName, createEntity,
"*", withTracing)
.onErrorMap(ServiceBusAdministrationAsyncClient::mapException)
.map(response -> deserializeSubscription(topicName, response));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Updates a topic with its context.
*
* @param topic Information about the topic to update. You must provide all the property values that are desired
* on the updated entity. Any values not provided are set to the service default values.
* @param context Context to pass into request.
*
* @return A Mono that completes with the updated {@link TopicProperties}.
*/
Mono<Response<TopicProperties>> updateTopicWithResponse(TopicProperties topic, Context context) {
if (topic == null) {
return monoError(logger, new NullPointerException("'topic' cannot be null"));
} else if (context == null) {
return monoError(logger, new NullPointerException("'context' cannot be null."));
}
final TopicDescription implementation = EntityHelper.toImplementation(topic);
final CreateTopicBodyContent content = new CreateTopicBodyContent()
.setType(CONTENT_TYPE)
.setTopicDescription(implementation);
final CreateTopicBody createEntity = new CreateTopicBody()
.setContent(content);
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
try {
return entityClient.putWithResponseAsync(topic.getName(), createEntity, "*", withTracing)
.onErrorMap(ServiceBusAdministrationAsyncClient::mapException)
.map(response -> deserializeTopic(response));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
private <T> T deserialize(Object object, Class<T> clazz) {
if (object == null) {
return null;
}
final String contents = String.valueOf(object);
if (contents.isEmpty()) {
return null;
}
try {
return serializer.deserialize(contents, clazz);
} catch (IOException e) {
throw logger.logExceptionAsError(new RuntimeException(String.format(
"Exception while deserializing. Body: [%s]. Class: %s", contents, clazz), e));
}
}
/**
* Given an HTTP response, will deserialize it into a strongly typed Response object.
*
* @param response HTTP response to deserialize response body from.
* @param clazz Class to deserialize response type into.
* @param <T> Class type to deserialize response into.
*
* @return A Response with a strongly typed response value.
*/
private <T> Response<T> deserialize(Response<Object> response, Class<T> clazz) {
final T deserialize = deserialize(response.getValue(), clazz);
return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(),
deserialize);
}
/**
* Converts a Response into its corresponding {@link QueueDescriptionEntry} then mapped into {@link
* QueueProperties}.
*
* @param response HTTP Response to deserialize.
*
* @return The corresponding HTTP response with convenience properties set.
*/
/**
* Converts a Response into its corresponding {@link RuleDescriptionEntry} then mapped into {@link RuleProperties}.
*
* @param response HTTP Response to deserialize.
*
* @return The corresponding HTTP response with convenience properties set.
*/
private Response<RuleProperties> deserializeRule(Response<Object> response) {
final RuleDescriptionEntry entry = deserialize(response.getValue(), RuleDescriptionEntry.class);
if (entry == null) {
return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null);
} else if (entry.getContent() == null) {
logger.info("entry.getContent() is null. The entity may not exist. {}", entry);
return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null);
}
final RuleDescription description = entry.getContent().getRuleDescription();
final RuleProperties result = EntityHelper.toModel(description);
return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), result);
}
/**
* Converts a Response into its corresponding {@link SubscriptionDescriptionEntry} then mapped into {@link
* SubscriptionProperties}.
*
* @param response HTTP Response to deserialize.
*
* @return The corresponding HTTP response with convenience properties set.
*/
private Response<SubscriptionProperties> deserializeSubscription(String topicName, Response<Object> response) {
final SubscriptionDescriptionEntry entry = deserialize(response.getValue(), SubscriptionDescriptionEntry.class);
if (entry == null) {
return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null);
} else if (entry.getContent() == null) {
logger.warning("entry.getContent() is null. There should have been content returned. Entry: {}", entry);
return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null);
}
final SubscriptionProperties subscription = EntityHelper.toModel(
entry.getContent().getSubscriptionDescription());
final String subscriptionName = getTitleValue(entry.getTitle());
EntityHelper.setSubscriptionName(subscription, subscriptionName);
EntityHelper.setTopicName(subscription, topicName);
return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(),
subscription);
}
/**
* Converts a Response into its corresponding {@link TopicDescriptionEntry} then mapped into {@link
* QueueProperties}.
*
* @param response HTTP Response to deserialize.
*
* @return The corresponding HTTP response with convenience properties set.
*/
private Response<TopicProperties> deserializeTopic(Response<Object> response) {
final TopicDescriptionEntry entry = deserialize(response.getValue(), TopicDescriptionEntry.class);
if (entry == null) {
return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null);
} else if (entry.getContent() == null) {
logger.warning("entry.getContent() is null. There should have been content returned. Entry: {}", entry);
return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null);
} else if (entry.getContent().getTopicDescription() == null) {
final QueueDescriptionEntry entryQueue = deserialize(response.getValue(), QueueDescriptionEntry.class);
if (entryQueue != null && entryQueue.getContent() != null && entryQueue.getContent().getQueueDescription() != null) {
logger.warning("'{}' is not a topic, it is a queue.", entryQueue.getTitle());
return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null);
}
}
final TopicProperties result = EntityHelper.toModel(entry.getContent().getTopicDescription());
final String topicName = getTitleValue(entry.getTitle());
EntityHelper.setTopicName(result, topicName);
return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), result);
}
/**
* Creates a {@link FeedPage} given the elements and a set of response links to get the next link from.
*
* @param entities Entities in the feed.
* @param responseLinks Links returned from the feed.
* @param <TResult> Type of Service Bus entities in page.
*
* @return A {@link FeedPage} indicating whether this can be continued or not.
* @throws MalformedURLException if the "next" page link does not contain a well-formed URL.
*/
private <TResult, TFeed> FeedPage<TResult> extractPage(Response<TFeed> response, List<TResult> entities,
List<ResponseLink> responseLinks)
throws MalformedURLException, UnsupportedEncodingException {
final Optional<ResponseLink> nextLink = responseLinks.stream()
.filter(link -> link.getRel().equalsIgnoreCase("next"))
.findFirst();
if (!nextLink.isPresent()) {
return new FeedPage<>(response.getStatusCode(), response.getHeaders(), response.getRequest(), entities);
}
final URL url = new URL(nextLink.get().getHref());
final String decode = URLDecoder.decode(url.getQuery(), StandardCharsets.UTF_8.name());
final Optional<Integer> skipParameter = Arrays.stream(decode.split("&|&"))
.map(part -> part.split("=", 2))
.filter(parts -> parts[0].equalsIgnoreCase("$skip") && parts.length == 2)
.map(parts -> Integer.valueOf(parts[1]))
.findFirst();
if (skipParameter.isPresent()) {
return new FeedPage<>(response.getStatusCode(), response.getHeaders(), response.getRequest(), entities,
skipParameter.get());
} else {
logger.warning("There should have been a skip parameter for the next page.");
return new FeedPage<>(response.getStatusCode(), response.getHeaders(), response.getRequest(), entities);
}
}
/**
* Helper method that invokes the service method, extracts the data and translates it to a PagedResponse.
*
* @param skip Number of elements to skip.
* @param context Context for the query.
*
* @return A Mono that completes with a paged response of queues.
*/
private Mono<PagedResponse<QueueProperties>> listQueues(int skip, Context context) {
return managementClient.listEntitiesWithResponseAsync(QUEUES_ENTITY_TYPE, skip, NUMBER_OF_ELEMENTS, context)
.onErrorMap(ServiceBusAdministrationAsyncClient::mapException)
.flatMap(response -> {
final Response<QueueDescriptionFeed> feedResponse = deserialize(response, QueueDescriptionFeed.class);
final QueueDescriptionFeed feed = feedResponse.getValue();
if (feed == null) {
logger.warning("Could not deserialize QueueDescriptionFeed. skip {}, top: {}", skip,
NUMBER_OF_ELEMENTS);
return Mono.empty();
}
final List<QueueProperties> entities = feed.getEntry().stream()
.filter(e -> e.getContent() != null && e.getContent().getQueueDescription() != null)
.map(e -> {
final String queueName = getTitleValue(e.getTitle());
final QueueProperties queueProperties = EntityHelper.toModel(
e.getContent().getQueueDescription());
EntityHelper.setQueueName(queueProperties, queueName);
return queueProperties;
})
.collect(Collectors.toList());
try {
return Mono.just(extractPage(feedResponse, entities, feed.getLink()));
} catch (MalformedURLException | UnsupportedEncodingException error) {
return Mono.error(new RuntimeException("Could not parse response into FeedPage<QueueDescription>",
error));
}
});
}
/**
* Helper method that invokes the service method, extracts the data and translates it to a PagedResponse.
*
* @param skip Number of elements to skip.
* @param context Context for the query.
*
* @return A Mono that completes with a paged response of rules.
*/
private Mono<PagedResponse<RuleProperties>> listRules(String topicName, String subscriptionName, int skip,
Context context) {
return managementClient.listRulesWithResponseAsync(topicName, subscriptionName, skip, NUMBER_OF_ELEMENTS,
context)
.onErrorMap(ServiceBusAdministrationAsyncClient::mapException)
.flatMap(response -> {
final Response<RuleDescriptionFeed> feedResponse = deserialize(response,
RuleDescriptionFeed.class);
final RuleDescriptionFeed feed = feedResponse.getValue();
if (feed == null) {
logger.warning("Could not deserialize RuleDescriptionFeed. skip {}, top: {}", skip,
NUMBER_OF_ELEMENTS);
return Mono.empty();
}
final List<RuleProperties> entities = feed.getEntry().stream()
.filter(e -> e.getContent() != null && e.getContent().getRuleDescription() != null)
.map(e -> {
return EntityHelper.toModel(e.getContent().getRuleDescription());
})
.collect(Collectors.toList());
try {
return Mono.just(extractPage(feedResponse, entities, feed.getLink()));
} catch (MalformedURLException | UnsupportedEncodingException error) {
return Mono.error(new RuntimeException(
"Could not parse response into FeedPage<RuleDescription>", error));
}
});
}
/**
* Helper method that invokes the service method, extracts the data and translates it to a PagedResponse.
*
* @param skip Number of elements to skip.
* @param context Context for the query.
*
* @return A Mono that completes with a paged response of subscriptions.
*/
private Mono<PagedResponse<SubscriptionProperties>> listSubscriptions(String topicName, int skip,
Context context) {
return managementClient.listSubscriptionsWithResponseAsync(topicName, skip, NUMBER_OF_ELEMENTS, context)
.onErrorMap(ServiceBusAdministrationAsyncClient::mapException)
.flatMap(response -> {
final Response<SubscriptionDescriptionFeed> feedResponse = deserialize(response,
SubscriptionDescriptionFeed.class);
final SubscriptionDescriptionFeed feed = feedResponse.getValue();
if (feed == null) {
logger.warning("Could not deserialize SubscriptionDescriptionFeed. skip {}, top: {}", skip,
NUMBER_OF_ELEMENTS);
return Mono.empty();
}
final List<SubscriptionProperties> entities = feed.getEntry().stream()
.filter(e -> e.getContent() != null && e.getContent().getSubscriptionDescription() != null)
.map(e -> {
final String subscriptionName = getTitleValue(e.getTitle());
final SubscriptionProperties description = EntityHelper.toModel(
e.getContent().getSubscriptionDescription());
EntityHelper.setTopicName(description, topicName);
EntityHelper.setSubscriptionName(description, subscriptionName);
return description;
})
.collect(Collectors.toList());
try {
return Mono.just(extractPage(feedResponse, entities, feed.getLink()));
} catch (MalformedURLException | UnsupportedEncodingException error) {
return Mono.error(new RuntimeException(
"Could not parse response into FeedPage<SubscriptionDescription>", error));
}
});
}
/**
* Helper method that invokes the service method, extracts the data and translates it to a PagedResponse.
*
* @param skip Number of elements to skip.
* @param context Context for the query.
*
* @return A Mono that completes with a paged response of topics.
*/
private Mono<PagedResponse<TopicProperties>> listTopics(int skip, Context context) {
return managementClient.listEntitiesWithResponseAsync(TOPICS_ENTITY_TYPE, skip, NUMBER_OF_ELEMENTS, context)
.onErrorMap(ServiceBusAdministrationAsyncClient::mapException)
.flatMap(response -> {
final Response<TopicDescriptionFeed> feedResponse = deserialize(response, TopicDescriptionFeed.class);
final TopicDescriptionFeed feed = feedResponse.getValue();
if (feed == null) {
logger.warning("Could not deserialize TopicDescriptionFeed. skip {}, top: {}", skip,
NUMBER_OF_ELEMENTS);
return Mono.empty();
}
final List<TopicProperties> entities = feed.getEntry().stream()
.filter(e -> e.getContent() != null && e.getContent().getTopicDescription() != null)
.map(e -> {
final String topicName = getTitleValue(e.getTitle());
final TopicProperties topicProperties = EntityHelper.toModel(
e.getContent().getTopicDescription());
EntityHelper.setTopicName(topicProperties, topicName);
return topicProperties;
})
.collect(Collectors.toList());
try {
return Mono.just(extractPage(feedResponse, entities, feed.getLink()));
} catch (MalformedURLException | UnsupportedEncodingException error) {
return Mono.error(new RuntimeException("Could not parse response into FeedPage<TopicDescription>",
error));
}
});
}
/**
* Given an XML title element, returns the XML text inside. Jackson deserializes Objects as LinkedHashMaps. XML text
* is represented as an entry with an empty string as the key.
*
* For example, the text returned from this {@code <title text="text/xml">QueueName</title>} is "QueueName".
*
* @param responseTitle XML title element.
*
* @return The XML text inside the title. {@code null} is returned if there is no value.
*/
@SuppressWarnings("unchecked")
private String getTitleValue(Object responseTitle) {
if (!(responseTitle instanceof Map)) {
return null;
}
final Map<String, String> map;
try {
map = (Map<String, String>) responseTitle;
return map.get("");
} catch (ClassCastException error) {
logger.warning("Unable to cast to Map<String,String>. Title: {}", responseTitle, error);
return null;
}
}
/**
* Maps an exception from the ATOM APIs to its associated {@link HttpResponseException}.
*
* @param exception Exception from the ATOM API.
*
* @return The corresponding {@link HttpResponseException} or {@code throwable} if it is not an instance of {@link
* ServiceBusManagementErrorException}.
*/
private static Throwable mapException(Throwable exception) {
if (!(exception instanceof ServiceBusManagementErrorException)) {
return exception;
}
final ServiceBusManagementErrorException managementError = ((ServiceBusManagementErrorException) exception);
final ServiceBusManagementError error = managementError.getValue();
final HttpResponse errorHttpResponse = managementError.getResponse();
final int statusCode = error != null && error.getCode() != null
? error.getCode()
: errorHttpResponse.getStatusCode();
final String errorDetail = error != null && error.getDetail() != null
? error.getDetail()
: managementError.getMessage();
switch (statusCode) {
case 401:
return new ClientAuthenticationException(errorDetail, managementError.getResponse(), exception);
case 404:
return new ResourceNotFoundException(errorDetail, managementError.getResponse(), exception);
case 409:
return new ResourceExistsException(errorDetail, managementError.getResponse(), exception);
case 412:
return new ResourceModifiedException(errorDetail, managementError.getResponse(), exception);
default:
return new HttpResponseException(errorDetail, managementError.getResponse(), exception);
}
}
/**
* A page of Service Bus entities.
*
* @param <T> The entity description from Service Bus.
*/
private static final class FeedPage<T> implements PagedResponse<T> {
private final int statusCode;
private final HttpHeaders header;
private final HttpRequest request;
private final IterableStream<T> entries;
private final String continuationToken;
/**
* Creates a page that does not have any more pages.
*
* @param entries Items in the page.
*/
private FeedPage(int statusCode, HttpHeaders header, HttpRequest request, List<T> entries) {
this.statusCode = statusCode;
this.header = header;
this.request = request;
this.entries = new IterableStream<>(entries);
this.continuationToken = null;
}
/**
* Creates an instance that has additional pages to fetch.
*
* @param entries Items in the page.
* @param skip Number of elements to "skip".
*/
private FeedPage(int statusCode, HttpHeaders header, HttpRequest request, List<T> entries, int skip) {
this.statusCode = statusCode;
this.header = header;
this.request = request;
this.entries = new IterableStream<>(entries);
this.continuationToken = String.valueOf(skip);
}
@Override
public IterableStream<T> getElements() {
return entries;
}
@Override
public String getContinuationToken() {
return continuationToken;
}
@Override
public int getStatusCode() {
return statusCode;
}
@Override
public HttpHeaders getHeaders() {
return header;
}
@Override
public HttpRequest getRequest() {
return request;
}
@Override
public void close() {
}
}
private static final class EntityNotFoundHttpResponse<T> extends HttpResponse {
private final int statusCode;
private final HttpHeaders headers;
private EntityNotFoundHttpResponse(Response<T> response) {
super(response.getRequest());
this.headers = response.getHeaders();
this.statusCode = response.getStatusCode();
}
@Override
public int getStatusCode() {
return statusCode;
}
@Override
public String getHeaderValue(String name) {
return headers.getValue(name);
}
@Override
public HttpHeaders getHeaders() {
return headers;
}
@Override
public Flux<ByteBuffer> getBody() {
return Flux.empty();
}
@Override
public Mono<byte[]> getBodyAsByteArray() {
return Mono.empty();
}
@Override
public Mono<String> getBodyAsString() {
return Mono.empty();
}
@Override
public Mono<String> getBodyAsString(Charset charset) {
return Mono.empty();
}
}
} |
We cannot throw HttpResponseException because we don't have a HTTPResponse. I think that we can handle this case as done in the [previous if block](https://github.com/Azure/azure-sdk-for-java/pull/19513/files/457d911af6e128fb7d963151f99d2d748e79e167#diff-8b1de19ce3e7548d62bea61e56b8d6dd9e11eeb8951f3afc1b5b09b9cf798e5cL2309-L2310). Then the code can be changed from: ```java throw logger.logExceptionAsError(new RuntimeException(String.format("'[%s]' is not a queue, it is a topic.", entryTopic.getTitle()))); ``` to: ```java logger.info("'{}' is not a queue, it is a topic.", entryTopic.getTitle()); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null); ``` If you agree, I will apply this change. | private Response<QueueProperties> deserializeQueue(Response<Object> response) {
final QueueDescriptionEntry entry = deserialize(response.getValue(), QueueDescriptionEntry.class);
if (entry == null) {
return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null);
} else if (entry.getContent() == null) {
logger.info("entry.getContent() is null. The entity may not exist. {}", entry);
return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null);
} else if (entry.getContent().getQueueDescription() == null) {
final TopicDescriptionEntry entryTopic = deserialize(response.getValue(), TopicDescriptionEntry.class);
if (entryTopic != null && entryTopic.getContent() != null && entryTopic.getContent().getTopicDescription() != null) {
throw logger.logExceptionAsError(
new RuntimeException(String.format("'[%s]' is not a queue, it is a topic.", entryTopic.getTitle())));
}
}
final QueueProperties result = EntityHelper.toModel(entry.getContent().getQueueDescription());
final String queueName = getTitleValue(entry.getTitle());
EntityHelper.setQueueName(result, queueName);
return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), result);
} | new RuntimeException(String.format("'[%s]' is not a queue, it is a topic.", entryTopic.getTitle()))); | private Response<QueueProperties> deserializeQueue(Response<Object> response) {
final QueueDescriptionEntry entry = deserialize(response.getValue(), QueueDescriptionEntry.class);
if (entry == null) {
return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null);
} else if (entry.getContent() == null) {
logger.info("entry.getContent() is null. The entity may not exist. {}", entry);
return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null);
} else if (entry.getContent().getQueueDescription() == null) {
final TopicDescriptionEntry entryTopic = deserialize(response.getValue(), TopicDescriptionEntry.class);
if (entryTopic != null && entryTopic.getContent() != null && entryTopic.getContent().getTopicDescription() != null) {
logger.warning("'{}' is not a queue, it is a topic.", entryTopic.getTitle());
return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null);
}
}
final QueueProperties result = EntityHelper.toModel(entry.getContent().getQueueDescription());
final String queueName = getTitleValue(entry.getTitle());
EntityHelper.setQueueName(result, queueName);
return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), result);
} | class ServiceBusAdministrationAsyncClient {
private static final String SERVICE_BUS_TRACING_NAMESPACE_VALUE = "Microsoft.ServiceBus";
private static final String CONTENT_TYPE = "application/xml";
private static final String QUEUES_ENTITY_TYPE = "queues";
private static final String TOPICS_ENTITY_TYPE = "topics";
private static final int NUMBER_OF_ELEMENTS = 100;
private final ServiceBusManagementClientImpl managementClient;
private final EntitiesImpl entityClient;
private final ClientLogger logger = new ClientLogger(ServiceBusAdministrationAsyncClient.class);
private final ServiceBusManagementSerializer serializer;
private final RulesImpl rulesClient;
/**
* Creates a new instance with the given management client and serializer.
*
* @param managementClient Client to make management calls.
* @param serializer Serializer to deserialize ATOM XML responses.
*/
ServiceBusAdministrationAsyncClient(ServiceBusManagementClientImpl managementClient,
ServiceBusManagementSerializer serializer) {
this.serializer = Objects.requireNonNull(serializer, "'serializer' cannot be null.");
this.managementClient = Objects.requireNonNull(managementClient, "'managementClient' cannot be null.");
this.entityClient = managementClient.getEntities();
this.rulesClient = managementClient.getRules();
}
/**
* Creates a queue with the given name.
*
* @param queueName Name of the queue to create.
*
* @return A Mono that completes with information about the created queue.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If the request body was invalid, the queue quota is exceeded, or an error
* occurred processing the request.
* @throws NullPointerException if {@code queueName} is null.
* @throws IllegalArgumentException if {@code queueName} is an empty string.
* @throws ResourceExistsException if a queue exists with the same {@code queueName}.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<QueueProperties> createQueue(String queueName) {
try {
return createQueue(queueName, new CreateQueueOptions());
} catch (RuntimeException e) {
return monoError(logger, e);
}
}
/**
* Creates a queue with the {@link CreateQueueOptions} and given queue name.
*
* @param queueName Name of the queue to create.
* @param queueOptions Options about the queue to create.
*
* @return A Mono that completes with information about the created queue.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If the request body was invalid, the queue quota is exceeded, or an error
* occurred processing the request.
* @throws IllegalArgumentException if {@code queueName} is an empty string.
* @throws NullPointerException if {@code queueName} or {@code queueOptions} is null.
* @throws ResourceExistsException if a queue exists with the same {@link QueueProperties
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<QueueProperties> createQueue(String queueName, CreateQueueOptions queueOptions) {
return createQueueWithResponse(queueName, queueOptions).map(Response::getValue);
}
/**
* Creates a queue and returns the created queue in addition to the HTTP response.
*
* @param queueName Name of the queue to create.
* @param queueOptions Options about the queue to create.
*
* @return A Mono that returns the created queue in addition to the HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If the request body was invalid, the queue quota is exceeded, or an error
* occurred processing the request.
* @throws IllegalArgumentException if {@code queueName} is an empty string.
* @throws NullPointerException if {@code queueName} or {@code queueOptions} is null.
* @throws ResourceExistsException if a queue exists with the same {@link QueueProperties
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<QueueProperties>> createQueueWithResponse(String queueName, CreateQueueOptions queueOptions) {
return withContext(context -> createQueueWithResponse(queueName, queueOptions, context));
}
/**
* Creates a rule under the given topic and subscription
*
* @param topicName Name of the topic associated with rule.
* @param subscriptionName Name of the subscription associated with the rule.
* @param ruleName Name of the rule.
*
* @return A Mono that completes with information about the created rule.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If the request body was invalid, the quota is exceeded, or an error occurred
* processing the request.
* @throws IllegalArgumentException if {@code topicName} or {@code ruleName} are are empty strings.
* @throws NullPointerException if {@code topicName} or {@code ruleName} are are null.
* @throws ResourceExistsException if a rule exists with the same topic, subscription, and rule name.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<RuleProperties> createRule(String topicName, String subscriptionName, String ruleName) {
try {
return createRule(topicName, subscriptionName, ruleName, new CreateRuleOptions());
} catch (RuntimeException e) {
return monoError(logger, e);
}
}
/**
* Creates a rule with the {@link CreateRuleOptions}.
*
* @param topicName Name of the topic associated with rule.
* @param subscriptionName Name of the subscription associated with the rule.
* @param ruleName Name of the rule.
* @param ruleOptions Information about the rule to create.
*
* @return A Mono that completes with information about the created rule.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If the request body was invalid, the quota is exceeded, or an error occurred
* processing the request.
* @throws IllegalArgumentException if {@code topicName} or {@code ruleName} are are empty strings.
* @throws NullPointerException if {@code topicName}, {@code ruleName}, or {@code ruleOptions}
* are are null.
* @throws ResourceExistsException if a rule exists with the same topic and rule name.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<RuleProperties> createRule(String topicName, String subscriptionName, String ruleName,
CreateRuleOptions ruleOptions) {
return createRuleWithResponse(topicName, subscriptionName, ruleName, ruleOptions)
.map(Response::getValue);
}
/**
* Creates a rule and returns the created rule in addition to the HTTP response.
*
* @param topicName Name of the topic associated with rule.
* @param subscriptionName Name of the subscription associated with the rule.
* @param ruleName Name of the rule.
* @param ruleOptions Information about the rule to create.
*
* @return A Mono that returns the created rule in addition to the HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If the request body was invalid, the quota is exceeded, or an error occurred
* processing the request.
* @throws IllegalArgumentException if {@code topicName} or {@code ruleName} are are empty strings.
* @throws NullPointerException if {@code topicName}, {@code ruleName}, or {@code ruleOptions}
* are are null.
* @throws ResourceExistsException if a rule exists with the same topic and rule name.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<RuleProperties>> createRuleWithResponse(String topicName, String subscriptionName,
String ruleName, CreateRuleOptions ruleOptions) {
return withContext(context -> createRuleWithResponse(topicName, subscriptionName, ruleName, ruleOptions,
context));
}
/**
* Creates a subscription with the given topic and subscription names.
*
* @param topicName Name of the topic associated with subscription.
* @param subscriptionName Name of the subscription.
*
* @return A Mono that completes with information about the created subscription.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If the request body was invalid, the quota is exceeded, or an error occurred
* processing the request.
* @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} are are empty strings.
* @throws NullPointerException if {@code topicName} or {@code subscriptionName} are are null.
* @throws ResourceExistsException if a subscription exists with the same topic and subscription name.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<SubscriptionProperties> createSubscription(String topicName, String subscriptionName) {
try {
return createSubscription(topicName, subscriptionName, new CreateSubscriptionOptions());
} catch (RuntimeException e) {
return monoError(logger, e);
}
}
/**
* Creates a subscription with the {@link CreateSubscriptionOptions}.
*
* @param topicName Name of the topic associated with subscription.
* @param subscriptionName Name of the subscription.
* @param subscriptionOptions Information about the subscription to create.
*
* @return A Mono that completes with information about the created subscription.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If the request body was invalid, the quota is exceeded, or an error occurred
* processing the request.
* @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} are are empty strings.
* @throws NullPointerException if {@code topicName}, {@code subscriptionName}, or {@code subscriptionOptions}
* are are null.
* @throws ResourceExistsException if a subscription exists with the same topic and subscription name.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<SubscriptionProperties> createSubscription(String topicName, String subscriptionName,
CreateSubscriptionOptions subscriptionOptions) {
return createSubscriptionWithResponse(topicName, subscriptionName, subscriptionOptions)
.map(Response::getValue);
}
/**
* Creates a subscription and returns the created subscription in addition to the HTTP response.
*
* @param topicName Name of the topic associated with subscription.
* @param subscriptionName Name of the subscription.
* @param subscriptionOptions Information about the subscription to create.
*
* @return A Mono that returns the created subscription in addition to the HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If the request body was invalid, the quota is exceeded, or an error occurred
* processing the request.
* @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} are are empty strings.
* @throws NullPointerException if {@code topicName}, {@code subscriptionName}, or {@code subscriptionOptions}
* are are null.
* @throws ResourceExistsException if a subscription exists with the same topic and subscription name.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<SubscriptionProperties>> createSubscriptionWithResponse(String topicName,
String subscriptionName, CreateSubscriptionOptions subscriptionOptions) {
return withContext(context -> createSubscriptionWithResponse(topicName, subscriptionName, subscriptionOptions,
context));
}
/**
* Creates a topic with the given name.
*
* @param topicName Name of the topic to create.
*
* @return A Mono that completes with information about the created topic.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If the request body was invalid, the topic quota is exceeded, or an error
* occurred processing the request.
* @throws NullPointerException if {@code topicName} is null.
* @throws IllegalArgumentException if {@code topicName} is an empty string.
* @throws ResourceExistsException if a topic exists with the same {@code topicName}.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<TopicProperties> createTopic(String topicName) {
try {
return createTopic(topicName, new CreateTopicOptions());
} catch (RuntimeException e) {
return monoError(logger, e);
}
}
/**
* Creates a topic with the {@link CreateTopicOptions}.
*
* @param topicName Name of the topic to create.
* @param topicOptions The options used to create the topic.
*
* @return A Mono that completes with information about the created topic.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If the request body was invalid, the topic quota is exceeded, or an error
* occurred processing the request.
* @throws IllegalArgumentException if {@code topicName} is an empty string.
* @throws NullPointerException if {@code topicName} or {@code topicOptions} is null.
* @throws ResourceExistsException if a topic exists with the same {@code topicName}.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<TopicProperties> createTopic(String topicName, CreateTopicOptions topicOptions) {
return createTopicWithResponse(topicName, topicOptions).map(Response::getValue);
}
/**
* Creates a topic and returns the created topic in addition to the HTTP response.
*
* @param topicName Name of the topic to create.
* @param topicOptions The options used to create the topic.
*
* @return A Mono that returns the created topic in addition to the HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If the request body was invalid, the topic quota is exceeded, or an error
* occurred processing the request.
* @throws IllegalArgumentException if {@link TopicProperties
* string.
* @throws NullPointerException if {@code topicName} or {@code topicOptions} is null.
* @throws ResourceExistsException if a topic exists with the same {@code topicName}.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<TopicProperties>> createTopicWithResponse(String topicName, CreateTopicOptions topicOptions) {
return withContext(context -> createTopicWithResponse(topicName, topicOptions, context));
}
/**
* Deletes a queue the matching {@code queueName}.
*
* @param queueName Name of queue to delete.
*
* @return A Mono that completes when the queue is deleted.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws NullPointerException if {@code queueName} is null.
* @throws IllegalArgumentException if {@code queueName} is an empty string.
* @throws ResourceNotFoundException if the {@code queueName} does not exist.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Void> deleteQueue(String queueName) {
return deleteQueueWithResponse(queueName).then();
}
/**
* Deletes a queue the matching {@code queueName} and returns the HTTP response.
*
* @param queueName Name of queue to delete.
*
* @return A Mono that completes when the queue is deleted and returns the HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws NullPointerException if {@code queueName} is null.
* @throws IllegalArgumentException if {@code queueName} is an empty string.
* @throws ResourceNotFoundException if the {@code queueName} does not exist.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Void>> deleteQueueWithResponse(String queueName) {
return withContext(context -> deleteQueueWithResponse(queueName, context));
}
/**
* Deletes a rule the matching {@code ruleName}.
*
* @param topicName Name of topic associated with rule to delete.
* @param subscriptionName Name of the subscription associated with the rule to delete.
* @param ruleName Name of rule to delete.
*
* @return A Mono that completes when the rule is deleted.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code topicName} or {@code ruleName} is an empty string.
* @throws NullPointerException if {@code topicName} or {@code ruleName} is null.
* @throws ResourceNotFoundException if the {@code ruleName} does not exist.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Void> deleteRule(String topicName, String subscriptionName, String ruleName) {
return deleteRuleWithResponse(topicName, subscriptionName, ruleName).then();
}
/**
* Deletes a rule the matching {@code ruleName} and returns the HTTP response.
*
* @param topicName Name of topic associated with rule to delete.
* @param subscriptionName Name of the subscription associated with the rule to delete.
* @param ruleName Name of rule to delete.
*
* @return A Mono that completes when the rule is deleted and returns the HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code topicName}, {@code subscriptionName}, or {@code ruleName} is an
* empty string.
* @throws NullPointerException if {@code topicName}, {@code subscriptionName}, or {@code ruleName} is null.
* @throws ResourceNotFoundException if the {@code ruleName} does not exist.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Void>> deleteRuleWithResponse(String topicName, String subscriptionName,
String ruleName) {
return withContext(context -> deleteRuleWithResponse(topicName, subscriptionName, ruleName, context));
}
/**
* Deletes a subscription the matching {@code subscriptionName}.
*
* @param topicName Name of topic associated with subscription to delete.
* @param subscriptionName Name of subscription to delete.
*
* @return A Mono that completes when the subscription is deleted.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} is an empty string.
* @throws NullPointerException if {@code topicName} or {@code subscriptionName} is null.
* @throws ResourceNotFoundException if the {@code subscriptionName} does not exist.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Void> deleteSubscription(String topicName, String subscriptionName) {
return deleteSubscriptionWithResponse(topicName, subscriptionName).then();
}
/**
* Deletes a subscription the matching {@code subscriptionName} and returns the HTTP response.
*
* @param topicName Name of topic associated with subscription to delete.
* @param subscriptionName Name of subscription to delete.
*
* @return A Mono that completes when the subscription is deleted and returns the HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} is an empty string.
* @throws NullPointerException if {@code topicName} or {@code subscriptionName} is null.
* @throws ResourceNotFoundException if the {@code subscriptionName} does not exist.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Void>> deleteSubscriptionWithResponse(String topicName, String subscriptionName) {
return withContext(context -> deleteSubscriptionWithResponse(topicName, subscriptionName, context));
}
/**
* Deletes a topic the matching {@code topicName}.
*
* @param topicName Name of topic to delete.
*
* @return A Mono that completes when the topic is deleted.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code topicName} is an empty string.
* @throws NullPointerException if {@code topicName} is null.
* @throws ResourceNotFoundException if the {@code topicName} does not exist.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Void> deleteTopic(String topicName) {
return deleteTopicWithResponse(topicName).then();
}
/**
* Deletes a topic the matching {@code topicName} and returns the HTTP response.
*
* @param topicName Name of topic to delete.
*
* @return A Mono that completes when the topic is deleted and returns the HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code topicName} is an empty string.
* @throws NullPointerException if {@code topicName} is null.
* @throws ResourceNotFoundException if the {@code topicName} does not exist.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Void>> deleteTopicWithResponse(String topicName) {
return withContext(context -> deleteTopicWithResponse(topicName, context));
}
/**
* Gets information about the queue.
*
* @param queueName Name of queue to get information about.
*
* @return A Mono that completes with information about the queue.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code queueName} is an empty string.
* @throws NullPointerException if {@code queueName} is null.
* @throws ResourceNotFoundException if the {@code queueName} does not exist.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<QueueProperties> getQueue(String queueName) {
return getQueueWithResponse(queueName).map(Response::getValue);
}
/**
* Gets information about the queue along with its HTTP response.
*
* @param queueName Name of queue to get information about.
*
* @return A Mono that completes with information about the queue and the associated HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code queueName} is an empty string.
* @throws NullPointerException if {@code queueName} is null.
* @throws ResourceNotFoundException if the {@code queueName} does not exist.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<QueueProperties>> getQueueWithResponse(String queueName) {
return withContext(context -> getQueueWithResponse(queueName, context, Function.identity()));
}
/**
* Gets whether or not a queue with {@code queueName} exists in the Service Bus namespace.
*
* @param queueName Name of the queue.
*
* @return A Mono that completes indicating whether or not the queue exists.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code queueName} is an empty string.
* @throws NullPointerException if {@code queueName} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Boolean> getQueueExists(String queueName) {
return getQueueExistsWithResponse(queueName).map(Response::getValue);
}
/**
* Gets whether or not a queue with {@code queueName} exists in the Service Bus namespace.
*
* @param queueName Name of the queue.
*
* @return A Mono that completes indicating whether or not the queue exists along with its HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code queueName} is an empty string.
* @throws NullPointerException if {@code queueName} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Boolean>> getQueueExistsWithResponse(String queueName) {
return getEntityExistsWithResponse(getQueueWithResponse(queueName));
}
/**
* Gets runtime properties about the queue.
*
* @param queueName Name of queue to get information about.
*
* @return A Mono that completes with runtime properties about the queue.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code queueName} is an empty string.
* @throws NullPointerException if {@code queueName} is null.
* @throws ResourceNotFoundException if the {@code queueName} does not exist.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<QueueRuntimeProperties> getQueueRuntimeProperties(String queueName) {
return getQueueRuntimePropertiesWithResponse(queueName).map(response -> response.getValue());
}
/**
* Gets runtime properties about the queue along with its HTTP response.
*
* @param queueName Name of queue to get information about.
*
* @return A Mono that completes with runtime properties about the queue and the associated HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code queueName} is an empty string.
* @throws NullPointerException if {@code queueName} is null.
* @throws ResourceNotFoundException if the {@code queueName} does not exist.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<QueueRuntimeProperties>> getQueueRuntimePropertiesWithResponse(String queueName) {
return withContext(context -> getQueueWithResponse(queueName, context, QueueRuntimeProperties::new));
}
/**
* Gets information about the Service Bus namespace.
*
* @return A Mono that completes with information about the Service Bus namespace.
* @throws ClientAuthenticationException if the client's credentials do not have access to the namespace.
* @throws HttpResponseException If error occurred processing the request.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<NamespaceProperties> getNamespaceProperties() {
return getNamespacePropertiesWithResponse().map(Response::getValue);
}
/**
* Gets information about the Service Bus namespace along with its HTTP response.
*
* @return A Mono that completes with information about the namespace and the associated HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<NamespaceProperties>> getNamespacePropertiesWithResponse() {
return withContext(this::getNamespacePropertiesWithResponse);
}
/**
* Gets a rule from the service namespace.
*
* Only following data types are deserialized in Filters and Action parameters - string, int, long, boolean, double,
* and OffsetDateTime. Other data types would return its string value.
*
* @param topicName The name of the topic relative to service bus namespace.
* @param subscriptionName The subscription name the rule belongs to.
* @param ruleName The name of the rule to retrieve.
*
* @return The associated rule.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<RuleProperties> getRule(String topicName, String subscriptionName, String ruleName) {
return getRuleWithResponse(topicName, subscriptionName, ruleName).map(response -> response.getValue());
}
/**
* Gets a rule from the service namespace.
*
* Only following data types are deserialized in Filters and Action parameters - string, int, long, bool, double,
* and OffsetDateTime. Other data types would return its string value.
*
* @param topicName The name of the topic relative to service bus namespace.
* @param subscriptionName The subscription name the rule belongs to.
* @param ruleName The name of the rule to retrieve.
*
* @return The associated rule with the corresponding HTTP response.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<RuleProperties>> getRuleWithResponse(String topicName, String subscriptionName,
String ruleName) {
return withContext(context -> getRuleWithResponse(topicName, subscriptionName, ruleName, context));
}
/**
* Gets information about the queue.
*
* @param topicName Name of topic associated with subscription.
* @param subscriptionName Name of subscription to get information about.
*
* @return A Mono that completes with information about the subscription.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} are empty strings.
* @throws NullPointerException if {@code topicName} or {@code subscriptionName} are null.
* @throws ResourceNotFoundException if the {@code subscriptionName} does not exist in the {@code topicName}.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<SubscriptionProperties> getSubscription(String topicName, String subscriptionName) {
return getSubscriptionWithResponse(topicName, subscriptionName).map(Response::getValue);
}
/**
* Gets information about the subscription along with its HTTP response.
*
* @param topicName Name of topic associated with subscription.
* @param subscriptionName Name of subscription to get information about.
*
* @return A Mono that completes with information about the subscription and the associated HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} are empty strings.
* @throws NullPointerException if {@code topicName} or {@code subscriptionName} are null.
* @throws ResourceNotFoundException if the {@code subscriptionName} does not exist.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<SubscriptionProperties>> getSubscriptionWithResponse(String topicName,
String subscriptionName) {
return withContext(context -> getSubscriptionWithResponse(topicName, subscriptionName, context,
Function.identity()));
}
/**
* Gets whether or not a subscription within a topic exists.
*
* @param topicName Name of topic associated with subscription.
* @param subscriptionName Name of the subscription.
*
* @return A Mono that completes indicating whether or not the subscription exists.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code subscriptionName} is an empty string.
* @throws NullPointerException if {@code subscriptionName} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Boolean> getSubscriptionExists(String topicName, String subscriptionName) {
return getSubscriptionExistsWithResponse(topicName, subscriptionName).map(Response::getValue);
}
/**
* Gets whether or not a subscription within a topic exists.
*
* @param topicName Name of topic associated with subscription.
* @param subscriptionName Name of the subscription.
*
* @return A Mono that completes indicating whether or not the subscription exists along with its HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code subscriptionName} is an empty string.
* @throws NullPointerException if {@code subscriptionName} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Boolean>> getSubscriptionExistsWithResponse(String topicName, String subscriptionName) {
return getEntityExistsWithResponse(getSubscriptionWithResponse(topicName, subscriptionName));
}
/**
* Gets runtime properties about the subscription.
*
* @param topicName Name of topic associated with subscription.
* @param subscriptionName Name of subscription to get information about.
*
* @return A Mono that completes with runtime properties about the subscription.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} are empty strings.
* @throws NullPointerException if {@code topicName} or {@code subscriptionName} are null.
* @throws ResourceNotFoundException if the {@code subscriptionName} does not exist.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<SubscriptionRuntimeProperties> getSubscriptionRuntimeProperties(
String topicName, String subscriptionName) {
return getSubscriptionRuntimePropertiesWithResponse(topicName, subscriptionName)
.map(response -> response.getValue());
}
/**
* Gets runtime properties about the subscription.
*
* @param topicName Name of topic associated with subscription.
* @param subscriptionName Name of subscription to get information about.
*
* @return A Mono that completes with runtime properties about the subscription.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code subscriptionName} is an empty string.
* @throws NullPointerException if {@code subscriptionName} is null.
* @throws ResourceNotFoundException if the {@code subscriptionName} does not exist.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<SubscriptionRuntimeProperties>> getSubscriptionRuntimePropertiesWithResponse(
String topicName, String subscriptionName) {
return withContext(context -> getSubscriptionWithResponse(topicName, subscriptionName, context,
SubscriptionRuntimeProperties::new));
}
/**
* Gets information about the topic.
*
* @param topicName Name of topic to get information about.
*
* @return A Mono that completes with information about the topic.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code topicName} is an empty string.
* @throws NullPointerException if {@code topicName} is null.
* @throws ResourceNotFoundException if the {@code topicName} does not exist.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<TopicProperties> getTopic(String topicName) {
return getTopicWithResponse(topicName).map(Response::getValue);
}
/**
* Gets information about the topic along with its HTTP response.
*
* @param topicName Name of topic to get information about.
*
* @return A Mono that completes with information about the topic and the associated HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code topicName} is an empty string.
* @throws NullPointerException if {@code topicName} is null.
* @throws ResourceNotFoundException if the {@code topicName} does not exist.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<TopicProperties>> getTopicWithResponse(String topicName) {
return withContext(context -> getTopicWithResponse(topicName, context, Function.identity()));
}
/**
* Gets whether or not a topic with {@code topicName} exists in the Service Bus namespace.
*
* @param topicName Name of the topic.
*
* @return A Mono that completes indicating whether or not the topic exists.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code topicName} is an empty string.
* @throws NullPointerException if {@code topicName} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Boolean> getTopicExists(String topicName) {
return getTopicExistsWithResponse(topicName).map(Response::getValue);
}
/**
* Gets whether or not a topic with {@code topicName} exists in the Service Bus namespace.
*
* @param topicName Name of the topic.
*
* @return A Mono that completes indicating whether or not the topic exists along with its HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code topicName} is an empty string.
* @throws NullPointerException if {@code topicName} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Boolean>> getTopicExistsWithResponse(String topicName) {
return getEntityExistsWithResponse(getTopicWithResponse(topicName));
}
/**
* Gets runtime properties about the topic.
*
* @param topicName Name of topic to get information about.
*
* @return A Mono that completes with runtime properties about the topic.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code topicName} is an empty string.
* @throws NullPointerException if {@code topicName} is null.
* @throws ResourceNotFoundException if the {@code topicName} does not exist.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<TopicRuntimeProperties> getTopicRuntimeProperties(String topicName) {
return getTopicRuntimePropertiesWithResponse(topicName).map(response -> response.getValue());
}
/**
* Gets runtime properties about the topic with its HTTP response.
*
* @param topicName Name of topic to get information about.
*
* @return A Mono that completes with runtime properties about the topic and the associated HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code topicName} is an empty string.
* @throws NullPointerException if {@code topicName} is null.
* @throws ResourceNotFoundException if the {@code topicName} does not exist.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<TopicRuntimeProperties>> getTopicRuntimePropertiesWithResponse(String topicName) {
return withContext(context -> getTopicWithResponse(topicName, context, TopicRuntimeProperties::new));
}
/**
* Fetches all the queues in the Service Bus namespace.
*
* @return A Flux of {@link QueueProperties queues} in the Service Bus namespace.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @see <a href="https:
* authorization rules</a>
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux<QueueProperties> listQueues() {
return new PagedFlux<>(
() -> withContext(context -> listQueuesFirstPage(context)),
token -> withContext(context -> listQueuesNextPage(token, context)));
}
/**
* Fetches all the rules for a topic and subscription.
*
* @param topicName The topic name under which all the rules need to be retrieved.
* @param subscriptionName The name of the subscription for which all rules need to be retrieved.
*
* @return A Flux of {@link RuleProperties rules} for the {@code topicName} and {@code subscriptionName}.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws NullPointerException if {@code topicName} or {@code subscriptionName} is null.
* @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} is an empty string.
* @see <a href="https:
* authorization rules</a>
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux<RuleProperties> listRules(String topicName, String subscriptionName) {
if (topicName == null) {
return pagedFluxError(logger, new NullPointerException("'topicName' cannot be null."));
} else if (topicName.isEmpty()) {
return pagedFluxError(logger, new IllegalArgumentException("'topicName' cannot be an empty string."));
}
return new PagedFlux<>(
() -> withContext(context -> listRulesFirstPage(topicName, subscriptionName, context)),
token -> withContext(context -> listRulesNextPage(topicName, subscriptionName, token, context)));
}
/**
* Fetches all the subscriptions for a topic.
*
* @param topicName The topic name under which all the subscriptions need to be retrieved.
*
* @return A Flux of {@link SubscriptionProperties subscriptions} for the {@code topicName}.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws NullPointerException if {@code topicName} is null.
* @throws IllegalArgumentException if {@code topicName} is an empty string.
* @see <a href="https:
* authorization rules</a>
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux<SubscriptionProperties> listSubscriptions(String topicName) {
if (topicName == null) {
return pagedFluxError(logger, new NullPointerException("'topicName' cannot be null."));
} else if (topicName.isEmpty()) {
return pagedFluxError(logger, new IllegalArgumentException("'topicName' cannot be an empty string."));
}
return new PagedFlux<>(
() -> withContext(context -> listSubscriptionsFirstPage(topicName, context)),
token -> withContext(context -> listSubscriptionsNextPage(topicName, token, context)));
}
/**
* Fetches all the topics in the Service Bus namespace.
*
* @return A Flux of {@link TopicProperties topics} in the Service Bus namespace.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @see <a href="https:
* authorization rules</a>
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux<TopicProperties> listTopics() {
return new PagedFlux<>(
() -> withContext(context -> listTopicsFirstPage(context)),
token -> withContext(context -> listTopicsNextPage(token, context)));
}
/**
* Updates a queue with the given {@link QueueProperties}. The {@link QueueProperties} must be fully populated as
* all of the properties are replaced. If a property is not set the service default value is used.
*
* The suggested flow is:
* <ol>
* <li>{@link
* <li>Update the required elements.</li>
* <li>Pass the updated description into this method.</li>
* </ol>
*
* <p>
* There are a subset of properties that can be updated. More information can be found in the links below. They are:
* <ul>
* <li>{@link QueueProperties
* <li>{@link QueueProperties
* <li>{@link QueueProperties
* </li>
* <li>{@link QueueProperties
* </ul>
*
* @param queue Information about the queue to update. You must provide all the property values that are desired
* on the updated entity. Any values not provided are set to the service default values.
*
* @return A Mono that completes with the updated queue.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If the request body was invalid, the queue quota is exceeded, or an error
* occurred processing the request.
* @throws NullPointerException if {@code queue} is null.
* @see <a href="https:
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<QueueProperties> updateQueue(QueueProperties queue) {
return updateQueueWithResponse(queue).map(Response::getValue);
}
/**
* Updates a queue with the given {@link QueueProperties}. The {@link QueueProperties} must be fully populated as
* all of the properties are replaced. If a property is not set the service default value is used.
*
* The suggested flow is:
* <ol>
* <li>{@link
* <li>Update the required elements.</li>
* <li>Pass the updated description into this method.</li>
* </ol>
*
* <p>
* There are a subset of properties that can be updated. More information can be found in the links below. They are:
* <ul>
* <li>{@link QueueProperties
* <li>{@link QueueProperties
* <li>{@link QueueProperties
* </li>
* <li>{@link QueueProperties
* </ul>
*
* @param queue Information about the queue to update. You must provide all the property values that are desired
* on the updated entity. Any values not provided are set to the service default values.
*
* @return A Mono that returns the updated queue in addition to the HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If the request body was invalid, the queue quota is exceeded, or an error
* occurred processing the request.
* @throws NullPointerException if {@code queue} is null.
* @see <a href="https:
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<QueueProperties>> updateQueueWithResponse(QueueProperties queue) {
return withContext(context -> updateQueueWithResponse(queue, context));
}
/**
* Updates a rule with the given {@link RuleProperties}. The {@link RuleProperties} must be fully populated as all
* of the properties are replaced. If a property is not set the service default value is used.
*
* The suggested flow is:
* <ol>
* <li>{@link
* <li>Update the required elements.</li>
* <li>Pass the updated description into this method.</li>
* </ol>
*
* @param topicName The topic name under which the rule is updated.
* @param subscriptionName The name of the subscription for which the rule is updated.
* @param rule Information about the rule to update. You must provide all the property values that are desired
* on the updated entity. Any values not provided are set to the service default values.
*
* @return A Mono that returns the updated rule.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If the request body was invalid, the rule quota is exceeded, or an error
* occurred processing the request.
* @throws IllegalArgumentException if {@link RuleProperties
* @throws NullPointerException if {@code rule} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<RuleProperties> updateRule(String topicName, String subscriptionName, RuleProperties rule) {
return updateRuleWithResponse(topicName, subscriptionName, rule).map(Response::getValue);
}
/**
* Updates a rule with the given {@link RuleProperties}. The {@link RuleProperties} must be fully populated as all
* of the properties are replaced. If a property is not set the service default value is used.
*
* The suggested flow is:
* <ol>
* <li>{@link
* <li>Update the required elements.</li>
* <li>Pass the updated description into this method.</li>
* </ol>
*
* @param topicName The topic name under which the rule is updated.
* @param subscriptionName The name of the subscription for which the rule is updated.
* @param rule Information about the rule to update. You must provide all the property values that are desired
* on the updated entity. Any values not provided are set to the service default values.
*
* @return A Mono that returns the updated rule in addition to the HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If the request body was invalid, the rule quota is exceeded, or an error
* occurred processing the request.
* @throws IllegalArgumentException if {@link RuleProperties
* @throws NullPointerException if {@code rule} is null.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<RuleProperties>> updateRuleWithResponse(String topicName, String subscriptionName,
RuleProperties rule) {
return withContext(context -> updateRuleWithResponse(topicName, subscriptionName, rule, context));
}
/**
* Updates a subscription with the given {@link SubscriptionProperties}. The {@link SubscriptionProperties} must be
* fully populated as all of the properties are replaced. If a property is not set the service default value is
* used.
*
* The suggested flow is:
* <ol>
* <li>{@link
* <li>Update the required elements.</li>
* <li>Pass the updated description into this method.</li>
* </ol>
*
* <p>
* There are a subset of properties that can be updated. More information can be found in the links below. They are:
* <ul>
* <li>{@link SubscriptionProperties
* <li>{@link SubscriptionProperties
* <li>{@link SubscriptionProperties
* </ul>
*
* @param subscription Information about the subscription to update. You must provide all the property values
* that are desired on the updated entity. Any values not provided are set to the service default values.
*
* @return A Mono that returns the updated subscription.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If the request body was invalid, the subscription quota is exceeded, or an
* error occurred processing the request.
* @throws IllegalArgumentException if {@link SubscriptionProperties
* SubscriptionProperties
* @throws NullPointerException if {@code subscription} is null.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<SubscriptionProperties> updateSubscription(SubscriptionProperties subscription) {
return updateSubscriptionWithResponse(subscription).map(Response::getValue);
}
/**
* Updates a subscription with the given {@link SubscriptionProperties}. The {@link SubscriptionProperties} must be
* fully populated as all of the properties are replaced. If a property is not set the service default value is
* used.
*
* The suggested flow is:
* <ol>
* <li>{@link
* <li>Update the required elements.</li>
* <li>Pass the updated description into this method.</li>
* </ol>
*
* <p>
* There are a subset of properties that can be updated. More information can be found in the links below. They are:
* <ul>
* <li>{@link SubscriptionProperties
* <li>{@link SubscriptionProperties
* <li>{@link SubscriptionProperties
* </ul>
*
* @param subscription Information about the subscription to update. You must provide all the property values
* that are desired on the updated entity. Any values not provided are set to the service default values.
*
* @return A Mono that returns the updated subscription in addition to the HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If the request body was invalid, the subscription quota is exceeded, or an
* error occurred processing the request.
* @throws IllegalArgumentException if {@link SubscriptionProperties
* SubscriptionProperties
* @throws NullPointerException if {@code subscription} is null.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<SubscriptionProperties>> updateSubscriptionWithResponse(
SubscriptionProperties subscription) {
return withContext(context -> updateSubscriptionWithResponse(subscription, context));
}
/**
* Updates a topic with the given {@link TopicProperties}. The {@link TopicProperties} must be fully populated as
* all of the properties are replaced. If a property is not set the service default value is used.
*
* The suggested flow is:
* <ol>
* <li>{@link
* <li>Update the required elements.</li>
* <li>Pass the updated description into this method.</li>
* </ol>
*
* <p>
* There are a subset of properties that can be updated. More information can be found in the links below. They are:
* <ul>
* <li>{@link TopicProperties
* <li>{@link TopicProperties
* </li>
* </ul>
*
* @param topic Information about the topic to update. You must provide all the property values that are desired
* on the updated entity. Any values not provided are set to the service default values.
*
* @return A Mono that completes with the updated topic.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If the request body was invalid, the topic quota is exceeded, or an error
* occurred processing the request.
* @throws IllegalArgumentException if {@link TopicProperties
* string.
* @throws NullPointerException if {@code topic} is null.
* @see <a href="https:
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<TopicProperties> updateTopic(TopicProperties topic) {
return updateTopicWithResponse(topic).map(Response::getValue);
}
/**
* Updates a topic with the given {@link TopicProperties}. The {@link TopicProperties} must be fully populated as
* all of the properties are replaced. If a property is not set the service default value is used.
*
* The suggested flow is:
* <ol>
* <li>{@link
* <li>Update the required elements.</li>
* <li>Pass the updated description into this method.</li>
* </ol>
*
* <p>
* There are a subset of properties that can be updated. More information can be found in the links below. They are:
* <ul>
* <li>{@link TopicProperties
* <li>{@link TopicProperties
* </li>
* </ul>
*
* @param topic Information about the topic to update. You must provide all the property values that are desired
* on the updated entity. Any values not provided are set to the service default values.
*
* @return A Mono that completes with the updated topic and its HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If the request body was invalid, the topic quota is exceeded, or an error
* occurred processing the request.
* @throws IllegalArgumentException if {@link TopicProperties
* string.
* @throws NullPointerException if {@code topic} is null.
* @see <a href="https:
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<TopicProperties>> updateTopicWithResponse(TopicProperties topic) {
return withContext(context -> updateTopicWithResponse(topic, context));
}
/**
* Creates a queue with its context.
*
* @param createQueueOptions Queue to create.
* @param context Context to pass into request.
*
* @return A Mono that completes with the created {@link QueueProperties}.
*/
Mono<Response<QueueProperties>> createQueueWithResponse(String queueName, CreateQueueOptions createQueueOptions,
Context context) {
if (queueName == null) {
return monoError(logger, new NullPointerException("'queueName' cannot be null."));
} else if (queueName.isEmpty()) {
return monoError(logger, new IllegalArgumentException("'queueName' cannot be empty."));
}
if (createQueueOptions == null) {
return monoError(logger, new NullPointerException("'createQueueOptions' cannot be null."));
} else if (context == null) {
return monoError(logger, new NullPointerException("'context' cannot be null."));
}
final QueueDescription description = EntityHelper.getQueueDescription(createQueueOptions);
final CreateQueueBodyContent content = new CreateQueueBodyContent()
.setType(CONTENT_TYPE)
.setQueueDescription(description);
final CreateQueueBody createEntity = new CreateQueueBody()
.setContent(content);
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
try {
return entityClient.putWithResponseAsync(queueName, createEntity, null, withTracing)
.onErrorMap(ServiceBusAdministrationAsyncClient::mapException)
.map(this::deserializeQueue);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Creates a rule with its context.
*
* @param ruleOptions Rule to create.
* @param context Context to pass into request.
*
* @return A Mono that completes with the created {@link RuleProperties}.
*/
Mono<Response<RuleProperties>> createRuleWithResponse(String topicName, String subscriptionName, String ruleName,
CreateRuleOptions ruleOptions, Context context) {
if (topicName == null) {
return monoError(logger, new NullPointerException("'topicName' cannot be null."));
} else if (topicName.isEmpty()) {
return monoError(logger, new IllegalArgumentException("'topicName' cannot be empty."));
}
if (subscriptionName == null) {
return monoError(logger, new NullPointerException("'subscriptionName' cannot be null."));
} else if (subscriptionName.isEmpty()) {
return monoError(logger, new IllegalArgumentException("'subscriptionName' cannot be empty."));
}
if (ruleName == null) {
return monoError(logger, new NullPointerException("'ruleName' cannot be null."));
} else if (ruleName.isEmpty()) {
return monoError(logger, new IllegalArgumentException("'ruleName' cannot be empty."));
}
if (ruleOptions == null) {
return monoError(logger, new NullPointerException("'rule' cannot be null."));
}
final RuleActionImpl action = ruleOptions.getAction() != null
? EntityHelper.toImplementation(ruleOptions.getAction())
: null;
final RuleFilterImpl filter = ruleOptions.getFilter() != null
? EntityHelper.toImplementation(ruleOptions.getFilter())
: null;
final RuleDescription rule = new RuleDescription()
.setAction(action)
.setFilter(filter)
.setName(ruleName);
final CreateRuleBodyContent content = new CreateRuleBodyContent()
.setType(CONTENT_TYPE)
.setRuleDescription(rule);
final CreateRuleBody createEntity = new CreateRuleBody().setContent(content);
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
try {
return managementClient.getRules().putWithResponseAsync(topicName, subscriptionName, ruleName, createEntity,
null, withTracing)
.onErrorMap(ServiceBusAdministrationAsyncClient::mapException)
.map(response -> deserializeRule(response));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Creates a subscription with its context.
*
* @param subscriptionOptions Subscription to create.
* @param context Context to pass into request.
*
* @return A Mono that completes with the created {@link SubscriptionProperties}.
*/
Mono<Response<SubscriptionProperties>> createSubscriptionWithResponse(String topicName, String subscriptionName,
CreateSubscriptionOptions subscriptionOptions, Context context) {
if (topicName == null) {
return monoError(logger, new NullPointerException("'topicName' cannot be null."));
} else if (topicName.isEmpty()) {
return monoError(logger, new IllegalArgumentException("'topicName' cannot be empty."));
}
if (subscriptionName == null) {
return monoError(logger, new NullPointerException("'subscriptionName' cannot be null."));
} else if (subscriptionName.isEmpty()) {
return monoError(logger, new IllegalArgumentException("'subscriptionName' cannot be empty."));
}
if (subscriptionOptions == null) {
return monoError(logger, new NullPointerException("'subscription' cannot be null."));
}
final SubscriptionDescription subscription = EntityHelper.getSubscriptionDescription(subscriptionOptions);
final CreateSubscriptionBodyContent content = new CreateSubscriptionBodyContent()
.setType(CONTENT_TYPE)
.setSubscriptionDescription(subscription);
final CreateSubscriptionBody createEntity = new CreateSubscriptionBody().setContent(content);
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
try {
return managementClient.getSubscriptions().putWithResponseAsync(topicName, subscriptionName, createEntity,
null, withTracing)
.onErrorMap(ServiceBusAdministrationAsyncClient::mapException)
.map(response -> deserializeSubscription(topicName, response));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Creates a topicOptions with its context.
*
* @param topicOptions Topic to create.
* @param context Context to pass into request.
*
* @return A Mono that completes with the created {@link TopicProperties}.
*/
Mono<Response<TopicProperties>> createTopicWithResponse(String topicName, CreateTopicOptions topicOptions,
Context context) {
if (topicName == null) {
return monoError(logger, new NullPointerException("'topicName' cannot be null."));
} else if (topicName.isEmpty()) {
return monoError(logger, new IllegalArgumentException("'topicName' cannot be empty."));
}
if (topicOptions == null) {
return monoError(logger, new NullPointerException("'topicOptions' cannot be null"));
} else if (context == null) {
return monoError(logger, new NullPointerException("'context' cannot be null."));
}
final TopicDescription topic = EntityHelper.getTopicDescription(topicOptions);
final CreateTopicBodyContent content = new CreateTopicBodyContent()
.setType(CONTENT_TYPE)
.setTopicDescription(topic);
final CreateTopicBody createEntity = new CreateTopicBody()
.setContent(content);
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
try {
return entityClient.putWithResponseAsync(topicName, createEntity, null, withTracing)
.onErrorMap(ServiceBusAdministrationAsyncClient::mapException)
.map(this::deserializeTopic);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Deletes a queue with its context.
*
* @param queueName Name of queue to delete.
* @param context Context to pass into request.
*
* @return A Mono that completes when the queue is deleted.
*/
Mono<Response<Void>> deleteQueueWithResponse(String queueName, Context context) {
if (queueName == null) {
return monoError(logger, new NullPointerException("'queueName' cannot be null"));
} else if (queueName.isEmpty()) {
return monoError(logger, new IllegalArgumentException("'queueName' cannot be an empty string."));
} else if (context == null) {
return monoError(logger, new NullPointerException("'context' cannot be null."));
}
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
try {
return entityClient.deleteWithResponseAsync(queueName, withTracing)
.onErrorMap(ServiceBusAdministrationAsyncClient::mapException)
.map(response -> {
return new SimpleResponse<>(response.getRequest(), response.getStatusCode(),
response.getHeaders(), null);
});
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Deletes a queue with its context.
*
* @param topicName Name of topic to delete.
* @param subscriptionName Name of the subscription for the rule.
* @param ruleName Name of the rule.
* @param context Context to pass into request.
*
* @return A Mono that completes with the created {@link QueueProperties}.
*/
Mono<Response<Void>> deleteRuleWithResponse(String topicName, String subscriptionName, String ruleName,
Context context) {
if (topicName == null) {
return monoError(logger, new NullPointerException("'topicName' cannot be null"));
} else if (topicName.isEmpty()) {
return monoError(logger, new IllegalArgumentException("'topicName' cannot be an empty string."));
} else if (subscriptionName == null) {
return monoError(logger, new NullPointerException("'subscriptionName' cannot be null"));
} else if (subscriptionName.isEmpty()) {
return monoError(logger, new IllegalArgumentException("'subscriptionName' cannot be an empty string."));
} else if (ruleName == null) {
return monoError(logger, new NullPointerException("'ruleName' cannot be null"));
} else if (ruleName.isEmpty()) {
return monoError(logger, new IllegalArgumentException("'ruleName' cannot be an empty string."));
} else if (context == null) {
return monoError(logger, new NullPointerException("'context' cannot be null."));
}
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
try {
return rulesClient.deleteWithResponseAsync(topicName, subscriptionName, ruleName, withTracing)
.onErrorMap(ServiceBusAdministrationAsyncClient::mapException)
.map(response -> new SimpleResponse<>(response.getRequest(), response.getStatusCode(),
response.getHeaders(), null));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Deletes a subscription with its context.
*
* @param topicName Name of topic associated with subscription to delete.
* @param subscriptionName Name of subscription to delete.
* @param context Context to pass into request.
*
* @return A Mono that completes with the created {@link SubscriptionProperties}.
*/
Mono<Response<Void>> deleteSubscriptionWithResponse(String topicName, String subscriptionName, Context context) {
if (subscriptionName == null) {
return monoError(logger, new NullPointerException("'subscriptionName' cannot be null"));
} else if (subscriptionName.isEmpty()) {
return monoError(logger, new IllegalArgumentException("'subscriptionName' cannot be an empty string."));
} else if (topicName == null) {
return monoError(logger, new NullPointerException("'topicName' cannot be null"));
} else if (topicName.isEmpty()) {
return monoError(logger, new IllegalArgumentException("'topicName' cannot be an empty string."));
} else if (context == null) {
return monoError(logger, new NullPointerException("'context' cannot be null."));
}
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
try {
return managementClient.getSubscriptions().deleteWithResponseAsync(topicName, subscriptionName,
withTracing)
.onErrorMap(ServiceBusAdministrationAsyncClient::mapException)
.map(response -> new SimpleResponse<>(response.getRequest(), response.getStatusCode(),
response.getHeaders(), null));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Deletes a topic with its context.
*
* @param topicName Name of topic to delete.
* @param context Context to pass into request.
*
* @return A Mono that completes with the created {@link TopicProperties}.
*/
Mono<Response<Void>> deleteTopicWithResponse(String topicName, Context context) {
if (topicName == null) {
return monoError(logger, new NullPointerException("'topicName' cannot be null"));
} else if (topicName.isEmpty()) {
return monoError(logger, new IllegalArgumentException("'topicName' cannot be an empty string."));
} else if (context == null) {
return monoError(logger, new NullPointerException("'context' cannot be null."));
}
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
try {
return entityClient.deleteWithResponseAsync(topicName, withTracing)
.onErrorMap(ServiceBusAdministrationAsyncClient::mapException)
.map(response -> new SimpleResponse<>(response.getRequest(), response.getStatusCode(),
response.getHeaders(), null));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Gets whether an entity exists.
*
* @param getEntityOperation Operation to get information about entity. If {@link ResourceNotFoundException} is
* thrown, then it is mapped to false.
* @param <T> Entity type.
*
* @return True if the entity exists, false otherwise.
*/
<T> Mono<Response<Boolean>> getEntityExistsWithResponse(Mono<Response<T>> getEntityOperation) {
return getEntityOperation.map(response -> {
final boolean exists = response.getValue() != null;
return (Response<Boolean>) new SimpleResponse<>(response.getRequest(), response.getStatusCode(),
response.getHeaders(), exists);
})
.onErrorResume(ResourceNotFoundException.class, exception -> {
final HttpResponse response = exception.getResponse();
final Response<Boolean> result = new SimpleResponse<>(response.getRequest(), response.getStatusCode(),
response.getHeaders(), false);
return Mono.just(result);
});
}
/**
* Gets a queue with its context.
*
* @param queueName Name of queue to fetch information for.
* @param context Context to pass into request.
*
* @return A Mono that completes with the {@link QueueProperties}.
*/
<T> Mono<Response<T>> getQueueWithResponse(String queueName, Context context,
Function<QueueProperties, T> mapper) {
if (queueName == null) {
return monoError(logger, new NullPointerException("'queueName' cannot be null"));
} else if (queueName.isEmpty()) {
return monoError(logger, new IllegalArgumentException("'queueName' cannot be empty."));
} else if (context == null) {
return monoError(logger, new NullPointerException("'context' cannot be null."));
}
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
try {
return entityClient.getWithResponseAsync(queueName, true, withTracing)
.onErrorMap(ServiceBusAdministrationAsyncClient::mapException)
.handle((response, sink) -> {
final Response<QueueProperties> deserialize = deserializeQueue(response);
if (deserialize.getValue() == null) {
final HttpResponse notFoundResponse = new EntityNotFoundHttpResponse<>(deserialize);
sink.error(new ResourceNotFoundException(String.format("Queue '%s' does not exist.", queueName),
notFoundResponse));
} else {
final T mapped = mapper.apply(deserialize.getValue());
sink.next(new SimpleResponse<>(response.getRequest(), response.getStatusCode(),
response.getHeaders(), mapped));
}
});
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<RuleProperties>> getRuleWithResponse(String topicName, String subscriptionName,
String ruleName, Context context) {
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
try {
return rulesClient.getWithResponseAsync(topicName, subscriptionName, ruleName, true, withTracing)
.onErrorMap(ServiceBusAdministrationAsyncClient::mapException)
.map(this::deserializeRule);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Gets a subscription with its context.
*
* @param topicName Name of the topic associated with the subscription.
* @param subscriptionName Name of subscription to fetch information for.
* @param context Context to pass into request.
*
* @return A Mono that completes with the {@link SubscriptionProperties}.
*/
<T> Mono<Response<T>> getSubscriptionWithResponse(String topicName, String subscriptionName, Context context,
Function<SubscriptionProperties, T> mapper) {
if (topicName == null) {
return monoError(logger, new NullPointerException("'topicName' cannot be null."));
} else if (topicName.isEmpty()) {
return monoError(logger, new IllegalArgumentException("'topicName' cannot be an empty string."));
} else if (subscriptionName == null) {
return monoError(logger, new NullPointerException("'subscriptionName' cannot be null."));
} else if (subscriptionName.isEmpty()) {
return monoError(logger, new IllegalArgumentException("'subscriptionName' cannot be an empty string."));
} else if (context == null) {
return monoError(logger, new NullPointerException("'context' cannot be null."));
}
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
try {
return managementClient.getSubscriptions().getWithResponseAsync(topicName, subscriptionName, true,
withTracing)
.onErrorMap(ServiceBusAdministrationAsyncClient::mapException)
.handle((response, sink) -> {
final Response<SubscriptionProperties> deserialize = deserializeSubscription(topicName, response);
if (deserialize.getValue() == null) {
final HttpResponse notFoundResponse = new EntityNotFoundHttpResponse<>(deserialize);
sink.error(new ResourceNotFoundException(String.format(
"Subscription '%s' in topic '%s' does not exist.", topicName, subscriptionName),
notFoundResponse));
} else {
final T mapped = mapper.apply(deserialize.getValue());
sink.next(new SimpleResponse<>(response.getRequest(), response.getStatusCode(),
response.getHeaders(), mapped));
}
});
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Gets the namespace properties with its context.
*
* @param context Context to pass into request.
*
* @return A Mono that completes with the {@link NamespaceProperties}.
*/
Mono<Response<NamespaceProperties>> getNamespacePropertiesWithResponse(Context context) {
return managementClient.getNamespaces().getWithResponseAsync(context).handle((response, sink) -> {
final NamespacePropertiesEntry entry = response.getValue();
if (entry == null || entry.getContent() == null) {
sink.error(new AzureException(
"There was no content inside namespace response. Entry: " + response));
return;
}
final NamespaceProperties namespaceProperties = entry.getContent().getNamespaceProperties();
final Response<NamespaceProperties> result = new SimpleResponse<>(response.getRequest(),
response.getStatusCode(), response.getHeaders(), namespaceProperties);
sink.next(result);
});
}
/**
* Gets a topic with its context.
*
* @param topicName Name of topic to fetch information for.
* @param context Context to pass into request.
*
* @return A Mono that completes with the {@link TopicProperties}.
*/
<T> Mono<Response<T>> getTopicWithResponse(String topicName, Context context,
Function<TopicProperties, T> mapper) {
if (topicName == null) {
return monoError(logger, new NullPointerException("'topicName' cannot be null"));
} else if (topicName.isEmpty()) {
return monoError(logger, new IllegalArgumentException("'topicName' cannot be empty."));
} else if (context == null) {
return monoError(logger, new NullPointerException("'context' cannot be null."));
}
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
try {
return entityClient.getWithResponseAsync(topicName, true, withTracing)
.onErrorMap(ServiceBusAdministrationAsyncClient::mapException)
.handle((response, sink) -> {
final Response<TopicProperties> deserialize = deserializeTopic(response);
if (deserialize.getValue() == null) {
final HttpResponse notFoundResponse = new EntityNotFoundHttpResponse<>(deserialize);
sink.error(new ResourceNotFoundException(String.format("Topic '%s' does not exist.", topicName),
notFoundResponse));
} else {
final T mapped = mapper.apply(deserialize.getValue());
sink.next(new SimpleResponse<>(response.getRequest(), response.getStatusCode(),
response.getHeaders(), mapped));
}
});
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Gets the first page of queues with context.
*
* @param context Context to pass into request.
*
* @return A Mono that completes with a page of queues.
*/
Mono<PagedResponse<QueueProperties>> listQueuesFirstPage(Context context) {
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
try {
return listQueues(0, withTracing);
} catch (RuntimeException e) {
return monoError(logger, e);
}
}
/**
* Gets the next page of queues with context.
*
* @param continuationToken Number of items to skip in feed.
* @param context Context to pass into request.
*
* @return A Mono that completes with a page of queues or empty if there are no items left.
*/
Mono<PagedResponse<QueueProperties>> listQueuesNextPage(String continuationToken, Context context) {
if (continuationToken == null || continuationToken.isEmpty()) {
return Mono.empty();
}
try {
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
final int skip = Integer.parseInt(continuationToken);
return listQueues(skip, withTracing);
} catch (RuntimeException e) {
return monoError(logger, e);
}
}
/**
* Gets the first page of rules with context.
*
* @param context Context to pass into request.
*
* @return A Mono that completes with a page of rules.
*/
Mono<PagedResponse<RuleProperties>> listRulesFirstPage(String topicName, String subscriptionName, Context context) {
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
try {
return listRules(topicName, subscriptionName, 0, withTracing);
} catch (RuntimeException e) {
return monoError(logger, e);
}
}
/**
* Gets the next page of rules with context.
*
* @param continuationToken Number of items to skip in feed.
* @param context Context to pass into request.
*
* @return A Mono that completes with a page of rules or empty if there are no items left.
*/
Mono<PagedResponse<RuleProperties>> listRulesNextPage(String topicName, String subscriptionName,
String continuationToken, Context context) {
if (continuationToken == null || continuationToken.isEmpty()) {
return Mono.empty();
}
try {
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
final int skip = Integer.parseInt(continuationToken);
return listRules(topicName, subscriptionName, skip, withTracing);
} catch (RuntimeException e) {
return monoError(logger, e);
}
}
/**
* Gets the first page of subscriptions with context.
*
* @param context Context to pass into request.
*
* @return A Mono that completes with a page of subscriptions.
*/
Mono<PagedResponse<SubscriptionProperties>> listSubscriptionsFirstPage(String topicName, Context context) {
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
try {
return listSubscriptions(topicName, 0, withTracing);
} catch (RuntimeException e) {
return monoError(logger, e);
}
}
/**
* Gets the next page of subscriptions with context.
*
* @param continuationToken Number of items to skip in feed.
* @param context Context to pass into request.
*
* @return A Mono that completes with a page of subscriptions or empty if there are no items left.
*/
Mono<PagedResponse<SubscriptionProperties>> listSubscriptionsNextPage(String topicName, String continuationToken,
Context context) {
if (continuationToken == null || continuationToken.isEmpty()) {
return Mono.empty();
}
try {
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
final int skip = Integer.parseInt(continuationToken);
return listSubscriptions(topicName, skip, withTracing);
} catch (RuntimeException e) {
return monoError(logger, e);
}
}
/**
* Gets the first page of topics with context.
*
* @param context Context to pass into request.
*
* @return A Mono that completes with a page of topics.
*/
Mono<PagedResponse<TopicProperties>> listTopicsFirstPage(Context context) {
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
try {
return listTopics(0, withTracing);
} catch (RuntimeException e) {
return monoError(logger, e);
}
}
/**
* Gets the next page of topics with context.
*
* @param continuationToken Number of items to skip in feed.
* @param context Context to pass into request.
*
* @return A Mono that completes with a page of topics or empty if there are no items left.
*/
Mono<PagedResponse<TopicProperties>> listTopicsNextPage(String continuationToken, Context context) {
if (continuationToken == null || continuationToken.isEmpty()) {
return Mono.empty();
}
try {
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
final int skip = Integer.parseInt(continuationToken);
return listTopics(skip, withTracing);
} catch (RuntimeException e) {
return monoError(logger, e);
}
}
/**
* Updates a queue with its context.
*
* @param queue Information about the queue to update. You must provide all the property values that are desired
* on the updated entity. Any values not provided are set to the service default values.
* @param context Context to pass into request.
*
* @return A Mono that completes with the updated {@link QueueProperties}.
*/
Mono<Response<QueueProperties>> updateQueueWithResponse(QueueProperties queue, Context context) {
if (queue == null) {
return monoError(logger, new NullPointerException("'queue' cannot be null"));
} else if (context == null) {
return monoError(logger, new NullPointerException("'context' cannot be null."));
}
final QueueDescription queueDescription = EntityHelper.toImplementation(queue);
final CreateQueueBodyContent content = new CreateQueueBodyContent()
.setType(CONTENT_TYPE)
.setQueueDescription(queueDescription);
final CreateQueueBody createEntity = new CreateQueueBody()
.setContent(content);
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
try {
return entityClient.putWithResponseAsync(queue.getName(), createEntity, "*", withTracing)
.onErrorMap(ServiceBusAdministrationAsyncClient::mapException)
.map(response -> deserializeQueue(response));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Updates a rule with its context.
*
* @param rule Information about the rule to update. You must provide all the property values that are desired
* on the updated entity. Any values not provided are set to the service default values.
* @param context Context to pass into request.
*
* @return A Mono that completes with the updated {@link RuleProperties}.
*/
Mono<Response<RuleProperties>> updateRuleWithResponse(String topicName, String subscriptionName,
RuleProperties rule, Context context) {
if (rule == null) {
return monoError(logger, new NullPointerException("'rule' cannot be null"));
} else if (context == null) {
return monoError(logger, new NullPointerException("'context' cannot be null."));
}
final RuleDescription implementation = EntityHelper.toImplementation(rule);
final CreateRuleBodyContent content = new CreateRuleBodyContent()
.setType(CONTENT_TYPE)
.setRuleDescription(implementation);
final CreateRuleBody ruleBody = new CreateRuleBody()
.setContent(content);
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
try {
return managementClient.getRules().putWithResponseAsync(topicName, subscriptionName, rule.getName(),
ruleBody, "*", withTracing)
.onErrorMap(ServiceBusAdministrationAsyncClient::mapException)
.map(response -> deserializeRule(response));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Updates a subscription with its context.
*
* @param subscription Information about the subscription to update. You must provide all the property values
* that are desired on the updated entity. Any values not provided are set to the service default values.
* @param context Context to pass into request.
*
* @return A Mono that completes with the updated {@link SubscriptionProperties}.
*/
Mono<Response<SubscriptionProperties>> updateSubscriptionWithResponse(SubscriptionProperties subscription,
Context context) {
if (subscription == null) {
return monoError(logger, new NullPointerException("'subscription' cannot be null"));
} else if (context == null) {
return monoError(logger, new NullPointerException("'context' cannot be null."));
}
final String topicName = subscription.getTopicName();
final String subscriptionName = subscription.getSubscriptionName();
final SubscriptionDescription implementation = EntityHelper.toImplementation(subscription);
final CreateSubscriptionBodyContent content = new CreateSubscriptionBodyContent()
.setType(CONTENT_TYPE)
.setSubscriptionDescription(implementation);
final CreateSubscriptionBody createEntity = new CreateSubscriptionBody()
.setContent(content);
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
try {
return managementClient.getSubscriptions().putWithResponseAsync(topicName, subscriptionName, createEntity,
"*", withTracing)
.onErrorMap(ServiceBusAdministrationAsyncClient::mapException)
.map(response -> deserializeSubscription(topicName, response));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Updates a topic with its context.
*
* @param topic Information about the topic to update. You must provide all the property values that are desired
* on the updated entity. Any values not provided are set to the service default values.
* @param context Context to pass into request.
*
* @return A Mono that completes with the updated {@link TopicProperties}.
*/
Mono<Response<TopicProperties>> updateTopicWithResponse(TopicProperties topic, Context context) {
if (topic == null) {
return monoError(logger, new NullPointerException("'topic' cannot be null"));
} else if (context == null) {
return monoError(logger, new NullPointerException("'context' cannot be null."));
}
final TopicDescription implementation = EntityHelper.toImplementation(topic);
final CreateTopicBodyContent content = new CreateTopicBodyContent()
.setType(CONTENT_TYPE)
.setTopicDescription(implementation);
final CreateTopicBody createEntity = new CreateTopicBody()
.setContent(content);
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
try {
return entityClient.putWithResponseAsync(topic.getName(), createEntity, "*", withTracing)
.onErrorMap(ServiceBusAdministrationAsyncClient::mapException)
.map(response -> deserializeTopic(response));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
private <T> T deserialize(Object object, Class<T> clazz) {
if (object == null) {
return null;
}
final String contents = String.valueOf(object);
if (contents.isEmpty()) {
return null;
}
try {
return serializer.deserialize(contents, clazz);
} catch (IOException e) {
throw logger.logExceptionAsError(new RuntimeException(String.format(
"Exception while deserializing. Body: [%s]. Class: %s", contents, clazz), e));
}
}
/**
* Given an HTTP response, will deserialize it into a strongly typed Response object.
*
* @param response HTTP response to deserialize response body from.
* @param clazz Class to deserialize response type into.
* @param <T> Class type to deserialize response into.
*
* @return A Response with a strongly typed response value.
*/
private <T> Response<T> deserialize(Response<Object> response, Class<T> clazz) {
final T deserialize = deserialize(response.getValue(), clazz);
return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(),
deserialize);
}
/**
* Converts a Response into its corresponding {@link QueueDescriptionEntry} then mapped into {@link
* QueueProperties}.
*
* @param response HTTP Response to deserialize.
*
* @return The corresponding HTTP response with convenience properties set.
*/
/**
* Converts a Response into its corresponding {@link RuleDescriptionEntry} then mapped into {@link RuleProperties}.
*
* @param response HTTP Response to deserialize.
*
* @return The corresponding HTTP response with convenience properties set.
*/
private Response<RuleProperties> deserializeRule(Response<Object> response) {
final RuleDescriptionEntry entry = deserialize(response.getValue(), RuleDescriptionEntry.class);
if (entry == null) {
return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null);
} else if (entry.getContent() == null) {
logger.info("entry.getContent() is null. The entity may not exist. {}", entry);
return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null);
}
final RuleDescription description = entry.getContent().getRuleDescription();
final RuleProperties result = EntityHelper.toModel(description);
return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), result);
}
/**
* Converts a Response into its corresponding {@link SubscriptionDescriptionEntry} then mapped into {@link
* SubscriptionProperties}.
*
* @param response HTTP Response to deserialize.
*
* @return The corresponding HTTP response with convenience properties set.
*/
private Response<SubscriptionProperties> deserializeSubscription(String topicName, Response<Object> response) {
final SubscriptionDescriptionEntry entry = deserialize(response.getValue(), SubscriptionDescriptionEntry.class);
if (entry == null) {
return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null);
} else if (entry.getContent() == null) {
logger.warning("entry.getContent() is null. There should have been content returned. Entry: {}", entry);
return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null);
}
final SubscriptionProperties subscription = EntityHelper.toModel(
entry.getContent().getSubscriptionDescription());
final String subscriptionName = getTitleValue(entry.getTitle());
EntityHelper.setSubscriptionName(subscription, subscriptionName);
EntityHelper.setTopicName(subscription, topicName);
return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(),
subscription);
}
/**
* Converts a Response into its corresponding {@link TopicDescriptionEntry} then mapped into {@link
* QueueProperties}.
*
* @param response HTTP Response to deserialize.
*
* @return The corresponding HTTP response with convenience properties set.
*/
private Response<TopicProperties> deserializeTopic(Response<Object> response) {
final TopicDescriptionEntry entry = deserialize(response.getValue(), TopicDescriptionEntry.class);
if (entry == null) {
return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null);
} else if (entry.getContent() == null) {
logger.warning("entry.getContent() is null. There should have been content returned. Entry: {}", entry);
return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null);
} else if (entry.getContent().getTopicDescription() == null) {
final QueueDescriptionEntry entryTopic = deserialize(response.getValue(), QueueDescriptionEntry.class);
if (entryTopic != null && entryTopic.getContent() != null && entryTopic.getContent().getQueueDescription() != null) {
throw logger.logExceptionAsError(
new RuntimeException(String.format("'[%s]' is not a topic, it is a queue.", entryTopic.getTitle())));
}
}
final TopicProperties result = EntityHelper.toModel(entry.getContent().getTopicDescription());
final String topicName = getTitleValue(entry.getTitle());
EntityHelper.setTopicName(result, topicName);
return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), result);
}
/**
* Creates a {@link FeedPage} given the elements and a set of response links to get the next link from.
*
* @param entities Entities in the feed.
* @param responseLinks Links returned from the feed.
* @param <TResult> Type of Service Bus entities in page.
*
* @return A {@link FeedPage} indicating whether this can be continued or not.
* @throws MalformedURLException if the "next" page link does not contain a well-formed URL.
*/
private <TResult, TFeed> FeedPage<TResult> extractPage(Response<TFeed> response, List<TResult> entities,
List<ResponseLink> responseLinks)
throws MalformedURLException, UnsupportedEncodingException {
final Optional<ResponseLink> nextLink = responseLinks.stream()
.filter(link -> link.getRel().equalsIgnoreCase("next"))
.findFirst();
if (!nextLink.isPresent()) {
return new FeedPage<>(response.getStatusCode(), response.getHeaders(), response.getRequest(), entities);
}
final URL url = new URL(nextLink.get().getHref());
final String decode = URLDecoder.decode(url.getQuery(), StandardCharsets.UTF_8.name());
final Optional<Integer> skipParameter = Arrays.stream(decode.split("&|&"))
.map(part -> part.split("=", 2))
.filter(parts -> parts[0].equalsIgnoreCase("$skip") && parts.length == 2)
.map(parts -> Integer.valueOf(parts[1]))
.findFirst();
if (skipParameter.isPresent()) {
return new FeedPage<>(response.getStatusCode(), response.getHeaders(), response.getRequest(), entities,
skipParameter.get());
} else {
logger.warning("There should have been a skip parameter for the next page.");
return new FeedPage<>(response.getStatusCode(), response.getHeaders(), response.getRequest(), entities);
}
}
/**
* Helper method that invokes the service method, extracts the data and translates it to a PagedResponse.
*
* @param skip Number of elements to skip.
* @param context Context for the query.
*
* @return A Mono that completes with a paged response of queues.
*/
private Mono<PagedResponse<QueueProperties>> listQueues(int skip, Context context) {
return managementClient.listEntitiesWithResponseAsync(QUEUES_ENTITY_TYPE, skip, NUMBER_OF_ELEMENTS, context)
.onErrorMap(ServiceBusAdministrationAsyncClient::mapException)
.flatMap(response -> {
final Response<QueueDescriptionFeed> feedResponse = deserialize(response, QueueDescriptionFeed.class);
final QueueDescriptionFeed feed = feedResponse.getValue();
if (feed == null) {
logger.warning("Could not deserialize QueueDescriptionFeed. skip {}, top: {}", skip,
NUMBER_OF_ELEMENTS);
return Mono.empty();
}
final List<QueueProperties> entities = feed.getEntry().stream()
.filter(e -> e.getContent() != null && e.getContent().getQueueDescription() != null)
.map(e -> {
final String queueName = getTitleValue(e.getTitle());
final QueueProperties queueProperties = EntityHelper.toModel(
e.getContent().getQueueDescription());
EntityHelper.setQueueName(queueProperties, queueName);
return queueProperties;
})
.collect(Collectors.toList());
try {
return Mono.just(extractPage(feedResponse, entities, feed.getLink()));
} catch (MalformedURLException | UnsupportedEncodingException error) {
return Mono.error(new RuntimeException("Could not parse response into FeedPage<QueueDescription>",
error));
}
});
}
/**
* Helper method that invokes the service method, extracts the data and translates it to a PagedResponse.
*
* @param skip Number of elements to skip.
* @param context Context for the query.
*
* @return A Mono that completes with a paged response of rules.
*/
private Mono<PagedResponse<RuleProperties>> listRules(String topicName, String subscriptionName, int skip,
Context context) {
return managementClient.listRulesWithResponseAsync(topicName, subscriptionName, skip, NUMBER_OF_ELEMENTS,
context)
.onErrorMap(ServiceBusAdministrationAsyncClient::mapException)
.flatMap(response -> {
final Response<RuleDescriptionFeed> feedResponse = deserialize(response,
RuleDescriptionFeed.class);
final RuleDescriptionFeed feed = feedResponse.getValue();
if (feed == null) {
logger.warning("Could not deserialize RuleDescriptionFeed. skip {}, top: {}", skip,
NUMBER_OF_ELEMENTS);
return Mono.empty();
}
final List<RuleProperties> entities = feed.getEntry().stream()
.filter(e -> e.getContent() != null && e.getContent().getRuleDescription() != null)
.map(e -> {
return EntityHelper.toModel(e.getContent().getRuleDescription());
})
.collect(Collectors.toList());
try {
return Mono.just(extractPage(feedResponse, entities, feed.getLink()));
} catch (MalformedURLException | UnsupportedEncodingException error) {
return Mono.error(new RuntimeException(
"Could not parse response into FeedPage<RuleDescription>", error));
}
});
}
/**
* Helper method that invokes the service method, extracts the data and translates it to a PagedResponse.
*
* @param skip Number of elements to skip.
* @param context Context for the query.
*
* @return A Mono that completes with a paged response of subscriptions.
*/
private Mono<PagedResponse<SubscriptionProperties>> listSubscriptions(String topicName, int skip,
Context context) {
return managementClient.listSubscriptionsWithResponseAsync(topicName, skip, NUMBER_OF_ELEMENTS, context)
.onErrorMap(ServiceBusAdministrationAsyncClient::mapException)
.flatMap(response -> {
final Response<SubscriptionDescriptionFeed> feedResponse = deserialize(response,
SubscriptionDescriptionFeed.class);
final SubscriptionDescriptionFeed feed = feedResponse.getValue();
if (feed == null) {
logger.warning("Could not deserialize SubscriptionDescriptionFeed. skip {}, top: {}", skip,
NUMBER_OF_ELEMENTS);
return Mono.empty();
}
final List<SubscriptionProperties> entities = feed.getEntry().stream()
.filter(e -> e.getContent() != null && e.getContent().getSubscriptionDescription() != null)
.map(e -> {
final String subscriptionName = getTitleValue(e.getTitle());
final SubscriptionProperties description = EntityHelper.toModel(
e.getContent().getSubscriptionDescription());
EntityHelper.setTopicName(description, topicName);
EntityHelper.setSubscriptionName(description, subscriptionName);
return description;
})
.collect(Collectors.toList());
try {
return Mono.just(extractPage(feedResponse, entities, feed.getLink()));
} catch (MalformedURLException | UnsupportedEncodingException error) {
return Mono.error(new RuntimeException(
"Could not parse response into FeedPage<SubscriptionDescription>", error));
}
});
}
/**
* Helper method that invokes the service method, extracts the data and translates it to a PagedResponse.
*
* @param skip Number of elements to skip.
* @param context Context for the query.
*
* @return A Mono that completes with a paged response of topics.
*/
private Mono<PagedResponse<TopicProperties>> listTopics(int skip, Context context) {
return managementClient.listEntitiesWithResponseAsync(TOPICS_ENTITY_TYPE, skip, NUMBER_OF_ELEMENTS, context)
.onErrorMap(ServiceBusAdministrationAsyncClient::mapException)
.flatMap(response -> {
final Response<TopicDescriptionFeed> feedResponse = deserialize(response, TopicDescriptionFeed.class);
final TopicDescriptionFeed feed = feedResponse.getValue();
if (feed == null) {
logger.warning("Could not deserialize TopicDescriptionFeed. skip {}, top: {}", skip,
NUMBER_OF_ELEMENTS);
return Mono.empty();
}
final List<TopicProperties> entities = feed.getEntry().stream()
.filter(e -> e.getContent() != null && e.getContent().getTopicDescription() != null)
.map(e -> {
final String topicName = getTitleValue(e.getTitle());
final TopicProperties topicProperties = EntityHelper.toModel(
e.getContent().getTopicDescription());
EntityHelper.setTopicName(topicProperties, topicName);
return topicProperties;
})
.collect(Collectors.toList());
try {
return Mono.just(extractPage(feedResponse, entities, feed.getLink()));
} catch (MalformedURLException | UnsupportedEncodingException error) {
return Mono.error(new RuntimeException("Could not parse response into FeedPage<TopicDescription>",
error));
}
});
}
/**
* Given an XML title element, returns the XML text inside. Jackson deserializes Objects as LinkedHashMaps. XML text
* is represented as an entry with an empty string as the key.
*
* For example, the text returned from this {@code <title text="text/xml">QueueName</title>} is "QueueName".
*
* @param responseTitle XML title element.
*
* @return The XML text inside the title. {@code null} is returned if there is no value.
*/
@SuppressWarnings("unchecked")
private String getTitleValue(Object responseTitle) {
if (!(responseTitle instanceof Map)) {
return null;
}
final Map<String, String> map;
try {
map = (Map<String, String>) responseTitle;
return map.get("");
} catch (ClassCastException error) {
logger.warning("Unable to cast to Map<String,String>. Title: {}", responseTitle, error);
return null;
}
}
/**
* Maps an exception from the ATOM APIs to its associated {@link HttpResponseException}.
*
* @param exception Exception from the ATOM API.
*
* @return The corresponding {@link HttpResponseException} or {@code throwable} if it is not an instance of {@link
* ServiceBusManagementErrorException}.
*/
private static Throwable mapException(Throwable exception) {
if (!(exception instanceof ServiceBusManagementErrorException)) {
return exception;
}
final ServiceBusManagementErrorException managementError = ((ServiceBusManagementErrorException) exception);
final ServiceBusManagementError error = managementError.getValue();
final HttpResponse errorHttpResponse = managementError.getResponse();
final int statusCode = error != null && error.getCode() != null
? error.getCode()
: errorHttpResponse.getStatusCode();
final String errorDetail = error != null && error.getDetail() != null
? error.getDetail()
: managementError.getMessage();
switch (statusCode) {
case 401:
return new ClientAuthenticationException(errorDetail, managementError.getResponse(), exception);
case 404:
return new ResourceNotFoundException(errorDetail, managementError.getResponse(), exception);
case 409:
return new ResourceExistsException(errorDetail, managementError.getResponse(), exception);
case 412:
return new ResourceModifiedException(errorDetail, managementError.getResponse(), exception);
default:
return new HttpResponseException(errorDetail, managementError.getResponse(), exception);
}
}
/**
* A page of Service Bus entities.
*
* @param <T> The entity description from Service Bus.
*/
private static final class FeedPage<T> implements PagedResponse<T> {
private final int statusCode;
private final HttpHeaders header;
private final HttpRequest request;
private final IterableStream<T> entries;
private final String continuationToken;
/**
* Creates a page that does not have any more pages.
*
* @param entries Items in the page.
*/
private FeedPage(int statusCode, HttpHeaders header, HttpRequest request, List<T> entries) {
this.statusCode = statusCode;
this.header = header;
this.request = request;
this.entries = new IterableStream<>(entries);
this.continuationToken = null;
}
/**
* Creates an instance that has additional pages to fetch.
*
* @param entries Items in the page.
* @param skip Number of elements to "skip".
*/
private FeedPage(int statusCode, HttpHeaders header, HttpRequest request, List<T> entries, int skip) {
this.statusCode = statusCode;
this.header = header;
this.request = request;
this.entries = new IterableStream<>(entries);
this.continuationToken = String.valueOf(skip);
}
@Override
public IterableStream<T> getElements() {
return entries;
}
@Override
public String getContinuationToken() {
return continuationToken;
}
@Override
public int getStatusCode() {
return statusCode;
}
@Override
public HttpHeaders getHeaders() {
return header;
}
@Override
public HttpRequest getRequest() {
return request;
}
@Override
public void close() {
}
}
private static final class EntityNotFoundHttpResponse<T> extends HttpResponse {
private final int statusCode;
private final HttpHeaders headers;
private EntityNotFoundHttpResponse(Response<T> response) {
super(response.getRequest());
this.headers = response.getHeaders();
this.statusCode = response.getStatusCode();
}
@Override
public int getStatusCode() {
return statusCode;
}
@Override
public String getHeaderValue(String name) {
return headers.getValue(name);
}
@Override
public HttpHeaders getHeaders() {
return headers;
}
@Override
public Flux<ByteBuffer> getBody() {
return Flux.empty();
}
@Override
public Mono<byte[]> getBodyAsByteArray() {
return Mono.empty();
}
@Override
public Mono<String> getBodyAsString() {
return Mono.empty();
}
@Override
public Mono<String> getBodyAsString(Charset charset) {
return Mono.empty();
}
}
} | class ServiceBusAdministrationAsyncClient {
private static final String SERVICE_BUS_TRACING_NAMESPACE_VALUE = "Microsoft.ServiceBus";
private static final String CONTENT_TYPE = "application/xml";
private static final String QUEUES_ENTITY_TYPE = "queues";
private static final String TOPICS_ENTITY_TYPE = "topics";
private static final int NUMBER_OF_ELEMENTS = 100;
private final ServiceBusManagementClientImpl managementClient;
private final EntitiesImpl entityClient;
private final ClientLogger logger = new ClientLogger(ServiceBusAdministrationAsyncClient.class);
private final ServiceBusManagementSerializer serializer;
private final RulesImpl rulesClient;
/**
* Creates a new instance with the given management client and serializer.
*
* @param managementClient Client to make management calls.
* @param serializer Serializer to deserialize ATOM XML responses.
*/
ServiceBusAdministrationAsyncClient(ServiceBusManagementClientImpl managementClient,
ServiceBusManagementSerializer serializer) {
this.serializer = Objects.requireNonNull(serializer, "'serializer' cannot be null.");
this.managementClient = Objects.requireNonNull(managementClient, "'managementClient' cannot be null.");
this.entityClient = managementClient.getEntities();
this.rulesClient = managementClient.getRules();
}
/**
* Creates a queue with the given name.
*
* @param queueName Name of the queue to create.
*
* @return A Mono that completes with information about the created queue.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If the request body was invalid, the queue quota is exceeded, or an error
* occurred processing the request.
* @throws NullPointerException if {@code queueName} is null.
* @throws IllegalArgumentException if {@code queueName} is an empty string.
* @throws ResourceExistsException if a queue exists with the same {@code queueName}.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<QueueProperties> createQueue(String queueName) {
try {
return createQueue(queueName, new CreateQueueOptions());
} catch (RuntimeException e) {
return monoError(logger, e);
}
}
/**
* Creates a queue with the {@link CreateQueueOptions} and given queue name.
*
* @param queueName Name of the queue to create.
* @param queueOptions Options about the queue to create.
*
* @return A Mono that completes with information about the created queue.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If the request body was invalid, the queue quota is exceeded, or an error
* occurred processing the request.
* @throws IllegalArgumentException if {@code queueName} is an empty string.
* @throws NullPointerException if {@code queueName} or {@code queueOptions} is null.
* @throws ResourceExistsException if a queue exists with the same {@link QueueProperties
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<QueueProperties> createQueue(String queueName, CreateQueueOptions queueOptions) {
return createQueueWithResponse(queueName, queueOptions).map(Response::getValue);
}
/**
* Creates a queue and returns the created queue in addition to the HTTP response.
*
* @param queueName Name of the queue to create.
* @param queueOptions Options about the queue to create.
*
* @return A Mono that returns the created queue in addition to the HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If the request body was invalid, the queue quota is exceeded, or an error
* occurred processing the request.
* @throws IllegalArgumentException if {@code queueName} is an empty string.
* @throws NullPointerException if {@code queueName} or {@code queueOptions} is null.
* @throws ResourceExistsException if a queue exists with the same {@link QueueProperties
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<QueueProperties>> createQueueWithResponse(String queueName, CreateQueueOptions queueOptions) {
return withContext(context -> createQueueWithResponse(queueName, queueOptions, context));
}
/**
* Creates a rule under the given topic and subscription
*
* @param topicName Name of the topic associated with rule.
* @param subscriptionName Name of the subscription associated with the rule.
* @param ruleName Name of the rule.
*
* @return A Mono that completes with information about the created rule.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If the request body was invalid, the quota is exceeded, or an error occurred
* processing the request.
* @throws IllegalArgumentException if {@code topicName} or {@code ruleName} are are empty strings.
* @throws NullPointerException if {@code topicName} or {@code ruleName} are are null.
* @throws ResourceExistsException if a rule exists with the same topic, subscription, and rule name.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<RuleProperties> createRule(String topicName, String subscriptionName, String ruleName) {
try {
return createRule(topicName, subscriptionName, ruleName, new CreateRuleOptions());
} catch (RuntimeException e) {
return monoError(logger, e);
}
}
/**
* Creates a rule with the {@link CreateRuleOptions}.
*
* @param topicName Name of the topic associated with rule.
* @param subscriptionName Name of the subscription associated with the rule.
* @param ruleName Name of the rule.
* @param ruleOptions Information about the rule to create.
*
* @return A Mono that completes with information about the created rule.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If the request body was invalid, the quota is exceeded, or an error occurred
* processing the request.
* @throws IllegalArgumentException if {@code topicName} or {@code ruleName} are are empty strings.
* @throws NullPointerException if {@code topicName}, {@code ruleName}, or {@code ruleOptions}
* are are null.
* @throws ResourceExistsException if a rule exists with the same topic and rule name.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<RuleProperties> createRule(String topicName, String subscriptionName, String ruleName,
CreateRuleOptions ruleOptions) {
return createRuleWithResponse(topicName, subscriptionName, ruleName, ruleOptions)
.map(Response::getValue);
}
/**
* Creates a rule and returns the created rule in addition to the HTTP response.
*
* @param topicName Name of the topic associated with rule.
* @param subscriptionName Name of the subscription associated with the rule.
* @param ruleName Name of the rule.
* @param ruleOptions Information about the rule to create.
*
* @return A Mono that returns the created rule in addition to the HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If the request body was invalid, the quota is exceeded, or an error occurred
* processing the request.
* @throws IllegalArgumentException if {@code topicName} or {@code ruleName} are are empty strings.
* @throws NullPointerException if {@code topicName}, {@code ruleName}, or {@code ruleOptions}
* are are null.
* @throws ResourceExistsException if a rule exists with the same topic and rule name.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<RuleProperties>> createRuleWithResponse(String topicName, String subscriptionName,
String ruleName, CreateRuleOptions ruleOptions) {
return withContext(context -> createRuleWithResponse(topicName, subscriptionName, ruleName, ruleOptions,
context));
}
/**
* Creates a subscription with the given topic and subscription names.
*
* @param topicName Name of the topic associated with subscription.
* @param subscriptionName Name of the subscription.
*
* @return A Mono that completes with information about the created subscription.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If the request body was invalid, the quota is exceeded, or an error occurred
* processing the request.
* @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} are are empty strings.
* @throws NullPointerException if {@code topicName} or {@code subscriptionName} are are null.
* @throws ResourceExistsException if a subscription exists with the same topic and subscription name.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<SubscriptionProperties> createSubscription(String topicName, String subscriptionName) {
try {
return createSubscription(topicName, subscriptionName, new CreateSubscriptionOptions());
} catch (RuntimeException e) {
return monoError(logger, e);
}
}
/**
* Creates a subscription with the {@link CreateSubscriptionOptions}.
*
* @param topicName Name of the topic associated with subscription.
* @param subscriptionName Name of the subscription.
* @param subscriptionOptions Information about the subscription to create.
*
* @return A Mono that completes with information about the created subscription.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If the request body was invalid, the quota is exceeded, or an error occurred
* processing the request.
* @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} are are empty strings.
* @throws NullPointerException if {@code topicName}, {@code subscriptionName}, or {@code subscriptionOptions}
* are are null.
* @throws ResourceExistsException if a subscription exists with the same topic and subscription name.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<SubscriptionProperties> createSubscription(String topicName, String subscriptionName,
CreateSubscriptionOptions subscriptionOptions) {
return createSubscriptionWithResponse(topicName, subscriptionName, subscriptionOptions)
.map(Response::getValue);
}
/**
* Creates a subscription and returns the created subscription in addition to the HTTP response.
*
* @param topicName Name of the topic associated with subscription.
* @param subscriptionName Name of the subscription.
* @param subscriptionOptions Information about the subscription to create.
*
* @return A Mono that returns the created subscription in addition to the HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If the request body was invalid, the quota is exceeded, or an error occurred
* processing the request.
* @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} are are empty strings.
* @throws NullPointerException if {@code topicName}, {@code subscriptionName}, or {@code subscriptionOptions}
* are are null.
* @throws ResourceExistsException if a subscription exists with the same topic and subscription name.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<SubscriptionProperties>> createSubscriptionWithResponse(String topicName,
String subscriptionName, CreateSubscriptionOptions subscriptionOptions) {
return withContext(context -> createSubscriptionWithResponse(topicName, subscriptionName, subscriptionOptions,
context));
}
/**
* Creates a topic with the given name.
*
* @param topicName Name of the topic to create.
*
* @return A Mono that completes with information about the created topic.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If the request body was invalid, the topic quota is exceeded, or an error
* occurred processing the request.
* @throws NullPointerException if {@code topicName} is null.
* @throws IllegalArgumentException if {@code topicName} is an empty string.
* @throws ResourceExistsException if a topic exists with the same {@code topicName}.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<TopicProperties> createTopic(String topicName) {
try {
return createTopic(topicName, new CreateTopicOptions());
} catch (RuntimeException e) {
return monoError(logger, e);
}
}
/**
* Creates a topic with the {@link CreateTopicOptions}.
*
* @param topicName Name of the topic to create.
* @param topicOptions The options used to create the topic.
*
* @return A Mono that completes with information about the created topic.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If the request body was invalid, the topic quota is exceeded, or an error
* occurred processing the request.
* @throws IllegalArgumentException if {@code topicName} is an empty string.
* @throws NullPointerException if {@code topicName} or {@code topicOptions} is null.
* @throws ResourceExistsException if a topic exists with the same {@code topicName}.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<TopicProperties> createTopic(String topicName, CreateTopicOptions topicOptions) {
return createTopicWithResponse(topicName, topicOptions).map(Response::getValue);
}
/**
* Creates a topic and returns the created topic in addition to the HTTP response.
*
* @param topicName Name of the topic to create.
* @param topicOptions The options used to create the topic.
*
* @return A Mono that returns the created topic in addition to the HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If the request body was invalid, the topic quota is exceeded, or an error
* occurred processing the request.
* @throws IllegalArgumentException if {@link TopicProperties
* string.
* @throws NullPointerException if {@code topicName} or {@code topicOptions} is null.
* @throws ResourceExistsException if a topic exists with the same {@code topicName}.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<TopicProperties>> createTopicWithResponse(String topicName, CreateTopicOptions topicOptions) {
return withContext(context -> createTopicWithResponse(topicName, topicOptions, context));
}
/**
* Deletes a queue the matching {@code queueName}.
*
* @param queueName Name of queue to delete.
*
* @return A Mono that completes when the queue is deleted.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws NullPointerException if {@code queueName} is null.
* @throws IllegalArgumentException if {@code queueName} is an empty string.
* @throws ResourceNotFoundException if the {@code queueName} does not exist.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Void> deleteQueue(String queueName) {
return deleteQueueWithResponse(queueName).then();
}
/**
* Deletes a queue the matching {@code queueName} and returns the HTTP response.
*
* @param queueName Name of queue to delete.
*
* @return A Mono that completes when the queue is deleted and returns the HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws NullPointerException if {@code queueName} is null.
* @throws IllegalArgumentException if {@code queueName} is an empty string.
* @throws ResourceNotFoundException if the {@code queueName} does not exist.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Void>> deleteQueueWithResponse(String queueName) {
return withContext(context -> deleteQueueWithResponse(queueName, context));
}
/**
* Deletes a rule the matching {@code ruleName}.
*
* @param topicName Name of topic associated with rule to delete.
* @param subscriptionName Name of the subscription associated with the rule to delete.
* @param ruleName Name of rule to delete.
*
* @return A Mono that completes when the rule is deleted.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code topicName} or {@code ruleName} is an empty string.
* @throws NullPointerException if {@code topicName} or {@code ruleName} is null.
* @throws ResourceNotFoundException if the {@code ruleName} does not exist.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Void> deleteRule(String topicName, String subscriptionName, String ruleName) {
return deleteRuleWithResponse(topicName, subscriptionName, ruleName).then();
}
/**
* Deletes a rule the matching {@code ruleName} and returns the HTTP response.
*
* @param topicName Name of topic associated with rule to delete.
* @param subscriptionName Name of the subscription associated with the rule to delete.
* @param ruleName Name of rule to delete.
*
* @return A Mono that completes when the rule is deleted and returns the HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code topicName}, {@code subscriptionName}, or {@code ruleName} is an
* empty string.
* @throws NullPointerException if {@code topicName}, {@code subscriptionName}, or {@code ruleName} is null.
* @throws ResourceNotFoundException if the {@code ruleName} does not exist.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Void>> deleteRuleWithResponse(String topicName, String subscriptionName,
String ruleName) {
return withContext(context -> deleteRuleWithResponse(topicName, subscriptionName, ruleName, context));
}
/**
* Deletes a subscription the matching {@code subscriptionName}.
*
* @param topicName Name of topic associated with subscription to delete.
* @param subscriptionName Name of subscription to delete.
*
* @return A Mono that completes when the subscription is deleted.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} is an empty string.
* @throws NullPointerException if {@code topicName} or {@code subscriptionName} is null.
* @throws ResourceNotFoundException if the {@code subscriptionName} does not exist.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Void> deleteSubscription(String topicName, String subscriptionName) {
return deleteSubscriptionWithResponse(topicName, subscriptionName).then();
}
/**
* Deletes a subscription the matching {@code subscriptionName} and returns the HTTP response.
*
* @param topicName Name of topic associated with subscription to delete.
* @param subscriptionName Name of subscription to delete.
*
* @return A Mono that completes when the subscription is deleted and returns the HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} is an empty string.
* @throws NullPointerException if {@code topicName} or {@code subscriptionName} is null.
* @throws ResourceNotFoundException if the {@code subscriptionName} does not exist.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Void>> deleteSubscriptionWithResponse(String topicName, String subscriptionName) {
return withContext(context -> deleteSubscriptionWithResponse(topicName, subscriptionName, context));
}
/**
* Deletes a topic the matching {@code topicName}.
*
* @param topicName Name of topic to delete.
*
* @return A Mono that completes when the topic is deleted.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code topicName} is an empty string.
* @throws NullPointerException if {@code topicName} is null.
* @throws ResourceNotFoundException if the {@code topicName} does not exist.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Void> deleteTopic(String topicName) {
return deleteTopicWithResponse(topicName).then();
}
/**
* Deletes a topic the matching {@code topicName} and returns the HTTP response.
*
* @param topicName Name of topic to delete.
*
* @return A Mono that completes when the topic is deleted and returns the HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code topicName} is an empty string.
* @throws NullPointerException if {@code topicName} is null.
* @throws ResourceNotFoundException if the {@code topicName} does not exist.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Void>> deleteTopicWithResponse(String topicName) {
return withContext(context -> deleteTopicWithResponse(topicName, context));
}
/**
* Gets information about the queue.
*
* @param queueName Name of queue to get information about.
*
* @return A Mono that completes with information about the queue.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code queueName} is an empty string.
* @throws NullPointerException if {@code queueName} is null.
* @throws ResourceNotFoundException if the {@code queueName} does not exist.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<QueueProperties> getQueue(String queueName) {
return getQueueWithResponse(queueName).map(Response::getValue);
}
/**
* Gets information about the queue along with its HTTP response.
*
* @param queueName Name of queue to get information about.
*
* @return A Mono that completes with information about the queue and the associated HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code queueName} is an empty string.
* @throws NullPointerException if {@code queueName} is null.
* @throws ResourceNotFoundException if the {@code queueName} does not exist.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<QueueProperties>> getQueueWithResponse(String queueName) {
return withContext(context -> getQueueWithResponse(queueName, context, Function.identity()));
}
/**
* Gets whether or not a queue with {@code queueName} exists in the Service Bus namespace.
*
* @param queueName Name of the queue.
*
* @return A Mono that completes indicating whether or not the queue exists.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code queueName} is an empty string.
* @throws NullPointerException if {@code queueName} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Boolean> getQueueExists(String queueName) {
return getQueueExistsWithResponse(queueName).map(Response::getValue);
}
/**
* Gets whether or not a queue with {@code queueName} exists in the Service Bus namespace.
*
* @param queueName Name of the queue.
*
* @return A Mono that completes indicating whether or not the queue exists along with its HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code queueName} is an empty string.
* @throws NullPointerException if {@code queueName} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Boolean>> getQueueExistsWithResponse(String queueName) {
return getEntityExistsWithResponse(getQueueWithResponse(queueName));
}
/**
* Gets runtime properties about the queue.
*
* @param queueName Name of queue to get information about.
*
* @return A Mono that completes with runtime properties about the queue.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code queueName} is an empty string.
* @throws NullPointerException if {@code queueName} is null.
* @throws ResourceNotFoundException if the {@code queueName} does not exist.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<QueueRuntimeProperties> getQueueRuntimeProperties(String queueName) {
return getQueueRuntimePropertiesWithResponse(queueName).map(response -> response.getValue());
}
/**
* Gets runtime properties about the queue along with its HTTP response.
*
* @param queueName Name of queue to get information about.
*
* @return A Mono that completes with runtime properties about the queue and the associated HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code queueName} is an empty string.
* @throws NullPointerException if {@code queueName} is null.
* @throws ResourceNotFoundException if the {@code queueName} does not exist.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<QueueRuntimeProperties>> getQueueRuntimePropertiesWithResponse(String queueName) {
return withContext(context -> getQueueWithResponse(queueName, context, QueueRuntimeProperties::new));
}
/**
* Gets information about the Service Bus namespace.
*
* @return A Mono that completes with information about the Service Bus namespace.
* @throws ClientAuthenticationException if the client's credentials do not have access to the namespace.
* @throws HttpResponseException If error occurred processing the request.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<NamespaceProperties> getNamespaceProperties() {
return getNamespacePropertiesWithResponse().map(Response::getValue);
}
/**
* Gets information about the Service Bus namespace along with its HTTP response.
*
* @return A Mono that completes with information about the namespace and the associated HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<NamespaceProperties>> getNamespacePropertiesWithResponse() {
return withContext(this::getNamespacePropertiesWithResponse);
}
/**
* Gets a rule from the service namespace.
*
* Only following data types are deserialized in Filters and Action parameters - string, int, long, boolean, double,
* and OffsetDateTime. Other data types would return its string value.
*
* @param topicName The name of the topic relative to service bus namespace.
* @param subscriptionName The subscription name the rule belongs to.
* @param ruleName The name of the rule to retrieve.
*
* @return The associated rule.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<RuleProperties> getRule(String topicName, String subscriptionName, String ruleName) {
return getRuleWithResponse(topicName, subscriptionName, ruleName).map(response -> response.getValue());
}
/**
* Gets a rule from the service namespace.
*
* Only following data types are deserialized in Filters and Action parameters - string, int, long, bool, double,
* and OffsetDateTime. Other data types would return its string value.
*
* @param topicName The name of the topic relative to service bus namespace.
* @param subscriptionName The subscription name the rule belongs to.
* @param ruleName The name of the rule to retrieve.
*
* @return The associated rule with the corresponding HTTP response.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<RuleProperties>> getRuleWithResponse(String topicName, String subscriptionName,
String ruleName) {
return withContext(context -> getRuleWithResponse(topicName, subscriptionName, ruleName, context));
}
/**
* Gets information about the queue.
*
* @param topicName Name of topic associated with subscription.
* @param subscriptionName Name of subscription to get information about.
*
* @return A Mono that completes with information about the subscription.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} are empty strings.
* @throws NullPointerException if {@code topicName} or {@code subscriptionName} are null.
* @throws ResourceNotFoundException if the {@code subscriptionName} does not exist in the {@code topicName}.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<SubscriptionProperties> getSubscription(String topicName, String subscriptionName) {
return getSubscriptionWithResponse(topicName, subscriptionName).map(Response::getValue);
}
/**
* Gets information about the subscription along with its HTTP response.
*
* @param topicName Name of topic associated with subscription.
* @param subscriptionName Name of subscription to get information about.
*
* @return A Mono that completes with information about the subscription and the associated HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} are empty strings.
* @throws NullPointerException if {@code topicName} or {@code subscriptionName} are null.
* @throws ResourceNotFoundException if the {@code subscriptionName} does not exist.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<SubscriptionProperties>> getSubscriptionWithResponse(String topicName,
String subscriptionName) {
return withContext(context -> getSubscriptionWithResponse(topicName, subscriptionName, context,
Function.identity()));
}
/**
* Gets whether or not a subscription within a topic exists.
*
* @param topicName Name of topic associated with subscription.
* @param subscriptionName Name of the subscription.
*
* @return A Mono that completes indicating whether or not the subscription exists.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code subscriptionName} is an empty string.
* @throws NullPointerException if {@code subscriptionName} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Boolean> getSubscriptionExists(String topicName, String subscriptionName) {
return getSubscriptionExistsWithResponse(topicName, subscriptionName).map(Response::getValue);
}
/**
* Gets whether or not a subscription within a topic exists.
*
* @param topicName Name of topic associated with subscription.
* @param subscriptionName Name of the subscription.
*
* @return A Mono that completes indicating whether or not the subscription exists along with its HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code subscriptionName} is an empty string.
* @throws NullPointerException if {@code subscriptionName} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Boolean>> getSubscriptionExistsWithResponse(String topicName, String subscriptionName) {
return getEntityExistsWithResponse(getSubscriptionWithResponse(topicName, subscriptionName));
}
/**
* Gets runtime properties about the subscription.
*
* @param topicName Name of topic associated with subscription.
* @param subscriptionName Name of subscription to get information about.
*
* @return A Mono that completes with runtime properties about the subscription.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} are empty strings.
* @throws NullPointerException if {@code topicName} or {@code subscriptionName} are null.
* @throws ResourceNotFoundException if the {@code subscriptionName} does not exist.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<SubscriptionRuntimeProperties> getSubscriptionRuntimeProperties(
String topicName, String subscriptionName) {
return getSubscriptionRuntimePropertiesWithResponse(topicName, subscriptionName)
.map(response -> response.getValue());
}
/**
* Gets runtime properties about the subscription.
*
* @param topicName Name of topic associated with subscription.
* @param subscriptionName Name of subscription to get information about.
*
* @return A Mono that completes with runtime properties about the subscription.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code subscriptionName} is an empty string.
* @throws NullPointerException if {@code subscriptionName} is null.
* @throws ResourceNotFoundException if the {@code subscriptionName} does not exist.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<SubscriptionRuntimeProperties>> getSubscriptionRuntimePropertiesWithResponse(
String topicName, String subscriptionName) {
return withContext(context -> getSubscriptionWithResponse(topicName, subscriptionName, context,
SubscriptionRuntimeProperties::new));
}
/**
* Gets information about the topic.
*
* @param topicName Name of topic to get information about.
*
* @return A Mono that completes with information about the topic.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code topicName} is an empty string.
* @throws NullPointerException if {@code topicName} is null.
* @throws ResourceNotFoundException if the {@code topicName} does not exist.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<TopicProperties> getTopic(String topicName) {
return getTopicWithResponse(topicName).map(Response::getValue);
}
/**
* Gets information about the topic along with its HTTP response.
*
* @param topicName Name of topic to get information about.
*
* @return A Mono that completes with information about the topic and the associated HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code topicName} is an empty string.
* @throws NullPointerException if {@code topicName} is null.
* @throws ResourceNotFoundException if the {@code topicName} does not exist.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<TopicProperties>> getTopicWithResponse(String topicName) {
return withContext(context -> getTopicWithResponse(topicName, context, Function.identity()));
}
/**
* Gets whether or not a topic with {@code topicName} exists in the Service Bus namespace.
*
* @param topicName Name of the topic.
*
* @return A Mono that completes indicating whether or not the topic exists.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code topicName} is an empty string.
* @throws NullPointerException if {@code topicName} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Boolean> getTopicExists(String topicName) {
return getTopicExistsWithResponse(topicName).map(Response::getValue);
}
/**
* Gets whether or not a topic with {@code topicName} exists in the Service Bus namespace.
*
* @param topicName Name of the topic.
*
* @return A Mono that completes indicating whether or not the topic exists along with its HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code topicName} is an empty string.
* @throws NullPointerException if {@code topicName} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Boolean>> getTopicExistsWithResponse(String topicName) {
return getEntityExistsWithResponse(getTopicWithResponse(topicName));
}
/**
* Gets runtime properties about the topic.
*
* @param topicName Name of topic to get information about.
*
* @return A Mono that completes with runtime properties about the topic.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code topicName} is an empty string.
* @throws NullPointerException if {@code topicName} is null.
* @throws ResourceNotFoundException if the {@code topicName} does not exist.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<TopicRuntimeProperties> getTopicRuntimeProperties(String topicName) {
return getTopicRuntimePropertiesWithResponse(topicName).map(response -> response.getValue());
}
/**
* Gets runtime properties about the topic with its HTTP response.
*
* @param topicName Name of topic to get information about.
*
* @return A Mono that completes with runtime properties about the topic and the associated HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code topicName} is an empty string.
* @throws NullPointerException if {@code topicName} is null.
* @throws ResourceNotFoundException if the {@code topicName} does not exist.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<TopicRuntimeProperties>> getTopicRuntimePropertiesWithResponse(String topicName) {
return withContext(context -> getTopicWithResponse(topicName, context, TopicRuntimeProperties::new));
}
/**
* Fetches all the queues in the Service Bus namespace.
*
* @return A Flux of {@link QueueProperties queues} in the Service Bus namespace.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @see <a href="https:
* authorization rules</a>
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux<QueueProperties> listQueues() {
return new PagedFlux<>(
() -> withContext(context -> listQueuesFirstPage(context)),
token -> withContext(context -> listQueuesNextPage(token, context)));
}
/**
* Fetches all the rules for a topic and subscription.
*
* @param topicName The topic name under which all the rules need to be retrieved.
* @param subscriptionName The name of the subscription for which all rules need to be retrieved.
*
* @return A Flux of {@link RuleProperties rules} for the {@code topicName} and {@code subscriptionName}.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws NullPointerException if {@code topicName} or {@code subscriptionName} is null.
* @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} is an empty string.
* @see <a href="https:
* authorization rules</a>
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux<RuleProperties> listRules(String topicName, String subscriptionName) {
if (topicName == null) {
return pagedFluxError(logger, new NullPointerException("'topicName' cannot be null."));
} else if (topicName.isEmpty()) {
return pagedFluxError(logger, new IllegalArgumentException("'topicName' cannot be an empty string."));
}
return new PagedFlux<>(
() -> withContext(context -> listRulesFirstPage(topicName, subscriptionName, context)),
token -> withContext(context -> listRulesNextPage(topicName, subscriptionName, token, context)));
}
/**
* Fetches all the subscriptions for a topic.
*
* @param topicName The topic name under which all the subscriptions need to be retrieved.
*
* @return A Flux of {@link SubscriptionProperties subscriptions} for the {@code topicName}.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws NullPointerException if {@code topicName} is null.
* @throws IllegalArgumentException if {@code topicName} is an empty string.
* @see <a href="https:
* authorization rules</a>
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux<SubscriptionProperties> listSubscriptions(String topicName) {
if (topicName == null) {
return pagedFluxError(logger, new NullPointerException("'topicName' cannot be null."));
} else if (topicName.isEmpty()) {
return pagedFluxError(logger, new IllegalArgumentException("'topicName' cannot be an empty string."));
}
return new PagedFlux<>(
() -> withContext(context -> listSubscriptionsFirstPage(topicName, context)),
token -> withContext(context -> listSubscriptionsNextPage(topicName, token, context)));
}
/**
* Fetches all the topics in the Service Bus namespace.
*
* @return A Flux of {@link TopicProperties topics} in the Service Bus namespace.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @see <a href="https:
* authorization rules</a>
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux<TopicProperties> listTopics() {
return new PagedFlux<>(
() -> withContext(context -> listTopicsFirstPage(context)),
token -> withContext(context -> listTopicsNextPage(token, context)));
}
/**
* Updates a queue with the given {@link QueueProperties}. The {@link QueueProperties} must be fully populated as
* all of the properties are replaced. If a property is not set the service default value is used.
*
* The suggested flow is:
* <ol>
* <li>{@link
* <li>Update the required elements.</li>
* <li>Pass the updated description into this method.</li>
* </ol>
*
* <p>
* There are a subset of properties that can be updated. More information can be found in the links below. They are:
* <ul>
* <li>{@link QueueProperties
* <li>{@link QueueProperties
* <li>{@link QueueProperties
* </li>
* <li>{@link QueueProperties
* </ul>
*
* @param queue Information about the queue to update. You must provide all the property values that are desired
* on the updated entity. Any values not provided are set to the service default values.
*
* @return A Mono that completes with the updated queue.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If the request body was invalid, the queue quota is exceeded, or an error
* occurred processing the request.
* @throws NullPointerException if {@code queue} is null.
* @see <a href="https:
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<QueueProperties> updateQueue(QueueProperties queue) {
return updateQueueWithResponse(queue).map(Response::getValue);
}
/**
* Updates a queue with the given {@link QueueProperties}. The {@link QueueProperties} must be fully populated as
* all of the properties are replaced. If a property is not set the service default value is used.
*
* The suggested flow is:
* <ol>
* <li>{@link
* <li>Update the required elements.</li>
* <li>Pass the updated description into this method.</li>
* </ol>
*
* <p>
* There are a subset of properties that can be updated. More information can be found in the links below. They are:
* <ul>
* <li>{@link QueueProperties
* <li>{@link QueueProperties
* <li>{@link QueueProperties
* </li>
* <li>{@link QueueProperties
* </ul>
*
* @param queue Information about the queue to update. You must provide all the property values that are desired
* on the updated entity. Any values not provided are set to the service default values.
*
* @return A Mono that returns the updated queue in addition to the HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If the request body was invalid, the queue quota is exceeded, or an error
* occurred processing the request.
* @throws NullPointerException if {@code queue} is null.
* @see <a href="https:
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<QueueProperties>> updateQueueWithResponse(QueueProperties queue) {
return withContext(context -> updateQueueWithResponse(queue, context));
}
/**
* Updates a rule with the given {@link RuleProperties}. The {@link RuleProperties} must be fully populated as all
* of the properties are replaced. If a property is not set the service default value is used.
*
* The suggested flow is:
* <ol>
* <li>{@link
* <li>Update the required elements.</li>
* <li>Pass the updated description into this method.</li>
* </ol>
*
* @param topicName The topic name under which the rule is updated.
* @param subscriptionName The name of the subscription for which the rule is updated.
* @param rule Information about the rule to update. You must provide all the property values that are desired
* on the updated entity. Any values not provided are set to the service default values.
*
* @return A Mono that returns the updated rule.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If the request body was invalid, the rule quota is exceeded, or an error
* occurred processing the request.
* @throws IllegalArgumentException if {@link RuleProperties
* @throws NullPointerException if {@code rule} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<RuleProperties> updateRule(String topicName, String subscriptionName, RuleProperties rule) {
return updateRuleWithResponse(topicName, subscriptionName, rule).map(Response::getValue);
}
/**
* Updates a rule with the given {@link RuleProperties}. The {@link RuleProperties} must be fully populated as all
* of the properties are replaced. If a property is not set the service default value is used.
*
* The suggested flow is:
* <ol>
* <li>{@link
* <li>Update the required elements.</li>
* <li>Pass the updated description into this method.</li>
* </ol>
*
* @param topicName The topic name under which the rule is updated.
* @param subscriptionName The name of the subscription for which the rule is updated.
* @param rule Information about the rule to update. You must provide all the property values that are desired
* on the updated entity. Any values not provided are set to the service default values.
*
* @return A Mono that returns the updated rule in addition to the HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If the request body was invalid, the rule quota is exceeded, or an error
* occurred processing the request.
* @throws IllegalArgumentException if {@link RuleProperties
* @throws NullPointerException if {@code rule} is null.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<RuleProperties>> updateRuleWithResponse(String topicName, String subscriptionName,
RuleProperties rule) {
return withContext(context -> updateRuleWithResponse(topicName, subscriptionName, rule, context));
}
/**
* Updates a subscription with the given {@link SubscriptionProperties}. The {@link SubscriptionProperties} must be
* fully populated as all of the properties are replaced. If a property is not set the service default value is
* used.
*
* The suggested flow is:
* <ol>
* <li>{@link
* <li>Update the required elements.</li>
* <li>Pass the updated description into this method.</li>
* </ol>
*
* <p>
* There are a subset of properties that can be updated. More information can be found in the links below. They are:
* <ul>
* <li>{@link SubscriptionProperties
* <li>{@link SubscriptionProperties
* <li>{@link SubscriptionProperties
* </ul>
*
* @param subscription Information about the subscription to update. You must provide all the property values
* that are desired on the updated entity. Any values not provided are set to the service default values.
*
* @return A Mono that returns the updated subscription.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If the request body was invalid, the subscription quota is exceeded, or an
* error occurred processing the request.
* @throws IllegalArgumentException if {@link SubscriptionProperties
* SubscriptionProperties
* @throws NullPointerException if {@code subscription} is null.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<SubscriptionProperties> updateSubscription(SubscriptionProperties subscription) {
return updateSubscriptionWithResponse(subscription).map(Response::getValue);
}
/**
* Updates a subscription with the given {@link SubscriptionProperties}. The {@link SubscriptionProperties} must be
* fully populated as all of the properties are replaced. If a property is not set the service default value is
* used.
*
* The suggested flow is:
* <ol>
* <li>{@link
* <li>Update the required elements.</li>
* <li>Pass the updated description into this method.</li>
* </ol>
*
* <p>
* There are a subset of properties that can be updated. More information can be found in the links below. They are:
* <ul>
* <li>{@link SubscriptionProperties
* <li>{@link SubscriptionProperties
* <li>{@link SubscriptionProperties
* </ul>
*
* @param subscription Information about the subscription to update. You must provide all the property values
* that are desired on the updated entity. Any values not provided are set to the service default values.
*
* @return A Mono that returns the updated subscription in addition to the HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If the request body was invalid, the subscription quota is exceeded, or an
* error occurred processing the request.
* @throws IllegalArgumentException if {@link SubscriptionProperties
* SubscriptionProperties
* @throws NullPointerException if {@code subscription} is null.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<SubscriptionProperties>> updateSubscriptionWithResponse(
SubscriptionProperties subscription) {
return withContext(context -> updateSubscriptionWithResponse(subscription, context));
}
/**
* Updates a topic with the given {@link TopicProperties}. The {@link TopicProperties} must be fully populated as
* all of the properties are replaced. If a property is not set the service default value is used.
*
* The suggested flow is:
* <ol>
* <li>{@link
* <li>Update the required elements.</li>
* <li>Pass the updated description into this method.</li>
* </ol>
*
* <p>
* There are a subset of properties that can be updated. More information can be found in the links below. They are:
* <ul>
* <li>{@link TopicProperties
* <li>{@link TopicProperties
* </li>
* </ul>
*
* @param topic Information about the topic to update. You must provide all the property values that are desired
* on the updated entity. Any values not provided are set to the service default values.
*
* @return A Mono that completes with the updated topic.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If the request body was invalid, the topic quota is exceeded, or an error
* occurred processing the request.
* @throws IllegalArgumentException if {@link TopicProperties
* string.
* @throws NullPointerException if {@code topic} is null.
* @see <a href="https:
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<TopicProperties> updateTopic(TopicProperties topic) {
return updateTopicWithResponse(topic).map(Response::getValue);
}
/**
* Updates a topic with the given {@link TopicProperties}. The {@link TopicProperties} must be fully populated as
* all of the properties are replaced. If a property is not set the service default value is used.
*
* The suggested flow is:
* <ol>
* <li>{@link
* <li>Update the required elements.</li>
* <li>Pass the updated description into this method.</li>
* </ol>
*
* <p>
* There are a subset of properties that can be updated. More information can be found in the links below. They are:
* <ul>
* <li>{@link TopicProperties
* <li>{@link TopicProperties
* </li>
* </ul>
*
* @param topic Information about the topic to update. You must provide all the property values that are desired
* on the updated entity. Any values not provided are set to the service default values.
*
* @return A Mono that completes with the updated topic and its HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If the request body was invalid, the topic quota is exceeded, or an error
* occurred processing the request.
* @throws IllegalArgumentException if {@link TopicProperties
* string.
* @throws NullPointerException if {@code topic} is null.
* @see <a href="https:
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<TopicProperties>> updateTopicWithResponse(TopicProperties topic) {
return withContext(context -> updateTopicWithResponse(topic, context));
}
/**
* Creates a queue with its context.
*
* @param createQueueOptions Queue to create.
* @param context Context to pass into request.
*
* @return A Mono that completes with the created {@link QueueProperties}.
*/
Mono<Response<QueueProperties>> createQueueWithResponse(String queueName, CreateQueueOptions createQueueOptions,
Context context) {
if (queueName == null) {
return monoError(logger, new NullPointerException("'queueName' cannot be null."));
} else if (queueName.isEmpty()) {
return monoError(logger, new IllegalArgumentException("'queueName' cannot be empty."));
}
if (createQueueOptions == null) {
return monoError(logger, new NullPointerException("'createQueueOptions' cannot be null."));
} else if (context == null) {
return monoError(logger, new NullPointerException("'context' cannot be null."));
}
final QueueDescription description = EntityHelper.getQueueDescription(createQueueOptions);
final CreateQueueBodyContent content = new CreateQueueBodyContent()
.setType(CONTENT_TYPE)
.setQueueDescription(description);
final CreateQueueBody createEntity = new CreateQueueBody()
.setContent(content);
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
try {
return entityClient.putWithResponseAsync(queueName, createEntity, null, withTracing)
.onErrorMap(ServiceBusAdministrationAsyncClient::mapException)
.map(this::deserializeQueue);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Creates a rule with its context.
*
* @param ruleOptions Rule to create.
* @param context Context to pass into request.
*
* @return A Mono that completes with the created {@link RuleProperties}.
*/
Mono<Response<RuleProperties>> createRuleWithResponse(String topicName, String subscriptionName, String ruleName,
CreateRuleOptions ruleOptions, Context context) {
if (topicName == null) {
return monoError(logger, new NullPointerException("'topicName' cannot be null."));
} else if (topicName.isEmpty()) {
return monoError(logger, new IllegalArgumentException("'topicName' cannot be empty."));
}
if (subscriptionName == null) {
return monoError(logger, new NullPointerException("'subscriptionName' cannot be null."));
} else if (subscriptionName.isEmpty()) {
return monoError(logger, new IllegalArgumentException("'subscriptionName' cannot be empty."));
}
if (ruleName == null) {
return monoError(logger, new NullPointerException("'ruleName' cannot be null."));
} else if (ruleName.isEmpty()) {
return monoError(logger, new IllegalArgumentException("'ruleName' cannot be empty."));
}
if (ruleOptions == null) {
return monoError(logger, new NullPointerException("'rule' cannot be null."));
}
final RuleActionImpl action = ruleOptions.getAction() != null
? EntityHelper.toImplementation(ruleOptions.getAction())
: null;
final RuleFilterImpl filter = ruleOptions.getFilter() != null
? EntityHelper.toImplementation(ruleOptions.getFilter())
: null;
final RuleDescription rule = new RuleDescription()
.setAction(action)
.setFilter(filter)
.setName(ruleName);
final CreateRuleBodyContent content = new CreateRuleBodyContent()
.setType(CONTENT_TYPE)
.setRuleDescription(rule);
final CreateRuleBody createEntity = new CreateRuleBody().setContent(content);
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
try {
return managementClient.getRules().putWithResponseAsync(topicName, subscriptionName, ruleName, createEntity,
null, withTracing)
.onErrorMap(ServiceBusAdministrationAsyncClient::mapException)
.map(response -> deserializeRule(response));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Creates a subscription with its context.
*
* @param subscriptionOptions Subscription to create.
* @param context Context to pass into request.
*
* @return A Mono that completes with the created {@link SubscriptionProperties}.
*/
Mono<Response<SubscriptionProperties>> createSubscriptionWithResponse(String topicName, String subscriptionName,
CreateSubscriptionOptions subscriptionOptions, Context context) {
if (topicName == null) {
return monoError(logger, new NullPointerException("'topicName' cannot be null."));
} else if (topicName.isEmpty()) {
return monoError(logger, new IllegalArgumentException("'topicName' cannot be empty."));
}
if (subscriptionName == null) {
return monoError(logger, new NullPointerException("'subscriptionName' cannot be null."));
} else if (subscriptionName.isEmpty()) {
return monoError(logger, new IllegalArgumentException("'subscriptionName' cannot be empty."));
}
if (subscriptionOptions == null) {
return monoError(logger, new NullPointerException("'subscription' cannot be null."));
}
final SubscriptionDescription subscription = EntityHelper.getSubscriptionDescription(subscriptionOptions);
final CreateSubscriptionBodyContent content = new CreateSubscriptionBodyContent()
.setType(CONTENT_TYPE)
.setSubscriptionDescription(subscription);
final CreateSubscriptionBody createEntity = new CreateSubscriptionBody().setContent(content);
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
try {
return managementClient.getSubscriptions().putWithResponseAsync(topicName, subscriptionName, createEntity,
null, withTracing)
.onErrorMap(ServiceBusAdministrationAsyncClient::mapException)
.map(response -> deserializeSubscription(topicName, response));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Creates a topicOptions with its context.
*
* @param topicOptions Topic to create.
* @param context Context to pass into request.
*
* @return A Mono that completes with the created {@link TopicProperties}.
*/
Mono<Response<TopicProperties>> createTopicWithResponse(String topicName, CreateTopicOptions topicOptions,
Context context) {
if (topicName == null) {
return monoError(logger, new NullPointerException("'topicName' cannot be null."));
} else if (topicName.isEmpty()) {
return monoError(logger, new IllegalArgumentException("'topicName' cannot be empty."));
}
if (topicOptions == null) {
return monoError(logger, new NullPointerException("'topicOptions' cannot be null"));
} else if (context == null) {
return monoError(logger, new NullPointerException("'context' cannot be null."));
}
final TopicDescription topic = EntityHelper.getTopicDescription(topicOptions);
final CreateTopicBodyContent content = new CreateTopicBodyContent()
.setType(CONTENT_TYPE)
.setTopicDescription(topic);
final CreateTopicBody createEntity = new CreateTopicBody()
.setContent(content);
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
try {
return entityClient.putWithResponseAsync(topicName, createEntity, null, withTracing)
.onErrorMap(ServiceBusAdministrationAsyncClient::mapException)
.map(this::deserializeTopic);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Deletes a queue with its context.
*
* @param queueName Name of queue to delete.
* @param context Context to pass into request.
*
* @return A Mono that completes when the queue is deleted.
*/
Mono<Response<Void>> deleteQueueWithResponse(String queueName, Context context) {
if (queueName == null) {
return monoError(logger, new NullPointerException("'queueName' cannot be null"));
} else if (queueName.isEmpty()) {
return monoError(logger, new IllegalArgumentException("'queueName' cannot be an empty string."));
} else if (context == null) {
return monoError(logger, new NullPointerException("'context' cannot be null."));
}
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
try {
return entityClient.deleteWithResponseAsync(queueName, withTracing)
.onErrorMap(ServiceBusAdministrationAsyncClient::mapException)
.map(response -> {
return new SimpleResponse<>(response.getRequest(), response.getStatusCode(),
response.getHeaders(), null);
});
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Deletes a queue with its context.
*
* @param topicName Name of topic to delete.
* @param subscriptionName Name of the subscription for the rule.
* @param ruleName Name of the rule.
* @param context Context to pass into request.
*
* @return A Mono that completes with the created {@link QueueProperties}.
*/
Mono<Response<Void>> deleteRuleWithResponse(String topicName, String subscriptionName, String ruleName,
Context context) {
if (topicName == null) {
return monoError(logger, new NullPointerException("'topicName' cannot be null"));
} else if (topicName.isEmpty()) {
return monoError(logger, new IllegalArgumentException("'topicName' cannot be an empty string."));
} else if (subscriptionName == null) {
return monoError(logger, new NullPointerException("'subscriptionName' cannot be null"));
} else if (subscriptionName.isEmpty()) {
return monoError(logger, new IllegalArgumentException("'subscriptionName' cannot be an empty string."));
} else if (ruleName == null) {
return monoError(logger, new NullPointerException("'ruleName' cannot be null"));
} else if (ruleName.isEmpty()) {
return monoError(logger, new IllegalArgumentException("'ruleName' cannot be an empty string."));
} else if (context == null) {
return monoError(logger, new NullPointerException("'context' cannot be null."));
}
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
try {
return rulesClient.deleteWithResponseAsync(topicName, subscriptionName, ruleName, withTracing)
.onErrorMap(ServiceBusAdministrationAsyncClient::mapException)
.map(response -> new SimpleResponse<>(response.getRequest(), response.getStatusCode(),
response.getHeaders(), null));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Deletes a subscription with its context.
*
* @param topicName Name of topic associated with subscription to delete.
* @param subscriptionName Name of subscription to delete.
* @param context Context to pass into request.
*
* @return A Mono that completes with the created {@link SubscriptionProperties}.
*/
Mono<Response<Void>> deleteSubscriptionWithResponse(String topicName, String subscriptionName, Context context) {
if (subscriptionName == null) {
return monoError(logger, new NullPointerException("'subscriptionName' cannot be null"));
} else if (subscriptionName.isEmpty()) {
return monoError(logger, new IllegalArgumentException("'subscriptionName' cannot be an empty string."));
} else if (topicName == null) {
return monoError(logger, new NullPointerException("'topicName' cannot be null"));
} else if (topicName.isEmpty()) {
return monoError(logger, new IllegalArgumentException("'topicName' cannot be an empty string."));
} else if (context == null) {
return monoError(logger, new NullPointerException("'context' cannot be null."));
}
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
try {
return managementClient.getSubscriptions().deleteWithResponseAsync(topicName, subscriptionName,
withTracing)
.onErrorMap(ServiceBusAdministrationAsyncClient::mapException)
.map(response -> new SimpleResponse<>(response.getRequest(), response.getStatusCode(),
response.getHeaders(), null));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Deletes a topic with its context.
*
* @param topicName Name of topic to delete.
* @param context Context to pass into request.
*
* @return A Mono that completes with the created {@link TopicProperties}.
*/
Mono<Response<Void>> deleteTopicWithResponse(String topicName, Context context) {
if (topicName == null) {
return monoError(logger, new NullPointerException("'topicName' cannot be null"));
} else if (topicName.isEmpty()) {
return monoError(logger, new IllegalArgumentException("'topicName' cannot be an empty string."));
} else if (context == null) {
return monoError(logger, new NullPointerException("'context' cannot be null."));
}
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
try {
return entityClient.deleteWithResponseAsync(topicName, withTracing)
.onErrorMap(ServiceBusAdministrationAsyncClient::mapException)
.map(response -> new SimpleResponse<>(response.getRequest(), response.getStatusCode(),
response.getHeaders(), null));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Gets whether an entity exists.
*
* @param getEntityOperation Operation to get information about entity. If {@link ResourceNotFoundException} is
* thrown, then it is mapped to false.
* @param <T> Entity type.
*
* @return True if the entity exists, false otherwise.
*/
<T> Mono<Response<Boolean>> getEntityExistsWithResponse(Mono<Response<T>> getEntityOperation) {
return getEntityOperation.map(response -> {
final boolean exists = response.getValue() != null;
return (Response<Boolean>) new SimpleResponse<>(response.getRequest(), response.getStatusCode(),
response.getHeaders(), exists);
})
.onErrorResume(ResourceNotFoundException.class, exception -> {
final HttpResponse response = exception.getResponse();
final Response<Boolean> result = new SimpleResponse<>(response.getRequest(), response.getStatusCode(),
response.getHeaders(), false);
return Mono.just(result);
});
}
/**
* Gets a queue with its context.
*
* @param queueName Name of queue to fetch information for.
* @param context Context to pass into request.
*
* @return A Mono that completes with the {@link QueueProperties}.
*/
<T> Mono<Response<T>> getQueueWithResponse(String queueName, Context context,
Function<QueueProperties, T> mapper) {
if (queueName == null) {
return monoError(logger, new NullPointerException("'queueName' cannot be null"));
} else if (queueName.isEmpty()) {
return monoError(logger, new IllegalArgumentException("'queueName' cannot be empty."));
} else if (context == null) {
return monoError(logger, new NullPointerException("'context' cannot be null."));
}
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
try {
return entityClient.getWithResponseAsync(queueName, true, withTracing)
.onErrorMap(ServiceBusAdministrationAsyncClient::mapException)
.handle((response, sink) -> {
final Response<QueueProperties> deserialize = deserializeQueue(response);
if (deserialize.getValue() == null) {
final HttpResponse notFoundResponse = new EntityNotFoundHttpResponse<>(deserialize);
sink.error(new ResourceNotFoundException(String.format("Queue '%s' does not exist.", queueName),
notFoundResponse));
} else {
final T mapped = mapper.apply(deserialize.getValue());
sink.next(new SimpleResponse<>(response.getRequest(), response.getStatusCode(),
response.getHeaders(), mapped));
}
});
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<RuleProperties>> getRuleWithResponse(String topicName, String subscriptionName,
String ruleName, Context context) {
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
try {
return rulesClient.getWithResponseAsync(topicName, subscriptionName, ruleName, true, withTracing)
.onErrorMap(ServiceBusAdministrationAsyncClient::mapException)
.map(this::deserializeRule);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Gets a subscription with its context.
*
* @param topicName Name of the topic associated with the subscription.
* @param subscriptionName Name of subscription to fetch information for.
* @param context Context to pass into request.
*
* @return A Mono that completes with the {@link SubscriptionProperties}.
*/
<T> Mono<Response<T>> getSubscriptionWithResponse(String topicName, String subscriptionName, Context context,
Function<SubscriptionProperties, T> mapper) {
if (topicName == null) {
return monoError(logger, new NullPointerException("'topicName' cannot be null."));
} else if (topicName.isEmpty()) {
return monoError(logger, new IllegalArgumentException("'topicName' cannot be an empty string."));
} else if (subscriptionName == null) {
return monoError(logger, new NullPointerException("'subscriptionName' cannot be null."));
} else if (subscriptionName.isEmpty()) {
return monoError(logger, new IllegalArgumentException("'subscriptionName' cannot be an empty string."));
} else if (context == null) {
return monoError(logger, new NullPointerException("'context' cannot be null."));
}
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
try {
return managementClient.getSubscriptions().getWithResponseAsync(topicName, subscriptionName, true,
withTracing)
.onErrorMap(ServiceBusAdministrationAsyncClient::mapException)
.handle((response, sink) -> {
final Response<SubscriptionProperties> deserialize = deserializeSubscription(topicName, response);
if (deserialize.getValue() == null) {
final HttpResponse notFoundResponse = new EntityNotFoundHttpResponse<>(deserialize);
sink.error(new ResourceNotFoundException(String.format(
"Subscription '%s' in topic '%s' does not exist.", topicName, subscriptionName),
notFoundResponse));
} else {
final T mapped = mapper.apply(deserialize.getValue());
sink.next(new SimpleResponse<>(response.getRequest(), response.getStatusCode(),
response.getHeaders(), mapped));
}
});
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Gets the namespace properties with its context.
*
* @param context Context to pass into request.
*
* @return A Mono that completes with the {@link NamespaceProperties}.
*/
Mono<Response<NamespaceProperties>> getNamespacePropertiesWithResponse(Context context) {
return managementClient.getNamespaces().getWithResponseAsync(context).handle((response, sink) -> {
final NamespacePropertiesEntry entry = response.getValue();
if (entry == null || entry.getContent() == null) {
sink.error(new AzureException(
"There was no content inside namespace response. Entry: " + response));
return;
}
final NamespaceProperties namespaceProperties = entry.getContent().getNamespaceProperties();
final Response<NamespaceProperties> result = new SimpleResponse<>(response.getRequest(),
response.getStatusCode(), response.getHeaders(), namespaceProperties);
sink.next(result);
});
}
/**
* Gets a topic with its context.
*
* @param topicName Name of topic to fetch information for.
* @param context Context to pass into request.
*
* @return A Mono that completes with the {@link TopicProperties}.
*/
<T> Mono<Response<T>> getTopicWithResponse(String topicName, Context context,
Function<TopicProperties, T> mapper) {
if (topicName == null) {
return monoError(logger, new NullPointerException("'topicName' cannot be null"));
} else if (topicName.isEmpty()) {
return monoError(logger, new IllegalArgumentException("'topicName' cannot be empty."));
} else if (context == null) {
return monoError(logger, new NullPointerException("'context' cannot be null."));
}
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
try {
return entityClient.getWithResponseAsync(topicName, true, withTracing)
.onErrorMap(ServiceBusAdministrationAsyncClient::mapException)
.handle((response, sink) -> {
final Response<TopicProperties> deserialize = deserializeTopic(response);
if (deserialize.getValue() == null) {
final HttpResponse notFoundResponse = new EntityNotFoundHttpResponse<>(deserialize);
sink.error(new ResourceNotFoundException(String.format("Topic '%s' does not exist.", topicName),
notFoundResponse));
} else {
final T mapped = mapper.apply(deserialize.getValue());
sink.next(new SimpleResponse<>(response.getRequest(), response.getStatusCode(),
response.getHeaders(), mapped));
}
});
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Gets the first page of queues with context.
*
* @param context Context to pass into request.
*
* @return A Mono that completes with a page of queues.
*/
Mono<PagedResponse<QueueProperties>> listQueuesFirstPage(Context context) {
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
try {
return listQueues(0, withTracing);
} catch (RuntimeException e) {
return monoError(logger, e);
}
}
/**
* Gets the next page of queues with context.
*
* @param continuationToken Number of items to skip in feed.
* @param context Context to pass into request.
*
* @return A Mono that completes with a page of queues or empty if there are no items left.
*/
Mono<PagedResponse<QueueProperties>> listQueuesNextPage(String continuationToken, Context context) {
if (continuationToken == null || continuationToken.isEmpty()) {
return Mono.empty();
}
try {
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
final int skip = Integer.parseInt(continuationToken);
return listQueues(skip, withTracing);
} catch (RuntimeException e) {
return monoError(logger, e);
}
}
/**
* Gets the first page of rules with context.
*
* @param context Context to pass into request.
*
* @return A Mono that completes with a page of rules.
*/
Mono<PagedResponse<RuleProperties>> listRulesFirstPage(String topicName, String subscriptionName, Context context) {
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
try {
return listRules(topicName, subscriptionName, 0, withTracing);
} catch (RuntimeException e) {
return monoError(logger, e);
}
}
/**
* Gets the next page of rules with context.
*
* @param continuationToken Number of items to skip in feed.
* @param context Context to pass into request.
*
* @return A Mono that completes with a page of rules or empty if there are no items left.
*/
Mono<PagedResponse<RuleProperties>> listRulesNextPage(String topicName, String subscriptionName,
String continuationToken, Context context) {
if (continuationToken == null || continuationToken.isEmpty()) {
return Mono.empty();
}
try {
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
final int skip = Integer.parseInt(continuationToken);
return listRules(topicName, subscriptionName, skip, withTracing);
} catch (RuntimeException e) {
return monoError(logger, e);
}
}
/**
* Gets the first page of subscriptions with context.
*
* @param context Context to pass into request.
*
* @return A Mono that completes with a page of subscriptions.
*/
Mono<PagedResponse<SubscriptionProperties>> listSubscriptionsFirstPage(String topicName, Context context) {
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
try {
return listSubscriptions(topicName, 0, withTracing);
} catch (RuntimeException e) {
return monoError(logger, e);
}
}
/**
* Gets the next page of subscriptions with context.
*
* @param continuationToken Number of items to skip in feed.
* @param context Context to pass into request.
*
* @return A Mono that completes with a page of subscriptions or empty if there are no items left.
*/
Mono<PagedResponse<SubscriptionProperties>> listSubscriptionsNextPage(String topicName, String continuationToken,
Context context) {
if (continuationToken == null || continuationToken.isEmpty()) {
return Mono.empty();
}
try {
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
final int skip = Integer.parseInt(continuationToken);
return listSubscriptions(topicName, skip, withTracing);
} catch (RuntimeException e) {
return monoError(logger, e);
}
}
/**
* Gets the first page of topics with context.
*
* @param context Context to pass into request.
*
* @return A Mono that completes with a page of topics.
*/
Mono<PagedResponse<TopicProperties>> listTopicsFirstPage(Context context) {
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
try {
return listTopics(0, withTracing);
} catch (RuntimeException e) {
return monoError(logger, e);
}
}
/**
* Gets the next page of topics with context.
*
* @param continuationToken Number of items to skip in feed.
* @param context Context to pass into request.
*
* @return A Mono that completes with a page of topics or empty if there are no items left.
*/
Mono<PagedResponse<TopicProperties>> listTopicsNextPage(String continuationToken, Context context) {
if (continuationToken == null || continuationToken.isEmpty()) {
return Mono.empty();
}
try {
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
final int skip = Integer.parseInt(continuationToken);
return listTopics(skip, withTracing);
} catch (RuntimeException e) {
return monoError(logger, e);
}
}
/**
* Updates a queue with its context.
*
* @param queue Information about the queue to update. You must provide all the property values that are desired
* on the updated entity. Any values not provided are set to the service default values.
* @param context Context to pass into request.
*
* @return A Mono that completes with the updated {@link QueueProperties}.
*/
Mono<Response<QueueProperties>> updateQueueWithResponse(QueueProperties queue, Context context) {
if (queue == null) {
return monoError(logger, new NullPointerException("'queue' cannot be null"));
} else if (context == null) {
return monoError(logger, new NullPointerException("'context' cannot be null."));
}
final QueueDescription queueDescription = EntityHelper.toImplementation(queue);
final CreateQueueBodyContent content = new CreateQueueBodyContent()
.setType(CONTENT_TYPE)
.setQueueDescription(queueDescription);
final CreateQueueBody createEntity = new CreateQueueBody()
.setContent(content);
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
try {
return entityClient.putWithResponseAsync(queue.getName(), createEntity, "*", withTracing)
.onErrorMap(ServiceBusAdministrationAsyncClient::mapException)
.map(response -> deserializeQueue(response));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Updates a rule with its context.
*
* @param rule Information about the rule to update. You must provide all the property values that are desired
* on the updated entity. Any values not provided are set to the service default values.
* @param context Context to pass into request.
*
* @return A Mono that completes with the updated {@link RuleProperties}.
*/
Mono<Response<RuleProperties>> updateRuleWithResponse(String topicName, String subscriptionName,
RuleProperties rule, Context context) {
if (rule == null) {
return monoError(logger, new NullPointerException("'rule' cannot be null"));
} else if (context == null) {
return monoError(logger, new NullPointerException("'context' cannot be null."));
}
final RuleDescription implementation = EntityHelper.toImplementation(rule);
final CreateRuleBodyContent content = new CreateRuleBodyContent()
.setType(CONTENT_TYPE)
.setRuleDescription(implementation);
final CreateRuleBody ruleBody = new CreateRuleBody()
.setContent(content);
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
try {
return managementClient.getRules().putWithResponseAsync(topicName, subscriptionName, rule.getName(),
ruleBody, "*", withTracing)
.onErrorMap(ServiceBusAdministrationAsyncClient::mapException)
.map(response -> deserializeRule(response));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Updates a subscription with its context.
*
* @param subscription Information about the subscription to update. You must provide all the property values
* that are desired on the updated entity. Any values not provided are set to the service default values.
* @param context Context to pass into request.
*
* @return A Mono that completes with the updated {@link SubscriptionProperties}.
*/
Mono<Response<SubscriptionProperties>> updateSubscriptionWithResponse(SubscriptionProperties subscription,
Context context) {
if (subscription == null) {
return monoError(logger, new NullPointerException("'subscription' cannot be null"));
} else if (context == null) {
return monoError(logger, new NullPointerException("'context' cannot be null."));
}
final String topicName = subscription.getTopicName();
final String subscriptionName = subscription.getSubscriptionName();
final SubscriptionDescription implementation = EntityHelper.toImplementation(subscription);
final CreateSubscriptionBodyContent content = new CreateSubscriptionBodyContent()
.setType(CONTENT_TYPE)
.setSubscriptionDescription(implementation);
final CreateSubscriptionBody createEntity = new CreateSubscriptionBody()
.setContent(content);
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
try {
return managementClient.getSubscriptions().putWithResponseAsync(topicName, subscriptionName, createEntity,
"*", withTracing)
.onErrorMap(ServiceBusAdministrationAsyncClient::mapException)
.map(response -> deserializeSubscription(topicName, response));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Updates a topic with its context.
*
* @param topic Information about the topic to update. You must provide all the property values that are desired
* on the updated entity. Any values not provided are set to the service default values.
* @param context Context to pass into request.
*
* @return A Mono that completes with the updated {@link TopicProperties}.
*/
Mono<Response<TopicProperties>> updateTopicWithResponse(TopicProperties topic, Context context) {
if (topic == null) {
return monoError(logger, new NullPointerException("'topic' cannot be null"));
} else if (context == null) {
return monoError(logger, new NullPointerException("'context' cannot be null."));
}
final TopicDescription implementation = EntityHelper.toImplementation(topic);
final CreateTopicBodyContent content = new CreateTopicBodyContent()
.setType(CONTENT_TYPE)
.setTopicDescription(implementation);
final CreateTopicBody createEntity = new CreateTopicBody()
.setContent(content);
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
try {
return entityClient.putWithResponseAsync(topic.getName(), createEntity, "*", withTracing)
.onErrorMap(ServiceBusAdministrationAsyncClient::mapException)
.map(response -> deserializeTopic(response));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
private <T> T deserialize(Object object, Class<T> clazz) {
if (object == null) {
return null;
}
final String contents = String.valueOf(object);
if (contents.isEmpty()) {
return null;
}
try {
return serializer.deserialize(contents, clazz);
} catch (IOException e) {
throw logger.logExceptionAsError(new RuntimeException(String.format(
"Exception while deserializing. Body: [%s]. Class: %s", contents, clazz), e));
}
}
/**
* Given an HTTP response, will deserialize it into a strongly typed Response object.
*
* @param response HTTP response to deserialize response body from.
* @param clazz Class to deserialize response type into.
* @param <T> Class type to deserialize response into.
*
* @return A Response with a strongly typed response value.
*/
private <T> Response<T> deserialize(Response<Object> response, Class<T> clazz) {
final T deserialize = deserialize(response.getValue(), clazz);
return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(),
deserialize);
}
/**
* Converts a Response into its corresponding {@link QueueDescriptionEntry} then mapped into {@link
* QueueProperties}.
*
* @param response HTTP Response to deserialize.
*
* @return The corresponding HTTP response with convenience properties set.
*/
/**
* Converts a Response into its corresponding {@link RuleDescriptionEntry} then mapped into {@link RuleProperties}.
*
* @param response HTTP Response to deserialize.
*
* @return The corresponding HTTP response with convenience properties set.
*/
private Response<RuleProperties> deserializeRule(Response<Object> response) {
final RuleDescriptionEntry entry = deserialize(response.getValue(), RuleDescriptionEntry.class);
if (entry == null) {
return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null);
} else if (entry.getContent() == null) {
logger.info("entry.getContent() is null. The entity may not exist. {}", entry);
return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null);
}
final RuleDescription description = entry.getContent().getRuleDescription();
final RuleProperties result = EntityHelper.toModel(description);
return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), result);
}
/**
* Converts a Response into its corresponding {@link SubscriptionDescriptionEntry} then mapped into {@link
* SubscriptionProperties}.
*
* @param response HTTP Response to deserialize.
*
* @return The corresponding HTTP response with convenience properties set.
*/
private Response<SubscriptionProperties> deserializeSubscription(String topicName, Response<Object> response) {
final SubscriptionDescriptionEntry entry = deserialize(response.getValue(), SubscriptionDescriptionEntry.class);
if (entry == null) {
return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null);
} else if (entry.getContent() == null) {
logger.warning("entry.getContent() is null. There should have been content returned. Entry: {}", entry);
return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null);
}
final SubscriptionProperties subscription = EntityHelper.toModel(
entry.getContent().getSubscriptionDescription());
final String subscriptionName = getTitleValue(entry.getTitle());
EntityHelper.setSubscriptionName(subscription, subscriptionName);
EntityHelper.setTopicName(subscription, topicName);
return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(),
subscription);
}
/**
* Converts a Response into its corresponding {@link TopicDescriptionEntry} then mapped into {@link
* QueueProperties}.
*
* @param response HTTP Response to deserialize.
*
* @return The corresponding HTTP response with convenience properties set.
*/
private Response<TopicProperties> deserializeTopic(Response<Object> response) {
final TopicDescriptionEntry entry = deserialize(response.getValue(), TopicDescriptionEntry.class);
if (entry == null) {
return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null);
} else if (entry.getContent() == null) {
logger.warning("entry.getContent() is null. There should have been content returned. Entry: {}", entry);
return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null);
} else if (entry.getContent().getTopicDescription() == null) {
final QueueDescriptionEntry entryQueue = deserialize(response.getValue(), QueueDescriptionEntry.class);
if (entryQueue != null && entryQueue.getContent() != null && entryQueue.getContent().getQueueDescription() != null) {
logger.warning("'{}' is not a topic, it is a queue.", entryQueue.getTitle());
return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null);
}
}
final TopicProperties result = EntityHelper.toModel(entry.getContent().getTopicDescription());
final String topicName = getTitleValue(entry.getTitle());
EntityHelper.setTopicName(result, topicName);
return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), result);
}
/**
* Creates a {@link FeedPage} given the elements and a set of response links to get the next link from.
*
* @param entities Entities in the feed.
* @param responseLinks Links returned from the feed.
* @param <TResult> Type of Service Bus entities in page.
*
* @return A {@link FeedPage} indicating whether this can be continued or not.
* @throws MalformedURLException if the "next" page link does not contain a well-formed URL.
*/
private <TResult, TFeed> FeedPage<TResult> extractPage(Response<TFeed> response, List<TResult> entities,
List<ResponseLink> responseLinks)
throws MalformedURLException, UnsupportedEncodingException {
final Optional<ResponseLink> nextLink = responseLinks.stream()
.filter(link -> link.getRel().equalsIgnoreCase("next"))
.findFirst();
if (!nextLink.isPresent()) {
return new FeedPage<>(response.getStatusCode(), response.getHeaders(), response.getRequest(), entities);
}
final URL url = new URL(nextLink.get().getHref());
final String decode = URLDecoder.decode(url.getQuery(), StandardCharsets.UTF_8.name());
final Optional<Integer> skipParameter = Arrays.stream(decode.split("&|&"))
.map(part -> part.split("=", 2))
.filter(parts -> parts[0].equalsIgnoreCase("$skip") && parts.length == 2)
.map(parts -> Integer.valueOf(parts[1]))
.findFirst();
if (skipParameter.isPresent()) {
return new FeedPage<>(response.getStatusCode(), response.getHeaders(), response.getRequest(), entities,
skipParameter.get());
} else {
logger.warning("There should have been a skip parameter for the next page.");
return new FeedPage<>(response.getStatusCode(), response.getHeaders(), response.getRequest(), entities);
}
}
/**
* Helper method that invokes the service method, extracts the data and translates it to a PagedResponse.
*
* @param skip Number of elements to skip.
* @param context Context for the query.
*
* @return A Mono that completes with a paged response of queues.
*/
private Mono<PagedResponse<QueueProperties>> listQueues(int skip, Context context) {
return managementClient.listEntitiesWithResponseAsync(QUEUES_ENTITY_TYPE, skip, NUMBER_OF_ELEMENTS, context)
.onErrorMap(ServiceBusAdministrationAsyncClient::mapException)
.flatMap(response -> {
final Response<QueueDescriptionFeed> feedResponse = deserialize(response, QueueDescriptionFeed.class);
final QueueDescriptionFeed feed = feedResponse.getValue();
if (feed == null) {
logger.warning("Could not deserialize QueueDescriptionFeed. skip {}, top: {}", skip,
NUMBER_OF_ELEMENTS);
return Mono.empty();
}
final List<QueueProperties> entities = feed.getEntry().stream()
.filter(e -> e.getContent() != null && e.getContent().getQueueDescription() != null)
.map(e -> {
final String queueName = getTitleValue(e.getTitle());
final QueueProperties queueProperties = EntityHelper.toModel(
e.getContent().getQueueDescription());
EntityHelper.setQueueName(queueProperties, queueName);
return queueProperties;
})
.collect(Collectors.toList());
try {
return Mono.just(extractPage(feedResponse, entities, feed.getLink()));
} catch (MalformedURLException | UnsupportedEncodingException error) {
return Mono.error(new RuntimeException("Could not parse response into FeedPage<QueueDescription>",
error));
}
});
}
/**
* Helper method that invokes the service method, extracts the data and translates it to a PagedResponse.
*
* @param skip Number of elements to skip.
* @param context Context for the query.
*
* @return A Mono that completes with a paged response of rules.
*/
private Mono<PagedResponse<RuleProperties>> listRules(String topicName, String subscriptionName, int skip,
Context context) {
return managementClient.listRulesWithResponseAsync(topicName, subscriptionName, skip, NUMBER_OF_ELEMENTS,
context)
.onErrorMap(ServiceBusAdministrationAsyncClient::mapException)
.flatMap(response -> {
final Response<RuleDescriptionFeed> feedResponse = deserialize(response,
RuleDescriptionFeed.class);
final RuleDescriptionFeed feed = feedResponse.getValue();
if (feed == null) {
logger.warning("Could not deserialize RuleDescriptionFeed. skip {}, top: {}", skip,
NUMBER_OF_ELEMENTS);
return Mono.empty();
}
final List<RuleProperties> entities = feed.getEntry().stream()
.filter(e -> e.getContent() != null && e.getContent().getRuleDescription() != null)
.map(e -> {
return EntityHelper.toModel(e.getContent().getRuleDescription());
})
.collect(Collectors.toList());
try {
return Mono.just(extractPage(feedResponse, entities, feed.getLink()));
} catch (MalformedURLException | UnsupportedEncodingException error) {
return Mono.error(new RuntimeException(
"Could not parse response into FeedPage<RuleDescription>", error));
}
});
}
/**
* Helper method that invokes the service method, extracts the data and translates it to a PagedResponse.
*
* @param skip Number of elements to skip.
* @param context Context for the query.
*
* @return A Mono that completes with a paged response of subscriptions.
*/
private Mono<PagedResponse<SubscriptionProperties>> listSubscriptions(String topicName, int skip,
Context context) {
return managementClient.listSubscriptionsWithResponseAsync(topicName, skip, NUMBER_OF_ELEMENTS, context)
.onErrorMap(ServiceBusAdministrationAsyncClient::mapException)
.flatMap(response -> {
final Response<SubscriptionDescriptionFeed> feedResponse = deserialize(response,
SubscriptionDescriptionFeed.class);
final SubscriptionDescriptionFeed feed = feedResponse.getValue();
if (feed == null) {
logger.warning("Could not deserialize SubscriptionDescriptionFeed. skip {}, top: {}", skip,
NUMBER_OF_ELEMENTS);
return Mono.empty();
}
final List<SubscriptionProperties> entities = feed.getEntry().stream()
.filter(e -> e.getContent() != null && e.getContent().getSubscriptionDescription() != null)
.map(e -> {
final String subscriptionName = getTitleValue(e.getTitle());
final SubscriptionProperties description = EntityHelper.toModel(
e.getContent().getSubscriptionDescription());
EntityHelper.setTopicName(description, topicName);
EntityHelper.setSubscriptionName(description, subscriptionName);
return description;
})
.collect(Collectors.toList());
try {
return Mono.just(extractPage(feedResponse, entities, feed.getLink()));
} catch (MalformedURLException | UnsupportedEncodingException error) {
return Mono.error(new RuntimeException(
"Could not parse response into FeedPage<SubscriptionDescription>", error));
}
});
}
/**
* Helper method that invokes the service method, extracts the data and translates it to a PagedResponse.
*
* @param skip Number of elements to skip.
* @param context Context for the query.
*
* @return A Mono that completes with a paged response of topics.
*/
private Mono<PagedResponse<TopicProperties>> listTopics(int skip, Context context) {
return managementClient.listEntitiesWithResponseAsync(TOPICS_ENTITY_TYPE, skip, NUMBER_OF_ELEMENTS, context)
.onErrorMap(ServiceBusAdministrationAsyncClient::mapException)
.flatMap(response -> {
final Response<TopicDescriptionFeed> feedResponse = deserialize(response, TopicDescriptionFeed.class);
final TopicDescriptionFeed feed = feedResponse.getValue();
if (feed == null) {
logger.warning("Could not deserialize TopicDescriptionFeed. skip {}, top: {}", skip,
NUMBER_OF_ELEMENTS);
return Mono.empty();
}
final List<TopicProperties> entities = feed.getEntry().stream()
.filter(e -> e.getContent() != null && e.getContent().getTopicDescription() != null)
.map(e -> {
final String topicName = getTitleValue(e.getTitle());
final TopicProperties topicProperties = EntityHelper.toModel(
e.getContent().getTopicDescription());
EntityHelper.setTopicName(topicProperties, topicName);
return topicProperties;
})
.collect(Collectors.toList());
try {
return Mono.just(extractPage(feedResponse, entities, feed.getLink()));
} catch (MalformedURLException | UnsupportedEncodingException error) {
return Mono.error(new RuntimeException("Could not parse response into FeedPage<TopicDescription>",
error));
}
});
}
/**
* Given an XML title element, returns the XML text inside. Jackson deserializes Objects as LinkedHashMaps. XML text
* is represented as an entry with an empty string as the key.
*
* For example, the text returned from this {@code <title text="text/xml">QueueName</title>} is "QueueName".
*
* @param responseTitle XML title element.
*
* @return The XML text inside the title. {@code null} is returned if there is no value.
*/
@SuppressWarnings("unchecked")
private String getTitleValue(Object responseTitle) {
if (!(responseTitle instanceof Map)) {
return null;
}
final Map<String, String> map;
try {
map = (Map<String, String>) responseTitle;
return map.get("");
} catch (ClassCastException error) {
logger.warning("Unable to cast to Map<String,String>. Title: {}", responseTitle, error);
return null;
}
}
/**
* Maps an exception from the ATOM APIs to its associated {@link HttpResponseException}.
*
* @param exception Exception from the ATOM API.
*
* @return The corresponding {@link HttpResponseException} or {@code throwable} if it is not an instance of {@link
* ServiceBusManagementErrorException}.
*/
private static Throwable mapException(Throwable exception) {
if (!(exception instanceof ServiceBusManagementErrorException)) {
return exception;
}
final ServiceBusManagementErrorException managementError = ((ServiceBusManagementErrorException) exception);
final ServiceBusManagementError error = managementError.getValue();
final HttpResponse errorHttpResponse = managementError.getResponse();
final int statusCode = error != null && error.getCode() != null
? error.getCode()
: errorHttpResponse.getStatusCode();
final String errorDetail = error != null && error.getDetail() != null
? error.getDetail()
: managementError.getMessage();
switch (statusCode) {
case 401:
return new ClientAuthenticationException(errorDetail, managementError.getResponse(), exception);
case 404:
return new ResourceNotFoundException(errorDetail, managementError.getResponse(), exception);
case 409:
return new ResourceExistsException(errorDetail, managementError.getResponse(), exception);
case 412:
return new ResourceModifiedException(errorDetail, managementError.getResponse(), exception);
default:
return new HttpResponseException(errorDetail, managementError.getResponse(), exception);
}
}
/**
* A page of Service Bus entities.
*
* @param <T> The entity description from Service Bus.
*/
private static final class FeedPage<T> implements PagedResponse<T> {
private final int statusCode;
private final HttpHeaders header;
private final HttpRequest request;
private final IterableStream<T> entries;
private final String continuationToken;
/**
* Creates a page that does not have any more pages.
*
* @param entries Items in the page.
*/
private FeedPage(int statusCode, HttpHeaders header, HttpRequest request, List<T> entries) {
this.statusCode = statusCode;
this.header = header;
this.request = request;
this.entries = new IterableStream<>(entries);
this.continuationToken = null;
}
/**
* Creates an instance that has additional pages to fetch.
*
* @param entries Items in the page.
* @param skip Number of elements to "skip".
*/
private FeedPage(int statusCode, HttpHeaders header, HttpRequest request, List<T> entries, int skip) {
this.statusCode = statusCode;
this.header = header;
this.request = request;
this.entries = new IterableStream<>(entries);
this.continuationToken = String.valueOf(skip);
}
@Override
public IterableStream<T> getElements() {
return entries;
}
@Override
public String getContinuationToken() {
return continuationToken;
}
@Override
public int getStatusCode() {
return statusCode;
}
@Override
public HttpHeaders getHeaders() {
return header;
}
@Override
public HttpRequest getRequest() {
return request;
}
@Override
public void close() {
}
}
private static final class EntityNotFoundHttpResponse<T> extends HttpResponse {
private final int statusCode;
private final HttpHeaders headers;
private EntityNotFoundHttpResponse(Response<T> response) {
super(response.getRequest());
this.headers = response.getHeaders();
this.statusCode = response.getStatusCode();
}
@Override
public int getStatusCode() {
return statusCode;
}
@Override
public String getHeaderValue(String name) {
return headers.getValue(name);
}
@Override
public HttpHeaders getHeaders() {
return headers;
}
@Override
public Flux<ByteBuffer> getBody() {
return Flux.empty();
}
@Override
public Mono<byte[]> getBodyAsByteArray() {
return Mono.empty();
}
@Override
public Mono<String> getBodyAsString() {
return Mono.empty();
}
@Override
public Mono<String> getBodyAsString(Charset charset) {
return Mono.empty();
}
}
} |
@conniey do you agree? | private Response<QueueProperties> deserializeQueue(Response<Object> response) {
final QueueDescriptionEntry entry = deserialize(response.getValue(), QueueDescriptionEntry.class);
if (entry == null) {
return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null);
} else if (entry.getContent() == null) {
logger.info("entry.getContent() is null. The entity may not exist. {}", entry);
return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null);
} else if (entry.getContent().getQueueDescription() == null) {
final TopicDescriptionEntry entryTopic = deserialize(response.getValue(), TopicDescriptionEntry.class);
if (entryTopic != null && entryTopic.getContent() != null && entryTopic.getContent().getTopicDescription() != null) {
throw logger.logExceptionAsError(
new RuntimeException(String.format("'[%s]' is not a queue, it is a topic.", entryTopic.getTitle())));
}
}
final QueueProperties result = EntityHelper.toModel(entry.getContent().getQueueDescription());
final String queueName = getTitleValue(entry.getTitle());
EntityHelper.setQueueName(result, queueName);
return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), result);
} | new RuntimeException(String.format("'[%s]' is not a queue, it is a topic.", entryTopic.getTitle()))); | private Response<QueueProperties> deserializeQueue(Response<Object> response) {
final QueueDescriptionEntry entry = deserialize(response.getValue(), QueueDescriptionEntry.class);
if (entry == null) {
return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null);
} else if (entry.getContent() == null) {
logger.info("entry.getContent() is null. The entity may not exist. {}", entry);
return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null);
} else if (entry.getContent().getQueueDescription() == null) {
final TopicDescriptionEntry entryTopic = deserialize(response.getValue(), TopicDescriptionEntry.class);
if (entryTopic != null && entryTopic.getContent() != null && entryTopic.getContent().getTopicDescription() != null) {
logger.warning("'{}' is not a queue, it is a topic.", entryTopic.getTitle());
return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null);
}
}
final QueueProperties result = EntityHelper.toModel(entry.getContent().getQueueDescription());
final String queueName = getTitleValue(entry.getTitle());
EntityHelper.setQueueName(result, queueName);
return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), result);
} | class ServiceBusAdministrationAsyncClient {
private static final String SERVICE_BUS_TRACING_NAMESPACE_VALUE = "Microsoft.ServiceBus";
private static final String CONTENT_TYPE = "application/xml";
private static final String QUEUES_ENTITY_TYPE = "queues";
private static final String TOPICS_ENTITY_TYPE = "topics";
private static final int NUMBER_OF_ELEMENTS = 100;
private final ServiceBusManagementClientImpl managementClient;
private final EntitiesImpl entityClient;
private final ClientLogger logger = new ClientLogger(ServiceBusAdministrationAsyncClient.class);
private final ServiceBusManagementSerializer serializer;
private final RulesImpl rulesClient;
/**
* Creates a new instance with the given management client and serializer.
*
* @param managementClient Client to make management calls.
* @param serializer Serializer to deserialize ATOM XML responses.
*/
ServiceBusAdministrationAsyncClient(ServiceBusManagementClientImpl managementClient,
ServiceBusManagementSerializer serializer) {
this.serializer = Objects.requireNonNull(serializer, "'serializer' cannot be null.");
this.managementClient = Objects.requireNonNull(managementClient, "'managementClient' cannot be null.");
this.entityClient = managementClient.getEntities();
this.rulesClient = managementClient.getRules();
}
/**
* Creates a queue with the given name.
*
* @param queueName Name of the queue to create.
*
* @return A Mono that completes with information about the created queue.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If the request body was invalid, the queue quota is exceeded, or an error
* occurred processing the request.
* @throws NullPointerException if {@code queueName} is null.
* @throws IllegalArgumentException if {@code queueName} is an empty string.
* @throws ResourceExistsException if a queue exists with the same {@code queueName}.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<QueueProperties> createQueue(String queueName) {
try {
return createQueue(queueName, new CreateQueueOptions());
} catch (RuntimeException e) {
return monoError(logger, e);
}
}
/**
* Creates a queue with the {@link CreateQueueOptions} and given queue name.
*
* @param queueName Name of the queue to create.
* @param queueOptions Options about the queue to create.
*
* @return A Mono that completes with information about the created queue.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If the request body was invalid, the queue quota is exceeded, or an error
* occurred processing the request.
* @throws IllegalArgumentException if {@code queueName} is an empty string.
* @throws NullPointerException if {@code queueName} or {@code queueOptions} is null.
* @throws ResourceExistsException if a queue exists with the same {@link QueueProperties
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<QueueProperties> createQueue(String queueName, CreateQueueOptions queueOptions) {
return createQueueWithResponse(queueName, queueOptions).map(Response::getValue);
}
/**
* Creates a queue and returns the created queue in addition to the HTTP response.
*
* @param queueName Name of the queue to create.
* @param queueOptions Options about the queue to create.
*
* @return A Mono that returns the created queue in addition to the HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If the request body was invalid, the queue quota is exceeded, or an error
* occurred processing the request.
* @throws IllegalArgumentException if {@code queueName} is an empty string.
* @throws NullPointerException if {@code queueName} or {@code queueOptions} is null.
* @throws ResourceExistsException if a queue exists with the same {@link QueueProperties
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<QueueProperties>> createQueueWithResponse(String queueName, CreateQueueOptions queueOptions) {
return withContext(context -> createQueueWithResponse(queueName, queueOptions, context));
}
/**
* Creates a rule under the given topic and subscription
*
* @param topicName Name of the topic associated with rule.
* @param subscriptionName Name of the subscription associated with the rule.
* @param ruleName Name of the rule.
*
* @return A Mono that completes with information about the created rule.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If the request body was invalid, the quota is exceeded, or an error occurred
* processing the request.
* @throws IllegalArgumentException if {@code topicName} or {@code ruleName} are are empty strings.
* @throws NullPointerException if {@code topicName} or {@code ruleName} are are null.
* @throws ResourceExistsException if a rule exists with the same topic, subscription, and rule name.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<RuleProperties> createRule(String topicName, String subscriptionName, String ruleName) {
try {
return createRule(topicName, subscriptionName, ruleName, new CreateRuleOptions());
} catch (RuntimeException e) {
return monoError(logger, e);
}
}
/**
* Creates a rule with the {@link CreateRuleOptions}.
*
* @param topicName Name of the topic associated with rule.
* @param subscriptionName Name of the subscription associated with the rule.
* @param ruleName Name of the rule.
* @param ruleOptions Information about the rule to create.
*
* @return A Mono that completes with information about the created rule.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If the request body was invalid, the quota is exceeded, or an error occurred
* processing the request.
* @throws IllegalArgumentException if {@code topicName} or {@code ruleName} are are empty strings.
* @throws NullPointerException if {@code topicName}, {@code ruleName}, or {@code ruleOptions}
* are are null.
* @throws ResourceExistsException if a rule exists with the same topic and rule name.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<RuleProperties> createRule(String topicName, String subscriptionName, String ruleName,
CreateRuleOptions ruleOptions) {
return createRuleWithResponse(topicName, subscriptionName, ruleName, ruleOptions)
.map(Response::getValue);
}
/**
* Creates a rule and returns the created rule in addition to the HTTP response.
*
* @param topicName Name of the topic associated with rule.
* @param subscriptionName Name of the subscription associated with the rule.
* @param ruleName Name of the rule.
* @param ruleOptions Information about the rule to create.
*
* @return A Mono that returns the created rule in addition to the HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If the request body was invalid, the quota is exceeded, or an error occurred
* processing the request.
* @throws IllegalArgumentException if {@code topicName} or {@code ruleName} are are empty strings.
* @throws NullPointerException if {@code topicName}, {@code ruleName}, or {@code ruleOptions}
* are are null.
* @throws ResourceExistsException if a rule exists with the same topic and rule name.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<RuleProperties>> createRuleWithResponse(String topicName, String subscriptionName,
String ruleName, CreateRuleOptions ruleOptions) {
return withContext(context -> createRuleWithResponse(topicName, subscriptionName, ruleName, ruleOptions,
context));
}
/**
* Creates a subscription with the given topic and subscription names.
*
* @param topicName Name of the topic associated with subscription.
* @param subscriptionName Name of the subscription.
*
* @return A Mono that completes with information about the created subscription.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If the request body was invalid, the quota is exceeded, or an error occurred
* processing the request.
* @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} are are empty strings.
* @throws NullPointerException if {@code topicName} or {@code subscriptionName} are are null.
* @throws ResourceExistsException if a subscription exists with the same topic and subscription name.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<SubscriptionProperties> createSubscription(String topicName, String subscriptionName) {
try {
return createSubscription(topicName, subscriptionName, new CreateSubscriptionOptions());
} catch (RuntimeException e) {
return monoError(logger, e);
}
}
/**
* Creates a subscription with the {@link CreateSubscriptionOptions}.
*
* @param topicName Name of the topic associated with subscription.
* @param subscriptionName Name of the subscription.
* @param subscriptionOptions Information about the subscription to create.
*
* @return A Mono that completes with information about the created subscription.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If the request body was invalid, the quota is exceeded, or an error occurred
* processing the request.
* @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} are are empty strings.
* @throws NullPointerException if {@code topicName}, {@code subscriptionName}, or {@code subscriptionOptions}
* are are null.
* @throws ResourceExistsException if a subscription exists with the same topic and subscription name.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<SubscriptionProperties> createSubscription(String topicName, String subscriptionName,
CreateSubscriptionOptions subscriptionOptions) {
return createSubscriptionWithResponse(topicName, subscriptionName, subscriptionOptions)
.map(Response::getValue);
}
/**
* Creates a subscription and returns the created subscription in addition to the HTTP response.
*
* @param topicName Name of the topic associated with subscription.
* @param subscriptionName Name of the subscription.
* @param subscriptionOptions Information about the subscription to create.
*
* @return A Mono that returns the created subscription in addition to the HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If the request body was invalid, the quota is exceeded, or an error occurred
* processing the request.
* @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} are are empty strings.
* @throws NullPointerException if {@code topicName}, {@code subscriptionName}, or {@code subscriptionOptions}
* are are null.
* @throws ResourceExistsException if a subscription exists with the same topic and subscription name.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<SubscriptionProperties>> createSubscriptionWithResponse(String topicName,
String subscriptionName, CreateSubscriptionOptions subscriptionOptions) {
return withContext(context -> createSubscriptionWithResponse(topicName, subscriptionName, subscriptionOptions,
context));
}
/**
* Creates a topic with the given name.
*
* @param topicName Name of the topic to create.
*
* @return A Mono that completes with information about the created topic.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If the request body was invalid, the topic quota is exceeded, or an error
* occurred processing the request.
* @throws NullPointerException if {@code topicName} is null.
* @throws IllegalArgumentException if {@code topicName} is an empty string.
* @throws ResourceExistsException if a topic exists with the same {@code topicName}.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<TopicProperties> createTopic(String topicName) {
try {
return createTopic(topicName, new CreateTopicOptions());
} catch (RuntimeException e) {
return monoError(logger, e);
}
}
/**
* Creates a topic with the {@link CreateTopicOptions}.
*
* @param topicName Name of the topic to create.
* @param topicOptions The options used to create the topic.
*
* @return A Mono that completes with information about the created topic.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If the request body was invalid, the topic quota is exceeded, or an error
* occurred processing the request.
* @throws IllegalArgumentException if {@code topicName} is an empty string.
* @throws NullPointerException if {@code topicName} or {@code topicOptions} is null.
* @throws ResourceExistsException if a topic exists with the same {@code topicName}.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<TopicProperties> createTopic(String topicName, CreateTopicOptions topicOptions) {
return createTopicWithResponse(topicName, topicOptions).map(Response::getValue);
}
/**
* Creates a topic and returns the created topic in addition to the HTTP response.
*
* @param topicName Name of the topic to create.
* @param topicOptions The options used to create the topic.
*
* @return A Mono that returns the created topic in addition to the HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If the request body was invalid, the topic quota is exceeded, or an error
* occurred processing the request.
* @throws IllegalArgumentException if {@link TopicProperties
* string.
* @throws NullPointerException if {@code topicName} or {@code topicOptions} is null.
* @throws ResourceExistsException if a topic exists with the same {@code topicName}.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<TopicProperties>> createTopicWithResponse(String topicName, CreateTopicOptions topicOptions) {
return withContext(context -> createTopicWithResponse(topicName, topicOptions, context));
}
/**
* Deletes a queue the matching {@code queueName}.
*
* @param queueName Name of queue to delete.
*
* @return A Mono that completes when the queue is deleted.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws NullPointerException if {@code queueName} is null.
* @throws IllegalArgumentException if {@code queueName} is an empty string.
* @throws ResourceNotFoundException if the {@code queueName} does not exist.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Void> deleteQueue(String queueName) {
return deleteQueueWithResponse(queueName).then();
}
/**
* Deletes a queue the matching {@code queueName} and returns the HTTP response.
*
* @param queueName Name of queue to delete.
*
* @return A Mono that completes when the queue is deleted and returns the HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws NullPointerException if {@code queueName} is null.
* @throws IllegalArgumentException if {@code queueName} is an empty string.
* @throws ResourceNotFoundException if the {@code queueName} does not exist.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Void>> deleteQueueWithResponse(String queueName) {
return withContext(context -> deleteQueueWithResponse(queueName, context));
}
/**
* Deletes a rule the matching {@code ruleName}.
*
* @param topicName Name of topic associated with rule to delete.
* @param subscriptionName Name of the subscription associated with the rule to delete.
* @param ruleName Name of rule to delete.
*
* @return A Mono that completes when the rule is deleted.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code topicName} or {@code ruleName} is an empty string.
* @throws NullPointerException if {@code topicName} or {@code ruleName} is null.
* @throws ResourceNotFoundException if the {@code ruleName} does not exist.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Void> deleteRule(String topicName, String subscriptionName, String ruleName) {
return deleteRuleWithResponse(topicName, subscriptionName, ruleName).then();
}
/**
* Deletes a rule the matching {@code ruleName} and returns the HTTP response.
*
* @param topicName Name of topic associated with rule to delete.
* @param subscriptionName Name of the subscription associated with the rule to delete.
* @param ruleName Name of rule to delete.
*
* @return A Mono that completes when the rule is deleted and returns the HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code topicName}, {@code subscriptionName}, or {@code ruleName} is an
* empty string.
* @throws NullPointerException if {@code topicName}, {@code subscriptionName}, or {@code ruleName} is null.
* @throws ResourceNotFoundException if the {@code ruleName} does not exist.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Void>> deleteRuleWithResponse(String topicName, String subscriptionName,
String ruleName) {
return withContext(context -> deleteRuleWithResponse(topicName, subscriptionName, ruleName, context));
}
/**
* Deletes a subscription the matching {@code subscriptionName}.
*
* @param topicName Name of topic associated with subscription to delete.
* @param subscriptionName Name of subscription to delete.
*
* @return A Mono that completes when the subscription is deleted.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} is an empty string.
* @throws NullPointerException if {@code topicName} or {@code subscriptionName} is null.
* @throws ResourceNotFoundException if the {@code subscriptionName} does not exist.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Void> deleteSubscription(String topicName, String subscriptionName) {
return deleteSubscriptionWithResponse(topicName, subscriptionName).then();
}
/**
* Deletes a subscription the matching {@code subscriptionName} and returns the HTTP response.
*
* @param topicName Name of topic associated with subscription to delete.
* @param subscriptionName Name of subscription to delete.
*
* @return A Mono that completes when the subscription is deleted and returns the HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} is an empty string.
* @throws NullPointerException if {@code topicName} or {@code subscriptionName} is null.
* @throws ResourceNotFoundException if the {@code subscriptionName} does not exist.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Void>> deleteSubscriptionWithResponse(String topicName, String subscriptionName) {
return withContext(context -> deleteSubscriptionWithResponse(topicName, subscriptionName, context));
}
/**
* Deletes a topic the matching {@code topicName}.
*
* @param topicName Name of topic to delete.
*
* @return A Mono that completes when the topic is deleted.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code topicName} is an empty string.
* @throws NullPointerException if {@code topicName} is null.
* @throws ResourceNotFoundException if the {@code topicName} does not exist.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Void> deleteTopic(String topicName) {
return deleteTopicWithResponse(topicName).then();
}
/**
* Deletes a topic the matching {@code topicName} and returns the HTTP response.
*
* @param topicName Name of topic to delete.
*
* @return A Mono that completes when the topic is deleted and returns the HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code topicName} is an empty string.
* @throws NullPointerException if {@code topicName} is null.
* @throws ResourceNotFoundException if the {@code topicName} does not exist.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Void>> deleteTopicWithResponse(String topicName) {
return withContext(context -> deleteTopicWithResponse(topicName, context));
}
/**
* Gets information about the queue.
*
* @param queueName Name of queue to get information about.
*
* @return A Mono that completes with information about the queue.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code queueName} is an empty string.
* @throws NullPointerException if {@code queueName} is null.
* @throws ResourceNotFoundException if the {@code queueName} does not exist.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<QueueProperties> getQueue(String queueName) {
return getQueueWithResponse(queueName).map(Response::getValue);
}
/**
* Gets information about the queue along with its HTTP response.
*
* @param queueName Name of queue to get information about.
*
* @return A Mono that completes with information about the queue and the associated HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code queueName} is an empty string.
* @throws NullPointerException if {@code queueName} is null.
* @throws ResourceNotFoundException if the {@code queueName} does not exist.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<QueueProperties>> getQueueWithResponse(String queueName) {
return withContext(context -> getQueueWithResponse(queueName, context, Function.identity()));
}
/**
* Gets whether or not a queue with {@code queueName} exists in the Service Bus namespace.
*
* @param queueName Name of the queue.
*
* @return A Mono that completes indicating whether or not the queue exists.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code queueName} is an empty string.
* @throws NullPointerException if {@code queueName} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Boolean> getQueueExists(String queueName) {
return getQueueExistsWithResponse(queueName).map(Response::getValue);
}
/**
* Gets whether or not a queue with {@code queueName} exists in the Service Bus namespace.
*
* @param queueName Name of the queue.
*
* @return A Mono that completes indicating whether or not the queue exists along with its HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code queueName} is an empty string.
* @throws NullPointerException if {@code queueName} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Boolean>> getQueueExistsWithResponse(String queueName) {
return getEntityExistsWithResponse(getQueueWithResponse(queueName));
}
/**
* Gets runtime properties about the queue.
*
* @param queueName Name of queue to get information about.
*
* @return A Mono that completes with runtime properties about the queue.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code queueName} is an empty string.
* @throws NullPointerException if {@code queueName} is null.
* @throws ResourceNotFoundException if the {@code queueName} does not exist.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<QueueRuntimeProperties> getQueueRuntimeProperties(String queueName) {
return getQueueRuntimePropertiesWithResponse(queueName).map(response -> response.getValue());
}
/**
* Gets runtime properties about the queue along with its HTTP response.
*
* @param queueName Name of queue to get information about.
*
* @return A Mono that completes with runtime properties about the queue and the associated HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code queueName} is an empty string.
* @throws NullPointerException if {@code queueName} is null.
* @throws ResourceNotFoundException if the {@code queueName} does not exist.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<QueueRuntimeProperties>> getQueueRuntimePropertiesWithResponse(String queueName) {
return withContext(context -> getQueueWithResponse(queueName, context, QueueRuntimeProperties::new));
}
/**
* Gets information about the Service Bus namespace.
*
* @return A Mono that completes with information about the Service Bus namespace.
* @throws ClientAuthenticationException if the client's credentials do not have access to the namespace.
* @throws HttpResponseException If error occurred processing the request.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<NamespaceProperties> getNamespaceProperties() {
return getNamespacePropertiesWithResponse().map(Response::getValue);
}
/**
* Gets information about the Service Bus namespace along with its HTTP response.
*
* @return A Mono that completes with information about the namespace and the associated HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<NamespaceProperties>> getNamespacePropertiesWithResponse() {
return withContext(this::getNamespacePropertiesWithResponse);
}
/**
* Gets a rule from the service namespace.
*
* Only following data types are deserialized in Filters and Action parameters - string, int, long, boolean, double,
* and OffsetDateTime. Other data types would return its string value.
*
* @param topicName The name of the topic relative to service bus namespace.
* @param subscriptionName The subscription name the rule belongs to.
* @param ruleName The name of the rule to retrieve.
*
* @return The associated rule.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<RuleProperties> getRule(String topicName, String subscriptionName, String ruleName) {
return getRuleWithResponse(topicName, subscriptionName, ruleName).map(response -> response.getValue());
}
/**
* Gets a rule from the service namespace.
*
* Only following data types are deserialized in Filters and Action parameters - string, int, long, bool, double,
* and OffsetDateTime. Other data types would return its string value.
*
* @param topicName The name of the topic relative to service bus namespace.
* @param subscriptionName The subscription name the rule belongs to.
* @param ruleName The name of the rule to retrieve.
*
* @return The associated rule with the corresponding HTTP response.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<RuleProperties>> getRuleWithResponse(String topicName, String subscriptionName,
String ruleName) {
return withContext(context -> getRuleWithResponse(topicName, subscriptionName, ruleName, context));
}
/**
* Gets information about the queue.
*
* @param topicName Name of topic associated with subscription.
* @param subscriptionName Name of subscription to get information about.
*
* @return A Mono that completes with information about the subscription.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} are empty strings.
* @throws NullPointerException if {@code topicName} or {@code subscriptionName} are null.
* @throws ResourceNotFoundException if the {@code subscriptionName} does not exist in the {@code topicName}.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<SubscriptionProperties> getSubscription(String topicName, String subscriptionName) {
return getSubscriptionWithResponse(topicName, subscriptionName).map(Response::getValue);
}
/**
* Gets information about the subscription along with its HTTP response.
*
* @param topicName Name of topic associated with subscription.
* @param subscriptionName Name of subscription to get information about.
*
* @return A Mono that completes with information about the subscription and the associated HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} are empty strings.
* @throws NullPointerException if {@code topicName} or {@code subscriptionName} are null.
* @throws ResourceNotFoundException if the {@code subscriptionName} does not exist.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<SubscriptionProperties>> getSubscriptionWithResponse(String topicName,
String subscriptionName) {
return withContext(context -> getSubscriptionWithResponse(topicName, subscriptionName, context,
Function.identity()));
}
/**
* Gets whether or not a subscription within a topic exists.
*
* @param topicName Name of topic associated with subscription.
* @param subscriptionName Name of the subscription.
*
* @return A Mono that completes indicating whether or not the subscription exists.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code subscriptionName} is an empty string.
* @throws NullPointerException if {@code subscriptionName} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Boolean> getSubscriptionExists(String topicName, String subscriptionName) {
return getSubscriptionExistsWithResponse(topicName, subscriptionName).map(Response::getValue);
}
/**
* Gets whether or not a subscription within a topic exists.
*
* @param topicName Name of topic associated with subscription.
* @param subscriptionName Name of the subscription.
*
* @return A Mono that completes indicating whether or not the subscription exists along with its HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code subscriptionName} is an empty string.
* @throws NullPointerException if {@code subscriptionName} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Boolean>> getSubscriptionExistsWithResponse(String topicName, String subscriptionName) {
return getEntityExistsWithResponse(getSubscriptionWithResponse(topicName, subscriptionName));
}
/**
* Gets runtime properties about the subscription.
*
* @param topicName Name of topic associated with subscription.
* @param subscriptionName Name of subscription to get information about.
*
* @return A Mono that completes with runtime properties about the subscription.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} are empty strings.
* @throws NullPointerException if {@code topicName} or {@code subscriptionName} are null.
* @throws ResourceNotFoundException if the {@code subscriptionName} does not exist.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<SubscriptionRuntimeProperties> getSubscriptionRuntimeProperties(
String topicName, String subscriptionName) {
return getSubscriptionRuntimePropertiesWithResponse(topicName, subscriptionName)
.map(response -> response.getValue());
}
/**
* Gets runtime properties about the subscription.
*
* @param topicName Name of topic associated with subscription.
* @param subscriptionName Name of subscription to get information about.
*
* @return A Mono that completes with runtime properties about the subscription.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code subscriptionName} is an empty string.
* @throws NullPointerException if {@code subscriptionName} is null.
* @throws ResourceNotFoundException if the {@code subscriptionName} does not exist.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<SubscriptionRuntimeProperties>> getSubscriptionRuntimePropertiesWithResponse(
String topicName, String subscriptionName) {
return withContext(context -> getSubscriptionWithResponse(topicName, subscriptionName, context,
SubscriptionRuntimeProperties::new));
}
/**
* Gets information about the topic.
*
* @param topicName Name of topic to get information about.
*
* @return A Mono that completes with information about the topic.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code topicName} is an empty string.
* @throws NullPointerException if {@code topicName} is null.
* @throws ResourceNotFoundException if the {@code topicName} does not exist.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<TopicProperties> getTopic(String topicName) {
return getTopicWithResponse(topicName).map(Response::getValue);
}
/**
* Gets information about the topic along with its HTTP response.
*
* @param topicName Name of topic to get information about.
*
* @return A Mono that completes with information about the topic and the associated HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code topicName} is an empty string.
* @throws NullPointerException if {@code topicName} is null.
* @throws ResourceNotFoundException if the {@code topicName} does not exist.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<TopicProperties>> getTopicWithResponse(String topicName) {
return withContext(context -> getTopicWithResponse(topicName, context, Function.identity()));
}
/**
* Gets whether or not a topic with {@code topicName} exists in the Service Bus namespace.
*
* @param topicName Name of the topic.
*
* @return A Mono that completes indicating whether or not the topic exists.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code topicName} is an empty string.
* @throws NullPointerException if {@code topicName} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Boolean> getTopicExists(String topicName) {
return getTopicExistsWithResponse(topicName).map(Response::getValue);
}
/**
* Gets whether or not a topic with {@code topicName} exists in the Service Bus namespace.
*
* @param topicName Name of the topic.
*
* @return A Mono that completes indicating whether or not the topic exists along with its HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code topicName} is an empty string.
* @throws NullPointerException if {@code topicName} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Boolean>> getTopicExistsWithResponse(String topicName) {
return getEntityExistsWithResponse(getTopicWithResponse(topicName));
}
/**
* Gets runtime properties about the topic.
*
* @param topicName Name of topic to get information about.
*
* @return A Mono that completes with runtime properties about the topic.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code topicName} is an empty string.
* @throws NullPointerException if {@code topicName} is null.
* @throws ResourceNotFoundException if the {@code topicName} does not exist.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<TopicRuntimeProperties> getTopicRuntimeProperties(String topicName) {
return getTopicRuntimePropertiesWithResponse(topicName).map(response -> response.getValue());
}
/**
* Gets runtime properties about the topic with its HTTP response.
*
* @param topicName Name of topic to get information about.
*
* @return A Mono that completes with runtime properties about the topic and the associated HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code topicName} is an empty string.
* @throws NullPointerException if {@code topicName} is null.
* @throws ResourceNotFoundException if the {@code topicName} does not exist.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<TopicRuntimeProperties>> getTopicRuntimePropertiesWithResponse(String topicName) {
return withContext(context -> getTopicWithResponse(topicName, context, TopicRuntimeProperties::new));
}
/**
* Fetches all the queues in the Service Bus namespace.
*
* @return A Flux of {@link QueueProperties queues} in the Service Bus namespace.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @see <a href="https:
* authorization rules</a>
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux<QueueProperties> listQueues() {
return new PagedFlux<>(
() -> withContext(context -> listQueuesFirstPage(context)),
token -> withContext(context -> listQueuesNextPage(token, context)));
}
/**
* Fetches all the rules for a topic and subscription.
*
* @param topicName The topic name under which all the rules need to be retrieved.
* @param subscriptionName The name of the subscription for which all rules need to be retrieved.
*
* @return A Flux of {@link RuleProperties rules} for the {@code topicName} and {@code subscriptionName}.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws NullPointerException if {@code topicName} or {@code subscriptionName} is null.
* @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} is an empty string.
* @see <a href="https:
* authorization rules</a>
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux<RuleProperties> listRules(String topicName, String subscriptionName) {
if (topicName == null) {
return pagedFluxError(logger, new NullPointerException("'topicName' cannot be null."));
} else if (topicName.isEmpty()) {
return pagedFluxError(logger, new IllegalArgumentException("'topicName' cannot be an empty string."));
}
return new PagedFlux<>(
() -> withContext(context -> listRulesFirstPage(topicName, subscriptionName, context)),
token -> withContext(context -> listRulesNextPage(topicName, subscriptionName, token, context)));
}
/**
* Fetches all the subscriptions for a topic.
*
* @param topicName The topic name under which all the subscriptions need to be retrieved.
*
* @return A Flux of {@link SubscriptionProperties subscriptions} for the {@code topicName}.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws NullPointerException if {@code topicName} is null.
* @throws IllegalArgumentException if {@code topicName} is an empty string.
* @see <a href="https:
* authorization rules</a>
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux<SubscriptionProperties> listSubscriptions(String topicName) {
if (topicName == null) {
return pagedFluxError(logger, new NullPointerException("'topicName' cannot be null."));
} else if (topicName.isEmpty()) {
return pagedFluxError(logger, new IllegalArgumentException("'topicName' cannot be an empty string."));
}
return new PagedFlux<>(
() -> withContext(context -> listSubscriptionsFirstPage(topicName, context)),
token -> withContext(context -> listSubscriptionsNextPage(topicName, token, context)));
}
/**
* Fetches all the topics in the Service Bus namespace.
*
* @return A Flux of {@link TopicProperties topics} in the Service Bus namespace.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @see <a href="https:
* authorization rules</a>
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux<TopicProperties> listTopics() {
return new PagedFlux<>(
() -> withContext(context -> listTopicsFirstPage(context)),
token -> withContext(context -> listTopicsNextPage(token, context)));
}
/**
* Updates a queue with the given {@link QueueProperties}. The {@link QueueProperties} must be fully populated as
* all of the properties are replaced. If a property is not set the service default value is used.
*
* The suggested flow is:
* <ol>
* <li>{@link
* <li>Update the required elements.</li>
* <li>Pass the updated description into this method.</li>
* </ol>
*
* <p>
* There are a subset of properties that can be updated. More information can be found in the links below. They are:
* <ul>
* <li>{@link QueueProperties
* <li>{@link QueueProperties
* <li>{@link QueueProperties
* </li>
* <li>{@link QueueProperties
* </ul>
*
* @param queue Information about the queue to update. You must provide all the property values that are desired
* on the updated entity. Any values not provided are set to the service default values.
*
* @return A Mono that completes with the updated queue.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If the request body was invalid, the queue quota is exceeded, or an error
* occurred processing the request.
* @throws NullPointerException if {@code queue} is null.
* @see <a href="https:
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<QueueProperties> updateQueue(QueueProperties queue) {
return updateQueueWithResponse(queue).map(Response::getValue);
}
/**
* Updates a queue with the given {@link QueueProperties}. The {@link QueueProperties} must be fully populated as
* all of the properties are replaced. If a property is not set the service default value is used.
*
* The suggested flow is:
* <ol>
* <li>{@link
* <li>Update the required elements.</li>
* <li>Pass the updated description into this method.</li>
* </ol>
*
* <p>
* There are a subset of properties that can be updated. More information can be found in the links below. They are:
* <ul>
* <li>{@link QueueProperties
* <li>{@link QueueProperties
* <li>{@link QueueProperties
* </li>
* <li>{@link QueueProperties
* </ul>
*
* @param queue Information about the queue to update. You must provide all the property values that are desired
* on the updated entity. Any values not provided are set to the service default values.
*
* @return A Mono that returns the updated queue in addition to the HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If the request body was invalid, the queue quota is exceeded, or an error
* occurred processing the request.
* @throws NullPointerException if {@code queue} is null.
* @see <a href="https:
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<QueueProperties>> updateQueueWithResponse(QueueProperties queue) {
return withContext(context -> updateQueueWithResponse(queue, context));
}
/**
* Updates a rule with the given {@link RuleProperties}. The {@link RuleProperties} must be fully populated as all
* of the properties are replaced. If a property is not set the service default value is used.
*
* The suggested flow is:
* <ol>
* <li>{@link
* <li>Update the required elements.</li>
* <li>Pass the updated description into this method.</li>
* </ol>
*
* @param topicName The topic name under which the rule is updated.
* @param subscriptionName The name of the subscription for which the rule is updated.
* @param rule Information about the rule to update. You must provide all the property values that are desired
* on the updated entity. Any values not provided are set to the service default values.
*
* @return A Mono that returns the updated rule.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If the request body was invalid, the rule quota is exceeded, or an error
* occurred processing the request.
* @throws IllegalArgumentException if {@link RuleProperties
* @throws NullPointerException if {@code rule} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<RuleProperties> updateRule(String topicName, String subscriptionName, RuleProperties rule) {
return updateRuleWithResponse(topicName, subscriptionName, rule).map(Response::getValue);
}
/**
* Updates a rule with the given {@link RuleProperties}. The {@link RuleProperties} must be fully populated as all
* of the properties are replaced. If a property is not set the service default value is used.
*
* The suggested flow is:
* <ol>
* <li>{@link
* <li>Update the required elements.</li>
* <li>Pass the updated description into this method.</li>
* </ol>
*
* @param topicName The topic name under which the rule is updated.
* @param subscriptionName The name of the subscription for which the rule is updated.
* @param rule Information about the rule to update. You must provide all the property values that are desired
* on the updated entity. Any values not provided are set to the service default values.
*
* @return A Mono that returns the updated rule in addition to the HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If the request body was invalid, the rule quota is exceeded, or an error
* occurred processing the request.
* @throws IllegalArgumentException if {@link RuleProperties
* @throws NullPointerException if {@code rule} is null.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<RuleProperties>> updateRuleWithResponse(String topicName, String subscriptionName,
RuleProperties rule) {
return withContext(context -> updateRuleWithResponse(topicName, subscriptionName, rule, context));
}
/**
* Updates a subscription with the given {@link SubscriptionProperties}. The {@link SubscriptionProperties} must be
* fully populated as all of the properties are replaced. If a property is not set the service default value is
* used.
*
* The suggested flow is:
* <ol>
* <li>{@link
* <li>Update the required elements.</li>
* <li>Pass the updated description into this method.</li>
* </ol>
*
* <p>
* There are a subset of properties that can be updated. More information can be found in the links below. They are:
* <ul>
* <li>{@link SubscriptionProperties
* <li>{@link SubscriptionProperties
* <li>{@link SubscriptionProperties
* </ul>
*
* @param subscription Information about the subscription to update. You must provide all the property values
* that are desired on the updated entity. Any values not provided are set to the service default values.
*
* @return A Mono that returns the updated subscription.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If the request body was invalid, the subscription quota is exceeded, or an
* error occurred processing the request.
* @throws IllegalArgumentException if {@link SubscriptionProperties
* SubscriptionProperties
* @throws NullPointerException if {@code subscription} is null.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<SubscriptionProperties> updateSubscription(SubscriptionProperties subscription) {
return updateSubscriptionWithResponse(subscription).map(Response::getValue);
}
/**
* Updates a subscription with the given {@link SubscriptionProperties}. The {@link SubscriptionProperties} must be
* fully populated as all of the properties are replaced. If a property is not set the service default value is
* used.
*
* The suggested flow is:
* <ol>
* <li>{@link
* <li>Update the required elements.</li>
* <li>Pass the updated description into this method.</li>
* </ol>
*
* <p>
* There are a subset of properties that can be updated. More information can be found in the links below. They are:
* <ul>
* <li>{@link SubscriptionProperties
* <li>{@link SubscriptionProperties
* <li>{@link SubscriptionProperties
* </ul>
*
* @param subscription Information about the subscription to update. You must provide all the property values
* that are desired on the updated entity. Any values not provided are set to the service default values.
*
* @return A Mono that returns the updated subscription in addition to the HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If the request body was invalid, the subscription quota is exceeded, or an
* error occurred processing the request.
* @throws IllegalArgumentException if {@link SubscriptionProperties
* SubscriptionProperties
* @throws NullPointerException if {@code subscription} is null.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<SubscriptionProperties>> updateSubscriptionWithResponse(
SubscriptionProperties subscription) {
return withContext(context -> updateSubscriptionWithResponse(subscription, context));
}
/**
* Updates a topic with the given {@link TopicProperties}. The {@link TopicProperties} must be fully populated as
* all of the properties are replaced. If a property is not set the service default value is used.
*
* The suggested flow is:
* <ol>
* <li>{@link
* <li>Update the required elements.</li>
* <li>Pass the updated description into this method.</li>
* </ol>
*
* <p>
* There are a subset of properties that can be updated. More information can be found in the links below. They are:
* <ul>
* <li>{@link TopicProperties
* <li>{@link TopicProperties
* </li>
* </ul>
*
* @param topic Information about the topic to update. You must provide all the property values that are desired
* on the updated entity. Any values not provided are set to the service default values.
*
* @return A Mono that completes with the updated topic.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If the request body was invalid, the topic quota is exceeded, or an error
* occurred processing the request.
* @throws IllegalArgumentException if {@link TopicProperties
* string.
* @throws NullPointerException if {@code topic} is null.
* @see <a href="https:
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<TopicProperties> updateTopic(TopicProperties topic) {
return updateTopicWithResponse(topic).map(Response::getValue);
}
/**
* Updates a topic with the given {@link TopicProperties}. The {@link TopicProperties} must be fully populated as
* all of the properties are replaced. If a property is not set the service default value is used.
*
* The suggested flow is:
* <ol>
* <li>{@link
* <li>Update the required elements.</li>
* <li>Pass the updated description into this method.</li>
* </ol>
*
* <p>
* There are a subset of properties that can be updated. More information can be found in the links below. They are:
* <ul>
* <li>{@link TopicProperties
* <li>{@link TopicProperties
* </li>
* </ul>
*
* @param topic Information about the topic to update. You must provide all the property values that are desired
* on the updated entity. Any values not provided are set to the service default values.
*
* @return A Mono that completes with the updated topic and its HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If the request body was invalid, the topic quota is exceeded, or an error
* occurred processing the request.
* @throws IllegalArgumentException if {@link TopicProperties
* string.
* @throws NullPointerException if {@code topic} is null.
* @see <a href="https:
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<TopicProperties>> updateTopicWithResponse(TopicProperties topic) {
return withContext(context -> updateTopicWithResponse(topic, context));
}
/**
* Creates a queue with its context.
*
* @param createQueueOptions Queue to create.
* @param context Context to pass into request.
*
* @return A Mono that completes with the created {@link QueueProperties}.
*/
Mono<Response<QueueProperties>> createQueueWithResponse(String queueName, CreateQueueOptions createQueueOptions,
Context context) {
if (queueName == null) {
return monoError(logger, new NullPointerException("'queueName' cannot be null."));
} else if (queueName.isEmpty()) {
return monoError(logger, new IllegalArgumentException("'queueName' cannot be empty."));
}
if (createQueueOptions == null) {
return monoError(logger, new NullPointerException("'createQueueOptions' cannot be null."));
} else if (context == null) {
return monoError(logger, new NullPointerException("'context' cannot be null."));
}
final QueueDescription description = EntityHelper.getQueueDescription(createQueueOptions);
final CreateQueueBodyContent content = new CreateQueueBodyContent()
.setType(CONTENT_TYPE)
.setQueueDescription(description);
final CreateQueueBody createEntity = new CreateQueueBody()
.setContent(content);
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
try {
return entityClient.putWithResponseAsync(queueName, createEntity, null, withTracing)
.onErrorMap(ServiceBusAdministrationAsyncClient::mapException)
.map(this::deserializeQueue);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Creates a rule with its context.
*
* @param ruleOptions Rule to create.
* @param context Context to pass into request.
*
* @return A Mono that completes with the created {@link RuleProperties}.
*/
Mono<Response<RuleProperties>> createRuleWithResponse(String topicName, String subscriptionName, String ruleName,
CreateRuleOptions ruleOptions, Context context) {
if (topicName == null) {
return monoError(logger, new NullPointerException("'topicName' cannot be null."));
} else if (topicName.isEmpty()) {
return monoError(logger, new IllegalArgumentException("'topicName' cannot be empty."));
}
if (subscriptionName == null) {
return monoError(logger, new NullPointerException("'subscriptionName' cannot be null."));
} else if (subscriptionName.isEmpty()) {
return monoError(logger, new IllegalArgumentException("'subscriptionName' cannot be empty."));
}
if (ruleName == null) {
return monoError(logger, new NullPointerException("'ruleName' cannot be null."));
} else if (ruleName.isEmpty()) {
return monoError(logger, new IllegalArgumentException("'ruleName' cannot be empty."));
}
if (ruleOptions == null) {
return monoError(logger, new NullPointerException("'rule' cannot be null."));
}
final RuleActionImpl action = ruleOptions.getAction() != null
? EntityHelper.toImplementation(ruleOptions.getAction())
: null;
final RuleFilterImpl filter = ruleOptions.getFilter() != null
? EntityHelper.toImplementation(ruleOptions.getFilter())
: null;
final RuleDescription rule = new RuleDescription()
.setAction(action)
.setFilter(filter)
.setName(ruleName);
final CreateRuleBodyContent content = new CreateRuleBodyContent()
.setType(CONTENT_TYPE)
.setRuleDescription(rule);
final CreateRuleBody createEntity = new CreateRuleBody().setContent(content);
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
try {
return managementClient.getRules().putWithResponseAsync(topicName, subscriptionName, ruleName, createEntity,
null, withTracing)
.onErrorMap(ServiceBusAdministrationAsyncClient::mapException)
.map(response -> deserializeRule(response));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Creates a subscription with its context.
*
* @param subscriptionOptions Subscription to create.
* @param context Context to pass into request.
*
* @return A Mono that completes with the created {@link SubscriptionProperties}.
*/
Mono<Response<SubscriptionProperties>> createSubscriptionWithResponse(String topicName, String subscriptionName,
CreateSubscriptionOptions subscriptionOptions, Context context) {
if (topicName == null) {
return monoError(logger, new NullPointerException("'topicName' cannot be null."));
} else if (topicName.isEmpty()) {
return monoError(logger, new IllegalArgumentException("'topicName' cannot be empty."));
}
if (subscriptionName == null) {
return monoError(logger, new NullPointerException("'subscriptionName' cannot be null."));
} else if (subscriptionName.isEmpty()) {
return monoError(logger, new IllegalArgumentException("'subscriptionName' cannot be empty."));
}
if (subscriptionOptions == null) {
return monoError(logger, new NullPointerException("'subscription' cannot be null."));
}
final SubscriptionDescription subscription = EntityHelper.getSubscriptionDescription(subscriptionOptions);
final CreateSubscriptionBodyContent content = new CreateSubscriptionBodyContent()
.setType(CONTENT_TYPE)
.setSubscriptionDescription(subscription);
final CreateSubscriptionBody createEntity = new CreateSubscriptionBody().setContent(content);
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
try {
return managementClient.getSubscriptions().putWithResponseAsync(topicName, subscriptionName, createEntity,
null, withTracing)
.onErrorMap(ServiceBusAdministrationAsyncClient::mapException)
.map(response -> deserializeSubscription(topicName, response));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Creates a topicOptions with its context.
*
* @param topicOptions Topic to create.
* @param context Context to pass into request.
*
* @return A Mono that completes with the created {@link TopicProperties}.
*/
Mono<Response<TopicProperties>> createTopicWithResponse(String topicName, CreateTopicOptions topicOptions,
Context context) {
if (topicName == null) {
return monoError(logger, new NullPointerException("'topicName' cannot be null."));
} else if (topicName.isEmpty()) {
return monoError(logger, new IllegalArgumentException("'topicName' cannot be empty."));
}
if (topicOptions == null) {
return monoError(logger, new NullPointerException("'topicOptions' cannot be null"));
} else if (context == null) {
return monoError(logger, new NullPointerException("'context' cannot be null."));
}
final TopicDescription topic = EntityHelper.getTopicDescription(topicOptions);
final CreateTopicBodyContent content = new CreateTopicBodyContent()
.setType(CONTENT_TYPE)
.setTopicDescription(topic);
final CreateTopicBody createEntity = new CreateTopicBody()
.setContent(content);
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
try {
return entityClient.putWithResponseAsync(topicName, createEntity, null, withTracing)
.onErrorMap(ServiceBusAdministrationAsyncClient::mapException)
.map(this::deserializeTopic);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Deletes a queue with its context.
*
* @param queueName Name of queue to delete.
* @param context Context to pass into request.
*
* @return A Mono that completes when the queue is deleted.
*/
Mono<Response<Void>> deleteQueueWithResponse(String queueName, Context context) {
if (queueName == null) {
return monoError(logger, new NullPointerException("'queueName' cannot be null"));
} else if (queueName.isEmpty()) {
return monoError(logger, new IllegalArgumentException("'queueName' cannot be an empty string."));
} else if (context == null) {
return monoError(logger, new NullPointerException("'context' cannot be null."));
}
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
try {
return entityClient.deleteWithResponseAsync(queueName, withTracing)
.onErrorMap(ServiceBusAdministrationAsyncClient::mapException)
.map(response -> {
return new SimpleResponse<>(response.getRequest(), response.getStatusCode(),
response.getHeaders(), null);
});
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Deletes a queue with its context.
*
* @param topicName Name of topic to delete.
* @param subscriptionName Name of the subscription for the rule.
* @param ruleName Name of the rule.
* @param context Context to pass into request.
*
* @return A Mono that completes with the created {@link QueueProperties}.
*/
Mono<Response<Void>> deleteRuleWithResponse(String topicName, String subscriptionName, String ruleName,
Context context) {
if (topicName == null) {
return monoError(logger, new NullPointerException("'topicName' cannot be null"));
} else if (topicName.isEmpty()) {
return monoError(logger, new IllegalArgumentException("'topicName' cannot be an empty string."));
} else if (subscriptionName == null) {
return monoError(logger, new NullPointerException("'subscriptionName' cannot be null"));
} else if (subscriptionName.isEmpty()) {
return monoError(logger, new IllegalArgumentException("'subscriptionName' cannot be an empty string."));
} else if (ruleName == null) {
return monoError(logger, new NullPointerException("'ruleName' cannot be null"));
} else if (ruleName.isEmpty()) {
return monoError(logger, new IllegalArgumentException("'ruleName' cannot be an empty string."));
} else if (context == null) {
return monoError(logger, new NullPointerException("'context' cannot be null."));
}
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
try {
return rulesClient.deleteWithResponseAsync(topicName, subscriptionName, ruleName, withTracing)
.onErrorMap(ServiceBusAdministrationAsyncClient::mapException)
.map(response -> new SimpleResponse<>(response.getRequest(), response.getStatusCode(),
response.getHeaders(), null));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Deletes a subscription with its context.
*
* @param topicName Name of topic associated with subscription to delete.
* @param subscriptionName Name of subscription to delete.
* @param context Context to pass into request.
*
* @return A Mono that completes with the created {@link SubscriptionProperties}.
*/
Mono<Response<Void>> deleteSubscriptionWithResponse(String topicName, String subscriptionName, Context context) {
if (subscriptionName == null) {
return monoError(logger, new NullPointerException("'subscriptionName' cannot be null"));
} else if (subscriptionName.isEmpty()) {
return monoError(logger, new IllegalArgumentException("'subscriptionName' cannot be an empty string."));
} else if (topicName == null) {
return monoError(logger, new NullPointerException("'topicName' cannot be null"));
} else if (topicName.isEmpty()) {
return monoError(logger, new IllegalArgumentException("'topicName' cannot be an empty string."));
} else if (context == null) {
return monoError(logger, new NullPointerException("'context' cannot be null."));
}
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
try {
return managementClient.getSubscriptions().deleteWithResponseAsync(topicName, subscriptionName,
withTracing)
.onErrorMap(ServiceBusAdministrationAsyncClient::mapException)
.map(response -> new SimpleResponse<>(response.getRequest(), response.getStatusCode(),
response.getHeaders(), null));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Deletes a topic with its context.
*
* @param topicName Name of topic to delete.
* @param context Context to pass into request.
*
* @return A Mono that completes with the created {@link TopicProperties}.
*/
Mono<Response<Void>> deleteTopicWithResponse(String topicName, Context context) {
if (topicName == null) {
return monoError(logger, new NullPointerException("'topicName' cannot be null"));
} else if (topicName.isEmpty()) {
return monoError(logger, new IllegalArgumentException("'topicName' cannot be an empty string."));
} else if (context == null) {
return monoError(logger, new NullPointerException("'context' cannot be null."));
}
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
try {
return entityClient.deleteWithResponseAsync(topicName, withTracing)
.onErrorMap(ServiceBusAdministrationAsyncClient::mapException)
.map(response -> new SimpleResponse<>(response.getRequest(), response.getStatusCode(),
response.getHeaders(), null));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Gets whether an entity exists.
*
* @param getEntityOperation Operation to get information about entity. If {@link ResourceNotFoundException} is
* thrown, then it is mapped to false.
* @param <T> Entity type.
*
* @return True if the entity exists, false otherwise.
*/
<T> Mono<Response<Boolean>> getEntityExistsWithResponse(Mono<Response<T>> getEntityOperation) {
return getEntityOperation.map(response -> {
final boolean exists = response.getValue() != null;
return (Response<Boolean>) new SimpleResponse<>(response.getRequest(), response.getStatusCode(),
response.getHeaders(), exists);
})
.onErrorResume(ResourceNotFoundException.class, exception -> {
final HttpResponse response = exception.getResponse();
final Response<Boolean> result = new SimpleResponse<>(response.getRequest(), response.getStatusCode(),
response.getHeaders(), false);
return Mono.just(result);
});
}
/**
* Gets a queue with its context.
*
* @param queueName Name of queue to fetch information for.
* @param context Context to pass into request.
*
* @return A Mono that completes with the {@link QueueProperties}.
*/
<T> Mono<Response<T>> getQueueWithResponse(String queueName, Context context,
Function<QueueProperties, T> mapper) {
if (queueName == null) {
return monoError(logger, new NullPointerException("'queueName' cannot be null"));
} else if (queueName.isEmpty()) {
return monoError(logger, new IllegalArgumentException("'queueName' cannot be empty."));
} else if (context == null) {
return monoError(logger, new NullPointerException("'context' cannot be null."));
}
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
try {
return entityClient.getWithResponseAsync(queueName, true, withTracing)
.onErrorMap(ServiceBusAdministrationAsyncClient::mapException)
.handle((response, sink) -> {
final Response<QueueProperties> deserialize = deserializeQueue(response);
if (deserialize.getValue() == null) {
final HttpResponse notFoundResponse = new EntityNotFoundHttpResponse<>(deserialize);
sink.error(new ResourceNotFoundException(String.format("Queue '%s' does not exist.", queueName),
notFoundResponse));
} else {
final T mapped = mapper.apply(deserialize.getValue());
sink.next(new SimpleResponse<>(response.getRequest(), response.getStatusCode(),
response.getHeaders(), mapped));
}
});
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<RuleProperties>> getRuleWithResponse(String topicName, String subscriptionName,
String ruleName, Context context) {
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
try {
return rulesClient.getWithResponseAsync(topicName, subscriptionName, ruleName, true, withTracing)
.onErrorMap(ServiceBusAdministrationAsyncClient::mapException)
.map(this::deserializeRule);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Gets a subscription with its context.
*
* @param topicName Name of the topic associated with the subscription.
* @param subscriptionName Name of subscription to fetch information for.
* @param context Context to pass into request.
*
* @return A Mono that completes with the {@link SubscriptionProperties}.
*/
<T> Mono<Response<T>> getSubscriptionWithResponse(String topicName, String subscriptionName, Context context,
Function<SubscriptionProperties, T> mapper) {
if (topicName == null) {
return monoError(logger, new NullPointerException("'topicName' cannot be null."));
} else if (topicName.isEmpty()) {
return monoError(logger, new IllegalArgumentException("'topicName' cannot be an empty string."));
} else if (subscriptionName == null) {
return monoError(logger, new NullPointerException("'subscriptionName' cannot be null."));
} else if (subscriptionName.isEmpty()) {
return monoError(logger, new IllegalArgumentException("'subscriptionName' cannot be an empty string."));
} else if (context == null) {
return monoError(logger, new NullPointerException("'context' cannot be null."));
}
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
try {
return managementClient.getSubscriptions().getWithResponseAsync(topicName, subscriptionName, true,
withTracing)
.onErrorMap(ServiceBusAdministrationAsyncClient::mapException)
.handle((response, sink) -> {
final Response<SubscriptionProperties> deserialize = deserializeSubscription(topicName, response);
if (deserialize.getValue() == null) {
final HttpResponse notFoundResponse = new EntityNotFoundHttpResponse<>(deserialize);
sink.error(new ResourceNotFoundException(String.format(
"Subscription '%s' in topic '%s' does not exist.", topicName, subscriptionName),
notFoundResponse));
} else {
final T mapped = mapper.apply(deserialize.getValue());
sink.next(new SimpleResponse<>(response.getRequest(), response.getStatusCode(),
response.getHeaders(), mapped));
}
});
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Gets the namespace properties with its context.
*
* @param context Context to pass into request.
*
* @return A Mono that completes with the {@link NamespaceProperties}.
*/
Mono<Response<NamespaceProperties>> getNamespacePropertiesWithResponse(Context context) {
return managementClient.getNamespaces().getWithResponseAsync(context).handle((response, sink) -> {
final NamespacePropertiesEntry entry = response.getValue();
if (entry == null || entry.getContent() == null) {
sink.error(new AzureException(
"There was no content inside namespace response. Entry: " + response));
return;
}
final NamespaceProperties namespaceProperties = entry.getContent().getNamespaceProperties();
final Response<NamespaceProperties> result = new SimpleResponse<>(response.getRequest(),
response.getStatusCode(), response.getHeaders(), namespaceProperties);
sink.next(result);
});
}
/**
* Gets a topic with its context.
*
* @param topicName Name of topic to fetch information for.
* @param context Context to pass into request.
*
* @return A Mono that completes with the {@link TopicProperties}.
*/
<T> Mono<Response<T>> getTopicWithResponse(String topicName, Context context,
Function<TopicProperties, T> mapper) {
if (topicName == null) {
return monoError(logger, new NullPointerException("'topicName' cannot be null"));
} else if (topicName.isEmpty()) {
return monoError(logger, new IllegalArgumentException("'topicName' cannot be empty."));
} else if (context == null) {
return monoError(logger, new NullPointerException("'context' cannot be null."));
}
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
try {
return entityClient.getWithResponseAsync(topicName, true, withTracing)
.onErrorMap(ServiceBusAdministrationAsyncClient::mapException)
.handle((response, sink) -> {
final Response<TopicProperties> deserialize = deserializeTopic(response);
if (deserialize.getValue() == null) {
final HttpResponse notFoundResponse = new EntityNotFoundHttpResponse<>(deserialize);
sink.error(new ResourceNotFoundException(String.format("Topic '%s' does not exist.", topicName),
notFoundResponse));
} else {
final T mapped = mapper.apply(deserialize.getValue());
sink.next(new SimpleResponse<>(response.getRequest(), response.getStatusCode(),
response.getHeaders(), mapped));
}
});
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Gets the first page of queues with context.
*
* @param context Context to pass into request.
*
* @return A Mono that completes with a page of queues.
*/
Mono<PagedResponse<QueueProperties>> listQueuesFirstPage(Context context) {
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
try {
return listQueues(0, withTracing);
} catch (RuntimeException e) {
return monoError(logger, e);
}
}
/**
* Gets the next page of queues with context.
*
* @param continuationToken Number of items to skip in feed.
* @param context Context to pass into request.
*
* @return A Mono that completes with a page of queues or empty if there are no items left.
*/
Mono<PagedResponse<QueueProperties>> listQueuesNextPage(String continuationToken, Context context) {
if (continuationToken == null || continuationToken.isEmpty()) {
return Mono.empty();
}
try {
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
final int skip = Integer.parseInt(continuationToken);
return listQueues(skip, withTracing);
} catch (RuntimeException e) {
return monoError(logger, e);
}
}
/**
* Gets the first page of rules with context.
*
* @param context Context to pass into request.
*
* @return A Mono that completes with a page of rules.
*/
Mono<PagedResponse<RuleProperties>> listRulesFirstPage(String topicName, String subscriptionName, Context context) {
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
try {
return listRules(topicName, subscriptionName, 0, withTracing);
} catch (RuntimeException e) {
return monoError(logger, e);
}
}
/**
* Gets the next page of rules with context.
*
* @param continuationToken Number of items to skip in feed.
* @param context Context to pass into request.
*
* @return A Mono that completes with a page of rules or empty if there are no items left.
*/
Mono<PagedResponse<RuleProperties>> listRulesNextPage(String topicName, String subscriptionName,
String continuationToken, Context context) {
if (continuationToken == null || continuationToken.isEmpty()) {
return Mono.empty();
}
try {
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
final int skip = Integer.parseInt(continuationToken);
return listRules(topicName, subscriptionName, skip, withTracing);
} catch (RuntimeException e) {
return monoError(logger, e);
}
}
/**
* Gets the first page of subscriptions with context.
*
* @param context Context to pass into request.
*
* @return A Mono that completes with a page of subscriptions.
*/
Mono<PagedResponse<SubscriptionProperties>> listSubscriptionsFirstPage(String topicName, Context context) {
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
try {
return listSubscriptions(topicName, 0, withTracing);
} catch (RuntimeException e) {
return monoError(logger, e);
}
}
/**
* Gets the next page of subscriptions with context.
*
* @param continuationToken Number of items to skip in feed.
* @param context Context to pass into request.
*
* @return A Mono that completes with a page of subscriptions or empty if there are no items left.
*/
Mono<PagedResponse<SubscriptionProperties>> listSubscriptionsNextPage(String topicName, String continuationToken,
Context context) {
if (continuationToken == null || continuationToken.isEmpty()) {
return Mono.empty();
}
try {
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
final int skip = Integer.parseInt(continuationToken);
return listSubscriptions(topicName, skip, withTracing);
} catch (RuntimeException e) {
return monoError(logger, e);
}
}
/**
* Gets the first page of topics with context.
*
* @param context Context to pass into request.
*
* @return A Mono that completes with a page of topics.
*/
Mono<PagedResponse<TopicProperties>> listTopicsFirstPage(Context context) {
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
try {
return listTopics(0, withTracing);
} catch (RuntimeException e) {
return monoError(logger, e);
}
}
/**
* Gets the next page of topics with context.
*
* @param continuationToken Number of items to skip in feed.
* @param context Context to pass into request.
*
* @return A Mono that completes with a page of topics or empty if there are no items left.
*/
Mono<PagedResponse<TopicProperties>> listTopicsNextPage(String continuationToken, Context context) {
if (continuationToken == null || continuationToken.isEmpty()) {
return Mono.empty();
}
try {
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
final int skip = Integer.parseInt(continuationToken);
return listTopics(skip, withTracing);
} catch (RuntimeException e) {
return monoError(logger, e);
}
}
/**
* Updates a queue with its context.
*
* @param queue Information about the queue to update. You must provide all the property values that are desired
* on the updated entity. Any values not provided are set to the service default values.
* @param context Context to pass into request.
*
* @return A Mono that completes with the updated {@link QueueProperties}.
*/
Mono<Response<QueueProperties>> updateQueueWithResponse(QueueProperties queue, Context context) {
if (queue == null) {
return monoError(logger, new NullPointerException("'queue' cannot be null"));
} else if (context == null) {
return monoError(logger, new NullPointerException("'context' cannot be null."));
}
final QueueDescription queueDescription = EntityHelper.toImplementation(queue);
final CreateQueueBodyContent content = new CreateQueueBodyContent()
.setType(CONTENT_TYPE)
.setQueueDescription(queueDescription);
final CreateQueueBody createEntity = new CreateQueueBody()
.setContent(content);
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
try {
return entityClient.putWithResponseAsync(queue.getName(), createEntity, "*", withTracing)
.onErrorMap(ServiceBusAdministrationAsyncClient::mapException)
.map(response -> deserializeQueue(response));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Updates a rule with its context.
*
* @param rule Information about the rule to update. You must provide all the property values that are desired
* on the updated entity. Any values not provided are set to the service default values.
* @param context Context to pass into request.
*
* @return A Mono that completes with the updated {@link RuleProperties}.
*/
Mono<Response<RuleProperties>> updateRuleWithResponse(String topicName, String subscriptionName,
RuleProperties rule, Context context) {
if (rule == null) {
return monoError(logger, new NullPointerException("'rule' cannot be null"));
} else if (context == null) {
return monoError(logger, new NullPointerException("'context' cannot be null."));
}
final RuleDescription implementation = EntityHelper.toImplementation(rule);
final CreateRuleBodyContent content = new CreateRuleBodyContent()
.setType(CONTENT_TYPE)
.setRuleDescription(implementation);
final CreateRuleBody ruleBody = new CreateRuleBody()
.setContent(content);
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
try {
return managementClient.getRules().putWithResponseAsync(topicName, subscriptionName, rule.getName(),
ruleBody, "*", withTracing)
.onErrorMap(ServiceBusAdministrationAsyncClient::mapException)
.map(response -> deserializeRule(response));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Updates a subscription with its context.
*
* @param subscription Information about the subscription to update. You must provide all the property values
* that are desired on the updated entity. Any values not provided are set to the service default values.
* @param context Context to pass into request.
*
* @return A Mono that completes with the updated {@link SubscriptionProperties}.
*/
Mono<Response<SubscriptionProperties>> updateSubscriptionWithResponse(SubscriptionProperties subscription,
Context context) {
if (subscription == null) {
return monoError(logger, new NullPointerException("'subscription' cannot be null"));
} else if (context == null) {
return monoError(logger, new NullPointerException("'context' cannot be null."));
}
final String topicName = subscription.getTopicName();
final String subscriptionName = subscription.getSubscriptionName();
final SubscriptionDescription implementation = EntityHelper.toImplementation(subscription);
final CreateSubscriptionBodyContent content = new CreateSubscriptionBodyContent()
.setType(CONTENT_TYPE)
.setSubscriptionDescription(implementation);
final CreateSubscriptionBody createEntity = new CreateSubscriptionBody()
.setContent(content);
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
try {
return managementClient.getSubscriptions().putWithResponseAsync(topicName, subscriptionName, createEntity,
"*", withTracing)
.onErrorMap(ServiceBusAdministrationAsyncClient::mapException)
.map(response -> deserializeSubscription(topicName, response));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Updates a topic with its context.
*
* @param topic Information about the topic to update. You must provide all the property values that are desired
* on the updated entity. Any values not provided are set to the service default values.
* @param context Context to pass into request.
*
* @return A Mono that completes with the updated {@link TopicProperties}.
*/
Mono<Response<TopicProperties>> updateTopicWithResponse(TopicProperties topic, Context context) {
if (topic == null) {
return monoError(logger, new NullPointerException("'topic' cannot be null"));
} else if (context == null) {
return monoError(logger, new NullPointerException("'context' cannot be null."));
}
final TopicDescription implementation = EntityHelper.toImplementation(topic);
final CreateTopicBodyContent content = new CreateTopicBodyContent()
.setType(CONTENT_TYPE)
.setTopicDescription(implementation);
final CreateTopicBody createEntity = new CreateTopicBody()
.setContent(content);
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
try {
return entityClient.putWithResponseAsync(topic.getName(), createEntity, "*", withTracing)
.onErrorMap(ServiceBusAdministrationAsyncClient::mapException)
.map(response -> deserializeTopic(response));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
private <T> T deserialize(Object object, Class<T> clazz) {
if (object == null) {
return null;
}
final String contents = String.valueOf(object);
if (contents.isEmpty()) {
return null;
}
try {
return serializer.deserialize(contents, clazz);
} catch (IOException e) {
throw logger.logExceptionAsError(new RuntimeException(String.format(
"Exception while deserializing. Body: [%s]. Class: %s", contents, clazz), e));
}
}
/**
* Given an HTTP response, will deserialize it into a strongly typed Response object.
*
* @param response HTTP response to deserialize response body from.
* @param clazz Class to deserialize response type into.
* @param <T> Class type to deserialize response into.
*
* @return A Response with a strongly typed response value.
*/
private <T> Response<T> deserialize(Response<Object> response, Class<T> clazz) {
final T deserialize = deserialize(response.getValue(), clazz);
return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(),
deserialize);
}
/**
* Converts a Response into its corresponding {@link QueueDescriptionEntry} then mapped into {@link
* QueueProperties}.
*
* @param response HTTP Response to deserialize.
*
* @return The corresponding HTTP response with convenience properties set.
*/
/**
* Converts a Response into its corresponding {@link RuleDescriptionEntry} then mapped into {@link RuleProperties}.
*
* @param response HTTP Response to deserialize.
*
* @return The corresponding HTTP response with convenience properties set.
*/
private Response<RuleProperties> deserializeRule(Response<Object> response) {
final RuleDescriptionEntry entry = deserialize(response.getValue(), RuleDescriptionEntry.class);
if (entry == null) {
return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null);
} else if (entry.getContent() == null) {
logger.info("entry.getContent() is null. The entity may not exist. {}", entry);
return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null);
}
final RuleDescription description = entry.getContent().getRuleDescription();
final RuleProperties result = EntityHelper.toModel(description);
return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), result);
}
/**
* Converts a Response into its corresponding {@link SubscriptionDescriptionEntry} then mapped into {@link
* SubscriptionProperties}.
*
* @param response HTTP Response to deserialize.
*
* @return The corresponding HTTP response with convenience properties set.
*/
private Response<SubscriptionProperties> deserializeSubscription(String topicName, Response<Object> response) {
final SubscriptionDescriptionEntry entry = deserialize(response.getValue(), SubscriptionDescriptionEntry.class);
if (entry == null) {
return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null);
} else if (entry.getContent() == null) {
logger.warning("entry.getContent() is null. There should have been content returned. Entry: {}", entry);
return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null);
}
final SubscriptionProperties subscription = EntityHelper.toModel(
entry.getContent().getSubscriptionDescription());
final String subscriptionName = getTitleValue(entry.getTitle());
EntityHelper.setSubscriptionName(subscription, subscriptionName);
EntityHelper.setTopicName(subscription, topicName);
return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(),
subscription);
}
/**
* Converts a Response into its corresponding {@link TopicDescriptionEntry} then mapped into {@link
* QueueProperties}.
*
* @param response HTTP Response to deserialize.
*
* @return The corresponding HTTP response with convenience properties set.
*/
private Response<TopicProperties> deserializeTopic(Response<Object> response) {
final TopicDescriptionEntry entry = deserialize(response.getValue(), TopicDescriptionEntry.class);
if (entry == null) {
return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null);
} else if (entry.getContent() == null) {
logger.warning("entry.getContent() is null. There should have been content returned. Entry: {}", entry);
return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null);
} else if (entry.getContent().getTopicDescription() == null) {
final QueueDescriptionEntry entryTopic = deserialize(response.getValue(), QueueDescriptionEntry.class);
if (entryTopic != null && entryTopic.getContent() != null && entryTopic.getContent().getQueueDescription() != null) {
throw logger.logExceptionAsError(
new RuntimeException(String.format("'[%s]' is not a topic, it is a queue.", entryTopic.getTitle())));
}
}
final TopicProperties result = EntityHelper.toModel(entry.getContent().getTopicDescription());
final String topicName = getTitleValue(entry.getTitle());
EntityHelper.setTopicName(result, topicName);
return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), result);
}
/**
* Creates a {@link FeedPage} given the elements and a set of response links to get the next link from.
*
* @param entities Entities in the feed.
* @param responseLinks Links returned from the feed.
* @param <TResult> Type of Service Bus entities in page.
*
* @return A {@link FeedPage} indicating whether this can be continued or not.
* @throws MalformedURLException if the "next" page link does not contain a well-formed URL.
*/
private <TResult, TFeed> FeedPage<TResult> extractPage(Response<TFeed> response, List<TResult> entities,
List<ResponseLink> responseLinks)
throws MalformedURLException, UnsupportedEncodingException {
final Optional<ResponseLink> nextLink = responseLinks.stream()
.filter(link -> link.getRel().equalsIgnoreCase("next"))
.findFirst();
if (!nextLink.isPresent()) {
return new FeedPage<>(response.getStatusCode(), response.getHeaders(), response.getRequest(), entities);
}
final URL url = new URL(nextLink.get().getHref());
final String decode = URLDecoder.decode(url.getQuery(), StandardCharsets.UTF_8.name());
final Optional<Integer> skipParameter = Arrays.stream(decode.split("&|&"))
.map(part -> part.split("=", 2))
.filter(parts -> parts[0].equalsIgnoreCase("$skip") && parts.length == 2)
.map(parts -> Integer.valueOf(parts[1]))
.findFirst();
if (skipParameter.isPresent()) {
return new FeedPage<>(response.getStatusCode(), response.getHeaders(), response.getRequest(), entities,
skipParameter.get());
} else {
logger.warning("There should have been a skip parameter for the next page.");
return new FeedPage<>(response.getStatusCode(), response.getHeaders(), response.getRequest(), entities);
}
}
/**
* Helper method that invokes the service method, extracts the data and translates it to a PagedResponse.
*
* @param skip Number of elements to skip.
* @param context Context for the query.
*
* @return A Mono that completes with a paged response of queues.
*/
private Mono<PagedResponse<QueueProperties>> listQueues(int skip, Context context) {
return managementClient.listEntitiesWithResponseAsync(QUEUES_ENTITY_TYPE, skip, NUMBER_OF_ELEMENTS, context)
.onErrorMap(ServiceBusAdministrationAsyncClient::mapException)
.flatMap(response -> {
final Response<QueueDescriptionFeed> feedResponse = deserialize(response, QueueDescriptionFeed.class);
final QueueDescriptionFeed feed = feedResponse.getValue();
if (feed == null) {
logger.warning("Could not deserialize QueueDescriptionFeed. skip {}, top: {}", skip,
NUMBER_OF_ELEMENTS);
return Mono.empty();
}
final List<QueueProperties> entities = feed.getEntry().stream()
.filter(e -> e.getContent() != null && e.getContent().getQueueDescription() != null)
.map(e -> {
final String queueName = getTitleValue(e.getTitle());
final QueueProperties queueProperties = EntityHelper.toModel(
e.getContent().getQueueDescription());
EntityHelper.setQueueName(queueProperties, queueName);
return queueProperties;
})
.collect(Collectors.toList());
try {
return Mono.just(extractPage(feedResponse, entities, feed.getLink()));
} catch (MalformedURLException | UnsupportedEncodingException error) {
return Mono.error(new RuntimeException("Could not parse response into FeedPage<QueueDescription>",
error));
}
});
}
/**
* Helper method that invokes the service method, extracts the data and translates it to a PagedResponse.
*
* @param skip Number of elements to skip.
* @param context Context for the query.
*
* @return A Mono that completes with a paged response of rules.
*/
private Mono<PagedResponse<RuleProperties>> listRules(String topicName, String subscriptionName, int skip,
Context context) {
return managementClient.listRulesWithResponseAsync(topicName, subscriptionName, skip, NUMBER_OF_ELEMENTS,
context)
.onErrorMap(ServiceBusAdministrationAsyncClient::mapException)
.flatMap(response -> {
final Response<RuleDescriptionFeed> feedResponse = deserialize(response,
RuleDescriptionFeed.class);
final RuleDescriptionFeed feed = feedResponse.getValue();
if (feed == null) {
logger.warning("Could not deserialize RuleDescriptionFeed. skip {}, top: {}", skip,
NUMBER_OF_ELEMENTS);
return Mono.empty();
}
final List<RuleProperties> entities = feed.getEntry().stream()
.filter(e -> e.getContent() != null && e.getContent().getRuleDescription() != null)
.map(e -> {
return EntityHelper.toModel(e.getContent().getRuleDescription());
})
.collect(Collectors.toList());
try {
return Mono.just(extractPage(feedResponse, entities, feed.getLink()));
} catch (MalformedURLException | UnsupportedEncodingException error) {
return Mono.error(new RuntimeException(
"Could not parse response into FeedPage<RuleDescription>", error));
}
});
}
/**
* Helper method that invokes the service method, extracts the data and translates it to a PagedResponse.
*
* @param skip Number of elements to skip.
* @param context Context for the query.
*
* @return A Mono that completes with a paged response of subscriptions.
*/
private Mono<PagedResponse<SubscriptionProperties>> listSubscriptions(String topicName, int skip,
Context context) {
return managementClient.listSubscriptionsWithResponseAsync(topicName, skip, NUMBER_OF_ELEMENTS, context)
.onErrorMap(ServiceBusAdministrationAsyncClient::mapException)
.flatMap(response -> {
final Response<SubscriptionDescriptionFeed> feedResponse = deserialize(response,
SubscriptionDescriptionFeed.class);
final SubscriptionDescriptionFeed feed = feedResponse.getValue();
if (feed == null) {
logger.warning("Could not deserialize SubscriptionDescriptionFeed. skip {}, top: {}", skip,
NUMBER_OF_ELEMENTS);
return Mono.empty();
}
final List<SubscriptionProperties> entities = feed.getEntry().stream()
.filter(e -> e.getContent() != null && e.getContent().getSubscriptionDescription() != null)
.map(e -> {
final String subscriptionName = getTitleValue(e.getTitle());
final SubscriptionProperties description = EntityHelper.toModel(
e.getContent().getSubscriptionDescription());
EntityHelper.setTopicName(description, topicName);
EntityHelper.setSubscriptionName(description, subscriptionName);
return description;
})
.collect(Collectors.toList());
try {
return Mono.just(extractPage(feedResponse, entities, feed.getLink()));
} catch (MalformedURLException | UnsupportedEncodingException error) {
return Mono.error(new RuntimeException(
"Could not parse response into FeedPage<SubscriptionDescription>", error));
}
});
}
/**
* Helper method that invokes the service method, extracts the data and translates it to a PagedResponse.
*
* @param skip Number of elements to skip.
* @param context Context for the query.
*
* @return A Mono that completes with a paged response of topics.
*/
private Mono<PagedResponse<TopicProperties>> listTopics(int skip, Context context) {
return managementClient.listEntitiesWithResponseAsync(TOPICS_ENTITY_TYPE, skip, NUMBER_OF_ELEMENTS, context)
.onErrorMap(ServiceBusAdministrationAsyncClient::mapException)
.flatMap(response -> {
final Response<TopicDescriptionFeed> feedResponse = deserialize(response, TopicDescriptionFeed.class);
final TopicDescriptionFeed feed = feedResponse.getValue();
if (feed == null) {
logger.warning("Could not deserialize TopicDescriptionFeed. skip {}, top: {}", skip,
NUMBER_OF_ELEMENTS);
return Mono.empty();
}
final List<TopicProperties> entities = feed.getEntry().stream()
.filter(e -> e.getContent() != null && e.getContent().getTopicDescription() != null)
.map(e -> {
final String topicName = getTitleValue(e.getTitle());
final TopicProperties topicProperties = EntityHelper.toModel(
e.getContent().getTopicDescription());
EntityHelper.setTopicName(topicProperties, topicName);
return topicProperties;
})
.collect(Collectors.toList());
try {
return Mono.just(extractPage(feedResponse, entities, feed.getLink()));
} catch (MalformedURLException | UnsupportedEncodingException error) {
return Mono.error(new RuntimeException("Could not parse response into FeedPage<TopicDescription>",
error));
}
});
}
/**
* Given an XML title element, returns the XML text inside. Jackson deserializes Objects as LinkedHashMaps. XML text
* is represented as an entry with an empty string as the key.
*
* For example, the text returned from this {@code <title text="text/xml">QueueName</title>} is "QueueName".
*
* @param responseTitle XML title element.
*
* @return The XML text inside the title. {@code null} is returned if there is no value.
*/
@SuppressWarnings("unchecked")
private String getTitleValue(Object responseTitle) {
if (!(responseTitle instanceof Map)) {
return null;
}
final Map<String, String> map;
try {
map = (Map<String, String>) responseTitle;
return map.get("");
} catch (ClassCastException error) {
logger.warning("Unable to cast to Map<String,String>. Title: {}", responseTitle, error);
return null;
}
}
/**
* Maps an exception from the ATOM APIs to its associated {@link HttpResponseException}.
*
* @param exception Exception from the ATOM API.
*
* @return The corresponding {@link HttpResponseException} or {@code throwable} if it is not an instance of {@link
* ServiceBusManagementErrorException}.
*/
private static Throwable mapException(Throwable exception) {
if (!(exception instanceof ServiceBusManagementErrorException)) {
return exception;
}
final ServiceBusManagementErrorException managementError = ((ServiceBusManagementErrorException) exception);
final ServiceBusManagementError error = managementError.getValue();
final HttpResponse errorHttpResponse = managementError.getResponse();
final int statusCode = error != null && error.getCode() != null
? error.getCode()
: errorHttpResponse.getStatusCode();
final String errorDetail = error != null && error.getDetail() != null
? error.getDetail()
: managementError.getMessage();
switch (statusCode) {
case 401:
return new ClientAuthenticationException(errorDetail, managementError.getResponse(), exception);
case 404:
return new ResourceNotFoundException(errorDetail, managementError.getResponse(), exception);
case 409:
return new ResourceExistsException(errorDetail, managementError.getResponse(), exception);
case 412:
return new ResourceModifiedException(errorDetail, managementError.getResponse(), exception);
default:
return new HttpResponseException(errorDetail, managementError.getResponse(), exception);
}
}
/**
* A page of Service Bus entities.
*
* @param <T> The entity description from Service Bus.
*/
private static final class FeedPage<T> implements PagedResponse<T> {
private final int statusCode;
private final HttpHeaders header;
private final HttpRequest request;
private final IterableStream<T> entries;
private final String continuationToken;
/**
* Creates a page that does not have any more pages.
*
* @param entries Items in the page.
*/
private FeedPage(int statusCode, HttpHeaders header, HttpRequest request, List<T> entries) {
this.statusCode = statusCode;
this.header = header;
this.request = request;
this.entries = new IterableStream<>(entries);
this.continuationToken = null;
}
/**
* Creates an instance that has additional pages to fetch.
*
* @param entries Items in the page.
* @param skip Number of elements to "skip".
*/
private FeedPage(int statusCode, HttpHeaders header, HttpRequest request, List<T> entries, int skip) {
this.statusCode = statusCode;
this.header = header;
this.request = request;
this.entries = new IterableStream<>(entries);
this.continuationToken = String.valueOf(skip);
}
@Override
public IterableStream<T> getElements() {
return entries;
}
@Override
public String getContinuationToken() {
return continuationToken;
}
@Override
public int getStatusCode() {
return statusCode;
}
@Override
public HttpHeaders getHeaders() {
return header;
}
@Override
public HttpRequest getRequest() {
return request;
}
@Override
public void close() {
}
}
private static final class EntityNotFoundHttpResponse<T> extends HttpResponse {
private final int statusCode;
private final HttpHeaders headers;
private EntityNotFoundHttpResponse(Response<T> response) {
super(response.getRequest());
this.headers = response.getHeaders();
this.statusCode = response.getStatusCode();
}
@Override
public int getStatusCode() {
return statusCode;
}
@Override
public String getHeaderValue(String name) {
return headers.getValue(name);
}
@Override
public HttpHeaders getHeaders() {
return headers;
}
@Override
public Flux<ByteBuffer> getBody() {
return Flux.empty();
}
@Override
public Mono<byte[]> getBodyAsByteArray() {
return Mono.empty();
}
@Override
public Mono<String> getBodyAsString() {
return Mono.empty();
}
@Override
public Mono<String> getBodyAsString(Charset charset) {
return Mono.empty();
}
}
} | class ServiceBusAdministrationAsyncClient {
private static final String SERVICE_BUS_TRACING_NAMESPACE_VALUE = "Microsoft.ServiceBus";
private static final String CONTENT_TYPE = "application/xml";
private static final String QUEUES_ENTITY_TYPE = "queues";
private static final String TOPICS_ENTITY_TYPE = "topics";
private static final int NUMBER_OF_ELEMENTS = 100;
private final ServiceBusManagementClientImpl managementClient;
private final EntitiesImpl entityClient;
private final ClientLogger logger = new ClientLogger(ServiceBusAdministrationAsyncClient.class);
private final ServiceBusManagementSerializer serializer;
private final RulesImpl rulesClient;
/**
* Creates a new instance with the given management client and serializer.
*
* @param managementClient Client to make management calls.
* @param serializer Serializer to deserialize ATOM XML responses.
*/
ServiceBusAdministrationAsyncClient(ServiceBusManagementClientImpl managementClient,
ServiceBusManagementSerializer serializer) {
this.serializer = Objects.requireNonNull(serializer, "'serializer' cannot be null.");
this.managementClient = Objects.requireNonNull(managementClient, "'managementClient' cannot be null.");
this.entityClient = managementClient.getEntities();
this.rulesClient = managementClient.getRules();
}
/**
* Creates a queue with the given name.
*
* @param queueName Name of the queue to create.
*
* @return A Mono that completes with information about the created queue.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If the request body was invalid, the queue quota is exceeded, or an error
* occurred processing the request.
* @throws NullPointerException if {@code queueName} is null.
* @throws IllegalArgumentException if {@code queueName} is an empty string.
* @throws ResourceExistsException if a queue exists with the same {@code queueName}.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<QueueProperties> createQueue(String queueName) {
try {
return createQueue(queueName, new CreateQueueOptions());
} catch (RuntimeException e) {
return monoError(logger, e);
}
}
/**
* Creates a queue with the {@link CreateQueueOptions} and given queue name.
*
* @param queueName Name of the queue to create.
* @param queueOptions Options about the queue to create.
*
* @return A Mono that completes with information about the created queue.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If the request body was invalid, the queue quota is exceeded, or an error
* occurred processing the request.
* @throws IllegalArgumentException if {@code queueName} is an empty string.
* @throws NullPointerException if {@code queueName} or {@code queueOptions} is null.
* @throws ResourceExistsException if a queue exists with the same {@link QueueProperties
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<QueueProperties> createQueue(String queueName, CreateQueueOptions queueOptions) {
return createQueueWithResponse(queueName, queueOptions).map(Response::getValue);
}
/**
* Creates a queue and returns the created queue in addition to the HTTP response.
*
* @param queueName Name of the queue to create.
* @param queueOptions Options about the queue to create.
*
* @return A Mono that returns the created queue in addition to the HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If the request body was invalid, the queue quota is exceeded, or an error
* occurred processing the request.
* @throws IllegalArgumentException if {@code queueName} is an empty string.
* @throws NullPointerException if {@code queueName} or {@code queueOptions} is null.
* @throws ResourceExistsException if a queue exists with the same {@link QueueProperties
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<QueueProperties>> createQueueWithResponse(String queueName, CreateQueueOptions queueOptions) {
return withContext(context -> createQueueWithResponse(queueName, queueOptions, context));
}
/**
* Creates a rule under the given topic and subscription
*
* @param topicName Name of the topic associated with rule.
* @param subscriptionName Name of the subscription associated with the rule.
* @param ruleName Name of the rule.
*
* @return A Mono that completes with information about the created rule.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If the request body was invalid, the quota is exceeded, or an error occurred
* processing the request.
* @throws IllegalArgumentException if {@code topicName} or {@code ruleName} are are empty strings.
* @throws NullPointerException if {@code topicName} or {@code ruleName} are are null.
* @throws ResourceExistsException if a rule exists with the same topic, subscription, and rule name.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<RuleProperties> createRule(String topicName, String subscriptionName, String ruleName) {
try {
return createRule(topicName, subscriptionName, ruleName, new CreateRuleOptions());
} catch (RuntimeException e) {
return monoError(logger, e);
}
}
/**
* Creates a rule with the {@link CreateRuleOptions}.
*
* @param topicName Name of the topic associated with rule.
* @param subscriptionName Name of the subscription associated with the rule.
* @param ruleName Name of the rule.
* @param ruleOptions Information about the rule to create.
*
* @return A Mono that completes with information about the created rule.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If the request body was invalid, the quota is exceeded, or an error occurred
* processing the request.
* @throws IllegalArgumentException if {@code topicName} or {@code ruleName} are are empty strings.
* @throws NullPointerException if {@code topicName}, {@code ruleName}, or {@code ruleOptions}
* are are null.
* @throws ResourceExistsException if a rule exists with the same topic and rule name.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<RuleProperties> createRule(String topicName, String subscriptionName, String ruleName,
CreateRuleOptions ruleOptions) {
return createRuleWithResponse(topicName, subscriptionName, ruleName, ruleOptions)
.map(Response::getValue);
}
/**
* Creates a rule and returns the created rule in addition to the HTTP response.
*
* @param topicName Name of the topic associated with rule.
* @param subscriptionName Name of the subscription associated with the rule.
* @param ruleName Name of the rule.
* @param ruleOptions Information about the rule to create.
*
* @return A Mono that returns the created rule in addition to the HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If the request body was invalid, the quota is exceeded, or an error occurred
* processing the request.
* @throws IllegalArgumentException if {@code topicName} or {@code ruleName} are are empty strings.
* @throws NullPointerException if {@code topicName}, {@code ruleName}, or {@code ruleOptions}
* are are null.
* @throws ResourceExistsException if a rule exists with the same topic and rule name.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<RuleProperties>> createRuleWithResponse(String topicName, String subscriptionName,
String ruleName, CreateRuleOptions ruleOptions) {
return withContext(context -> createRuleWithResponse(topicName, subscriptionName, ruleName, ruleOptions,
context));
}
/**
* Creates a subscription with the given topic and subscription names.
*
* @param topicName Name of the topic associated with subscription.
* @param subscriptionName Name of the subscription.
*
* @return A Mono that completes with information about the created subscription.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If the request body was invalid, the quota is exceeded, or an error occurred
* processing the request.
* @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} are are empty strings.
* @throws NullPointerException if {@code topicName} or {@code subscriptionName} are are null.
* @throws ResourceExistsException if a subscription exists with the same topic and subscription name.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<SubscriptionProperties> createSubscription(String topicName, String subscriptionName) {
try {
return createSubscription(topicName, subscriptionName, new CreateSubscriptionOptions());
} catch (RuntimeException e) {
return monoError(logger, e);
}
}
/**
* Creates a subscription with the {@link CreateSubscriptionOptions}.
*
* @param topicName Name of the topic associated with subscription.
* @param subscriptionName Name of the subscription.
* @param subscriptionOptions Information about the subscription to create.
*
* @return A Mono that completes with information about the created subscription.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If the request body was invalid, the quota is exceeded, or an error occurred
* processing the request.
* @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} are are empty strings.
* @throws NullPointerException if {@code topicName}, {@code subscriptionName}, or {@code subscriptionOptions}
* are are null.
* @throws ResourceExistsException if a subscription exists with the same topic and subscription name.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<SubscriptionProperties> createSubscription(String topicName, String subscriptionName,
CreateSubscriptionOptions subscriptionOptions) {
return createSubscriptionWithResponse(topicName, subscriptionName, subscriptionOptions)
.map(Response::getValue);
}
/**
* Creates a subscription and returns the created subscription in addition to the HTTP response.
*
* @param topicName Name of the topic associated with subscription.
* @param subscriptionName Name of the subscription.
* @param subscriptionOptions Information about the subscription to create.
*
* @return A Mono that returns the created subscription in addition to the HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If the request body was invalid, the quota is exceeded, or an error occurred
* processing the request.
* @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} are are empty strings.
* @throws NullPointerException if {@code topicName}, {@code subscriptionName}, or {@code subscriptionOptions}
* are are null.
* @throws ResourceExistsException if a subscription exists with the same topic and subscription name.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<SubscriptionProperties>> createSubscriptionWithResponse(String topicName,
String subscriptionName, CreateSubscriptionOptions subscriptionOptions) {
return withContext(context -> createSubscriptionWithResponse(topicName, subscriptionName, subscriptionOptions,
context));
}
/**
* Creates a topic with the given name.
*
* @param topicName Name of the topic to create.
*
* @return A Mono that completes with information about the created topic.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If the request body was invalid, the topic quota is exceeded, or an error
* occurred processing the request.
* @throws NullPointerException if {@code topicName} is null.
* @throws IllegalArgumentException if {@code topicName} is an empty string.
* @throws ResourceExistsException if a topic exists with the same {@code topicName}.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<TopicProperties> createTopic(String topicName) {
try {
return createTopic(topicName, new CreateTopicOptions());
} catch (RuntimeException e) {
return monoError(logger, e);
}
}
/**
* Creates a topic with the {@link CreateTopicOptions}.
*
* @param topicName Name of the topic to create.
* @param topicOptions The options used to create the topic.
*
* @return A Mono that completes with information about the created topic.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If the request body was invalid, the topic quota is exceeded, or an error
* occurred processing the request.
* @throws IllegalArgumentException if {@code topicName} is an empty string.
* @throws NullPointerException if {@code topicName} or {@code topicOptions} is null.
* @throws ResourceExistsException if a topic exists with the same {@code topicName}.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<TopicProperties> createTopic(String topicName, CreateTopicOptions topicOptions) {
return createTopicWithResponse(topicName, topicOptions).map(Response::getValue);
}
/**
* Creates a topic and returns the created topic in addition to the HTTP response.
*
* @param topicName Name of the topic to create.
* @param topicOptions The options used to create the topic.
*
* @return A Mono that returns the created topic in addition to the HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If the request body was invalid, the topic quota is exceeded, or an error
* occurred processing the request.
* @throws IllegalArgumentException if {@link TopicProperties
* string.
* @throws NullPointerException if {@code topicName} or {@code topicOptions} is null.
* @throws ResourceExistsException if a topic exists with the same {@code topicName}.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<TopicProperties>> createTopicWithResponse(String topicName, CreateTopicOptions topicOptions) {
return withContext(context -> createTopicWithResponse(topicName, topicOptions, context));
}
/**
* Deletes a queue the matching {@code queueName}.
*
* @param queueName Name of queue to delete.
*
* @return A Mono that completes when the queue is deleted.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws NullPointerException if {@code queueName} is null.
* @throws IllegalArgumentException if {@code queueName} is an empty string.
* @throws ResourceNotFoundException if the {@code queueName} does not exist.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Void> deleteQueue(String queueName) {
return deleteQueueWithResponse(queueName).then();
}
/**
* Deletes a queue the matching {@code queueName} and returns the HTTP response.
*
* @param queueName Name of queue to delete.
*
* @return A Mono that completes when the queue is deleted and returns the HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws NullPointerException if {@code queueName} is null.
* @throws IllegalArgumentException if {@code queueName} is an empty string.
* @throws ResourceNotFoundException if the {@code queueName} does not exist.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Void>> deleteQueueWithResponse(String queueName) {
return withContext(context -> deleteQueueWithResponse(queueName, context));
}
/**
* Deletes a rule the matching {@code ruleName}.
*
* @param topicName Name of topic associated with rule to delete.
* @param subscriptionName Name of the subscription associated with the rule to delete.
* @param ruleName Name of rule to delete.
*
* @return A Mono that completes when the rule is deleted.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code topicName} or {@code ruleName} is an empty string.
* @throws NullPointerException if {@code topicName} or {@code ruleName} is null.
* @throws ResourceNotFoundException if the {@code ruleName} does not exist.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Void> deleteRule(String topicName, String subscriptionName, String ruleName) {
return deleteRuleWithResponse(topicName, subscriptionName, ruleName).then();
}
/**
* Deletes a rule the matching {@code ruleName} and returns the HTTP response.
*
* @param topicName Name of topic associated with rule to delete.
* @param subscriptionName Name of the subscription associated with the rule to delete.
* @param ruleName Name of rule to delete.
*
* @return A Mono that completes when the rule is deleted and returns the HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code topicName}, {@code subscriptionName}, or {@code ruleName} is an
* empty string.
* @throws NullPointerException if {@code topicName}, {@code subscriptionName}, or {@code ruleName} is null.
* @throws ResourceNotFoundException if the {@code ruleName} does not exist.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Void>> deleteRuleWithResponse(String topicName, String subscriptionName,
String ruleName) {
return withContext(context -> deleteRuleWithResponse(topicName, subscriptionName, ruleName, context));
}
/**
* Deletes a subscription the matching {@code subscriptionName}.
*
* @param topicName Name of topic associated with subscription to delete.
* @param subscriptionName Name of subscription to delete.
*
* @return A Mono that completes when the subscription is deleted.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} is an empty string.
* @throws NullPointerException if {@code topicName} or {@code subscriptionName} is null.
* @throws ResourceNotFoundException if the {@code subscriptionName} does not exist.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Void> deleteSubscription(String topicName, String subscriptionName) {
return deleteSubscriptionWithResponse(topicName, subscriptionName).then();
}
/**
* Deletes a subscription the matching {@code subscriptionName} and returns the HTTP response.
*
* @param topicName Name of topic associated with subscription to delete.
* @param subscriptionName Name of subscription to delete.
*
* @return A Mono that completes when the subscription is deleted and returns the HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} is an empty string.
* @throws NullPointerException if {@code topicName} or {@code subscriptionName} is null.
* @throws ResourceNotFoundException if the {@code subscriptionName} does not exist.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Void>> deleteSubscriptionWithResponse(String topicName, String subscriptionName) {
return withContext(context -> deleteSubscriptionWithResponse(topicName, subscriptionName, context));
}
/**
* Deletes a topic the matching {@code topicName}.
*
* @param topicName Name of topic to delete.
*
* @return A Mono that completes when the topic is deleted.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code topicName} is an empty string.
* @throws NullPointerException if {@code topicName} is null.
* @throws ResourceNotFoundException if the {@code topicName} does not exist.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Void> deleteTopic(String topicName) {
return deleteTopicWithResponse(topicName).then();
}
/**
* Deletes a topic the matching {@code topicName} and returns the HTTP response.
*
* @param topicName Name of topic to delete.
*
* @return A Mono that completes when the topic is deleted and returns the HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code topicName} is an empty string.
* @throws NullPointerException if {@code topicName} is null.
* @throws ResourceNotFoundException if the {@code topicName} does not exist.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Void>> deleteTopicWithResponse(String topicName) {
return withContext(context -> deleteTopicWithResponse(topicName, context));
}
/**
* Gets information about the queue.
*
* @param queueName Name of queue to get information about.
*
* @return A Mono that completes with information about the queue.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code queueName} is an empty string.
* @throws NullPointerException if {@code queueName} is null.
* @throws ResourceNotFoundException if the {@code queueName} does not exist.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<QueueProperties> getQueue(String queueName) {
return getQueueWithResponse(queueName).map(Response::getValue);
}
/**
* Gets information about the queue along with its HTTP response.
*
* @param queueName Name of queue to get information about.
*
* @return A Mono that completes with information about the queue and the associated HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code queueName} is an empty string.
* @throws NullPointerException if {@code queueName} is null.
* @throws ResourceNotFoundException if the {@code queueName} does not exist.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<QueueProperties>> getQueueWithResponse(String queueName) {
return withContext(context -> getQueueWithResponse(queueName, context, Function.identity()));
}
/**
* Gets whether or not a queue with {@code queueName} exists in the Service Bus namespace.
*
* @param queueName Name of the queue.
*
* @return A Mono that completes indicating whether or not the queue exists.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code queueName} is an empty string.
* @throws NullPointerException if {@code queueName} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Boolean> getQueueExists(String queueName) {
return getQueueExistsWithResponse(queueName).map(Response::getValue);
}
/**
* Gets whether or not a queue with {@code queueName} exists in the Service Bus namespace.
*
* @param queueName Name of the queue.
*
* @return A Mono that completes indicating whether or not the queue exists along with its HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code queueName} is an empty string.
* @throws NullPointerException if {@code queueName} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Boolean>> getQueueExistsWithResponse(String queueName) {
return getEntityExistsWithResponse(getQueueWithResponse(queueName));
}
/**
* Gets runtime properties about the queue.
*
* @param queueName Name of queue to get information about.
*
* @return A Mono that completes with runtime properties about the queue.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code queueName} is an empty string.
* @throws NullPointerException if {@code queueName} is null.
* @throws ResourceNotFoundException if the {@code queueName} does not exist.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<QueueRuntimeProperties> getQueueRuntimeProperties(String queueName) {
return getQueueRuntimePropertiesWithResponse(queueName).map(response -> response.getValue());
}
/**
* Gets runtime properties about the queue along with its HTTP response.
*
* @param queueName Name of queue to get information about.
*
* @return A Mono that completes with runtime properties about the queue and the associated HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code queueName} is an empty string.
* @throws NullPointerException if {@code queueName} is null.
* @throws ResourceNotFoundException if the {@code queueName} does not exist.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<QueueRuntimeProperties>> getQueueRuntimePropertiesWithResponse(String queueName) {
return withContext(context -> getQueueWithResponse(queueName, context, QueueRuntimeProperties::new));
}
/**
* Gets information about the Service Bus namespace.
*
* @return A Mono that completes with information about the Service Bus namespace.
* @throws ClientAuthenticationException if the client's credentials do not have access to the namespace.
* @throws HttpResponseException If error occurred processing the request.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<NamespaceProperties> getNamespaceProperties() {
return getNamespacePropertiesWithResponse().map(Response::getValue);
}
/**
* Gets information about the Service Bus namespace along with its HTTP response.
*
* @return A Mono that completes with information about the namespace and the associated HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<NamespaceProperties>> getNamespacePropertiesWithResponse() {
return withContext(this::getNamespacePropertiesWithResponse);
}
/**
* Gets a rule from the service namespace.
*
* Only following data types are deserialized in Filters and Action parameters - string, int, long, boolean, double,
* and OffsetDateTime. Other data types would return its string value.
*
* @param topicName The name of the topic relative to service bus namespace.
* @param subscriptionName The subscription name the rule belongs to.
* @param ruleName The name of the rule to retrieve.
*
* @return The associated rule.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<RuleProperties> getRule(String topicName, String subscriptionName, String ruleName) {
return getRuleWithResponse(topicName, subscriptionName, ruleName).map(response -> response.getValue());
}
/**
* Gets a rule from the service namespace.
*
* Only following data types are deserialized in Filters and Action parameters - string, int, long, bool, double,
* and OffsetDateTime. Other data types would return its string value.
*
* @param topicName The name of the topic relative to service bus namespace.
* @param subscriptionName The subscription name the rule belongs to.
* @param ruleName The name of the rule to retrieve.
*
* @return The associated rule with the corresponding HTTP response.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<RuleProperties>> getRuleWithResponse(String topicName, String subscriptionName,
String ruleName) {
return withContext(context -> getRuleWithResponse(topicName, subscriptionName, ruleName, context));
}
/**
* Gets information about the queue.
*
* @param topicName Name of topic associated with subscription.
* @param subscriptionName Name of subscription to get information about.
*
* @return A Mono that completes with information about the subscription.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} are empty strings.
* @throws NullPointerException if {@code topicName} or {@code subscriptionName} are null.
* @throws ResourceNotFoundException if the {@code subscriptionName} does not exist in the {@code topicName}.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<SubscriptionProperties> getSubscription(String topicName, String subscriptionName) {
return getSubscriptionWithResponse(topicName, subscriptionName).map(Response::getValue);
}
/**
* Gets information about the subscription along with its HTTP response.
*
* @param topicName Name of topic associated with subscription.
* @param subscriptionName Name of subscription to get information about.
*
* @return A Mono that completes with information about the subscription and the associated HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} are empty strings.
* @throws NullPointerException if {@code topicName} or {@code subscriptionName} are null.
* @throws ResourceNotFoundException if the {@code subscriptionName} does not exist.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<SubscriptionProperties>> getSubscriptionWithResponse(String topicName,
String subscriptionName) {
return withContext(context -> getSubscriptionWithResponse(topicName, subscriptionName, context,
Function.identity()));
}
/**
* Gets whether or not a subscription within a topic exists.
*
* @param topicName Name of topic associated with subscription.
* @param subscriptionName Name of the subscription.
*
* @return A Mono that completes indicating whether or not the subscription exists.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code subscriptionName} is an empty string.
* @throws NullPointerException if {@code subscriptionName} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Boolean> getSubscriptionExists(String topicName, String subscriptionName) {
return getSubscriptionExistsWithResponse(topicName, subscriptionName).map(Response::getValue);
}
/**
* Gets whether or not a subscription within a topic exists.
*
* @param topicName Name of topic associated with subscription.
* @param subscriptionName Name of the subscription.
*
* @return A Mono that completes indicating whether or not the subscription exists along with its HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code subscriptionName} is an empty string.
* @throws NullPointerException if {@code subscriptionName} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Boolean>> getSubscriptionExistsWithResponse(String topicName, String subscriptionName) {
return getEntityExistsWithResponse(getSubscriptionWithResponse(topicName, subscriptionName));
}
/**
* Gets runtime properties about the subscription.
*
* @param topicName Name of topic associated with subscription.
* @param subscriptionName Name of subscription to get information about.
*
* @return A Mono that completes with runtime properties about the subscription.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} are empty strings.
* @throws NullPointerException if {@code topicName} or {@code subscriptionName} are null.
* @throws ResourceNotFoundException if the {@code subscriptionName} does not exist.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<SubscriptionRuntimeProperties> getSubscriptionRuntimeProperties(
String topicName, String subscriptionName) {
return getSubscriptionRuntimePropertiesWithResponse(topicName, subscriptionName)
.map(response -> response.getValue());
}
/**
* Gets runtime properties about the subscription.
*
* @param topicName Name of topic associated with subscription.
* @param subscriptionName Name of subscription to get information about.
*
* @return A Mono that completes with runtime properties about the subscription.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code subscriptionName} is an empty string.
* @throws NullPointerException if {@code subscriptionName} is null.
* @throws ResourceNotFoundException if the {@code subscriptionName} does not exist.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<SubscriptionRuntimeProperties>> getSubscriptionRuntimePropertiesWithResponse(
String topicName, String subscriptionName) {
return withContext(context -> getSubscriptionWithResponse(topicName, subscriptionName, context,
SubscriptionRuntimeProperties::new));
}
/**
* Gets information about the topic.
*
* @param topicName Name of topic to get information about.
*
* @return A Mono that completes with information about the topic.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code topicName} is an empty string.
* @throws NullPointerException if {@code topicName} is null.
* @throws ResourceNotFoundException if the {@code topicName} does not exist.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<TopicProperties> getTopic(String topicName) {
return getTopicWithResponse(topicName).map(Response::getValue);
}
/**
* Gets information about the topic along with its HTTP response.
*
* @param topicName Name of topic to get information about.
*
* @return A Mono that completes with information about the topic and the associated HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code topicName} is an empty string.
* @throws NullPointerException if {@code topicName} is null.
* @throws ResourceNotFoundException if the {@code topicName} does not exist.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<TopicProperties>> getTopicWithResponse(String topicName) {
return withContext(context -> getTopicWithResponse(topicName, context, Function.identity()));
}
/**
* Gets whether or not a topic with {@code topicName} exists in the Service Bus namespace.
*
* @param topicName Name of the topic.
*
* @return A Mono that completes indicating whether or not the topic exists.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code topicName} is an empty string.
* @throws NullPointerException if {@code topicName} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Boolean> getTopicExists(String topicName) {
return getTopicExistsWithResponse(topicName).map(Response::getValue);
}
/**
* Gets whether or not a topic with {@code topicName} exists in the Service Bus namespace.
*
* @param topicName Name of the topic.
*
* @return A Mono that completes indicating whether or not the topic exists along with its HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code topicName} is an empty string.
* @throws NullPointerException if {@code topicName} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Boolean>> getTopicExistsWithResponse(String topicName) {
return getEntityExistsWithResponse(getTopicWithResponse(topicName));
}
/**
* Gets runtime properties about the topic.
*
* @param topicName Name of topic to get information about.
*
* @return A Mono that completes with runtime properties about the topic.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code topicName} is an empty string.
* @throws NullPointerException if {@code topicName} is null.
* @throws ResourceNotFoundException if the {@code topicName} does not exist.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<TopicRuntimeProperties> getTopicRuntimeProperties(String topicName) {
return getTopicRuntimePropertiesWithResponse(topicName).map(response -> response.getValue());
}
/**
* Gets runtime properties about the topic with its HTTP response.
*
* @param topicName Name of topic to get information about.
*
* @return A Mono that completes with runtime properties about the topic and the associated HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code topicName} is an empty string.
* @throws NullPointerException if {@code topicName} is null.
* @throws ResourceNotFoundException if the {@code topicName} does not exist.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<TopicRuntimeProperties>> getTopicRuntimePropertiesWithResponse(String topicName) {
return withContext(context -> getTopicWithResponse(topicName, context, TopicRuntimeProperties::new));
}
/**
* Fetches all the queues in the Service Bus namespace.
*
* @return A Flux of {@link QueueProperties queues} in the Service Bus namespace.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @see <a href="https:
* authorization rules</a>
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux<QueueProperties> listQueues() {
return new PagedFlux<>(
() -> withContext(context -> listQueuesFirstPage(context)),
token -> withContext(context -> listQueuesNextPage(token, context)));
}
/**
* Fetches all the rules for a topic and subscription.
*
* @param topicName The topic name under which all the rules need to be retrieved.
* @param subscriptionName The name of the subscription for which all rules need to be retrieved.
*
* @return A Flux of {@link RuleProperties rules} for the {@code topicName} and {@code subscriptionName}.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws NullPointerException if {@code topicName} or {@code subscriptionName} is null.
* @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} is an empty string.
* @see <a href="https:
* authorization rules</a>
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux<RuleProperties> listRules(String topicName, String subscriptionName) {
if (topicName == null) {
return pagedFluxError(logger, new NullPointerException("'topicName' cannot be null."));
} else if (topicName.isEmpty()) {
return pagedFluxError(logger, new IllegalArgumentException("'topicName' cannot be an empty string."));
}
return new PagedFlux<>(
() -> withContext(context -> listRulesFirstPage(topicName, subscriptionName, context)),
token -> withContext(context -> listRulesNextPage(topicName, subscriptionName, token, context)));
}
/**
* Fetches all the subscriptions for a topic.
*
* @param topicName The topic name under which all the subscriptions need to be retrieved.
*
* @return A Flux of {@link SubscriptionProperties subscriptions} for the {@code topicName}.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws NullPointerException if {@code topicName} is null.
* @throws IllegalArgumentException if {@code topicName} is an empty string.
* @see <a href="https:
* authorization rules</a>
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux<SubscriptionProperties> listSubscriptions(String topicName) {
if (topicName == null) {
return pagedFluxError(logger, new NullPointerException("'topicName' cannot be null."));
} else if (topicName.isEmpty()) {
return pagedFluxError(logger, new IllegalArgumentException("'topicName' cannot be an empty string."));
}
return new PagedFlux<>(
() -> withContext(context -> listSubscriptionsFirstPage(topicName, context)),
token -> withContext(context -> listSubscriptionsNextPage(topicName, token, context)));
}
/**
* Fetches all the topics in the Service Bus namespace.
*
* @return A Flux of {@link TopicProperties topics} in the Service Bus namespace.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @see <a href="https:
* authorization rules</a>
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux<TopicProperties> listTopics() {
return new PagedFlux<>(
() -> withContext(context -> listTopicsFirstPage(context)),
token -> withContext(context -> listTopicsNextPage(token, context)));
}
/**
* Updates a queue with the given {@link QueueProperties}. The {@link QueueProperties} must be fully populated as
* all of the properties are replaced. If a property is not set the service default value is used.
*
* The suggested flow is:
* <ol>
* <li>{@link
* <li>Update the required elements.</li>
* <li>Pass the updated description into this method.</li>
* </ol>
*
* <p>
* There are a subset of properties that can be updated. More information can be found in the links below. They are:
* <ul>
* <li>{@link QueueProperties
* <li>{@link QueueProperties
* <li>{@link QueueProperties
* </li>
* <li>{@link QueueProperties
* </ul>
*
* @param queue Information about the queue to update. You must provide all the property values that are desired
* on the updated entity. Any values not provided are set to the service default values.
*
* @return A Mono that completes with the updated queue.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If the request body was invalid, the queue quota is exceeded, or an error
* occurred processing the request.
* @throws NullPointerException if {@code queue} is null.
* @see <a href="https:
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<QueueProperties> updateQueue(QueueProperties queue) {
return updateQueueWithResponse(queue).map(Response::getValue);
}
/**
* Updates a queue with the given {@link QueueProperties}. The {@link QueueProperties} must be fully populated as
* all of the properties are replaced. If a property is not set the service default value is used.
*
* The suggested flow is:
* <ol>
* <li>{@link
* <li>Update the required elements.</li>
* <li>Pass the updated description into this method.</li>
* </ol>
*
* <p>
* There are a subset of properties that can be updated. More information can be found in the links below. They are:
* <ul>
* <li>{@link QueueProperties
* <li>{@link QueueProperties
* <li>{@link QueueProperties
* </li>
* <li>{@link QueueProperties
* </ul>
*
* @param queue Information about the queue to update. You must provide all the property values that are desired
* on the updated entity. Any values not provided are set to the service default values.
*
* @return A Mono that returns the updated queue in addition to the HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If the request body was invalid, the queue quota is exceeded, or an error
* occurred processing the request.
* @throws NullPointerException if {@code queue} is null.
* @see <a href="https:
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<QueueProperties>> updateQueueWithResponse(QueueProperties queue) {
return withContext(context -> updateQueueWithResponse(queue, context));
}
/**
* Updates a rule with the given {@link RuleProperties}. The {@link RuleProperties} must be fully populated as all
* of the properties are replaced. If a property is not set the service default value is used.
*
* The suggested flow is:
* <ol>
* <li>{@link
* <li>Update the required elements.</li>
* <li>Pass the updated description into this method.</li>
* </ol>
*
* @param topicName The topic name under which the rule is updated.
* @param subscriptionName The name of the subscription for which the rule is updated.
* @param rule Information about the rule to update. You must provide all the property values that are desired
* on the updated entity. Any values not provided are set to the service default values.
*
* @return A Mono that returns the updated rule.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If the request body was invalid, the rule quota is exceeded, or an error
* occurred processing the request.
* @throws IllegalArgumentException if {@link RuleProperties
* @throws NullPointerException if {@code rule} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<RuleProperties> updateRule(String topicName, String subscriptionName, RuleProperties rule) {
return updateRuleWithResponse(topicName, subscriptionName, rule).map(Response::getValue);
}
/**
* Updates a rule with the given {@link RuleProperties}. The {@link RuleProperties} must be fully populated as all
* of the properties are replaced. If a property is not set the service default value is used.
*
* The suggested flow is:
* <ol>
* <li>{@link
* <li>Update the required elements.</li>
* <li>Pass the updated description into this method.</li>
* </ol>
*
* @param topicName The topic name under which the rule is updated.
* @param subscriptionName The name of the subscription for which the rule is updated.
* @param rule Information about the rule to update. You must provide all the property values that are desired
* on the updated entity. Any values not provided are set to the service default values.
*
* @return A Mono that returns the updated rule in addition to the HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If the request body was invalid, the rule quota is exceeded, or an error
* occurred processing the request.
* @throws IllegalArgumentException if {@link RuleProperties
* @throws NullPointerException if {@code rule} is null.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<RuleProperties>> updateRuleWithResponse(String topicName, String subscriptionName,
RuleProperties rule) {
return withContext(context -> updateRuleWithResponse(topicName, subscriptionName, rule, context));
}
/**
* Updates a subscription with the given {@link SubscriptionProperties}. The {@link SubscriptionProperties} must be
* fully populated as all of the properties are replaced. If a property is not set the service default value is
* used.
*
* The suggested flow is:
* <ol>
* <li>{@link
* <li>Update the required elements.</li>
* <li>Pass the updated description into this method.</li>
* </ol>
*
* <p>
* There are a subset of properties that can be updated. More information can be found in the links below. They are:
* <ul>
* <li>{@link SubscriptionProperties
* <li>{@link SubscriptionProperties
* <li>{@link SubscriptionProperties
* </ul>
*
* @param subscription Information about the subscription to update. You must provide all the property values
* that are desired on the updated entity. Any values not provided are set to the service default values.
*
* @return A Mono that returns the updated subscription.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If the request body was invalid, the subscription quota is exceeded, or an
* error occurred processing the request.
* @throws IllegalArgumentException if {@link SubscriptionProperties
* SubscriptionProperties
* @throws NullPointerException if {@code subscription} is null.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<SubscriptionProperties> updateSubscription(SubscriptionProperties subscription) {
return updateSubscriptionWithResponse(subscription).map(Response::getValue);
}
/**
* Updates a subscription with the given {@link SubscriptionProperties}. The {@link SubscriptionProperties} must be
* fully populated as all of the properties are replaced. If a property is not set the service default value is
* used.
*
* The suggested flow is:
* <ol>
* <li>{@link
* <li>Update the required elements.</li>
* <li>Pass the updated description into this method.</li>
* </ol>
*
* <p>
* There are a subset of properties that can be updated. More information can be found in the links below. They are:
* <ul>
* <li>{@link SubscriptionProperties
* <li>{@link SubscriptionProperties
* <li>{@link SubscriptionProperties
* </ul>
*
* @param subscription Information about the subscription to update. You must provide all the property values
* that are desired on the updated entity. Any values not provided are set to the service default values.
*
* @return A Mono that returns the updated subscription in addition to the HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If the request body was invalid, the subscription quota is exceeded, or an
* error occurred processing the request.
* @throws IllegalArgumentException if {@link SubscriptionProperties
* SubscriptionProperties
* @throws NullPointerException if {@code subscription} is null.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<SubscriptionProperties>> updateSubscriptionWithResponse(
SubscriptionProperties subscription) {
return withContext(context -> updateSubscriptionWithResponse(subscription, context));
}
/**
* Updates a topic with the given {@link TopicProperties}. The {@link TopicProperties} must be fully populated as
* all of the properties are replaced. If a property is not set the service default value is used.
*
* The suggested flow is:
* <ol>
* <li>{@link
* <li>Update the required elements.</li>
* <li>Pass the updated description into this method.</li>
* </ol>
*
* <p>
* There are a subset of properties that can be updated. More information can be found in the links below. They are:
* <ul>
* <li>{@link TopicProperties
* <li>{@link TopicProperties
* </li>
* </ul>
*
* @param topic Information about the topic to update. You must provide all the property values that are desired
* on the updated entity. Any values not provided are set to the service default values.
*
* @return A Mono that completes with the updated topic.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If the request body was invalid, the topic quota is exceeded, or an error
* occurred processing the request.
* @throws IllegalArgumentException if {@link TopicProperties
* string.
* @throws NullPointerException if {@code topic} is null.
* @see <a href="https:
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<TopicProperties> updateTopic(TopicProperties topic) {
return updateTopicWithResponse(topic).map(Response::getValue);
}
/**
* Updates a topic with the given {@link TopicProperties}. The {@link TopicProperties} must be fully populated as
* all of the properties are replaced. If a property is not set the service default value is used.
*
* The suggested flow is:
* <ol>
* <li>{@link
* <li>Update the required elements.</li>
* <li>Pass the updated description into this method.</li>
* </ol>
*
* <p>
* There are a subset of properties that can be updated. More information can be found in the links below. They are:
* <ul>
* <li>{@link TopicProperties
* <li>{@link TopicProperties
* </li>
* </ul>
*
* @param topic Information about the topic to update. You must provide all the property values that are desired
* on the updated entity. Any values not provided are set to the service default values.
*
* @return A Mono that completes with the updated topic and its HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If the request body was invalid, the topic quota is exceeded, or an error
* occurred processing the request.
* @throws IllegalArgumentException if {@link TopicProperties
* string.
* @throws NullPointerException if {@code topic} is null.
* @see <a href="https:
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<TopicProperties>> updateTopicWithResponse(TopicProperties topic) {
return withContext(context -> updateTopicWithResponse(topic, context));
}
/**
* Creates a queue with its context.
*
* @param createQueueOptions Queue to create.
* @param context Context to pass into request.
*
* @return A Mono that completes with the created {@link QueueProperties}.
*/
Mono<Response<QueueProperties>> createQueueWithResponse(String queueName, CreateQueueOptions createQueueOptions,
Context context) {
if (queueName == null) {
return monoError(logger, new NullPointerException("'queueName' cannot be null."));
} else if (queueName.isEmpty()) {
return monoError(logger, new IllegalArgumentException("'queueName' cannot be empty."));
}
if (createQueueOptions == null) {
return monoError(logger, new NullPointerException("'createQueueOptions' cannot be null."));
} else if (context == null) {
return monoError(logger, new NullPointerException("'context' cannot be null."));
}
final QueueDescription description = EntityHelper.getQueueDescription(createQueueOptions);
final CreateQueueBodyContent content = new CreateQueueBodyContent()
.setType(CONTENT_TYPE)
.setQueueDescription(description);
final CreateQueueBody createEntity = new CreateQueueBody()
.setContent(content);
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
try {
return entityClient.putWithResponseAsync(queueName, createEntity, null, withTracing)
.onErrorMap(ServiceBusAdministrationAsyncClient::mapException)
.map(this::deserializeQueue);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Creates a rule with its context.
*
* @param ruleOptions Rule to create.
* @param context Context to pass into request.
*
* @return A Mono that completes with the created {@link RuleProperties}.
*/
Mono<Response<RuleProperties>> createRuleWithResponse(String topicName, String subscriptionName, String ruleName,
CreateRuleOptions ruleOptions, Context context) {
if (topicName == null) {
return monoError(logger, new NullPointerException("'topicName' cannot be null."));
} else if (topicName.isEmpty()) {
return monoError(logger, new IllegalArgumentException("'topicName' cannot be empty."));
}
if (subscriptionName == null) {
return monoError(logger, new NullPointerException("'subscriptionName' cannot be null."));
} else if (subscriptionName.isEmpty()) {
return monoError(logger, new IllegalArgumentException("'subscriptionName' cannot be empty."));
}
if (ruleName == null) {
return monoError(logger, new NullPointerException("'ruleName' cannot be null."));
} else if (ruleName.isEmpty()) {
return monoError(logger, new IllegalArgumentException("'ruleName' cannot be empty."));
}
if (ruleOptions == null) {
return monoError(logger, new NullPointerException("'rule' cannot be null."));
}
final RuleActionImpl action = ruleOptions.getAction() != null
? EntityHelper.toImplementation(ruleOptions.getAction())
: null;
final RuleFilterImpl filter = ruleOptions.getFilter() != null
? EntityHelper.toImplementation(ruleOptions.getFilter())
: null;
final RuleDescription rule = new RuleDescription()
.setAction(action)
.setFilter(filter)
.setName(ruleName);
final CreateRuleBodyContent content = new CreateRuleBodyContent()
.setType(CONTENT_TYPE)
.setRuleDescription(rule);
final CreateRuleBody createEntity = new CreateRuleBody().setContent(content);
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
try {
return managementClient.getRules().putWithResponseAsync(topicName, subscriptionName, ruleName, createEntity,
null, withTracing)
.onErrorMap(ServiceBusAdministrationAsyncClient::mapException)
.map(response -> deserializeRule(response));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Creates a subscription with its context.
*
* @param subscriptionOptions Subscription to create.
* @param context Context to pass into request.
*
* @return A Mono that completes with the created {@link SubscriptionProperties}.
*/
Mono<Response<SubscriptionProperties>> createSubscriptionWithResponse(String topicName, String subscriptionName,
CreateSubscriptionOptions subscriptionOptions, Context context) {
if (topicName == null) {
return monoError(logger, new NullPointerException("'topicName' cannot be null."));
} else if (topicName.isEmpty()) {
return monoError(logger, new IllegalArgumentException("'topicName' cannot be empty."));
}
if (subscriptionName == null) {
return monoError(logger, new NullPointerException("'subscriptionName' cannot be null."));
} else if (subscriptionName.isEmpty()) {
return monoError(logger, new IllegalArgumentException("'subscriptionName' cannot be empty."));
}
if (subscriptionOptions == null) {
return monoError(logger, new NullPointerException("'subscription' cannot be null."));
}
final SubscriptionDescription subscription = EntityHelper.getSubscriptionDescription(subscriptionOptions);
final CreateSubscriptionBodyContent content = new CreateSubscriptionBodyContent()
.setType(CONTENT_TYPE)
.setSubscriptionDescription(subscription);
final CreateSubscriptionBody createEntity = new CreateSubscriptionBody().setContent(content);
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
try {
return managementClient.getSubscriptions().putWithResponseAsync(topicName, subscriptionName, createEntity,
null, withTracing)
.onErrorMap(ServiceBusAdministrationAsyncClient::mapException)
.map(response -> deserializeSubscription(topicName, response));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Creates a topicOptions with its context.
*
* @param topicOptions Topic to create.
* @param context Context to pass into request.
*
* @return A Mono that completes with the created {@link TopicProperties}.
*/
Mono<Response<TopicProperties>> createTopicWithResponse(String topicName, CreateTopicOptions topicOptions,
Context context) {
if (topicName == null) {
return monoError(logger, new NullPointerException("'topicName' cannot be null."));
} else if (topicName.isEmpty()) {
return monoError(logger, new IllegalArgumentException("'topicName' cannot be empty."));
}
if (topicOptions == null) {
return monoError(logger, new NullPointerException("'topicOptions' cannot be null"));
} else if (context == null) {
return monoError(logger, new NullPointerException("'context' cannot be null."));
}
final TopicDescription topic = EntityHelper.getTopicDescription(topicOptions);
final CreateTopicBodyContent content = new CreateTopicBodyContent()
.setType(CONTENT_TYPE)
.setTopicDescription(topic);
final CreateTopicBody createEntity = new CreateTopicBody()
.setContent(content);
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
try {
return entityClient.putWithResponseAsync(topicName, createEntity, null, withTracing)
.onErrorMap(ServiceBusAdministrationAsyncClient::mapException)
.map(this::deserializeTopic);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Deletes a queue with its context.
*
* @param queueName Name of queue to delete.
* @param context Context to pass into request.
*
* @return A Mono that completes when the queue is deleted.
*/
Mono<Response<Void>> deleteQueueWithResponse(String queueName, Context context) {
if (queueName == null) {
return monoError(logger, new NullPointerException("'queueName' cannot be null"));
} else if (queueName.isEmpty()) {
return monoError(logger, new IllegalArgumentException("'queueName' cannot be an empty string."));
} else if (context == null) {
return monoError(logger, new NullPointerException("'context' cannot be null."));
}
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
try {
return entityClient.deleteWithResponseAsync(queueName, withTracing)
.onErrorMap(ServiceBusAdministrationAsyncClient::mapException)
.map(response -> {
return new SimpleResponse<>(response.getRequest(), response.getStatusCode(),
response.getHeaders(), null);
});
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Deletes a queue with its context.
*
* @param topicName Name of topic to delete.
* @param subscriptionName Name of the subscription for the rule.
* @param ruleName Name of the rule.
* @param context Context to pass into request.
*
* @return A Mono that completes with the created {@link QueueProperties}.
*/
Mono<Response<Void>> deleteRuleWithResponse(String topicName, String subscriptionName, String ruleName,
Context context) {
if (topicName == null) {
return monoError(logger, new NullPointerException("'topicName' cannot be null"));
} else if (topicName.isEmpty()) {
return monoError(logger, new IllegalArgumentException("'topicName' cannot be an empty string."));
} else if (subscriptionName == null) {
return monoError(logger, new NullPointerException("'subscriptionName' cannot be null"));
} else if (subscriptionName.isEmpty()) {
return monoError(logger, new IllegalArgumentException("'subscriptionName' cannot be an empty string."));
} else if (ruleName == null) {
return monoError(logger, new NullPointerException("'ruleName' cannot be null"));
} else if (ruleName.isEmpty()) {
return monoError(logger, new IllegalArgumentException("'ruleName' cannot be an empty string."));
} else if (context == null) {
return monoError(logger, new NullPointerException("'context' cannot be null."));
}
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
try {
return rulesClient.deleteWithResponseAsync(topicName, subscriptionName, ruleName, withTracing)
.onErrorMap(ServiceBusAdministrationAsyncClient::mapException)
.map(response -> new SimpleResponse<>(response.getRequest(), response.getStatusCode(),
response.getHeaders(), null));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Deletes a subscription with its context.
*
* @param topicName Name of topic associated with subscription to delete.
* @param subscriptionName Name of subscription to delete.
* @param context Context to pass into request.
*
* @return A Mono that completes with the created {@link SubscriptionProperties}.
*/
Mono<Response<Void>> deleteSubscriptionWithResponse(String topicName, String subscriptionName, Context context) {
if (subscriptionName == null) {
return monoError(logger, new NullPointerException("'subscriptionName' cannot be null"));
} else if (subscriptionName.isEmpty()) {
return monoError(logger, new IllegalArgumentException("'subscriptionName' cannot be an empty string."));
} else if (topicName == null) {
return monoError(logger, new NullPointerException("'topicName' cannot be null"));
} else if (topicName.isEmpty()) {
return monoError(logger, new IllegalArgumentException("'topicName' cannot be an empty string."));
} else if (context == null) {
return monoError(logger, new NullPointerException("'context' cannot be null."));
}
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
try {
return managementClient.getSubscriptions().deleteWithResponseAsync(topicName, subscriptionName,
withTracing)
.onErrorMap(ServiceBusAdministrationAsyncClient::mapException)
.map(response -> new SimpleResponse<>(response.getRequest(), response.getStatusCode(),
response.getHeaders(), null));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Deletes a topic with its context.
*
* @param topicName Name of topic to delete.
* @param context Context to pass into request.
*
* @return A Mono that completes with the created {@link TopicProperties}.
*/
Mono<Response<Void>> deleteTopicWithResponse(String topicName, Context context) {
if (topicName == null) {
return monoError(logger, new NullPointerException("'topicName' cannot be null"));
} else if (topicName.isEmpty()) {
return monoError(logger, new IllegalArgumentException("'topicName' cannot be an empty string."));
} else if (context == null) {
return monoError(logger, new NullPointerException("'context' cannot be null."));
}
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
try {
return entityClient.deleteWithResponseAsync(topicName, withTracing)
.onErrorMap(ServiceBusAdministrationAsyncClient::mapException)
.map(response -> new SimpleResponse<>(response.getRequest(), response.getStatusCode(),
response.getHeaders(), null));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Gets whether an entity exists.
*
* @param getEntityOperation Operation to get information about entity. If {@link ResourceNotFoundException} is
* thrown, then it is mapped to false.
* @param <T> Entity type.
*
* @return True if the entity exists, false otherwise.
*/
<T> Mono<Response<Boolean>> getEntityExistsWithResponse(Mono<Response<T>> getEntityOperation) {
return getEntityOperation.map(response -> {
final boolean exists = response.getValue() != null;
return (Response<Boolean>) new SimpleResponse<>(response.getRequest(), response.getStatusCode(),
response.getHeaders(), exists);
})
.onErrorResume(ResourceNotFoundException.class, exception -> {
final HttpResponse response = exception.getResponse();
final Response<Boolean> result = new SimpleResponse<>(response.getRequest(), response.getStatusCode(),
response.getHeaders(), false);
return Mono.just(result);
});
}
/**
* Gets a queue with its context.
*
* @param queueName Name of queue to fetch information for.
* @param context Context to pass into request.
*
* @return A Mono that completes with the {@link QueueProperties}.
*/
<T> Mono<Response<T>> getQueueWithResponse(String queueName, Context context,
Function<QueueProperties, T> mapper) {
if (queueName == null) {
return monoError(logger, new NullPointerException("'queueName' cannot be null"));
} else if (queueName.isEmpty()) {
return monoError(logger, new IllegalArgumentException("'queueName' cannot be empty."));
} else if (context == null) {
return monoError(logger, new NullPointerException("'context' cannot be null."));
}
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
try {
return entityClient.getWithResponseAsync(queueName, true, withTracing)
.onErrorMap(ServiceBusAdministrationAsyncClient::mapException)
.handle((response, sink) -> {
final Response<QueueProperties> deserialize = deserializeQueue(response);
if (deserialize.getValue() == null) {
final HttpResponse notFoundResponse = new EntityNotFoundHttpResponse<>(deserialize);
sink.error(new ResourceNotFoundException(String.format("Queue '%s' does not exist.", queueName),
notFoundResponse));
} else {
final T mapped = mapper.apply(deserialize.getValue());
sink.next(new SimpleResponse<>(response.getRequest(), response.getStatusCode(),
response.getHeaders(), mapped));
}
});
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<RuleProperties>> getRuleWithResponse(String topicName, String subscriptionName,
String ruleName, Context context) {
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
try {
return rulesClient.getWithResponseAsync(topicName, subscriptionName, ruleName, true, withTracing)
.onErrorMap(ServiceBusAdministrationAsyncClient::mapException)
.map(this::deserializeRule);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Gets a subscription with its context.
*
* @param topicName Name of the topic associated with the subscription.
* @param subscriptionName Name of subscription to fetch information for.
* @param context Context to pass into request.
*
* @return A Mono that completes with the {@link SubscriptionProperties}.
*/
<T> Mono<Response<T>> getSubscriptionWithResponse(String topicName, String subscriptionName, Context context,
Function<SubscriptionProperties, T> mapper) {
if (topicName == null) {
return monoError(logger, new NullPointerException("'topicName' cannot be null."));
} else if (topicName.isEmpty()) {
return monoError(logger, new IllegalArgumentException("'topicName' cannot be an empty string."));
} else if (subscriptionName == null) {
return monoError(logger, new NullPointerException("'subscriptionName' cannot be null."));
} else if (subscriptionName.isEmpty()) {
return monoError(logger, new IllegalArgumentException("'subscriptionName' cannot be an empty string."));
} else if (context == null) {
return monoError(logger, new NullPointerException("'context' cannot be null."));
}
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
try {
return managementClient.getSubscriptions().getWithResponseAsync(topicName, subscriptionName, true,
withTracing)
.onErrorMap(ServiceBusAdministrationAsyncClient::mapException)
.handle((response, sink) -> {
final Response<SubscriptionProperties> deserialize = deserializeSubscription(topicName, response);
if (deserialize.getValue() == null) {
final HttpResponse notFoundResponse = new EntityNotFoundHttpResponse<>(deserialize);
sink.error(new ResourceNotFoundException(String.format(
"Subscription '%s' in topic '%s' does not exist.", topicName, subscriptionName),
notFoundResponse));
} else {
final T mapped = mapper.apply(deserialize.getValue());
sink.next(new SimpleResponse<>(response.getRequest(), response.getStatusCode(),
response.getHeaders(), mapped));
}
});
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Gets the namespace properties with its context.
*
* @param context Context to pass into request.
*
* @return A Mono that completes with the {@link NamespaceProperties}.
*/
Mono<Response<NamespaceProperties>> getNamespacePropertiesWithResponse(Context context) {
return managementClient.getNamespaces().getWithResponseAsync(context).handle((response, sink) -> {
final NamespacePropertiesEntry entry = response.getValue();
if (entry == null || entry.getContent() == null) {
sink.error(new AzureException(
"There was no content inside namespace response. Entry: " + response));
return;
}
final NamespaceProperties namespaceProperties = entry.getContent().getNamespaceProperties();
final Response<NamespaceProperties> result = new SimpleResponse<>(response.getRequest(),
response.getStatusCode(), response.getHeaders(), namespaceProperties);
sink.next(result);
});
}
/**
* Gets a topic with its context.
*
* @param topicName Name of topic to fetch information for.
* @param context Context to pass into request.
*
* @return A Mono that completes with the {@link TopicProperties}.
*/
<T> Mono<Response<T>> getTopicWithResponse(String topicName, Context context,
Function<TopicProperties, T> mapper) {
if (topicName == null) {
return monoError(logger, new NullPointerException("'topicName' cannot be null"));
} else if (topicName.isEmpty()) {
return monoError(logger, new IllegalArgumentException("'topicName' cannot be empty."));
} else if (context == null) {
return monoError(logger, new NullPointerException("'context' cannot be null."));
}
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
try {
return entityClient.getWithResponseAsync(topicName, true, withTracing)
.onErrorMap(ServiceBusAdministrationAsyncClient::mapException)
.handle((response, sink) -> {
final Response<TopicProperties> deserialize = deserializeTopic(response);
if (deserialize.getValue() == null) {
final HttpResponse notFoundResponse = new EntityNotFoundHttpResponse<>(deserialize);
sink.error(new ResourceNotFoundException(String.format("Topic '%s' does not exist.", topicName),
notFoundResponse));
} else {
final T mapped = mapper.apply(deserialize.getValue());
sink.next(new SimpleResponse<>(response.getRequest(), response.getStatusCode(),
response.getHeaders(), mapped));
}
});
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Gets the first page of queues with context.
*
* @param context Context to pass into request.
*
* @return A Mono that completes with a page of queues.
*/
Mono<PagedResponse<QueueProperties>> listQueuesFirstPage(Context context) {
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
try {
return listQueues(0, withTracing);
} catch (RuntimeException e) {
return monoError(logger, e);
}
}
/**
* Gets the next page of queues with context.
*
* @param continuationToken Number of items to skip in feed.
* @param context Context to pass into request.
*
* @return A Mono that completes with a page of queues or empty if there are no items left.
*/
Mono<PagedResponse<QueueProperties>> listQueuesNextPage(String continuationToken, Context context) {
if (continuationToken == null || continuationToken.isEmpty()) {
return Mono.empty();
}
try {
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
final int skip = Integer.parseInt(continuationToken);
return listQueues(skip, withTracing);
} catch (RuntimeException e) {
return monoError(logger, e);
}
}
/**
* Gets the first page of rules with context.
*
* @param context Context to pass into request.
*
* @return A Mono that completes with a page of rules.
*/
Mono<PagedResponse<RuleProperties>> listRulesFirstPage(String topicName, String subscriptionName, Context context) {
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
try {
return listRules(topicName, subscriptionName, 0, withTracing);
} catch (RuntimeException e) {
return monoError(logger, e);
}
}
/**
* Gets the next page of rules with context.
*
* @param continuationToken Number of items to skip in feed.
* @param context Context to pass into request.
*
* @return A Mono that completes with a page of rules or empty if there are no items left.
*/
Mono<PagedResponse<RuleProperties>> listRulesNextPage(String topicName, String subscriptionName,
String continuationToken, Context context) {
if (continuationToken == null || continuationToken.isEmpty()) {
return Mono.empty();
}
try {
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
final int skip = Integer.parseInt(continuationToken);
return listRules(topicName, subscriptionName, skip, withTracing);
} catch (RuntimeException e) {
return monoError(logger, e);
}
}
/**
* Gets the first page of subscriptions with context.
*
* @param context Context to pass into request.
*
* @return A Mono that completes with a page of subscriptions.
*/
Mono<PagedResponse<SubscriptionProperties>> listSubscriptionsFirstPage(String topicName, Context context) {
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
try {
return listSubscriptions(topicName, 0, withTracing);
} catch (RuntimeException e) {
return monoError(logger, e);
}
}
/**
* Gets the next page of subscriptions with context.
*
* @param continuationToken Number of items to skip in feed.
* @param context Context to pass into request.
*
* @return A Mono that completes with a page of subscriptions or empty if there are no items left.
*/
Mono<PagedResponse<SubscriptionProperties>> listSubscriptionsNextPage(String topicName, String continuationToken,
Context context) {
if (continuationToken == null || continuationToken.isEmpty()) {
return Mono.empty();
}
try {
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
final int skip = Integer.parseInt(continuationToken);
return listSubscriptions(topicName, skip, withTracing);
} catch (RuntimeException e) {
return monoError(logger, e);
}
}
/**
* Gets the first page of topics with context.
*
* @param context Context to pass into request.
*
* @return A Mono that completes with a page of topics.
*/
Mono<PagedResponse<TopicProperties>> listTopicsFirstPage(Context context) {
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
try {
return listTopics(0, withTracing);
} catch (RuntimeException e) {
return monoError(logger, e);
}
}
/**
* Gets the next page of topics with context.
*
* @param continuationToken Number of items to skip in feed.
* @param context Context to pass into request.
*
* @return A Mono that completes with a page of topics or empty if there are no items left.
*/
Mono<PagedResponse<TopicProperties>> listTopicsNextPage(String continuationToken, Context context) {
if (continuationToken == null || continuationToken.isEmpty()) {
return Mono.empty();
}
try {
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
final int skip = Integer.parseInt(continuationToken);
return listTopics(skip, withTracing);
} catch (RuntimeException e) {
return monoError(logger, e);
}
}
/**
* Updates a queue with its context.
*
* @param queue Information about the queue to update. You must provide all the property values that are desired
* on the updated entity. Any values not provided are set to the service default values.
* @param context Context to pass into request.
*
* @return A Mono that completes with the updated {@link QueueProperties}.
*/
Mono<Response<QueueProperties>> updateQueueWithResponse(QueueProperties queue, Context context) {
if (queue == null) {
return monoError(logger, new NullPointerException("'queue' cannot be null"));
} else if (context == null) {
return monoError(logger, new NullPointerException("'context' cannot be null."));
}
final QueueDescription queueDescription = EntityHelper.toImplementation(queue);
final CreateQueueBodyContent content = new CreateQueueBodyContent()
.setType(CONTENT_TYPE)
.setQueueDescription(queueDescription);
final CreateQueueBody createEntity = new CreateQueueBody()
.setContent(content);
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
try {
return entityClient.putWithResponseAsync(queue.getName(), createEntity, "*", withTracing)
.onErrorMap(ServiceBusAdministrationAsyncClient::mapException)
.map(response -> deserializeQueue(response));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Updates a rule with its context.
*
* @param rule Information about the rule to update. You must provide all the property values that are desired
* on the updated entity. Any values not provided are set to the service default values.
* @param context Context to pass into request.
*
* @return A Mono that completes with the updated {@link RuleProperties}.
*/
Mono<Response<RuleProperties>> updateRuleWithResponse(String topicName, String subscriptionName,
RuleProperties rule, Context context) {
if (rule == null) {
return monoError(logger, new NullPointerException("'rule' cannot be null"));
} else if (context == null) {
return monoError(logger, new NullPointerException("'context' cannot be null."));
}
final RuleDescription implementation = EntityHelper.toImplementation(rule);
final CreateRuleBodyContent content = new CreateRuleBodyContent()
.setType(CONTENT_TYPE)
.setRuleDescription(implementation);
final CreateRuleBody ruleBody = new CreateRuleBody()
.setContent(content);
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
try {
return managementClient.getRules().putWithResponseAsync(topicName, subscriptionName, rule.getName(),
ruleBody, "*", withTracing)
.onErrorMap(ServiceBusAdministrationAsyncClient::mapException)
.map(response -> deserializeRule(response));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Updates a subscription with its context.
*
* @param subscription Information about the subscription to update. You must provide all the property values
* that are desired on the updated entity. Any values not provided are set to the service default values.
* @param context Context to pass into request.
*
* @return A Mono that completes with the updated {@link SubscriptionProperties}.
*/
Mono<Response<SubscriptionProperties>> updateSubscriptionWithResponse(SubscriptionProperties subscription,
Context context) {
if (subscription == null) {
return monoError(logger, new NullPointerException("'subscription' cannot be null"));
} else if (context == null) {
return monoError(logger, new NullPointerException("'context' cannot be null."));
}
final String topicName = subscription.getTopicName();
final String subscriptionName = subscription.getSubscriptionName();
final SubscriptionDescription implementation = EntityHelper.toImplementation(subscription);
final CreateSubscriptionBodyContent content = new CreateSubscriptionBodyContent()
.setType(CONTENT_TYPE)
.setSubscriptionDescription(implementation);
final CreateSubscriptionBody createEntity = new CreateSubscriptionBody()
.setContent(content);
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
try {
return managementClient.getSubscriptions().putWithResponseAsync(topicName, subscriptionName, createEntity,
"*", withTracing)
.onErrorMap(ServiceBusAdministrationAsyncClient::mapException)
.map(response -> deserializeSubscription(topicName, response));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Updates a topic with its context.
*
* @param topic Information about the topic to update. You must provide all the property values that are desired
* on the updated entity. Any values not provided are set to the service default values.
* @param context Context to pass into request.
*
* @return A Mono that completes with the updated {@link TopicProperties}.
*/
Mono<Response<TopicProperties>> updateTopicWithResponse(TopicProperties topic, Context context) {
if (topic == null) {
return monoError(logger, new NullPointerException("'topic' cannot be null"));
} else if (context == null) {
return monoError(logger, new NullPointerException("'context' cannot be null."));
}
final TopicDescription implementation = EntityHelper.toImplementation(topic);
final CreateTopicBodyContent content = new CreateTopicBodyContent()
.setType(CONTENT_TYPE)
.setTopicDescription(implementation);
final CreateTopicBody createEntity = new CreateTopicBody()
.setContent(content);
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
try {
return entityClient.putWithResponseAsync(topic.getName(), createEntity, "*", withTracing)
.onErrorMap(ServiceBusAdministrationAsyncClient::mapException)
.map(response -> deserializeTopic(response));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
private <T> T deserialize(Object object, Class<T> clazz) {
if (object == null) {
return null;
}
final String contents = String.valueOf(object);
if (contents.isEmpty()) {
return null;
}
try {
return serializer.deserialize(contents, clazz);
} catch (IOException e) {
throw logger.logExceptionAsError(new RuntimeException(String.format(
"Exception while deserializing. Body: [%s]. Class: %s", contents, clazz), e));
}
}
/**
* Given an HTTP response, will deserialize it into a strongly typed Response object.
*
* @param response HTTP response to deserialize response body from.
* @param clazz Class to deserialize response type into.
* @param <T> Class type to deserialize response into.
*
* @return A Response with a strongly typed response value.
*/
private <T> Response<T> deserialize(Response<Object> response, Class<T> clazz) {
final T deserialize = deserialize(response.getValue(), clazz);
return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(),
deserialize);
}
/**
* Converts a Response into its corresponding {@link QueueDescriptionEntry} then mapped into {@link
* QueueProperties}.
*
* @param response HTTP Response to deserialize.
*
* @return The corresponding HTTP response with convenience properties set.
*/
/**
* Converts a Response into its corresponding {@link RuleDescriptionEntry} then mapped into {@link RuleProperties}.
*
* @param response HTTP Response to deserialize.
*
* @return The corresponding HTTP response with convenience properties set.
*/
private Response<RuleProperties> deserializeRule(Response<Object> response) {
final RuleDescriptionEntry entry = deserialize(response.getValue(), RuleDescriptionEntry.class);
if (entry == null) {
return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null);
} else if (entry.getContent() == null) {
logger.info("entry.getContent() is null. The entity may not exist. {}", entry);
return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null);
}
final RuleDescription description = entry.getContent().getRuleDescription();
final RuleProperties result = EntityHelper.toModel(description);
return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), result);
}
/**
* Converts a Response into its corresponding {@link SubscriptionDescriptionEntry} then mapped into {@link
* SubscriptionProperties}.
*
* @param response HTTP Response to deserialize.
*
* @return The corresponding HTTP response with convenience properties set.
*/
private Response<SubscriptionProperties> deserializeSubscription(String topicName, Response<Object> response) {
final SubscriptionDescriptionEntry entry = deserialize(response.getValue(), SubscriptionDescriptionEntry.class);
if (entry == null) {
return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null);
} else if (entry.getContent() == null) {
logger.warning("entry.getContent() is null. There should have been content returned. Entry: {}", entry);
return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null);
}
final SubscriptionProperties subscription = EntityHelper.toModel(
entry.getContent().getSubscriptionDescription());
final String subscriptionName = getTitleValue(entry.getTitle());
EntityHelper.setSubscriptionName(subscription, subscriptionName);
EntityHelper.setTopicName(subscription, topicName);
return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(),
subscription);
}
/**
* Converts a Response into its corresponding {@link TopicDescriptionEntry} then mapped into {@link
* QueueProperties}.
*
* @param response HTTP Response to deserialize.
*
* @return The corresponding HTTP response with convenience properties set.
*/
private Response<TopicProperties> deserializeTopic(Response<Object> response) {
final TopicDescriptionEntry entry = deserialize(response.getValue(), TopicDescriptionEntry.class);
if (entry == null) {
return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null);
} else if (entry.getContent() == null) {
logger.warning("entry.getContent() is null. There should have been content returned. Entry: {}", entry);
return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null);
} else if (entry.getContent().getTopicDescription() == null) {
final QueueDescriptionEntry entryQueue = deserialize(response.getValue(), QueueDescriptionEntry.class);
if (entryQueue != null && entryQueue.getContent() != null && entryQueue.getContent().getQueueDescription() != null) {
logger.warning("'{}' is not a topic, it is a queue.", entryQueue.getTitle());
return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null);
}
}
final TopicProperties result = EntityHelper.toModel(entry.getContent().getTopicDescription());
final String topicName = getTitleValue(entry.getTitle());
EntityHelper.setTopicName(result, topicName);
return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), result);
}
/**
* Creates a {@link FeedPage} given the elements and a set of response links to get the next link from.
*
* @param entities Entities in the feed.
* @param responseLinks Links returned from the feed.
* @param <TResult> Type of Service Bus entities in page.
*
* @return A {@link FeedPage} indicating whether this can be continued or not.
* @throws MalformedURLException if the "next" page link does not contain a well-formed URL.
*/
private <TResult, TFeed> FeedPage<TResult> extractPage(Response<TFeed> response, List<TResult> entities,
List<ResponseLink> responseLinks)
throws MalformedURLException, UnsupportedEncodingException {
final Optional<ResponseLink> nextLink = responseLinks.stream()
.filter(link -> link.getRel().equalsIgnoreCase("next"))
.findFirst();
if (!nextLink.isPresent()) {
return new FeedPage<>(response.getStatusCode(), response.getHeaders(), response.getRequest(), entities);
}
final URL url = new URL(nextLink.get().getHref());
final String decode = URLDecoder.decode(url.getQuery(), StandardCharsets.UTF_8.name());
final Optional<Integer> skipParameter = Arrays.stream(decode.split("&|&"))
.map(part -> part.split("=", 2))
.filter(parts -> parts[0].equalsIgnoreCase("$skip") && parts.length == 2)
.map(parts -> Integer.valueOf(parts[1]))
.findFirst();
if (skipParameter.isPresent()) {
return new FeedPage<>(response.getStatusCode(), response.getHeaders(), response.getRequest(), entities,
skipParameter.get());
} else {
logger.warning("There should have been a skip parameter for the next page.");
return new FeedPage<>(response.getStatusCode(), response.getHeaders(), response.getRequest(), entities);
}
}
/**
* Helper method that invokes the service method, extracts the data and translates it to a PagedResponse.
*
* @param skip Number of elements to skip.
* @param context Context for the query.
*
* @return A Mono that completes with a paged response of queues.
*/
private Mono<PagedResponse<QueueProperties>> listQueues(int skip, Context context) {
return managementClient.listEntitiesWithResponseAsync(QUEUES_ENTITY_TYPE, skip, NUMBER_OF_ELEMENTS, context)
.onErrorMap(ServiceBusAdministrationAsyncClient::mapException)
.flatMap(response -> {
final Response<QueueDescriptionFeed> feedResponse = deserialize(response, QueueDescriptionFeed.class);
final QueueDescriptionFeed feed = feedResponse.getValue();
if (feed == null) {
logger.warning("Could not deserialize QueueDescriptionFeed. skip {}, top: {}", skip,
NUMBER_OF_ELEMENTS);
return Mono.empty();
}
final List<QueueProperties> entities = feed.getEntry().stream()
.filter(e -> e.getContent() != null && e.getContent().getQueueDescription() != null)
.map(e -> {
final String queueName = getTitleValue(e.getTitle());
final QueueProperties queueProperties = EntityHelper.toModel(
e.getContent().getQueueDescription());
EntityHelper.setQueueName(queueProperties, queueName);
return queueProperties;
})
.collect(Collectors.toList());
try {
return Mono.just(extractPage(feedResponse, entities, feed.getLink()));
} catch (MalformedURLException | UnsupportedEncodingException error) {
return Mono.error(new RuntimeException("Could not parse response into FeedPage<QueueDescription>",
error));
}
});
}
/**
* Helper method that invokes the service method, extracts the data and translates it to a PagedResponse.
*
* @param skip Number of elements to skip.
* @param context Context for the query.
*
* @return A Mono that completes with a paged response of rules.
*/
private Mono<PagedResponse<RuleProperties>> listRules(String topicName, String subscriptionName, int skip,
Context context) {
return managementClient.listRulesWithResponseAsync(topicName, subscriptionName, skip, NUMBER_OF_ELEMENTS,
context)
.onErrorMap(ServiceBusAdministrationAsyncClient::mapException)
.flatMap(response -> {
final Response<RuleDescriptionFeed> feedResponse = deserialize(response,
RuleDescriptionFeed.class);
final RuleDescriptionFeed feed = feedResponse.getValue();
if (feed == null) {
logger.warning("Could not deserialize RuleDescriptionFeed. skip {}, top: {}", skip,
NUMBER_OF_ELEMENTS);
return Mono.empty();
}
final List<RuleProperties> entities = feed.getEntry().stream()
.filter(e -> e.getContent() != null && e.getContent().getRuleDescription() != null)
.map(e -> {
return EntityHelper.toModel(e.getContent().getRuleDescription());
})
.collect(Collectors.toList());
try {
return Mono.just(extractPage(feedResponse, entities, feed.getLink()));
} catch (MalformedURLException | UnsupportedEncodingException error) {
return Mono.error(new RuntimeException(
"Could not parse response into FeedPage<RuleDescription>", error));
}
});
}
/**
* Helper method that invokes the service method, extracts the data and translates it to a PagedResponse.
*
* @param skip Number of elements to skip.
* @param context Context for the query.
*
* @return A Mono that completes with a paged response of subscriptions.
*/
private Mono<PagedResponse<SubscriptionProperties>> listSubscriptions(String topicName, int skip,
Context context) {
return managementClient.listSubscriptionsWithResponseAsync(topicName, skip, NUMBER_OF_ELEMENTS, context)
.onErrorMap(ServiceBusAdministrationAsyncClient::mapException)
.flatMap(response -> {
final Response<SubscriptionDescriptionFeed> feedResponse = deserialize(response,
SubscriptionDescriptionFeed.class);
final SubscriptionDescriptionFeed feed = feedResponse.getValue();
if (feed == null) {
logger.warning("Could not deserialize SubscriptionDescriptionFeed. skip {}, top: {}", skip,
NUMBER_OF_ELEMENTS);
return Mono.empty();
}
final List<SubscriptionProperties> entities = feed.getEntry().stream()
.filter(e -> e.getContent() != null && e.getContent().getSubscriptionDescription() != null)
.map(e -> {
final String subscriptionName = getTitleValue(e.getTitle());
final SubscriptionProperties description = EntityHelper.toModel(
e.getContent().getSubscriptionDescription());
EntityHelper.setTopicName(description, topicName);
EntityHelper.setSubscriptionName(description, subscriptionName);
return description;
})
.collect(Collectors.toList());
try {
return Mono.just(extractPage(feedResponse, entities, feed.getLink()));
} catch (MalformedURLException | UnsupportedEncodingException error) {
return Mono.error(new RuntimeException(
"Could not parse response into FeedPage<SubscriptionDescription>", error));
}
});
}
/**
* Helper method that invokes the service method, extracts the data and translates it to a PagedResponse.
*
* @param skip Number of elements to skip.
* @param context Context for the query.
*
* @return A Mono that completes with a paged response of topics.
*/
private Mono<PagedResponse<TopicProperties>> listTopics(int skip, Context context) {
return managementClient.listEntitiesWithResponseAsync(TOPICS_ENTITY_TYPE, skip, NUMBER_OF_ELEMENTS, context)
.onErrorMap(ServiceBusAdministrationAsyncClient::mapException)
.flatMap(response -> {
final Response<TopicDescriptionFeed> feedResponse = deserialize(response, TopicDescriptionFeed.class);
final TopicDescriptionFeed feed = feedResponse.getValue();
if (feed == null) {
logger.warning("Could not deserialize TopicDescriptionFeed. skip {}, top: {}", skip,
NUMBER_OF_ELEMENTS);
return Mono.empty();
}
final List<TopicProperties> entities = feed.getEntry().stream()
.filter(e -> e.getContent() != null && e.getContent().getTopicDescription() != null)
.map(e -> {
final String topicName = getTitleValue(e.getTitle());
final TopicProperties topicProperties = EntityHelper.toModel(
e.getContent().getTopicDescription());
EntityHelper.setTopicName(topicProperties, topicName);
return topicProperties;
})
.collect(Collectors.toList());
try {
return Mono.just(extractPage(feedResponse, entities, feed.getLink()));
} catch (MalformedURLException | UnsupportedEncodingException error) {
return Mono.error(new RuntimeException("Could not parse response into FeedPage<TopicDescription>",
error));
}
});
}
/**
* Given an XML title element, returns the XML text inside. Jackson deserializes Objects as LinkedHashMaps. XML text
* is represented as an entry with an empty string as the key.
*
* For example, the text returned from this {@code <title text="text/xml">QueueName</title>} is "QueueName".
*
* @param responseTitle XML title element.
*
* @return The XML text inside the title. {@code null} is returned if there is no value.
*/
@SuppressWarnings("unchecked")
private String getTitleValue(Object responseTitle) {
if (!(responseTitle instanceof Map)) {
return null;
}
final Map<String, String> map;
try {
map = (Map<String, String>) responseTitle;
return map.get("");
} catch (ClassCastException error) {
logger.warning("Unable to cast to Map<String,String>. Title: {}", responseTitle, error);
return null;
}
}
/**
* Maps an exception from the ATOM APIs to its associated {@link HttpResponseException}.
*
* @param exception Exception from the ATOM API.
*
* @return The corresponding {@link HttpResponseException} or {@code throwable} if it is not an instance of {@link
* ServiceBusManagementErrorException}.
*/
private static Throwable mapException(Throwable exception) {
if (!(exception instanceof ServiceBusManagementErrorException)) {
return exception;
}
final ServiceBusManagementErrorException managementError = ((ServiceBusManagementErrorException) exception);
final ServiceBusManagementError error = managementError.getValue();
final HttpResponse errorHttpResponse = managementError.getResponse();
final int statusCode = error != null && error.getCode() != null
? error.getCode()
: errorHttpResponse.getStatusCode();
final String errorDetail = error != null && error.getDetail() != null
? error.getDetail()
: managementError.getMessage();
switch (statusCode) {
case 401:
return new ClientAuthenticationException(errorDetail, managementError.getResponse(), exception);
case 404:
return new ResourceNotFoundException(errorDetail, managementError.getResponse(), exception);
case 409:
return new ResourceExistsException(errorDetail, managementError.getResponse(), exception);
case 412:
return new ResourceModifiedException(errorDetail, managementError.getResponse(), exception);
default:
return new HttpResponseException(errorDetail, managementError.getResponse(), exception);
}
}
/**
* A page of Service Bus entities.
*
* @param <T> The entity description from Service Bus.
*/
private static final class FeedPage<T> implements PagedResponse<T> {
private final int statusCode;
private final HttpHeaders header;
private final HttpRequest request;
private final IterableStream<T> entries;
private final String continuationToken;
/**
* Creates a page that does not have any more pages.
*
* @param entries Items in the page.
*/
private FeedPage(int statusCode, HttpHeaders header, HttpRequest request, List<T> entries) {
this.statusCode = statusCode;
this.header = header;
this.request = request;
this.entries = new IterableStream<>(entries);
this.continuationToken = null;
}
/**
* Creates an instance that has additional pages to fetch.
*
* @param entries Items in the page.
* @param skip Number of elements to "skip".
*/
private FeedPage(int statusCode, HttpHeaders header, HttpRequest request, List<T> entries, int skip) {
this.statusCode = statusCode;
this.header = header;
this.request = request;
this.entries = new IterableStream<>(entries);
this.continuationToken = String.valueOf(skip);
}
@Override
public IterableStream<T> getElements() {
return entries;
}
@Override
public String getContinuationToken() {
return continuationToken;
}
@Override
public int getStatusCode() {
return statusCode;
}
@Override
public HttpHeaders getHeaders() {
return header;
}
@Override
public HttpRequest getRequest() {
return request;
}
@Override
public void close() {
}
}
private static final class EntityNotFoundHttpResponse<T> extends HttpResponse {
private final int statusCode;
private final HttpHeaders headers;
private EntityNotFoundHttpResponse(Response<T> response) {
super(response.getRequest());
this.headers = response.getHeaders();
this.statusCode = response.getStatusCode();
}
@Override
public int getStatusCode() {
return statusCode;
}
@Override
public String getHeaderValue(String name) {
return headers.getValue(name);
}
@Override
public HttpHeaders getHeaders() {
return headers;
}
@Override
public Flux<ByteBuffer> getBody() {
return Flux.empty();
}
@Override
public Mono<byte[]> getBodyAsByteArray() {
return Mono.empty();
}
@Override
public Mono<String> getBodyAsString() {
return Mono.empty();
}
@Override
public Mono<String> getBodyAsString(Charset charset) {
return Mono.empty();
}
}
} |
That is inline with what the existing logic does, so yes. | private Response<QueueProperties> deserializeQueue(Response<Object> response) {
final QueueDescriptionEntry entry = deserialize(response.getValue(), QueueDescriptionEntry.class);
if (entry == null) {
return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null);
} else if (entry.getContent() == null) {
logger.info("entry.getContent() is null. The entity may not exist. {}", entry);
return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null);
} else if (entry.getContent().getQueueDescription() == null) {
final TopicDescriptionEntry entryTopic = deserialize(response.getValue(), TopicDescriptionEntry.class);
if (entryTopic != null && entryTopic.getContent() != null && entryTopic.getContent().getTopicDescription() != null) {
throw logger.logExceptionAsError(
new RuntimeException(String.format("'[%s]' is not a queue, it is a topic.", entryTopic.getTitle())));
}
}
final QueueProperties result = EntityHelper.toModel(entry.getContent().getQueueDescription());
final String queueName = getTitleValue(entry.getTitle());
EntityHelper.setQueueName(result, queueName);
return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), result);
} | new RuntimeException(String.format("'[%s]' is not a queue, it is a topic.", entryTopic.getTitle()))); | private Response<QueueProperties> deserializeQueue(Response<Object> response) {
final QueueDescriptionEntry entry = deserialize(response.getValue(), QueueDescriptionEntry.class);
if (entry == null) {
return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null);
} else if (entry.getContent() == null) {
logger.info("entry.getContent() is null. The entity may not exist. {}", entry);
return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null);
} else if (entry.getContent().getQueueDescription() == null) {
final TopicDescriptionEntry entryTopic = deserialize(response.getValue(), TopicDescriptionEntry.class);
if (entryTopic != null && entryTopic.getContent() != null && entryTopic.getContent().getTopicDescription() != null) {
logger.warning("'{}' is not a queue, it is a topic.", entryTopic.getTitle());
return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null);
}
}
final QueueProperties result = EntityHelper.toModel(entry.getContent().getQueueDescription());
final String queueName = getTitleValue(entry.getTitle());
EntityHelper.setQueueName(result, queueName);
return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), result);
} | class ServiceBusAdministrationAsyncClient {
private static final String SERVICE_BUS_TRACING_NAMESPACE_VALUE = "Microsoft.ServiceBus";
private static final String CONTENT_TYPE = "application/xml";
private static final String QUEUES_ENTITY_TYPE = "queues";
private static final String TOPICS_ENTITY_TYPE = "topics";
private static final int NUMBER_OF_ELEMENTS = 100;
private final ServiceBusManagementClientImpl managementClient;
private final EntitiesImpl entityClient;
private final ClientLogger logger = new ClientLogger(ServiceBusAdministrationAsyncClient.class);
private final ServiceBusManagementSerializer serializer;
private final RulesImpl rulesClient;
/**
* Creates a new instance with the given management client and serializer.
*
* @param managementClient Client to make management calls.
* @param serializer Serializer to deserialize ATOM XML responses.
*/
ServiceBusAdministrationAsyncClient(ServiceBusManagementClientImpl managementClient,
ServiceBusManagementSerializer serializer) {
this.serializer = Objects.requireNonNull(serializer, "'serializer' cannot be null.");
this.managementClient = Objects.requireNonNull(managementClient, "'managementClient' cannot be null.");
this.entityClient = managementClient.getEntities();
this.rulesClient = managementClient.getRules();
}
/**
* Creates a queue with the given name.
*
* @param queueName Name of the queue to create.
*
* @return A Mono that completes with information about the created queue.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If the request body was invalid, the queue quota is exceeded, or an error
* occurred processing the request.
* @throws NullPointerException if {@code queueName} is null.
* @throws IllegalArgumentException if {@code queueName} is an empty string.
* @throws ResourceExistsException if a queue exists with the same {@code queueName}.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<QueueProperties> createQueue(String queueName) {
try {
return createQueue(queueName, new CreateQueueOptions());
} catch (RuntimeException e) {
return monoError(logger, e);
}
}
/**
* Creates a queue with the {@link CreateQueueOptions} and given queue name.
*
* @param queueName Name of the queue to create.
* @param queueOptions Options about the queue to create.
*
* @return A Mono that completes with information about the created queue.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If the request body was invalid, the queue quota is exceeded, or an error
* occurred processing the request.
* @throws IllegalArgumentException if {@code queueName} is an empty string.
* @throws NullPointerException if {@code queueName} or {@code queueOptions} is null.
* @throws ResourceExistsException if a queue exists with the same {@link QueueProperties
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<QueueProperties> createQueue(String queueName, CreateQueueOptions queueOptions) {
return createQueueWithResponse(queueName, queueOptions).map(Response::getValue);
}
/**
* Creates a queue and returns the created queue in addition to the HTTP response.
*
* @param queueName Name of the queue to create.
* @param queueOptions Options about the queue to create.
*
* @return A Mono that returns the created queue in addition to the HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If the request body was invalid, the queue quota is exceeded, or an error
* occurred processing the request.
* @throws IllegalArgumentException if {@code queueName} is an empty string.
* @throws NullPointerException if {@code queueName} or {@code queueOptions} is null.
* @throws ResourceExistsException if a queue exists with the same {@link QueueProperties
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<QueueProperties>> createQueueWithResponse(String queueName, CreateQueueOptions queueOptions) {
return withContext(context -> createQueueWithResponse(queueName, queueOptions, context));
}
/**
* Creates a rule under the given topic and subscription
*
* @param topicName Name of the topic associated with rule.
* @param subscriptionName Name of the subscription associated with the rule.
* @param ruleName Name of the rule.
*
* @return A Mono that completes with information about the created rule.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If the request body was invalid, the quota is exceeded, or an error occurred
* processing the request.
* @throws IllegalArgumentException if {@code topicName} or {@code ruleName} are are empty strings.
* @throws NullPointerException if {@code topicName} or {@code ruleName} are are null.
* @throws ResourceExistsException if a rule exists with the same topic, subscription, and rule name.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<RuleProperties> createRule(String topicName, String subscriptionName, String ruleName) {
try {
return createRule(topicName, subscriptionName, ruleName, new CreateRuleOptions());
} catch (RuntimeException e) {
return monoError(logger, e);
}
}
/**
* Creates a rule with the {@link CreateRuleOptions}.
*
* @param topicName Name of the topic associated with rule.
* @param subscriptionName Name of the subscription associated with the rule.
* @param ruleName Name of the rule.
* @param ruleOptions Information about the rule to create.
*
* @return A Mono that completes with information about the created rule.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If the request body was invalid, the quota is exceeded, or an error occurred
* processing the request.
* @throws IllegalArgumentException if {@code topicName} or {@code ruleName} are are empty strings.
* @throws NullPointerException if {@code topicName}, {@code ruleName}, or {@code ruleOptions}
* are are null.
* @throws ResourceExistsException if a rule exists with the same topic and rule name.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<RuleProperties> createRule(String topicName, String subscriptionName, String ruleName,
CreateRuleOptions ruleOptions) {
return createRuleWithResponse(topicName, subscriptionName, ruleName, ruleOptions)
.map(Response::getValue);
}
/**
* Creates a rule and returns the created rule in addition to the HTTP response.
*
* @param topicName Name of the topic associated with rule.
* @param subscriptionName Name of the subscription associated with the rule.
* @param ruleName Name of the rule.
* @param ruleOptions Information about the rule to create.
*
* @return A Mono that returns the created rule in addition to the HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If the request body was invalid, the quota is exceeded, or an error occurred
* processing the request.
* @throws IllegalArgumentException if {@code topicName} or {@code ruleName} are are empty strings.
* @throws NullPointerException if {@code topicName}, {@code ruleName}, or {@code ruleOptions}
* are are null.
* @throws ResourceExistsException if a rule exists with the same topic and rule name.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<RuleProperties>> createRuleWithResponse(String topicName, String subscriptionName,
String ruleName, CreateRuleOptions ruleOptions) {
return withContext(context -> createRuleWithResponse(topicName, subscriptionName, ruleName, ruleOptions,
context));
}
/**
* Creates a subscription with the given topic and subscription names.
*
* @param topicName Name of the topic associated with subscription.
* @param subscriptionName Name of the subscription.
*
* @return A Mono that completes with information about the created subscription.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If the request body was invalid, the quota is exceeded, or an error occurred
* processing the request.
* @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} are are empty strings.
* @throws NullPointerException if {@code topicName} or {@code subscriptionName} are are null.
* @throws ResourceExistsException if a subscription exists with the same topic and subscription name.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<SubscriptionProperties> createSubscription(String topicName, String subscriptionName) {
try {
return createSubscription(topicName, subscriptionName, new CreateSubscriptionOptions());
} catch (RuntimeException e) {
return monoError(logger, e);
}
}
/**
* Creates a subscription with the {@link CreateSubscriptionOptions}.
*
* @param topicName Name of the topic associated with subscription.
* @param subscriptionName Name of the subscription.
* @param subscriptionOptions Information about the subscription to create.
*
* @return A Mono that completes with information about the created subscription.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If the request body was invalid, the quota is exceeded, or an error occurred
* processing the request.
* @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} are are empty strings.
* @throws NullPointerException if {@code topicName}, {@code subscriptionName}, or {@code subscriptionOptions}
* are are null.
* @throws ResourceExistsException if a subscription exists with the same topic and subscription name.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<SubscriptionProperties> createSubscription(String topicName, String subscriptionName,
CreateSubscriptionOptions subscriptionOptions) {
return createSubscriptionWithResponse(topicName, subscriptionName, subscriptionOptions)
.map(Response::getValue);
}
/**
* Creates a subscription and returns the created subscription in addition to the HTTP response.
*
* @param topicName Name of the topic associated with subscription.
* @param subscriptionName Name of the subscription.
* @param subscriptionOptions Information about the subscription to create.
*
* @return A Mono that returns the created subscription in addition to the HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If the request body was invalid, the quota is exceeded, or an error occurred
* processing the request.
* @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} are are empty strings.
* @throws NullPointerException if {@code topicName}, {@code subscriptionName}, or {@code subscriptionOptions}
* are are null.
* @throws ResourceExistsException if a subscription exists with the same topic and subscription name.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<SubscriptionProperties>> createSubscriptionWithResponse(String topicName,
String subscriptionName, CreateSubscriptionOptions subscriptionOptions) {
return withContext(context -> createSubscriptionWithResponse(topicName, subscriptionName, subscriptionOptions,
context));
}
/**
* Creates a topic with the given name.
*
* @param topicName Name of the topic to create.
*
* @return A Mono that completes with information about the created topic.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If the request body was invalid, the topic quota is exceeded, or an error
* occurred processing the request.
* @throws NullPointerException if {@code topicName} is null.
* @throws IllegalArgumentException if {@code topicName} is an empty string.
* @throws ResourceExistsException if a topic exists with the same {@code topicName}.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<TopicProperties> createTopic(String topicName) {
try {
return createTopic(topicName, new CreateTopicOptions());
} catch (RuntimeException e) {
return monoError(logger, e);
}
}
/**
* Creates a topic with the {@link CreateTopicOptions}.
*
* @param topicName Name of the topic to create.
* @param topicOptions The options used to create the topic.
*
* @return A Mono that completes with information about the created topic.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If the request body was invalid, the topic quota is exceeded, or an error
* occurred processing the request.
* @throws IllegalArgumentException if {@code topicName} is an empty string.
* @throws NullPointerException if {@code topicName} or {@code topicOptions} is null.
* @throws ResourceExistsException if a topic exists with the same {@code topicName}.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<TopicProperties> createTopic(String topicName, CreateTopicOptions topicOptions) {
return createTopicWithResponse(topicName, topicOptions).map(Response::getValue);
}
/**
* Creates a topic and returns the created topic in addition to the HTTP response.
*
* @param topicName Name of the topic to create.
* @param topicOptions The options used to create the topic.
*
* @return A Mono that returns the created topic in addition to the HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If the request body was invalid, the topic quota is exceeded, or an error
* occurred processing the request.
* @throws IllegalArgumentException if {@link TopicProperties
* string.
* @throws NullPointerException if {@code topicName} or {@code topicOptions} is null.
* @throws ResourceExistsException if a topic exists with the same {@code topicName}.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<TopicProperties>> createTopicWithResponse(String topicName, CreateTopicOptions topicOptions) {
return withContext(context -> createTopicWithResponse(topicName, topicOptions, context));
}
/**
* Deletes a queue the matching {@code queueName}.
*
* @param queueName Name of queue to delete.
*
* @return A Mono that completes when the queue is deleted.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws NullPointerException if {@code queueName} is null.
* @throws IllegalArgumentException if {@code queueName} is an empty string.
* @throws ResourceNotFoundException if the {@code queueName} does not exist.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Void> deleteQueue(String queueName) {
return deleteQueueWithResponse(queueName).then();
}
/**
* Deletes a queue the matching {@code queueName} and returns the HTTP response.
*
* @param queueName Name of queue to delete.
*
* @return A Mono that completes when the queue is deleted and returns the HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws NullPointerException if {@code queueName} is null.
* @throws IllegalArgumentException if {@code queueName} is an empty string.
* @throws ResourceNotFoundException if the {@code queueName} does not exist.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Void>> deleteQueueWithResponse(String queueName) {
return withContext(context -> deleteQueueWithResponse(queueName, context));
}
/**
* Deletes a rule the matching {@code ruleName}.
*
* @param topicName Name of topic associated with rule to delete.
* @param subscriptionName Name of the subscription associated with the rule to delete.
* @param ruleName Name of rule to delete.
*
* @return A Mono that completes when the rule is deleted.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code topicName} or {@code ruleName} is an empty string.
* @throws NullPointerException if {@code topicName} or {@code ruleName} is null.
* @throws ResourceNotFoundException if the {@code ruleName} does not exist.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Void> deleteRule(String topicName, String subscriptionName, String ruleName) {
return deleteRuleWithResponse(topicName, subscriptionName, ruleName).then();
}
/**
* Deletes a rule the matching {@code ruleName} and returns the HTTP response.
*
* @param topicName Name of topic associated with rule to delete.
* @param subscriptionName Name of the subscription associated with the rule to delete.
* @param ruleName Name of rule to delete.
*
* @return A Mono that completes when the rule is deleted and returns the HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code topicName}, {@code subscriptionName}, or {@code ruleName} is an
* empty string.
* @throws NullPointerException if {@code topicName}, {@code subscriptionName}, or {@code ruleName} is null.
* @throws ResourceNotFoundException if the {@code ruleName} does not exist.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Void>> deleteRuleWithResponse(String topicName, String subscriptionName,
String ruleName) {
return withContext(context -> deleteRuleWithResponse(topicName, subscriptionName, ruleName, context));
}
/**
* Deletes a subscription the matching {@code subscriptionName}.
*
* @param topicName Name of topic associated with subscription to delete.
* @param subscriptionName Name of subscription to delete.
*
* @return A Mono that completes when the subscription is deleted.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} is an empty string.
* @throws NullPointerException if {@code topicName} or {@code subscriptionName} is null.
* @throws ResourceNotFoundException if the {@code subscriptionName} does not exist.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Void> deleteSubscription(String topicName, String subscriptionName) {
return deleteSubscriptionWithResponse(topicName, subscriptionName).then();
}
/**
* Deletes a subscription the matching {@code subscriptionName} and returns the HTTP response.
*
* @param topicName Name of topic associated with subscription to delete.
* @param subscriptionName Name of subscription to delete.
*
* @return A Mono that completes when the subscription is deleted and returns the HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} is an empty string.
* @throws NullPointerException if {@code topicName} or {@code subscriptionName} is null.
* @throws ResourceNotFoundException if the {@code subscriptionName} does not exist.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Void>> deleteSubscriptionWithResponse(String topicName, String subscriptionName) {
return withContext(context -> deleteSubscriptionWithResponse(topicName, subscriptionName, context));
}
/**
* Deletes a topic the matching {@code topicName}.
*
* @param topicName Name of topic to delete.
*
* @return A Mono that completes when the topic is deleted.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code topicName} is an empty string.
* @throws NullPointerException if {@code topicName} is null.
* @throws ResourceNotFoundException if the {@code topicName} does not exist.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Void> deleteTopic(String topicName) {
return deleteTopicWithResponse(topicName).then();
}
/**
* Deletes a topic the matching {@code topicName} and returns the HTTP response.
*
* @param topicName Name of topic to delete.
*
* @return A Mono that completes when the topic is deleted and returns the HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code topicName} is an empty string.
* @throws NullPointerException if {@code topicName} is null.
* @throws ResourceNotFoundException if the {@code topicName} does not exist.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Void>> deleteTopicWithResponse(String topicName) {
return withContext(context -> deleteTopicWithResponse(topicName, context));
}
/**
* Gets information about the queue.
*
* @param queueName Name of queue to get information about.
*
* @return A Mono that completes with information about the queue.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code queueName} is an empty string.
* @throws NullPointerException if {@code queueName} is null.
* @throws ResourceNotFoundException if the {@code queueName} does not exist.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<QueueProperties> getQueue(String queueName) {
return getQueueWithResponse(queueName).map(Response::getValue);
}
/**
* Gets information about the queue along with its HTTP response.
*
* @param queueName Name of queue to get information about.
*
* @return A Mono that completes with information about the queue and the associated HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code queueName} is an empty string.
* @throws NullPointerException if {@code queueName} is null.
* @throws ResourceNotFoundException if the {@code queueName} does not exist.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<QueueProperties>> getQueueWithResponse(String queueName) {
return withContext(context -> getQueueWithResponse(queueName, context, Function.identity()));
}
/**
* Gets whether or not a queue with {@code queueName} exists in the Service Bus namespace.
*
* @param queueName Name of the queue.
*
* @return A Mono that completes indicating whether or not the queue exists.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code queueName} is an empty string.
* @throws NullPointerException if {@code queueName} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Boolean> getQueueExists(String queueName) {
return getQueueExistsWithResponse(queueName).map(Response::getValue);
}
/**
* Gets whether or not a queue with {@code queueName} exists in the Service Bus namespace.
*
* @param queueName Name of the queue.
*
* @return A Mono that completes indicating whether or not the queue exists along with its HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code queueName} is an empty string.
* @throws NullPointerException if {@code queueName} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Boolean>> getQueueExistsWithResponse(String queueName) {
return getEntityExistsWithResponse(getQueueWithResponse(queueName));
}
/**
* Gets runtime properties about the queue.
*
* @param queueName Name of queue to get information about.
*
* @return A Mono that completes with runtime properties about the queue.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code queueName} is an empty string.
* @throws NullPointerException if {@code queueName} is null.
* @throws ResourceNotFoundException if the {@code queueName} does not exist.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<QueueRuntimeProperties> getQueueRuntimeProperties(String queueName) {
return getQueueRuntimePropertiesWithResponse(queueName).map(response -> response.getValue());
}
/**
* Gets runtime properties about the queue along with its HTTP response.
*
* @param queueName Name of queue to get information about.
*
* @return A Mono that completes with runtime properties about the queue and the associated HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code queueName} is an empty string.
* @throws NullPointerException if {@code queueName} is null.
* @throws ResourceNotFoundException if the {@code queueName} does not exist.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<QueueRuntimeProperties>> getQueueRuntimePropertiesWithResponse(String queueName) {
return withContext(context -> getQueueWithResponse(queueName, context, QueueRuntimeProperties::new));
}
/**
* Gets information about the Service Bus namespace.
*
* @return A Mono that completes with information about the Service Bus namespace.
* @throws ClientAuthenticationException if the client's credentials do not have access to the namespace.
* @throws HttpResponseException If error occurred processing the request.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<NamespaceProperties> getNamespaceProperties() {
return getNamespacePropertiesWithResponse().map(Response::getValue);
}
/**
* Gets information about the Service Bus namespace along with its HTTP response.
*
* @return A Mono that completes with information about the namespace and the associated HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<NamespaceProperties>> getNamespacePropertiesWithResponse() {
return withContext(this::getNamespacePropertiesWithResponse);
}
/**
* Gets a rule from the service namespace.
*
* Only following data types are deserialized in Filters and Action parameters - string, int, long, boolean, double,
* and OffsetDateTime. Other data types would return its string value.
*
* @param topicName The name of the topic relative to service bus namespace.
* @param subscriptionName The subscription name the rule belongs to.
* @param ruleName The name of the rule to retrieve.
*
* @return The associated rule.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<RuleProperties> getRule(String topicName, String subscriptionName, String ruleName) {
return getRuleWithResponse(topicName, subscriptionName, ruleName).map(response -> response.getValue());
}
/**
* Gets a rule from the service namespace.
*
* Only following data types are deserialized in Filters and Action parameters - string, int, long, bool, double,
* and OffsetDateTime. Other data types would return its string value.
*
* @param topicName The name of the topic relative to service bus namespace.
* @param subscriptionName The subscription name the rule belongs to.
* @param ruleName The name of the rule to retrieve.
*
* @return The associated rule with the corresponding HTTP response.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<RuleProperties>> getRuleWithResponse(String topicName, String subscriptionName,
String ruleName) {
return withContext(context -> getRuleWithResponse(topicName, subscriptionName, ruleName, context));
}
/**
* Gets information about the queue.
*
* @param topicName Name of topic associated with subscription.
* @param subscriptionName Name of subscription to get information about.
*
* @return A Mono that completes with information about the subscription.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} are empty strings.
* @throws NullPointerException if {@code topicName} or {@code subscriptionName} are null.
* @throws ResourceNotFoundException if the {@code subscriptionName} does not exist in the {@code topicName}.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<SubscriptionProperties> getSubscription(String topicName, String subscriptionName) {
return getSubscriptionWithResponse(topicName, subscriptionName).map(Response::getValue);
}
/**
* Gets information about the subscription along with its HTTP response.
*
* @param topicName Name of topic associated with subscription.
* @param subscriptionName Name of subscription to get information about.
*
* @return A Mono that completes with information about the subscription and the associated HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} are empty strings.
* @throws NullPointerException if {@code topicName} or {@code subscriptionName} are null.
* @throws ResourceNotFoundException if the {@code subscriptionName} does not exist.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<SubscriptionProperties>> getSubscriptionWithResponse(String topicName,
String subscriptionName) {
return withContext(context -> getSubscriptionWithResponse(topicName, subscriptionName, context,
Function.identity()));
}
/**
* Gets whether or not a subscription within a topic exists.
*
* @param topicName Name of topic associated with subscription.
* @param subscriptionName Name of the subscription.
*
* @return A Mono that completes indicating whether or not the subscription exists.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code subscriptionName} is an empty string.
* @throws NullPointerException if {@code subscriptionName} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Boolean> getSubscriptionExists(String topicName, String subscriptionName) {
return getSubscriptionExistsWithResponse(topicName, subscriptionName).map(Response::getValue);
}
/**
* Gets whether or not a subscription within a topic exists.
*
* @param topicName Name of topic associated with subscription.
* @param subscriptionName Name of the subscription.
*
* @return A Mono that completes indicating whether or not the subscription exists along with its HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code subscriptionName} is an empty string.
* @throws NullPointerException if {@code subscriptionName} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Boolean>> getSubscriptionExistsWithResponse(String topicName, String subscriptionName) {
return getEntityExistsWithResponse(getSubscriptionWithResponse(topicName, subscriptionName));
}
/**
* Gets runtime properties about the subscription.
*
* @param topicName Name of topic associated with subscription.
* @param subscriptionName Name of subscription to get information about.
*
* @return A Mono that completes with runtime properties about the subscription.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} are empty strings.
* @throws NullPointerException if {@code topicName} or {@code subscriptionName} are null.
* @throws ResourceNotFoundException if the {@code subscriptionName} does not exist.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<SubscriptionRuntimeProperties> getSubscriptionRuntimeProperties(
String topicName, String subscriptionName) {
return getSubscriptionRuntimePropertiesWithResponse(topicName, subscriptionName)
.map(response -> response.getValue());
}
/**
* Gets runtime properties about the subscription.
*
* @param topicName Name of topic associated with subscription.
* @param subscriptionName Name of subscription to get information about.
*
* @return A Mono that completes with runtime properties about the subscription.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code subscriptionName} is an empty string.
* @throws NullPointerException if {@code subscriptionName} is null.
* @throws ResourceNotFoundException if the {@code subscriptionName} does not exist.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<SubscriptionRuntimeProperties>> getSubscriptionRuntimePropertiesWithResponse(
String topicName, String subscriptionName) {
return withContext(context -> getSubscriptionWithResponse(topicName, subscriptionName, context,
SubscriptionRuntimeProperties::new));
}
/**
* Gets information about the topic.
*
* @param topicName Name of topic to get information about.
*
* @return A Mono that completes with information about the topic.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code topicName} is an empty string.
* @throws NullPointerException if {@code topicName} is null.
* @throws ResourceNotFoundException if the {@code topicName} does not exist.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<TopicProperties> getTopic(String topicName) {
return getTopicWithResponse(topicName).map(Response::getValue);
}
/**
* Gets information about the topic along with its HTTP response.
*
* @param topicName Name of topic to get information about.
*
* @return A Mono that completes with information about the topic and the associated HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code topicName} is an empty string.
* @throws NullPointerException if {@code topicName} is null.
* @throws ResourceNotFoundException if the {@code topicName} does not exist.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<TopicProperties>> getTopicWithResponse(String topicName) {
return withContext(context -> getTopicWithResponse(topicName, context, Function.identity()));
}
/**
* Gets whether or not a topic with {@code topicName} exists in the Service Bus namespace.
*
* @param topicName Name of the topic.
*
* @return A Mono that completes indicating whether or not the topic exists.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code topicName} is an empty string.
* @throws NullPointerException if {@code topicName} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Boolean> getTopicExists(String topicName) {
return getTopicExistsWithResponse(topicName).map(Response::getValue);
}
/**
* Gets whether or not a topic with {@code topicName} exists in the Service Bus namespace.
*
* @param topicName Name of the topic.
*
* @return A Mono that completes indicating whether or not the topic exists along with its HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code topicName} is an empty string.
* @throws NullPointerException if {@code topicName} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Boolean>> getTopicExistsWithResponse(String topicName) {
return getEntityExistsWithResponse(getTopicWithResponse(topicName));
}
/**
* Gets runtime properties about the topic.
*
* @param topicName Name of topic to get information about.
*
* @return A Mono that completes with runtime properties about the topic.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code topicName} is an empty string.
* @throws NullPointerException if {@code topicName} is null.
* @throws ResourceNotFoundException if the {@code topicName} does not exist.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<TopicRuntimeProperties> getTopicRuntimeProperties(String topicName) {
return getTopicRuntimePropertiesWithResponse(topicName).map(response -> response.getValue());
}
/**
* Gets runtime properties about the topic with its HTTP response.
*
* @param topicName Name of topic to get information about.
*
* @return A Mono that completes with runtime properties about the topic and the associated HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code topicName} is an empty string.
* @throws NullPointerException if {@code topicName} is null.
* @throws ResourceNotFoundException if the {@code topicName} does not exist.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<TopicRuntimeProperties>> getTopicRuntimePropertiesWithResponse(String topicName) {
return withContext(context -> getTopicWithResponse(topicName, context, TopicRuntimeProperties::new));
}
/**
* Fetches all the queues in the Service Bus namespace.
*
* @return A Flux of {@link QueueProperties queues} in the Service Bus namespace.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @see <a href="https:
* authorization rules</a>
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux<QueueProperties> listQueues() {
return new PagedFlux<>(
() -> withContext(context -> listQueuesFirstPage(context)),
token -> withContext(context -> listQueuesNextPage(token, context)));
}
/**
* Fetches all the rules for a topic and subscription.
*
* @param topicName The topic name under which all the rules need to be retrieved.
* @param subscriptionName The name of the subscription for which all rules need to be retrieved.
*
* @return A Flux of {@link RuleProperties rules} for the {@code topicName} and {@code subscriptionName}.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws NullPointerException if {@code topicName} or {@code subscriptionName} is null.
* @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} is an empty string.
* @see <a href="https:
* authorization rules</a>
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux<RuleProperties> listRules(String topicName, String subscriptionName) {
if (topicName == null) {
return pagedFluxError(logger, new NullPointerException("'topicName' cannot be null."));
} else if (topicName.isEmpty()) {
return pagedFluxError(logger, new IllegalArgumentException("'topicName' cannot be an empty string."));
}
return new PagedFlux<>(
() -> withContext(context -> listRulesFirstPage(topicName, subscriptionName, context)),
token -> withContext(context -> listRulesNextPage(topicName, subscriptionName, token, context)));
}
/**
* Fetches all the subscriptions for a topic.
*
* @param topicName The topic name under which all the subscriptions need to be retrieved.
*
* @return A Flux of {@link SubscriptionProperties subscriptions} for the {@code topicName}.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws NullPointerException if {@code topicName} is null.
* @throws IllegalArgumentException if {@code topicName} is an empty string.
* @see <a href="https:
* authorization rules</a>
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux<SubscriptionProperties> listSubscriptions(String topicName) {
if (topicName == null) {
return pagedFluxError(logger, new NullPointerException("'topicName' cannot be null."));
} else if (topicName.isEmpty()) {
return pagedFluxError(logger, new IllegalArgumentException("'topicName' cannot be an empty string."));
}
return new PagedFlux<>(
() -> withContext(context -> listSubscriptionsFirstPage(topicName, context)),
token -> withContext(context -> listSubscriptionsNextPage(topicName, token, context)));
}
/**
* Fetches all the topics in the Service Bus namespace.
*
* @return A Flux of {@link TopicProperties topics} in the Service Bus namespace.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @see <a href="https:
* authorization rules</a>
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux<TopicProperties> listTopics() {
return new PagedFlux<>(
() -> withContext(context -> listTopicsFirstPage(context)),
token -> withContext(context -> listTopicsNextPage(token, context)));
}
/**
* Updates a queue with the given {@link QueueProperties}. The {@link QueueProperties} must be fully populated as
* all of the properties are replaced. If a property is not set the service default value is used.
*
* The suggested flow is:
* <ol>
* <li>{@link
* <li>Update the required elements.</li>
* <li>Pass the updated description into this method.</li>
* </ol>
*
* <p>
* There are a subset of properties that can be updated. More information can be found in the links below. They are:
* <ul>
* <li>{@link QueueProperties
* <li>{@link QueueProperties
* <li>{@link QueueProperties
* </li>
* <li>{@link QueueProperties
* </ul>
*
* @param queue Information about the queue to update. You must provide all the property values that are desired
* on the updated entity. Any values not provided are set to the service default values.
*
* @return A Mono that completes with the updated queue.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If the request body was invalid, the queue quota is exceeded, or an error
* occurred processing the request.
* @throws NullPointerException if {@code queue} is null.
* @see <a href="https:
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<QueueProperties> updateQueue(QueueProperties queue) {
return updateQueueWithResponse(queue).map(Response::getValue);
}
/**
* Updates a queue with the given {@link QueueProperties}. The {@link QueueProperties} must be fully populated as
* all of the properties are replaced. If a property is not set the service default value is used.
*
* The suggested flow is:
* <ol>
* <li>{@link
* <li>Update the required elements.</li>
* <li>Pass the updated description into this method.</li>
* </ol>
*
* <p>
* There are a subset of properties that can be updated. More information can be found in the links below. They are:
* <ul>
* <li>{@link QueueProperties
* <li>{@link QueueProperties
* <li>{@link QueueProperties
* </li>
* <li>{@link QueueProperties
* </ul>
*
* @param queue Information about the queue to update. You must provide all the property values that are desired
* on the updated entity. Any values not provided are set to the service default values.
*
* @return A Mono that returns the updated queue in addition to the HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If the request body was invalid, the queue quota is exceeded, or an error
* occurred processing the request.
* @throws NullPointerException if {@code queue} is null.
* @see <a href="https:
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<QueueProperties>> updateQueueWithResponse(QueueProperties queue) {
return withContext(context -> updateQueueWithResponse(queue, context));
}
/**
* Updates a rule with the given {@link RuleProperties}. The {@link RuleProperties} must be fully populated as all
* of the properties are replaced. If a property is not set the service default value is used.
*
* The suggested flow is:
* <ol>
* <li>{@link
* <li>Update the required elements.</li>
* <li>Pass the updated description into this method.</li>
* </ol>
*
* @param topicName The topic name under which the rule is updated.
* @param subscriptionName The name of the subscription for which the rule is updated.
* @param rule Information about the rule to update. You must provide all the property values that are desired
* on the updated entity. Any values not provided are set to the service default values.
*
* @return A Mono that returns the updated rule.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If the request body was invalid, the rule quota is exceeded, or an error
* occurred processing the request.
* @throws IllegalArgumentException if {@link RuleProperties
* @throws NullPointerException if {@code rule} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<RuleProperties> updateRule(String topicName, String subscriptionName, RuleProperties rule) {
return updateRuleWithResponse(topicName, subscriptionName, rule).map(Response::getValue);
}
/**
* Updates a rule with the given {@link RuleProperties}. The {@link RuleProperties} must be fully populated as all
* of the properties are replaced. If a property is not set the service default value is used.
*
* The suggested flow is:
* <ol>
* <li>{@link
* <li>Update the required elements.</li>
* <li>Pass the updated description into this method.</li>
* </ol>
*
* @param topicName The topic name under which the rule is updated.
* @param subscriptionName The name of the subscription for which the rule is updated.
* @param rule Information about the rule to update. You must provide all the property values that are desired
* on the updated entity. Any values not provided are set to the service default values.
*
* @return A Mono that returns the updated rule in addition to the HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If the request body was invalid, the rule quota is exceeded, or an error
* occurred processing the request.
* @throws IllegalArgumentException if {@link RuleProperties
* @throws NullPointerException if {@code rule} is null.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<RuleProperties>> updateRuleWithResponse(String topicName, String subscriptionName,
RuleProperties rule) {
return withContext(context -> updateRuleWithResponse(topicName, subscriptionName, rule, context));
}
/**
* Updates a subscription with the given {@link SubscriptionProperties}. The {@link SubscriptionProperties} must be
* fully populated as all of the properties are replaced. If a property is not set the service default value is
* used.
*
* The suggested flow is:
* <ol>
* <li>{@link
* <li>Update the required elements.</li>
* <li>Pass the updated description into this method.</li>
* </ol>
*
* <p>
* There are a subset of properties that can be updated. More information can be found in the links below. They are:
* <ul>
* <li>{@link SubscriptionProperties
* <li>{@link SubscriptionProperties
* <li>{@link SubscriptionProperties
* </ul>
*
* @param subscription Information about the subscription to update. You must provide all the property values
* that are desired on the updated entity. Any values not provided are set to the service default values.
*
* @return A Mono that returns the updated subscription.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If the request body was invalid, the subscription quota is exceeded, or an
* error occurred processing the request.
* @throws IllegalArgumentException if {@link SubscriptionProperties
* SubscriptionProperties
* @throws NullPointerException if {@code subscription} is null.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<SubscriptionProperties> updateSubscription(SubscriptionProperties subscription) {
return updateSubscriptionWithResponse(subscription).map(Response::getValue);
}
/**
* Updates a subscription with the given {@link SubscriptionProperties}. The {@link SubscriptionProperties} must be
* fully populated as all of the properties are replaced. If a property is not set the service default value is
* used.
*
* The suggested flow is:
* <ol>
* <li>{@link
* <li>Update the required elements.</li>
* <li>Pass the updated description into this method.</li>
* </ol>
*
* <p>
* There are a subset of properties that can be updated. More information can be found in the links below. They are:
* <ul>
* <li>{@link SubscriptionProperties
* <li>{@link SubscriptionProperties
* <li>{@link SubscriptionProperties
* </ul>
*
* @param subscription Information about the subscription to update. You must provide all the property values
* that are desired on the updated entity. Any values not provided are set to the service default values.
*
* @return A Mono that returns the updated subscription in addition to the HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If the request body was invalid, the subscription quota is exceeded, or an
* error occurred processing the request.
* @throws IllegalArgumentException if {@link SubscriptionProperties
* SubscriptionProperties
* @throws NullPointerException if {@code subscription} is null.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<SubscriptionProperties>> updateSubscriptionWithResponse(
SubscriptionProperties subscription) {
return withContext(context -> updateSubscriptionWithResponse(subscription, context));
}
/**
* Updates a topic with the given {@link TopicProperties}. The {@link TopicProperties} must be fully populated as
* all of the properties are replaced. If a property is not set the service default value is used.
*
* The suggested flow is:
* <ol>
* <li>{@link
* <li>Update the required elements.</li>
* <li>Pass the updated description into this method.</li>
* </ol>
*
* <p>
* There are a subset of properties that can be updated. More information can be found in the links below. They are:
* <ul>
* <li>{@link TopicProperties
* <li>{@link TopicProperties
* </li>
* </ul>
*
* @param topic Information about the topic to update. You must provide all the property values that are desired
* on the updated entity. Any values not provided are set to the service default values.
*
* @return A Mono that completes with the updated topic.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If the request body was invalid, the topic quota is exceeded, or an error
* occurred processing the request.
* @throws IllegalArgumentException if {@link TopicProperties
* string.
* @throws NullPointerException if {@code topic} is null.
* @see <a href="https:
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<TopicProperties> updateTopic(TopicProperties topic) {
return updateTopicWithResponse(topic).map(Response::getValue);
}
/**
* Updates a topic with the given {@link TopicProperties}. The {@link TopicProperties} must be fully populated as
* all of the properties are replaced. If a property is not set the service default value is used.
*
* The suggested flow is:
* <ol>
* <li>{@link
* <li>Update the required elements.</li>
* <li>Pass the updated description into this method.</li>
* </ol>
*
* <p>
* There are a subset of properties that can be updated. More information can be found in the links below. They are:
* <ul>
* <li>{@link TopicProperties
* <li>{@link TopicProperties
* </li>
* </ul>
*
* @param topic Information about the topic to update. You must provide all the property values that are desired
* on the updated entity. Any values not provided are set to the service default values.
*
* @return A Mono that completes with the updated topic and its HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If the request body was invalid, the topic quota is exceeded, or an error
* occurred processing the request.
* @throws IllegalArgumentException if {@link TopicProperties
* string.
* @throws NullPointerException if {@code topic} is null.
* @see <a href="https:
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<TopicProperties>> updateTopicWithResponse(TopicProperties topic) {
return withContext(context -> updateTopicWithResponse(topic, context));
}
/**
* Creates a queue with its context.
*
* @param createQueueOptions Queue to create.
* @param context Context to pass into request.
*
* @return A Mono that completes with the created {@link QueueProperties}.
*/
Mono<Response<QueueProperties>> createQueueWithResponse(String queueName, CreateQueueOptions createQueueOptions,
Context context) {
if (queueName == null) {
return monoError(logger, new NullPointerException("'queueName' cannot be null."));
} else if (queueName.isEmpty()) {
return monoError(logger, new IllegalArgumentException("'queueName' cannot be empty."));
}
if (createQueueOptions == null) {
return monoError(logger, new NullPointerException("'createQueueOptions' cannot be null."));
} else if (context == null) {
return monoError(logger, new NullPointerException("'context' cannot be null."));
}
final QueueDescription description = EntityHelper.getQueueDescription(createQueueOptions);
final CreateQueueBodyContent content = new CreateQueueBodyContent()
.setType(CONTENT_TYPE)
.setQueueDescription(description);
final CreateQueueBody createEntity = new CreateQueueBody()
.setContent(content);
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
try {
return entityClient.putWithResponseAsync(queueName, createEntity, null, withTracing)
.onErrorMap(ServiceBusAdministrationAsyncClient::mapException)
.map(this::deserializeQueue);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Creates a rule with its context.
*
* @param ruleOptions Rule to create.
* @param context Context to pass into request.
*
* @return A Mono that completes with the created {@link RuleProperties}.
*/
Mono<Response<RuleProperties>> createRuleWithResponse(String topicName, String subscriptionName, String ruleName,
CreateRuleOptions ruleOptions, Context context) {
if (topicName == null) {
return monoError(logger, new NullPointerException("'topicName' cannot be null."));
} else if (topicName.isEmpty()) {
return monoError(logger, new IllegalArgumentException("'topicName' cannot be empty."));
}
if (subscriptionName == null) {
return monoError(logger, new NullPointerException("'subscriptionName' cannot be null."));
} else if (subscriptionName.isEmpty()) {
return monoError(logger, new IllegalArgumentException("'subscriptionName' cannot be empty."));
}
if (ruleName == null) {
return monoError(logger, new NullPointerException("'ruleName' cannot be null."));
} else if (ruleName.isEmpty()) {
return monoError(logger, new IllegalArgumentException("'ruleName' cannot be empty."));
}
if (ruleOptions == null) {
return monoError(logger, new NullPointerException("'rule' cannot be null."));
}
final RuleActionImpl action = ruleOptions.getAction() != null
? EntityHelper.toImplementation(ruleOptions.getAction())
: null;
final RuleFilterImpl filter = ruleOptions.getFilter() != null
? EntityHelper.toImplementation(ruleOptions.getFilter())
: null;
final RuleDescription rule = new RuleDescription()
.setAction(action)
.setFilter(filter)
.setName(ruleName);
final CreateRuleBodyContent content = new CreateRuleBodyContent()
.setType(CONTENT_TYPE)
.setRuleDescription(rule);
final CreateRuleBody createEntity = new CreateRuleBody().setContent(content);
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
try {
return managementClient.getRules().putWithResponseAsync(topicName, subscriptionName, ruleName, createEntity,
null, withTracing)
.onErrorMap(ServiceBusAdministrationAsyncClient::mapException)
.map(response -> deserializeRule(response));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Creates a subscription with its context.
*
* @param subscriptionOptions Subscription to create.
* @param context Context to pass into request.
*
* @return A Mono that completes with the created {@link SubscriptionProperties}.
*/
Mono<Response<SubscriptionProperties>> createSubscriptionWithResponse(String topicName, String subscriptionName,
CreateSubscriptionOptions subscriptionOptions, Context context) {
if (topicName == null) {
return monoError(logger, new NullPointerException("'topicName' cannot be null."));
} else if (topicName.isEmpty()) {
return monoError(logger, new IllegalArgumentException("'topicName' cannot be empty."));
}
if (subscriptionName == null) {
return monoError(logger, new NullPointerException("'subscriptionName' cannot be null."));
} else if (subscriptionName.isEmpty()) {
return monoError(logger, new IllegalArgumentException("'subscriptionName' cannot be empty."));
}
if (subscriptionOptions == null) {
return monoError(logger, new NullPointerException("'subscription' cannot be null."));
}
final SubscriptionDescription subscription = EntityHelper.getSubscriptionDescription(subscriptionOptions);
final CreateSubscriptionBodyContent content = new CreateSubscriptionBodyContent()
.setType(CONTENT_TYPE)
.setSubscriptionDescription(subscription);
final CreateSubscriptionBody createEntity = new CreateSubscriptionBody().setContent(content);
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
try {
return managementClient.getSubscriptions().putWithResponseAsync(topicName, subscriptionName, createEntity,
null, withTracing)
.onErrorMap(ServiceBusAdministrationAsyncClient::mapException)
.map(response -> deserializeSubscription(topicName, response));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Creates a topicOptions with its context.
*
* @param topicOptions Topic to create.
* @param context Context to pass into request.
*
* @return A Mono that completes with the created {@link TopicProperties}.
*/
Mono<Response<TopicProperties>> createTopicWithResponse(String topicName, CreateTopicOptions topicOptions,
Context context) {
if (topicName == null) {
return monoError(logger, new NullPointerException("'topicName' cannot be null."));
} else if (topicName.isEmpty()) {
return monoError(logger, new IllegalArgumentException("'topicName' cannot be empty."));
}
if (topicOptions == null) {
return monoError(logger, new NullPointerException("'topicOptions' cannot be null"));
} else if (context == null) {
return monoError(logger, new NullPointerException("'context' cannot be null."));
}
final TopicDescription topic = EntityHelper.getTopicDescription(topicOptions);
final CreateTopicBodyContent content = new CreateTopicBodyContent()
.setType(CONTENT_TYPE)
.setTopicDescription(topic);
final CreateTopicBody createEntity = new CreateTopicBody()
.setContent(content);
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
try {
return entityClient.putWithResponseAsync(topicName, createEntity, null, withTracing)
.onErrorMap(ServiceBusAdministrationAsyncClient::mapException)
.map(this::deserializeTopic);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Deletes a queue with its context.
*
* @param queueName Name of queue to delete.
* @param context Context to pass into request.
*
* @return A Mono that completes when the queue is deleted.
*/
Mono<Response<Void>> deleteQueueWithResponse(String queueName, Context context) {
if (queueName == null) {
return monoError(logger, new NullPointerException("'queueName' cannot be null"));
} else if (queueName.isEmpty()) {
return monoError(logger, new IllegalArgumentException("'queueName' cannot be an empty string."));
} else if (context == null) {
return monoError(logger, new NullPointerException("'context' cannot be null."));
}
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
try {
return entityClient.deleteWithResponseAsync(queueName, withTracing)
.onErrorMap(ServiceBusAdministrationAsyncClient::mapException)
.map(response -> {
return new SimpleResponse<>(response.getRequest(), response.getStatusCode(),
response.getHeaders(), null);
});
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Deletes a queue with its context.
*
* @param topicName Name of topic to delete.
* @param subscriptionName Name of the subscription for the rule.
* @param ruleName Name of the rule.
* @param context Context to pass into request.
*
* @return A Mono that completes with the created {@link QueueProperties}.
*/
Mono<Response<Void>> deleteRuleWithResponse(String topicName, String subscriptionName, String ruleName,
Context context) {
if (topicName == null) {
return monoError(logger, new NullPointerException("'topicName' cannot be null"));
} else if (topicName.isEmpty()) {
return monoError(logger, new IllegalArgumentException("'topicName' cannot be an empty string."));
} else if (subscriptionName == null) {
return monoError(logger, new NullPointerException("'subscriptionName' cannot be null"));
} else if (subscriptionName.isEmpty()) {
return monoError(logger, new IllegalArgumentException("'subscriptionName' cannot be an empty string."));
} else if (ruleName == null) {
return monoError(logger, new NullPointerException("'ruleName' cannot be null"));
} else if (ruleName.isEmpty()) {
return monoError(logger, new IllegalArgumentException("'ruleName' cannot be an empty string."));
} else if (context == null) {
return monoError(logger, new NullPointerException("'context' cannot be null."));
}
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
try {
return rulesClient.deleteWithResponseAsync(topicName, subscriptionName, ruleName, withTracing)
.onErrorMap(ServiceBusAdministrationAsyncClient::mapException)
.map(response -> new SimpleResponse<>(response.getRequest(), response.getStatusCode(),
response.getHeaders(), null));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Deletes a subscription with its context.
*
* @param topicName Name of topic associated with subscription to delete.
* @param subscriptionName Name of subscription to delete.
* @param context Context to pass into request.
*
* @return A Mono that completes with the created {@link SubscriptionProperties}.
*/
Mono<Response<Void>> deleteSubscriptionWithResponse(String topicName, String subscriptionName, Context context) {
if (subscriptionName == null) {
return monoError(logger, new NullPointerException("'subscriptionName' cannot be null"));
} else if (subscriptionName.isEmpty()) {
return monoError(logger, new IllegalArgumentException("'subscriptionName' cannot be an empty string."));
} else if (topicName == null) {
return monoError(logger, new NullPointerException("'topicName' cannot be null"));
} else if (topicName.isEmpty()) {
return monoError(logger, new IllegalArgumentException("'topicName' cannot be an empty string."));
} else if (context == null) {
return monoError(logger, new NullPointerException("'context' cannot be null."));
}
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
try {
return managementClient.getSubscriptions().deleteWithResponseAsync(topicName, subscriptionName,
withTracing)
.onErrorMap(ServiceBusAdministrationAsyncClient::mapException)
.map(response -> new SimpleResponse<>(response.getRequest(), response.getStatusCode(),
response.getHeaders(), null));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Deletes a topic with its context.
*
* @param topicName Name of topic to delete.
* @param context Context to pass into request.
*
* @return A Mono that completes with the created {@link TopicProperties}.
*/
Mono<Response<Void>> deleteTopicWithResponse(String topicName, Context context) {
if (topicName == null) {
return monoError(logger, new NullPointerException("'topicName' cannot be null"));
} else if (topicName.isEmpty()) {
return monoError(logger, new IllegalArgumentException("'topicName' cannot be an empty string."));
} else if (context == null) {
return monoError(logger, new NullPointerException("'context' cannot be null."));
}
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
try {
return entityClient.deleteWithResponseAsync(topicName, withTracing)
.onErrorMap(ServiceBusAdministrationAsyncClient::mapException)
.map(response -> new SimpleResponse<>(response.getRequest(), response.getStatusCode(),
response.getHeaders(), null));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Gets whether an entity exists.
*
* @param getEntityOperation Operation to get information about entity. If {@link ResourceNotFoundException} is
* thrown, then it is mapped to false.
* @param <T> Entity type.
*
* @return True if the entity exists, false otherwise.
*/
<T> Mono<Response<Boolean>> getEntityExistsWithResponse(Mono<Response<T>> getEntityOperation) {
return getEntityOperation.map(response -> {
final boolean exists = response.getValue() != null;
return (Response<Boolean>) new SimpleResponse<>(response.getRequest(), response.getStatusCode(),
response.getHeaders(), exists);
})
.onErrorResume(ResourceNotFoundException.class, exception -> {
final HttpResponse response = exception.getResponse();
final Response<Boolean> result = new SimpleResponse<>(response.getRequest(), response.getStatusCode(),
response.getHeaders(), false);
return Mono.just(result);
});
}
/**
* Gets a queue with its context.
*
* @param queueName Name of queue to fetch information for.
* @param context Context to pass into request.
*
* @return A Mono that completes with the {@link QueueProperties}.
*/
<T> Mono<Response<T>> getQueueWithResponse(String queueName, Context context,
Function<QueueProperties, T> mapper) {
if (queueName == null) {
return monoError(logger, new NullPointerException("'queueName' cannot be null"));
} else if (queueName.isEmpty()) {
return monoError(logger, new IllegalArgumentException("'queueName' cannot be empty."));
} else if (context == null) {
return monoError(logger, new NullPointerException("'context' cannot be null."));
}
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
try {
return entityClient.getWithResponseAsync(queueName, true, withTracing)
.onErrorMap(ServiceBusAdministrationAsyncClient::mapException)
.handle((response, sink) -> {
final Response<QueueProperties> deserialize = deserializeQueue(response);
if (deserialize.getValue() == null) {
final HttpResponse notFoundResponse = new EntityNotFoundHttpResponse<>(deserialize);
sink.error(new ResourceNotFoundException(String.format("Queue '%s' does not exist.", queueName),
notFoundResponse));
} else {
final T mapped = mapper.apply(deserialize.getValue());
sink.next(new SimpleResponse<>(response.getRequest(), response.getStatusCode(),
response.getHeaders(), mapped));
}
});
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<RuleProperties>> getRuleWithResponse(String topicName, String subscriptionName,
String ruleName, Context context) {
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
try {
return rulesClient.getWithResponseAsync(topicName, subscriptionName, ruleName, true, withTracing)
.onErrorMap(ServiceBusAdministrationAsyncClient::mapException)
.map(this::deserializeRule);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Gets a subscription with its context.
*
* @param topicName Name of the topic associated with the subscription.
* @param subscriptionName Name of subscription to fetch information for.
* @param context Context to pass into request.
*
* @return A Mono that completes with the {@link SubscriptionProperties}.
*/
<T> Mono<Response<T>> getSubscriptionWithResponse(String topicName, String subscriptionName, Context context,
Function<SubscriptionProperties, T> mapper) {
if (topicName == null) {
return monoError(logger, new NullPointerException("'topicName' cannot be null."));
} else if (topicName.isEmpty()) {
return monoError(logger, new IllegalArgumentException("'topicName' cannot be an empty string."));
} else if (subscriptionName == null) {
return monoError(logger, new NullPointerException("'subscriptionName' cannot be null."));
} else if (subscriptionName.isEmpty()) {
return monoError(logger, new IllegalArgumentException("'subscriptionName' cannot be an empty string."));
} else if (context == null) {
return monoError(logger, new NullPointerException("'context' cannot be null."));
}
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
try {
return managementClient.getSubscriptions().getWithResponseAsync(topicName, subscriptionName, true,
withTracing)
.onErrorMap(ServiceBusAdministrationAsyncClient::mapException)
.handle((response, sink) -> {
final Response<SubscriptionProperties> deserialize = deserializeSubscription(topicName, response);
if (deserialize.getValue() == null) {
final HttpResponse notFoundResponse = new EntityNotFoundHttpResponse<>(deserialize);
sink.error(new ResourceNotFoundException(String.format(
"Subscription '%s' in topic '%s' does not exist.", topicName, subscriptionName),
notFoundResponse));
} else {
final T mapped = mapper.apply(deserialize.getValue());
sink.next(new SimpleResponse<>(response.getRequest(), response.getStatusCode(),
response.getHeaders(), mapped));
}
});
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Gets the namespace properties with its context.
*
* @param context Context to pass into request.
*
* @return A Mono that completes with the {@link NamespaceProperties}.
*/
Mono<Response<NamespaceProperties>> getNamespacePropertiesWithResponse(Context context) {
return managementClient.getNamespaces().getWithResponseAsync(context).handle((response, sink) -> {
final NamespacePropertiesEntry entry = response.getValue();
if (entry == null || entry.getContent() == null) {
sink.error(new AzureException(
"There was no content inside namespace response. Entry: " + response));
return;
}
final NamespaceProperties namespaceProperties = entry.getContent().getNamespaceProperties();
final Response<NamespaceProperties> result = new SimpleResponse<>(response.getRequest(),
response.getStatusCode(), response.getHeaders(), namespaceProperties);
sink.next(result);
});
}
/**
* Gets a topic with its context.
*
* @param topicName Name of topic to fetch information for.
* @param context Context to pass into request.
*
* @return A Mono that completes with the {@link TopicProperties}.
*/
<T> Mono<Response<T>> getTopicWithResponse(String topicName, Context context,
Function<TopicProperties, T> mapper) {
if (topicName == null) {
return monoError(logger, new NullPointerException("'topicName' cannot be null"));
} else if (topicName.isEmpty()) {
return monoError(logger, new IllegalArgumentException("'topicName' cannot be empty."));
} else if (context == null) {
return monoError(logger, new NullPointerException("'context' cannot be null."));
}
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
try {
return entityClient.getWithResponseAsync(topicName, true, withTracing)
.onErrorMap(ServiceBusAdministrationAsyncClient::mapException)
.handle((response, sink) -> {
final Response<TopicProperties> deserialize = deserializeTopic(response);
if (deserialize.getValue() == null) {
final HttpResponse notFoundResponse = new EntityNotFoundHttpResponse<>(deserialize);
sink.error(new ResourceNotFoundException(String.format("Topic '%s' does not exist.", topicName),
notFoundResponse));
} else {
final T mapped = mapper.apply(deserialize.getValue());
sink.next(new SimpleResponse<>(response.getRequest(), response.getStatusCode(),
response.getHeaders(), mapped));
}
});
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Gets the first page of queues with context.
*
* @param context Context to pass into request.
*
* @return A Mono that completes with a page of queues.
*/
Mono<PagedResponse<QueueProperties>> listQueuesFirstPage(Context context) {
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
try {
return listQueues(0, withTracing);
} catch (RuntimeException e) {
return monoError(logger, e);
}
}
/**
* Gets the next page of queues with context.
*
* @param continuationToken Number of items to skip in feed.
* @param context Context to pass into request.
*
* @return A Mono that completes with a page of queues or empty if there are no items left.
*/
Mono<PagedResponse<QueueProperties>> listQueuesNextPage(String continuationToken, Context context) {
if (continuationToken == null || continuationToken.isEmpty()) {
return Mono.empty();
}
try {
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
final int skip = Integer.parseInt(continuationToken);
return listQueues(skip, withTracing);
} catch (RuntimeException e) {
return monoError(logger, e);
}
}
/**
* Gets the first page of rules with context.
*
* @param context Context to pass into request.
*
* @return A Mono that completes with a page of rules.
*/
Mono<PagedResponse<RuleProperties>> listRulesFirstPage(String topicName, String subscriptionName, Context context) {
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
try {
return listRules(topicName, subscriptionName, 0, withTracing);
} catch (RuntimeException e) {
return monoError(logger, e);
}
}
/**
* Gets the next page of rules with context.
*
* @param continuationToken Number of items to skip in feed.
* @param context Context to pass into request.
*
* @return A Mono that completes with a page of rules or empty if there are no items left.
*/
Mono<PagedResponse<RuleProperties>> listRulesNextPage(String topicName, String subscriptionName,
String continuationToken, Context context) {
if (continuationToken == null || continuationToken.isEmpty()) {
return Mono.empty();
}
try {
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
final int skip = Integer.parseInt(continuationToken);
return listRules(topicName, subscriptionName, skip, withTracing);
} catch (RuntimeException e) {
return monoError(logger, e);
}
}
/**
* Gets the first page of subscriptions with context.
*
* @param context Context to pass into request.
*
* @return A Mono that completes with a page of subscriptions.
*/
Mono<PagedResponse<SubscriptionProperties>> listSubscriptionsFirstPage(String topicName, Context context) {
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
try {
return listSubscriptions(topicName, 0, withTracing);
} catch (RuntimeException e) {
return monoError(logger, e);
}
}
/**
* Gets the next page of subscriptions with context.
*
* @param continuationToken Number of items to skip in feed.
* @param context Context to pass into request.
*
* @return A Mono that completes with a page of subscriptions or empty if there are no items left.
*/
Mono<PagedResponse<SubscriptionProperties>> listSubscriptionsNextPage(String topicName, String continuationToken,
Context context) {
if (continuationToken == null || continuationToken.isEmpty()) {
return Mono.empty();
}
try {
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
final int skip = Integer.parseInt(continuationToken);
return listSubscriptions(topicName, skip, withTracing);
} catch (RuntimeException e) {
return monoError(logger, e);
}
}
/**
* Gets the first page of topics with context.
*
* @param context Context to pass into request.
*
* @return A Mono that completes with a page of topics.
*/
Mono<PagedResponse<TopicProperties>> listTopicsFirstPage(Context context) {
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
try {
return listTopics(0, withTracing);
} catch (RuntimeException e) {
return monoError(logger, e);
}
}
/**
* Gets the next page of topics with context.
*
* @param continuationToken Number of items to skip in feed.
* @param context Context to pass into request.
*
* @return A Mono that completes with a page of topics or empty if there are no items left.
*/
Mono<PagedResponse<TopicProperties>> listTopicsNextPage(String continuationToken, Context context) {
if (continuationToken == null || continuationToken.isEmpty()) {
return Mono.empty();
}
try {
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
final int skip = Integer.parseInt(continuationToken);
return listTopics(skip, withTracing);
} catch (RuntimeException e) {
return monoError(logger, e);
}
}
/**
* Updates a queue with its context.
*
* @param queue Information about the queue to update. You must provide all the property values that are desired
* on the updated entity. Any values not provided are set to the service default values.
* @param context Context to pass into request.
*
* @return A Mono that completes with the updated {@link QueueProperties}.
*/
Mono<Response<QueueProperties>> updateQueueWithResponse(QueueProperties queue, Context context) {
if (queue == null) {
return monoError(logger, new NullPointerException("'queue' cannot be null"));
} else if (context == null) {
return monoError(logger, new NullPointerException("'context' cannot be null."));
}
final QueueDescription queueDescription = EntityHelper.toImplementation(queue);
final CreateQueueBodyContent content = new CreateQueueBodyContent()
.setType(CONTENT_TYPE)
.setQueueDescription(queueDescription);
final CreateQueueBody createEntity = new CreateQueueBody()
.setContent(content);
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
try {
return entityClient.putWithResponseAsync(queue.getName(), createEntity, "*", withTracing)
.onErrorMap(ServiceBusAdministrationAsyncClient::mapException)
.map(response -> deserializeQueue(response));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Updates a rule with its context.
*
* @param rule Information about the rule to update. You must provide all the property values that are desired
* on the updated entity. Any values not provided are set to the service default values.
* @param context Context to pass into request.
*
* @return A Mono that completes with the updated {@link RuleProperties}.
*/
Mono<Response<RuleProperties>> updateRuleWithResponse(String topicName, String subscriptionName,
RuleProperties rule, Context context) {
if (rule == null) {
return monoError(logger, new NullPointerException("'rule' cannot be null"));
} else if (context == null) {
return monoError(logger, new NullPointerException("'context' cannot be null."));
}
final RuleDescription implementation = EntityHelper.toImplementation(rule);
final CreateRuleBodyContent content = new CreateRuleBodyContent()
.setType(CONTENT_TYPE)
.setRuleDescription(implementation);
final CreateRuleBody ruleBody = new CreateRuleBody()
.setContent(content);
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
try {
return managementClient.getRules().putWithResponseAsync(topicName, subscriptionName, rule.getName(),
ruleBody, "*", withTracing)
.onErrorMap(ServiceBusAdministrationAsyncClient::mapException)
.map(response -> deserializeRule(response));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Updates a subscription with its context.
*
* @param subscription Information about the subscription to update. You must provide all the property values
* that are desired on the updated entity. Any values not provided are set to the service default values.
* @param context Context to pass into request.
*
* @return A Mono that completes with the updated {@link SubscriptionProperties}.
*/
Mono<Response<SubscriptionProperties>> updateSubscriptionWithResponse(SubscriptionProperties subscription,
Context context) {
if (subscription == null) {
return monoError(logger, new NullPointerException("'subscription' cannot be null"));
} else if (context == null) {
return monoError(logger, new NullPointerException("'context' cannot be null."));
}
final String topicName = subscription.getTopicName();
final String subscriptionName = subscription.getSubscriptionName();
final SubscriptionDescription implementation = EntityHelper.toImplementation(subscription);
final CreateSubscriptionBodyContent content = new CreateSubscriptionBodyContent()
.setType(CONTENT_TYPE)
.setSubscriptionDescription(implementation);
final CreateSubscriptionBody createEntity = new CreateSubscriptionBody()
.setContent(content);
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
try {
return managementClient.getSubscriptions().putWithResponseAsync(topicName, subscriptionName, createEntity,
"*", withTracing)
.onErrorMap(ServiceBusAdministrationAsyncClient::mapException)
.map(response -> deserializeSubscription(topicName, response));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Updates a topic with its context.
*
* @param topic Information about the topic to update. You must provide all the property values that are desired
* on the updated entity. Any values not provided are set to the service default values.
* @param context Context to pass into request.
*
* @return A Mono that completes with the updated {@link TopicProperties}.
*/
Mono<Response<TopicProperties>> updateTopicWithResponse(TopicProperties topic, Context context) {
if (topic == null) {
return monoError(logger, new NullPointerException("'topic' cannot be null"));
} else if (context == null) {
return monoError(logger, new NullPointerException("'context' cannot be null."));
}
final TopicDescription implementation = EntityHelper.toImplementation(topic);
final CreateTopicBodyContent content = new CreateTopicBodyContent()
.setType(CONTENT_TYPE)
.setTopicDescription(implementation);
final CreateTopicBody createEntity = new CreateTopicBody()
.setContent(content);
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
try {
return entityClient.putWithResponseAsync(topic.getName(), createEntity, "*", withTracing)
.onErrorMap(ServiceBusAdministrationAsyncClient::mapException)
.map(response -> deserializeTopic(response));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
private <T> T deserialize(Object object, Class<T> clazz) {
if (object == null) {
return null;
}
final String contents = String.valueOf(object);
if (contents.isEmpty()) {
return null;
}
try {
return serializer.deserialize(contents, clazz);
} catch (IOException e) {
throw logger.logExceptionAsError(new RuntimeException(String.format(
"Exception while deserializing. Body: [%s]. Class: %s", contents, clazz), e));
}
}
/**
* Given an HTTP response, will deserialize it into a strongly typed Response object.
*
* @param response HTTP response to deserialize response body from.
* @param clazz Class to deserialize response type into.
* @param <T> Class type to deserialize response into.
*
* @return A Response with a strongly typed response value.
*/
private <T> Response<T> deserialize(Response<Object> response, Class<T> clazz) {
final T deserialize = deserialize(response.getValue(), clazz);
return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(),
deserialize);
}
/**
* Converts a Response into its corresponding {@link QueueDescriptionEntry} then mapped into {@link
* QueueProperties}.
*
* @param response HTTP Response to deserialize.
*
* @return The corresponding HTTP response with convenience properties set.
*/
/**
* Converts a Response into its corresponding {@link RuleDescriptionEntry} then mapped into {@link RuleProperties}.
*
* @param response HTTP Response to deserialize.
*
* @return The corresponding HTTP response with convenience properties set.
*/
private Response<RuleProperties> deserializeRule(Response<Object> response) {
final RuleDescriptionEntry entry = deserialize(response.getValue(), RuleDescriptionEntry.class);
if (entry == null) {
return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null);
} else if (entry.getContent() == null) {
logger.info("entry.getContent() is null. The entity may not exist. {}", entry);
return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null);
}
final RuleDescription description = entry.getContent().getRuleDescription();
final RuleProperties result = EntityHelper.toModel(description);
return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), result);
}
/**
* Converts a Response into its corresponding {@link SubscriptionDescriptionEntry} then mapped into {@link
* SubscriptionProperties}.
*
* @param response HTTP Response to deserialize.
*
* @return The corresponding HTTP response with convenience properties set.
*/
private Response<SubscriptionProperties> deserializeSubscription(String topicName, Response<Object> response) {
final SubscriptionDescriptionEntry entry = deserialize(response.getValue(), SubscriptionDescriptionEntry.class);
if (entry == null) {
return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null);
} else if (entry.getContent() == null) {
logger.warning("entry.getContent() is null. There should have been content returned. Entry: {}", entry);
return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null);
}
final SubscriptionProperties subscription = EntityHelper.toModel(
entry.getContent().getSubscriptionDescription());
final String subscriptionName = getTitleValue(entry.getTitle());
EntityHelper.setSubscriptionName(subscription, subscriptionName);
EntityHelper.setTopicName(subscription, topicName);
return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(),
subscription);
}
/**
* Converts a Response into its corresponding {@link TopicDescriptionEntry} then mapped into {@link
* QueueProperties}.
*
* @param response HTTP Response to deserialize.
*
* @return The corresponding HTTP response with convenience properties set.
*/
private Response<TopicProperties> deserializeTopic(Response<Object> response) {
final TopicDescriptionEntry entry = deserialize(response.getValue(), TopicDescriptionEntry.class);
if (entry == null) {
return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null);
} else if (entry.getContent() == null) {
logger.warning("entry.getContent() is null. There should have been content returned. Entry: {}", entry);
return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null);
} else if (entry.getContent().getTopicDescription() == null) {
final QueueDescriptionEntry entryTopic = deserialize(response.getValue(), QueueDescriptionEntry.class);
if (entryTopic != null && entryTopic.getContent() != null && entryTopic.getContent().getQueueDescription() != null) {
throw logger.logExceptionAsError(
new RuntimeException(String.format("'[%s]' is not a topic, it is a queue.", entryTopic.getTitle())));
}
}
final TopicProperties result = EntityHelper.toModel(entry.getContent().getTopicDescription());
final String topicName = getTitleValue(entry.getTitle());
EntityHelper.setTopicName(result, topicName);
return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), result);
}
/**
* Creates a {@link FeedPage} given the elements and a set of response links to get the next link from.
*
* @param entities Entities in the feed.
* @param responseLinks Links returned from the feed.
* @param <TResult> Type of Service Bus entities in page.
*
* @return A {@link FeedPage} indicating whether this can be continued or not.
* @throws MalformedURLException if the "next" page link does not contain a well-formed URL.
*/
private <TResult, TFeed> FeedPage<TResult> extractPage(Response<TFeed> response, List<TResult> entities,
List<ResponseLink> responseLinks)
throws MalformedURLException, UnsupportedEncodingException {
final Optional<ResponseLink> nextLink = responseLinks.stream()
.filter(link -> link.getRel().equalsIgnoreCase("next"))
.findFirst();
if (!nextLink.isPresent()) {
return new FeedPage<>(response.getStatusCode(), response.getHeaders(), response.getRequest(), entities);
}
final URL url = new URL(nextLink.get().getHref());
final String decode = URLDecoder.decode(url.getQuery(), StandardCharsets.UTF_8.name());
final Optional<Integer> skipParameter = Arrays.stream(decode.split("&|&"))
.map(part -> part.split("=", 2))
.filter(parts -> parts[0].equalsIgnoreCase("$skip") && parts.length == 2)
.map(parts -> Integer.valueOf(parts[1]))
.findFirst();
if (skipParameter.isPresent()) {
return new FeedPage<>(response.getStatusCode(), response.getHeaders(), response.getRequest(), entities,
skipParameter.get());
} else {
logger.warning("There should have been a skip parameter for the next page.");
return new FeedPage<>(response.getStatusCode(), response.getHeaders(), response.getRequest(), entities);
}
}
/**
* Helper method that invokes the service method, extracts the data and translates it to a PagedResponse.
*
* @param skip Number of elements to skip.
* @param context Context for the query.
*
* @return A Mono that completes with a paged response of queues.
*/
private Mono<PagedResponse<QueueProperties>> listQueues(int skip, Context context) {
return managementClient.listEntitiesWithResponseAsync(QUEUES_ENTITY_TYPE, skip, NUMBER_OF_ELEMENTS, context)
.onErrorMap(ServiceBusAdministrationAsyncClient::mapException)
.flatMap(response -> {
final Response<QueueDescriptionFeed> feedResponse = deserialize(response, QueueDescriptionFeed.class);
final QueueDescriptionFeed feed = feedResponse.getValue();
if (feed == null) {
logger.warning("Could not deserialize QueueDescriptionFeed. skip {}, top: {}", skip,
NUMBER_OF_ELEMENTS);
return Mono.empty();
}
final List<QueueProperties> entities = feed.getEntry().stream()
.filter(e -> e.getContent() != null && e.getContent().getQueueDescription() != null)
.map(e -> {
final String queueName = getTitleValue(e.getTitle());
final QueueProperties queueProperties = EntityHelper.toModel(
e.getContent().getQueueDescription());
EntityHelper.setQueueName(queueProperties, queueName);
return queueProperties;
})
.collect(Collectors.toList());
try {
return Mono.just(extractPage(feedResponse, entities, feed.getLink()));
} catch (MalformedURLException | UnsupportedEncodingException error) {
return Mono.error(new RuntimeException("Could not parse response into FeedPage<QueueDescription>",
error));
}
});
}
/**
* Helper method that invokes the service method, extracts the data and translates it to a PagedResponse.
*
* @param skip Number of elements to skip.
* @param context Context for the query.
*
* @return A Mono that completes with a paged response of rules.
*/
private Mono<PagedResponse<RuleProperties>> listRules(String topicName, String subscriptionName, int skip,
Context context) {
return managementClient.listRulesWithResponseAsync(topicName, subscriptionName, skip, NUMBER_OF_ELEMENTS,
context)
.onErrorMap(ServiceBusAdministrationAsyncClient::mapException)
.flatMap(response -> {
final Response<RuleDescriptionFeed> feedResponse = deserialize(response,
RuleDescriptionFeed.class);
final RuleDescriptionFeed feed = feedResponse.getValue();
if (feed == null) {
logger.warning("Could not deserialize RuleDescriptionFeed. skip {}, top: {}", skip,
NUMBER_OF_ELEMENTS);
return Mono.empty();
}
final List<RuleProperties> entities = feed.getEntry().stream()
.filter(e -> e.getContent() != null && e.getContent().getRuleDescription() != null)
.map(e -> {
return EntityHelper.toModel(e.getContent().getRuleDescription());
})
.collect(Collectors.toList());
try {
return Mono.just(extractPage(feedResponse, entities, feed.getLink()));
} catch (MalformedURLException | UnsupportedEncodingException error) {
return Mono.error(new RuntimeException(
"Could not parse response into FeedPage<RuleDescription>", error));
}
});
}
/**
* Helper method that invokes the service method, extracts the data and translates it to a PagedResponse.
*
* @param skip Number of elements to skip.
* @param context Context for the query.
*
* @return A Mono that completes with a paged response of subscriptions.
*/
private Mono<PagedResponse<SubscriptionProperties>> listSubscriptions(String topicName, int skip,
Context context) {
return managementClient.listSubscriptionsWithResponseAsync(topicName, skip, NUMBER_OF_ELEMENTS, context)
.onErrorMap(ServiceBusAdministrationAsyncClient::mapException)
.flatMap(response -> {
final Response<SubscriptionDescriptionFeed> feedResponse = deserialize(response,
SubscriptionDescriptionFeed.class);
final SubscriptionDescriptionFeed feed = feedResponse.getValue();
if (feed == null) {
logger.warning("Could not deserialize SubscriptionDescriptionFeed. skip {}, top: {}", skip,
NUMBER_OF_ELEMENTS);
return Mono.empty();
}
final List<SubscriptionProperties> entities = feed.getEntry().stream()
.filter(e -> e.getContent() != null && e.getContent().getSubscriptionDescription() != null)
.map(e -> {
final String subscriptionName = getTitleValue(e.getTitle());
final SubscriptionProperties description = EntityHelper.toModel(
e.getContent().getSubscriptionDescription());
EntityHelper.setTopicName(description, topicName);
EntityHelper.setSubscriptionName(description, subscriptionName);
return description;
})
.collect(Collectors.toList());
try {
return Mono.just(extractPage(feedResponse, entities, feed.getLink()));
} catch (MalformedURLException | UnsupportedEncodingException error) {
return Mono.error(new RuntimeException(
"Could not parse response into FeedPage<SubscriptionDescription>", error));
}
});
}
/**
* Helper method that invokes the service method, extracts the data and translates it to a PagedResponse.
*
* @param skip Number of elements to skip.
* @param context Context for the query.
*
* @return A Mono that completes with a paged response of topics.
*/
private Mono<PagedResponse<TopicProperties>> listTopics(int skip, Context context) {
return managementClient.listEntitiesWithResponseAsync(TOPICS_ENTITY_TYPE, skip, NUMBER_OF_ELEMENTS, context)
.onErrorMap(ServiceBusAdministrationAsyncClient::mapException)
.flatMap(response -> {
final Response<TopicDescriptionFeed> feedResponse = deserialize(response, TopicDescriptionFeed.class);
final TopicDescriptionFeed feed = feedResponse.getValue();
if (feed == null) {
logger.warning("Could not deserialize TopicDescriptionFeed. skip {}, top: {}", skip,
NUMBER_OF_ELEMENTS);
return Mono.empty();
}
final List<TopicProperties> entities = feed.getEntry().stream()
.filter(e -> e.getContent() != null && e.getContent().getTopicDescription() != null)
.map(e -> {
final String topicName = getTitleValue(e.getTitle());
final TopicProperties topicProperties = EntityHelper.toModel(
e.getContent().getTopicDescription());
EntityHelper.setTopicName(topicProperties, topicName);
return topicProperties;
})
.collect(Collectors.toList());
try {
return Mono.just(extractPage(feedResponse, entities, feed.getLink()));
} catch (MalformedURLException | UnsupportedEncodingException error) {
return Mono.error(new RuntimeException("Could not parse response into FeedPage<TopicDescription>",
error));
}
});
}
/**
* Given an XML title element, returns the XML text inside. Jackson deserializes Objects as LinkedHashMaps. XML text
* is represented as an entry with an empty string as the key.
*
* For example, the text returned from this {@code <title text="text/xml">QueueName</title>} is "QueueName".
*
* @param responseTitle XML title element.
*
* @return The XML text inside the title. {@code null} is returned if there is no value.
*/
@SuppressWarnings("unchecked")
private String getTitleValue(Object responseTitle) {
if (!(responseTitle instanceof Map)) {
return null;
}
final Map<String, String> map;
try {
map = (Map<String, String>) responseTitle;
return map.get("");
} catch (ClassCastException error) {
logger.warning("Unable to cast to Map<String,String>. Title: {}", responseTitle, error);
return null;
}
}
/**
* Maps an exception from the ATOM APIs to its associated {@link HttpResponseException}.
*
* @param exception Exception from the ATOM API.
*
* @return The corresponding {@link HttpResponseException} or {@code throwable} if it is not an instance of {@link
* ServiceBusManagementErrorException}.
*/
private static Throwable mapException(Throwable exception) {
if (!(exception instanceof ServiceBusManagementErrorException)) {
return exception;
}
final ServiceBusManagementErrorException managementError = ((ServiceBusManagementErrorException) exception);
final ServiceBusManagementError error = managementError.getValue();
final HttpResponse errorHttpResponse = managementError.getResponse();
final int statusCode = error != null && error.getCode() != null
? error.getCode()
: errorHttpResponse.getStatusCode();
final String errorDetail = error != null && error.getDetail() != null
? error.getDetail()
: managementError.getMessage();
switch (statusCode) {
case 401:
return new ClientAuthenticationException(errorDetail, managementError.getResponse(), exception);
case 404:
return new ResourceNotFoundException(errorDetail, managementError.getResponse(), exception);
case 409:
return new ResourceExistsException(errorDetail, managementError.getResponse(), exception);
case 412:
return new ResourceModifiedException(errorDetail, managementError.getResponse(), exception);
default:
return new HttpResponseException(errorDetail, managementError.getResponse(), exception);
}
}
/**
* A page of Service Bus entities.
*
* @param <T> The entity description from Service Bus.
*/
private static final class FeedPage<T> implements PagedResponse<T> {
private final int statusCode;
private final HttpHeaders header;
private final HttpRequest request;
private final IterableStream<T> entries;
private final String continuationToken;
/**
* Creates a page that does not have any more pages.
*
* @param entries Items in the page.
*/
private FeedPage(int statusCode, HttpHeaders header, HttpRequest request, List<T> entries) {
this.statusCode = statusCode;
this.header = header;
this.request = request;
this.entries = new IterableStream<>(entries);
this.continuationToken = null;
}
/**
* Creates an instance that has additional pages to fetch.
*
* @param entries Items in the page.
* @param skip Number of elements to "skip".
*/
private FeedPage(int statusCode, HttpHeaders header, HttpRequest request, List<T> entries, int skip) {
this.statusCode = statusCode;
this.header = header;
this.request = request;
this.entries = new IterableStream<>(entries);
this.continuationToken = String.valueOf(skip);
}
@Override
public IterableStream<T> getElements() {
return entries;
}
@Override
public String getContinuationToken() {
return continuationToken;
}
@Override
public int getStatusCode() {
return statusCode;
}
@Override
public HttpHeaders getHeaders() {
return header;
}
@Override
public HttpRequest getRequest() {
return request;
}
@Override
public void close() {
}
}
private static final class EntityNotFoundHttpResponse<T> extends HttpResponse {
private final int statusCode;
private final HttpHeaders headers;
private EntityNotFoundHttpResponse(Response<T> response) {
super(response.getRequest());
this.headers = response.getHeaders();
this.statusCode = response.getStatusCode();
}
@Override
public int getStatusCode() {
return statusCode;
}
@Override
public String getHeaderValue(String name) {
return headers.getValue(name);
}
@Override
public HttpHeaders getHeaders() {
return headers;
}
@Override
public Flux<ByteBuffer> getBody() {
return Flux.empty();
}
@Override
public Mono<byte[]> getBodyAsByteArray() {
return Mono.empty();
}
@Override
public Mono<String> getBodyAsString() {
return Mono.empty();
}
@Override
public Mono<String> getBodyAsString(Charset charset) {
return Mono.empty();
}
}
} | class ServiceBusAdministrationAsyncClient {
private static final String SERVICE_BUS_TRACING_NAMESPACE_VALUE = "Microsoft.ServiceBus";
private static final String CONTENT_TYPE = "application/xml";
private static final String QUEUES_ENTITY_TYPE = "queues";
private static final String TOPICS_ENTITY_TYPE = "topics";
private static final int NUMBER_OF_ELEMENTS = 100;
private final ServiceBusManagementClientImpl managementClient;
private final EntitiesImpl entityClient;
private final ClientLogger logger = new ClientLogger(ServiceBusAdministrationAsyncClient.class);
private final ServiceBusManagementSerializer serializer;
private final RulesImpl rulesClient;
/**
* Creates a new instance with the given management client and serializer.
*
* @param managementClient Client to make management calls.
* @param serializer Serializer to deserialize ATOM XML responses.
*/
ServiceBusAdministrationAsyncClient(ServiceBusManagementClientImpl managementClient,
ServiceBusManagementSerializer serializer) {
this.serializer = Objects.requireNonNull(serializer, "'serializer' cannot be null.");
this.managementClient = Objects.requireNonNull(managementClient, "'managementClient' cannot be null.");
this.entityClient = managementClient.getEntities();
this.rulesClient = managementClient.getRules();
}
/**
* Creates a queue with the given name.
*
* @param queueName Name of the queue to create.
*
* @return A Mono that completes with information about the created queue.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If the request body was invalid, the queue quota is exceeded, or an error
* occurred processing the request.
* @throws NullPointerException if {@code queueName} is null.
* @throws IllegalArgumentException if {@code queueName} is an empty string.
* @throws ResourceExistsException if a queue exists with the same {@code queueName}.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<QueueProperties> createQueue(String queueName) {
try {
return createQueue(queueName, new CreateQueueOptions());
} catch (RuntimeException e) {
return monoError(logger, e);
}
}
/**
* Creates a queue with the {@link CreateQueueOptions} and given queue name.
*
* @param queueName Name of the queue to create.
* @param queueOptions Options about the queue to create.
*
* @return A Mono that completes with information about the created queue.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If the request body was invalid, the queue quota is exceeded, or an error
* occurred processing the request.
* @throws IllegalArgumentException if {@code queueName} is an empty string.
* @throws NullPointerException if {@code queueName} or {@code queueOptions} is null.
* @throws ResourceExistsException if a queue exists with the same {@link QueueProperties
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<QueueProperties> createQueue(String queueName, CreateQueueOptions queueOptions) {
return createQueueWithResponse(queueName, queueOptions).map(Response::getValue);
}
/**
* Creates a queue and returns the created queue in addition to the HTTP response.
*
* @param queueName Name of the queue to create.
* @param queueOptions Options about the queue to create.
*
* @return A Mono that returns the created queue in addition to the HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If the request body was invalid, the queue quota is exceeded, or an error
* occurred processing the request.
* @throws IllegalArgumentException if {@code queueName} is an empty string.
* @throws NullPointerException if {@code queueName} or {@code queueOptions} is null.
* @throws ResourceExistsException if a queue exists with the same {@link QueueProperties
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<QueueProperties>> createQueueWithResponse(String queueName, CreateQueueOptions queueOptions) {
return withContext(context -> createQueueWithResponse(queueName, queueOptions, context));
}
/**
* Creates a rule under the given topic and subscription
*
* @param topicName Name of the topic associated with rule.
* @param subscriptionName Name of the subscription associated with the rule.
* @param ruleName Name of the rule.
*
* @return A Mono that completes with information about the created rule.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If the request body was invalid, the quota is exceeded, or an error occurred
* processing the request.
* @throws IllegalArgumentException if {@code topicName} or {@code ruleName} are are empty strings.
* @throws NullPointerException if {@code topicName} or {@code ruleName} are are null.
* @throws ResourceExistsException if a rule exists with the same topic, subscription, and rule name.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<RuleProperties> createRule(String topicName, String subscriptionName, String ruleName) {
try {
return createRule(topicName, subscriptionName, ruleName, new CreateRuleOptions());
} catch (RuntimeException e) {
return monoError(logger, e);
}
}
/**
* Creates a rule with the {@link CreateRuleOptions}.
*
* @param topicName Name of the topic associated with rule.
* @param subscriptionName Name of the subscription associated with the rule.
* @param ruleName Name of the rule.
* @param ruleOptions Information about the rule to create.
*
* @return A Mono that completes with information about the created rule.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If the request body was invalid, the quota is exceeded, or an error occurred
* processing the request.
* @throws IllegalArgumentException if {@code topicName} or {@code ruleName} are are empty strings.
* @throws NullPointerException if {@code topicName}, {@code ruleName}, or {@code ruleOptions}
* are are null.
* @throws ResourceExistsException if a rule exists with the same topic and rule name.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<RuleProperties> createRule(String topicName, String subscriptionName, String ruleName,
CreateRuleOptions ruleOptions) {
return createRuleWithResponse(topicName, subscriptionName, ruleName, ruleOptions)
.map(Response::getValue);
}
/**
* Creates a rule and returns the created rule in addition to the HTTP response.
*
* @param topicName Name of the topic associated with rule.
* @param subscriptionName Name of the subscription associated with the rule.
* @param ruleName Name of the rule.
* @param ruleOptions Information about the rule to create.
*
* @return A Mono that returns the created rule in addition to the HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If the request body was invalid, the quota is exceeded, or an error occurred
* processing the request.
* @throws IllegalArgumentException if {@code topicName} or {@code ruleName} are are empty strings.
* @throws NullPointerException if {@code topicName}, {@code ruleName}, or {@code ruleOptions}
* are are null.
* @throws ResourceExistsException if a rule exists with the same topic and rule name.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<RuleProperties>> createRuleWithResponse(String topicName, String subscriptionName,
String ruleName, CreateRuleOptions ruleOptions) {
return withContext(context -> createRuleWithResponse(topicName, subscriptionName, ruleName, ruleOptions,
context));
}
/**
* Creates a subscription with the given topic and subscription names.
*
* @param topicName Name of the topic associated with subscription.
* @param subscriptionName Name of the subscription.
*
* @return A Mono that completes with information about the created subscription.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If the request body was invalid, the quota is exceeded, or an error occurred
* processing the request.
* @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} are are empty strings.
* @throws NullPointerException if {@code topicName} or {@code subscriptionName} are are null.
* @throws ResourceExistsException if a subscription exists with the same topic and subscription name.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<SubscriptionProperties> createSubscription(String topicName, String subscriptionName) {
try {
return createSubscription(topicName, subscriptionName, new CreateSubscriptionOptions());
} catch (RuntimeException e) {
return monoError(logger, e);
}
}
/**
* Creates a subscription with the {@link CreateSubscriptionOptions}.
*
* @param topicName Name of the topic associated with subscription.
* @param subscriptionName Name of the subscription.
* @param subscriptionOptions Information about the subscription to create.
*
* @return A Mono that completes with information about the created subscription.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If the request body was invalid, the quota is exceeded, or an error occurred
* processing the request.
* @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} are are empty strings.
* @throws NullPointerException if {@code topicName}, {@code subscriptionName}, or {@code subscriptionOptions}
* are are null.
* @throws ResourceExistsException if a subscription exists with the same topic and subscription name.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<SubscriptionProperties> createSubscription(String topicName, String subscriptionName,
CreateSubscriptionOptions subscriptionOptions) {
return createSubscriptionWithResponse(topicName, subscriptionName, subscriptionOptions)
.map(Response::getValue);
}
/**
* Creates a subscription and returns the created subscription in addition to the HTTP response.
*
* @param topicName Name of the topic associated with subscription.
* @param subscriptionName Name of the subscription.
* @param subscriptionOptions Information about the subscription to create.
*
* @return A Mono that returns the created subscription in addition to the HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If the request body was invalid, the quota is exceeded, or an error occurred
* processing the request.
* @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} are are empty strings.
* @throws NullPointerException if {@code topicName}, {@code subscriptionName}, or {@code subscriptionOptions}
* are are null.
* @throws ResourceExistsException if a subscription exists with the same topic and subscription name.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<SubscriptionProperties>> createSubscriptionWithResponse(String topicName,
String subscriptionName, CreateSubscriptionOptions subscriptionOptions) {
return withContext(context -> createSubscriptionWithResponse(topicName, subscriptionName, subscriptionOptions,
context));
}
/**
* Creates a topic with the given name.
*
* @param topicName Name of the topic to create.
*
* @return A Mono that completes with information about the created topic.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If the request body was invalid, the topic quota is exceeded, or an error
* occurred processing the request.
* @throws NullPointerException if {@code topicName} is null.
* @throws IllegalArgumentException if {@code topicName} is an empty string.
* @throws ResourceExistsException if a topic exists with the same {@code topicName}.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<TopicProperties> createTopic(String topicName) {
try {
return createTopic(topicName, new CreateTopicOptions());
} catch (RuntimeException e) {
return monoError(logger, e);
}
}
/**
* Creates a topic with the {@link CreateTopicOptions}.
*
* @param topicName Name of the topic to create.
* @param topicOptions The options used to create the topic.
*
* @return A Mono that completes with information about the created topic.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If the request body was invalid, the topic quota is exceeded, or an error
* occurred processing the request.
* @throws IllegalArgumentException if {@code topicName} is an empty string.
* @throws NullPointerException if {@code topicName} or {@code topicOptions} is null.
* @throws ResourceExistsException if a topic exists with the same {@code topicName}.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<TopicProperties> createTopic(String topicName, CreateTopicOptions topicOptions) {
return createTopicWithResponse(topicName, topicOptions).map(Response::getValue);
}
/**
* Creates a topic and returns the created topic in addition to the HTTP response.
*
* @param topicName Name of the topic to create.
* @param topicOptions The options used to create the topic.
*
* @return A Mono that returns the created topic in addition to the HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If the request body was invalid, the topic quota is exceeded, or an error
* occurred processing the request.
* @throws IllegalArgumentException if {@link TopicProperties
* string.
* @throws NullPointerException if {@code topicName} or {@code topicOptions} is null.
* @throws ResourceExistsException if a topic exists with the same {@code topicName}.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<TopicProperties>> createTopicWithResponse(String topicName, CreateTopicOptions topicOptions) {
return withContext(context -> createTopicWithResponse(topicName, topicOptions, context));
}
/**
* Deletes a queue the matching {@code queueName}.
*
* @param queueName Name of queue to delete.
*
* @return A Mono that completes when the queue is deleted.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws NullPointerException if {@code queueName} is null.
* @throws IllegalArgumentException if {@code queueName} is an empty string.
* @throws ResourceNotFoundException if the {@code queueName} does not exist.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Void> deleteQueue(String queueName) {
return deleteQueueWithResponse(queueName).then();
}
/**
* Deletes a queue the matching {@code queueName} and returns the HTTP response.
*
* @param queueName Name of queue to delete.
*
* @return A Mono that completes when the queue is deleted and returns the HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws NullPointerException if {@code queueName} is null.
* @throws IllegalArgumentException if {@code queueName} is an empty string.
* @throws ResourceNotFoundException if the {@code queueName} does not exist.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Void>> deleteQueueWithResponse(String queueName) {
return withContext(context -> deleteQueueWithResponse(queueName, context));
}
/**
* Deletes a rule the matching {@code ruleName}.
*
* @param topicName Name of topic associated with rule to delete.
* @param subscriptionName Name of the subscription associated with the rule to delete.
* @param ruleName Name of rule to delete.
*
* @return A Mono that completes when the rule is deleted.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code topicName} or {@code ruleName} is an empty string.
* @throws NullPointerException if {@code topicName} or {@code ruleName} is null.
* @throws ResourceNotFoundException if the {@code ruleName} does not exist.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Void> deleteRule(String topicName, String subscriptionName, String ruleName) {
return deleteRuleWithResponse(topicName, subscriptionName, ruleName).then();
}
/**
* Deletes a rule the matching {@code ruleName} and returns the HTTP response.
*
* @param topicName Name of topic associated with rule to delete.
* @param subscriptionName Name of the subscription associated with the rule to delete.
* @param ruleName Name of rule to delete.
*
* @return A Mono that completes when the rule is deleted and returns the HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code topicName}, {@code subscriptionName}, or {@code ruleName} is an
* empty string.
* @throws NullPointerException if {@code topicName}, {@code subscriptionName}, or {@code ruleName} is null.
* @throws ResourceNotFoundException if the {@code ruleName} does not exist.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Void>> deleteRuleWithResponse(String topicName, String subscriptionName,
String ruleName) {
return withContext(context -> deleteRuleWithResponse(topicName, subscriptionName, ruleName, context));
}
/**
* Deletes a subscription the matching {@code subscriptionName}.
*
* @param topicName Name of topic associated with subscription to delete.
* @param subscriptionName Name of subscription to delete.
*
* @return A Mono that completes when the subscription is deleted.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} is an empty string.
* @throws NullPointerException if {@code topicName} or {@code subscriptionName} is null.
* @throws ResourceNotFoundException if the {@code subscriptionName} does not exist.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Void> deleteSubscription(String topicName, String subscriptionName) {
return deleteSubscriptionWithResponse(topicName, subscriptionName).then();
}
/**
* Deletes a subscription the matching {@code subscriptionName} and returns the HTTP response.
*
* @param topicName Name of topic associated with subscription to delete.
* @param subscriptionName Name of subscription to delete.
*
* @return A Mono that completes when the subscription is deleted and returns the HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} is an empty string.
* @throws NullPointerException if {@code topicName} or {@code subscriptionName} is null.
* @throws ResourceNotFoundException if the {@code subscriptionName} does not exist.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Void>> deleteSubscriptionWithResponse(String topicName, String subscriptionName) {
return withContext(context -> deleteSubscriptionWithResponse(topicName, subscriptionName, context));
}
/**
* Deletes a topic the matching {@code topicName}.
*
* @param topicName Name of topic to delete.
*
* @return A Mono that completes when the topic is deleted.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code topicName} is an empty string.
* @throws NullPointerException if {@code topicName} is null.
* @throws ResourceNotFoundException if the {@code topicName} does not exist.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Void> deleteTopic(String topicName) {
return deleteTopicWithResponse(topicName).then();
}
/**
* Deletes a topic the matching {@code topicName} and returns the HTTP response.
*
* @param topicName Name of topic to delete.
*
* @return A Mono that completes when the topic is deleted and returns the HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code topicName} is an empty string.
* @throws NullPointerException if {@code topicName} is null.
* @throws ResourceNotFoundException if the {@code topicName} does not exist.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Void>> deleteTopicWithResponse(String topicName) {
return withContext(context -> deleteTopicWithResponse(topicName, context));
}
/**
* Gets information about the queue.
*
* @param queueName Name of queue to get information about.
*
* @return A Mono that completes with information about the queue.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code queueName} is an empty string.
* @throws NullPointerException if {@code queueName} is null.
* @throws ResourceNotFoundException if the {@code queueName} does not exist.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<QueueProperties> getQueue(String queueName) {
return getQueueWithResponse(queueName).map(Response::getValue);
}
/**
* Gets information about the queue along with its HTTP response.
*
* @param queueName Name of queue to get information about.
*
* @return A Mono that completes with information about the queue and the associated HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code queueName} is an empty string.
* @throws NullPointerException if {@code queueName} is null.
* @throws ResourceNotFoundException if the {@code queueName} does not exist.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<QueueProperties>> getQueueWithResponse(String queueName) {
return withContext(context -> getQueueWithResponse(queueName, context, Function.identity()));
}
/**
* Gets whether or not a queue with {@code queueName} exists in the Service Bus namespace.
*
* @param queueName Name of the queue.
*
* @return A Mono that completes indicating whether or not the queue exists.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code queueName} is an empty string.
* @throws NullPointerException if {@code queueName} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Boolean> getQueueExists(String queueName) {
return getQueueExistsWithResponse(queueName).map(Response::getValue);
}
/**
* Gets whether or not a queue with {@code queueName} exists in the Service Bus namespace.
*
* @param queueName Name of the queue.
*
* @return A Mono that completes indicating whether or not the queue exists along with its HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code queueName} is an empty string.
* @throws NullPointerException if {@code queueName} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Boolean>> getQueueExistsWithResponse(String queueName) {
return getEntityExistsWithResponse(getQueueWithResponse(queueName));
}
/**
* Gets runtime properties about the queue.
*
* @param queueName Name of queue to get information about.
*
* @return A Mono that completes with runtime properties about the queue.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code queueName} is an empty string.
* @throws NullPointerException if {@code queueName} is null.
* @throws ResourceNotFoundException if the {@code queueName} does not exist.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<QueueRuntimeProperties> getQueueRuntimeProperties(String queueName) {
return getQueueRuntimePropertiesWithResponse(queueName).map(response -> response.getValue());
}
/**
* Gets runtime properties about the queue along with its HTTP response.
*
* @param queueName Name of queue to get information about.
*
* @return A Mono that completes with runtime properties about the queue and the associated HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code queueName} is an empty string.
* @throws NullPointerException if {@code queueName} is null.
* @throws ResourceNotFoundException if the {@code queueName} does not exist.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<QueueRuntimeProperties>> getQueueRuntimePropertiesWithResponse(String queueName) {
return withContext(context -> getQueueWithResponse(queueName, context, QueueRuntimeProperties::new));
}
/**
* Gets information about the Service Bus namespace.
*
* @return A Mono that completes with information about the Service Bus namespace.
* @throws ClientAuthenticationException if the client's credentials do not have access to the namespace.
* @throws HttpResponseException If error occurred processing the request.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<NamespaceProperties> getNamespaceProperties() {
return getNamespacePropertiesWithResponse().map(Response::getValue);
}
/**
* Gets information about the Service Bus namespace along with its HTTP response.
*
* @return A Mono that completes with information about the namespace and the associated HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<NamespaceProperties>> getNamespacePropertiesWithResponse() {
return withContext(this::getNamespacePropertiesWithResponse);
}
/**
* Gets a rule from the service namespace.
*
* Only following data types are deserialized in Filters and Action parameters - string, int, long, boolean, double,
* and OffsetDateTime. Other data types would return its string value.
*
* @param topicName The name of the topic relative to service bus namespace.
* @param subscriptionName The subscription name the rule belongs to.
* @param ruleName The name of the rule to retrieve.
*
* @return The associated rule.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<RuleProperties> getRule(String topicName, String subscriptionName, String ruleName) {
return getRuleWithResponse(topicName, subscriptionName, ruleName).map(response -> response.getValue());
}
/**
* Gets a rule from the service namespace.
*
* Only following data types are deserialized in Filters and Action parameters - string, int, long, bool, double,
* and OffsetDateTime. Other data types would return its string value.
*
* @param topicName The name of the topic relative to service bus namespace.
* @param subscriptionName The subscription name the rule belongs to.
* @param ruleName The name of the rule to retrieve.
*
* @return The associated rule with the corresponding HTTP response.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<RuleProperties>> getRuleWithResponse(String topicName, String subscriptionName,
String ruleName) {
return withContext(context -> getRuleWithResponse(topicName, subscriptionName, ruleName, context));
}
/**
* Gets information about the queue.
*
* @param topicName Name of topic associated with subscription.
* @param subscriptionName Name of subscription to get information about.
*
* @return A Mono that completes with information about the subscription.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} are empty strings.
* @throws NullPointerException if {@code topicName} or {@code subscriptionName} are null.
* @throws ResourceNotFoundException if the {@code subscriptionName} does not exist in the {@code topicName}.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<SubscriptionProperties> getSubscription(String topicName, String subscriptionName) {
return getSubscriptionWithResponse(topicName, subscriptionName).map(Response::getValue);
}
/**
* Gets information about the subscription along with its HTTP response.
*
* @param topicName Name of topic associated with subscription.
* @param subscriptionName Name of subscription to get information about.
*
* @return A Mono that completes with information about the subscription and the associated HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} are empty strings.
* @throws NullPointerException if {@code topicName} or {@code subscriptionName} are null.
* @throws ResourceNotFoundException if the {@code subscriptionName} does not exist.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<SubscriptionProperties>> getSubscriptionWithResponse(String topicName,
String subscriptionName) {
return withContext(context -> getSubscriptionWithResponse(topicName, subscriptionName, context,
Function.identity()));
}
/**
* Gets whether or not a subscription within a topic exists.
*
* @param topicName Name of topic associated with subscription.
* @param subscriptionName Name of the subscription.
*
* @return A Mono that completes indicating whether or not the subscription exists.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code subscriptionName} is an empty string.
* @throws NullPointerException if {@code subscriptionName} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Boolean> getSubscriptionExists(String topicName, String subscriptionName) {
return getSubscriptionExistsWithResponse(topicName, subscriptionName).map(Response::getValue);
}
/**
* Gets whether or not a subscription within a topic exists.
*
* @param topicName Name of topic associated with subscription.
* @param subscriptionName Name of the subscription.
*
* @return A Mono that completes indicating whether or not the subscription exists along with its HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code subscriptionName} is an empty string.
* @throws NullPointerException if {@code subscriptionName} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Boolean>> getSubscriptionExistsWithResponse(String topicName, String subscriptionName) {
return getEntityExistsWithResponse(getSubscriptionWithResponse(topicName, subscriptionName));
}
/**
* Gets runtime properties about the subscription.
*
* @param topicName Name of topic associated with subscription.
* @param subscriptionName Name of subscription to get information about.
*
* @return A Mono that completes with runtime properties about the subscription.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} are empty strings.
* @throws NullPointerException if {@code topicName} or {@code subscriptionName} are null.
* @throws ResourceNotFoundException if the {@code subscriptionName} does not exist.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<SubscriptionRuntimeProperties> getSubscriptionRuntimeProperties(
String topicName, String subscriptionName) {
return getSubscriptionRuntimePropertiesWithResponse(topicName, subscriptionName)
.map(response -> response.getValue());
}
/**
* Gets runtime properties about the subscription.
*
* @param topicName Name of topic associated with subscription.
* @param subscriptionName Name of subscription to get information about.
*
* @return A Mono that completes with runtime properties about the subscription.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code subscriptionName} is an empty string.
* @throws NullPointerException if {@code subscriptionName} is null.
* @throws ResourceNotFoundException if the {@code subscriptionName} does not exist.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<SubscriptionRuntimeProperties>> getSubscriptionRuntimePropertiesWithResponse(
String topicName, String subscriptionName) {
return withContext(context -> getSubscriptionWithResponse(topicName, subscriptionName, context,
SubscriptionRuntimeProperties::new));
}
/**
* Gets information about the topic.
*
* @param topicName Name of topic to get information about.
*
* @return A Mono that completes with information about the topic.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code topicName} is an empty string.
* @throws NullPointerException if {@code topicName} is null.
* @throws ResourceNotFoundException if the {@code topicName} does not exist.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<TopicProperties> getTopic(String topicName) {
return getTopicWithResponse(topicName).map(Response::getValue);
}
/**
* Gets information about the topic along with its HTTP response.
*
* @param topicName Name of topic to get information about.
*
* @return A Mono that completes with information about the topic and the associated HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code topicName} is an empty string.
* @throws NullPointerException if {@code topicName} is null.
* @throws ResourceNotFoundException if the {@code topicName} does not exist.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<TopicProperties>> getTopicWithResponse(String topicName) {
return withContext(context -> getTopicWithResponse(topicName, context, Function.identity()));
}
/**
* Gets whether or not a topic with {@code topicName} exists in the Service Bus namespace.
*
* @param topicName Name of the topic.
*
* @return A Mono that completes indicating whether or not the topic exists.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code topicName} is an empty string.
* @throws NullPointerException if {@code topicName} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Boolean> getTopicExists(String topicName) {
return getTopicExistsWithResponse(topicName).map(Response::getValue);
}
/**
* Gets whether or not a topic with {@code topicName} exists in the Service Bus namespace.
*
* @param topicName Name of the topic.
*
* @return A Mono that completes indicating whether or not the topic exists along with its HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code topicName} is an empty string.
* @throws NullPointerException if {@code topicName} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Boolean>> getTopicExistsWithResponse(String topicName) {
return getEntityExistsWithResponse(getTopicWithResponse(topicName));
}
/**
* Gets runtime properties about the topic.
*
* @param topicName Name of topic to get information about.
*
* @return A Mono that completes with runtime properties about the topic.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code topicName} is an empty string.
* @throws NullPointerException if {@code topicName} is null.
* @throws ResourceNotFoundException if the {@code topicName} does not exist.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<TopicRuntimeProperties> getTopicRuntimeProperties(String topicName) {
return getTopicRuntimePropertiesWithResponse(topicName).map(response -> response.getValue());
}
/**
* Gets runtime properties about the topic with its HTTP response.
*
* @param topicName Name of topic to get information about.
*
* @return A Mono that completes with runtime properties about the topic and the associated HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If error occurred processing the request.
* @throws IllegalArgumentException if {@code topicName} is an empty string.
* @throws NullPointerException if {@code topicName} is null.
* @throws ResourceNotFoundException if the {@code topicName} does not exist.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<TopicRuntimeProperties>> getTopicRuntimePropertiesWithResponse(String topicName) {
return withContext(context -> getTopicWithResponse(topicName, context, TopicRuntimeProperties::new));
}
/**
* Fetches all the queues in the Service Bus namespace.
*
* @return A Flux of {@link QueueProperties queues} in the Service Bus namespace.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @see <a href="https:
* authorization rules</a>
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux<QueueProperties> listQueues() {
return new PagedFlux<>(
() -> withContext(context -> listQueuesFirstPage(context)),
token -> withContext(context -> listQueuesNextPage(token, context)));
}
/**
* Fetches all the rules for a topic and subscription.
*
* @param topicName The topic name under which all the rules need to be retrieved.
* @param subscriptionName The name of the subscription for which all rules need to be retrieved.
*
* @return A Flux of {@link RuleProperties rules} for the {@code topicName} and {@code subscriptionName}.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws NullPointerException if {@code topicName} or {@code subscriptionName} is null.
* @throws IllegalArgumentException if {@code topicName} or {@code subscriptionName} is an empty string.
* @see <a href="https:
* authorization rules</a>
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux<RuleProperties> listRules(String topicName, String subscriptionName) {
if (topicName == null) {
return pagedFluxError(logger, new NullPointerException("'topicName' cannot be null."));
} else if (topicName.isEmpty()) {
return pagedFluxError(logger, new IllegalArgumentException("'topicName' cannot be an empty string."));
}
return new PagedFlux<>(
() -> withContext(context -> listRulesFirstPage(topicName, subscriptionName, context)),
token -> withContext(context -> listRulesNextPage(topicName, subscriptionName, token, context)));
}
/**
* Fetches all the subscriptions for a topic.
*
* @param topicName The topic name under which all the subscriptions need to be retrieved.
*
* @return A Flux of {@link SubscriptionProperties subscriptions} for the {@code topicName}.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws NullPointerException if {@code topicName} is null.
* @throws IllegalArgumentException if {@code topicName} is an empty string.
* @see <a href="https:
* authorization rules</a>
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux<SubscriptionProperties> listSubscriptions(String topicName) {
if (topicName == null) {
return pagedFluxError(logger, new NullPointerException("'topicName' cannot be null."));
} else if (topicName.isEmpty()) {
return pagedFluxError(logger, new IllegalArgumentException("'topicName' cannot be an empty string."));
}
return new PagedFlux<>(
() -> withContext(context -> listSubscriptionsFirstPage(topicName, context)),
token -> withContext(context -> listSubscriptionsNextPage(topicName, token, context)));
}
/**
* Fetches all the topics in the Service Bus namespace.
*
* @return A Flux of {@link TopicProperties topics} in the Service Bus namespace.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @see <a href="https:
* authorization rules</a>
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux<TopicProperties> listTopics() {
return new PagedFlux<>(
() -> withContext(context -> listTopicsFirstPage(context)),
token -> withContext(context -> listTopicsNextPage(token, context)));
}
/**
* Updates a queue with the given {@link QueueProperties}. The {@link QueueProperties} must be fully populated as
* all of the properties are replaced. If a property is not set the service default value is used.
*
* The suggested flow is:
* <ol>
* <li>{@link
* <li>Update the required elements.</li>
* <li>Pass the updated description into this method.</li>
* </ol>
*
* <p>
* There are a subset of properties that can be updated. More information can be found in the links below. They are:
* <ul>
* <li>{@link QueueProperties
* <li>{@link QueueProperties
* <li>{@link QueueProperties
* </li>
* <li>{@link QueueProperties
* </ul>
*
* @param queue Information about the queue to update. You must provide all the property values that are desired
* on the updated entity. Any values not provided are set to the service default values.
*
* @return A Mono that completes with the updated queue.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If the request body was invalid, the queue quota is exceeded, or an error
* occurred processing the request.
* @throws NullPointerException if {@code queue} is null.
* @see <a href="https:
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<QueueProperties> updateQueue(QueueProperties queue) {
return updateQueueWithResponse(queue).map(Response::getValue);
}
/**
* Updates a queue with the given {@link QueueProperties}. The {@link QueueProperties} must be fully populated as
* all of the properties are replaced. If a property is not set the service default value is used.
*
* The suggested flow is:
* <ol>
* <li>{@link
* <li>Update the required elements.</li>
* <li>Pass the updated description into this method.</li>
* </ol>
*
* <p>
* There are a subset of properties that can be updated. More information can be found in the links below. They are:
* <ul>
* <li>{@link QueueProperties
* <li>{@link QueueProperties
* <li>{@link QueueProperties
* </li>
* <li>{@link QueueProperties
* </ul>
*
* @param queue Information about the queue to update. You must provide all the property values that are desired
* on the updated entity. Any values not provided are set to the service default values.
*
* @return A Mono that returns the updated queue in addition to the HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If the request body was invalid, the queue quota is exceeded, or an error
* occurred processing the request.
* @throws NullPointerException if {@code queue} is null.
* @see <a href="https:
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<QueueProperties>> updateQueueWithResponse(QueueProperties queue) {
return withContext(context -> updateQueueWithResponse(queue, context));
}
/**
* Updates a rule with the given {@link RuleProperties}. The {@link RuleProperties} must be fully populated as all
* of the properties are replaced. If a property is not set the service default value is used.
*
* The suggested flow is:
* <ol>
* <li>{@link
* <li>Update the required elements.</li>
* <li>Pass the updated description into this method.</li>
* </ol>
*
* @param topicName The topic name under which the rule is updated.
* @param subscriptionName The name of the subscription for which the rule is updated.
* @param rule Information about the rule to update. You must provide all the property values that are desired
* on the updated entity. Any values not provided are set to the service default values.
*
* @return A Mono that returns the updated rule.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If the request body was invalid, the rule quota is exceeded, or an error
* occurred processing the request.
* @throws IllegalArgumentException if {@link RuleProperties
* @throws NullPointerException if {@code rule} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<RuleProperties> updateRule(String topicName, String subscriptionName, RuleProperties rule) {
return updateRuleWithResponse(topicName, subscriptionName, rule).map(Response::getValue);
}
/**
* Updates a rule with the given {@link RuleProperties}. The {@link RuleProperties} must be fully populated as all
* of the properties are replaced. If a property is not set the service default value is used.
*
* The suggested flow is:
* <ol>
* <li>{@link
* <li>Update the required elements.</li>
* <li>Pass the updated description into this method.</li>
* </ol>
*
* @param topicName The topic name under which the rule is updated.
* @param subscriptionName The name of the subscription for which the rule is updated.
* @param rule Information about the rule to update. You must provide all the property values that are desired
* on the updated entity. Any values not provided are set to the service default values.
*
* @return A Mono that returns the updated rule in addition to the HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If the request body was invalid, the rule quota is exceeded, or an error
* occurred processing the request.
* @throws IllegalArgumentException if {@link RuleProperties
* @throws NullPointerException if {@code rule} is null.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<RuleProperties>> updateRuleWithResponse(String topicName, String subscriptionName,
RuleProperties rule) {
return withContext(context -> updateRuleWithResponse(topicName, subscriptionName, rule, context));
}
/**
* Updates a subscription with the given {@link SubscriptionProperties}. The {@link SubscriptionProperties} must be
* fully populated as all of the properties are replaced. If a property is not set the service default value is
* used.
*
* The suggested flow is:
* <ol>
* <li>{@link
* <li>Update the required elements.</li>
* <li>Pass the updated description into this method.</li>
* </ol>
*
* <p>
* There are a subset of properties that can be updated. More information can be found in the links below. They are:
* <ul>
* <li>{@link SubscriptionProperties
* <li>{@link SubscriptionProperties
* <li>{@link SubscriptionProperties
* </ul>
*
* @param subscription Information about the subscription to update. You must provide all the property values
* that are desired on the updated entity. Any values not provided are set to the service default values.
*
* @return A Mono that returns the updated subscription.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If the request body was invalid, the subscription quota is exceeded, or an
* error occurred processing the request.
* @throws IllegalArgumentException if {@link SubscriptionProperties
* SubscriptionProperties
* @throws NullPointerException if {@code subscription} is null.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<SubscriptionProperties> updateSubscription(SubscriptionProperties subscription) {
return updateSubscriptionWithResponse(subscription).map(Response::getValue);
}
/**
* Updates a subscription with the given {@link SubscriptionProperties}. The {@link SubscriptionProperties} must be
* fully populated as all of the properties are replaced. If a property is not set the service default value is
* used.
*
* The suggested flow is:
* <ol>
* <li>{@link
* <li>Update the required elements.</li>
* <li>Pass the updated description into this method.</li>
* </ol>
*
* <p>
* There are a subset of properties that can be updated. More information can be found in the links below. They are:
* <ul>
* <li>{@link SubscriptionProperties
* <li>{@link SubscriptionProperties
* <li>{@link SubscriptionProperties
* </ul>
*
* @param subscription Information about the subscription to update. You must provide all the property values
* that are desired on the updated entity. Any values not provided are set to the service default values.
*
* @return A Mono that returns the updated subscription in addition to the HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If the request body was invalid, the subscription quota is exceeded, or an
* error occurred processing the request.
* @throws IllegalArgumentException if {@link SubscriptionProperties
* SubscriptionProperties
* @throws NullPointerException if {@code subscription} is null.
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<SubscriptionProperties>> updateSubscriptionWithResponse(
SubscriptionProperties subscription) {
return withContext(context -> updateSubscriptionWithResponse(subscription, context));
}
/**
* Updates a topic with the given {@link TopicProperties}. The {@link TopicProperties} must be fully populated as
* all of the properties are replaced. If a property is not set the service default value is used.
*
* The suggested flow is:
* <ol>
* <li>{@link
* <li>Update the required elements.</li>
* <li>Pass the updated description into this method.</li>
* </ol>
*
* <p>
* There are a subset of properties that can be updated. More information can be found in the links below. They are:
* <ul>
* <li>{@link TopicProperties
* <li>{@link TopicProperties
* </li>
* </ul>
*
* @param topic Information about the topic to update. You must provide all the property values that are desired
* on the updated entity. Any values not provided are set to the service default values.
*
* @return A Mono that completes with the updated topic.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If the request body was invalid, the topic quota is exceeded, or an error
* occurred processing the request.
* @throws IllegalArgumentException if {@link TopicProperties
* string.
* @throws NullPointerException if {@code topic} is null.
* @see <a href="https:
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<TopicProperties> updateTopic(TopicProperties topic) {
return updateTopicWithResponse(topic).map(Response::getValue);
}
/**
* Updates a topic with the given {@link TopicProperties}. The {@link TopicProperties} must be fully populated as
* all of the properties are replaced. If a property is not set the service default value is used.
*
* The suggested flow is:
* <ol>
* <li>{@link
* <li>Update the required elements.</li>
* <li>Pass the updated description into this method.</li>
* </ol>
*
* <p>
* There are a subset of properties that can be updated. More information can be found in the links below. They are:
* <ul>
* <li>{@link TopicProperties
* <li>{@link TopicProperties
* </li>
* </ul>
*
* @param topic Information about the topic to update. You must provide all the property values that are desired
* on the updated entity. Any values not provided are set to the service default values.
*
* @return A Mono that completes with the updated topic and its HTTP response.
* @throws ClientAuthenticationException if the client's credentials do not have access to modify the
* namespace.
* @throws HttpResponseException If the request body was invalid, the topic quota is exceeded, or an error
* occurred processing the request.
* @throws IllegalArgumentException if {@link TopicProperties
* string.
* @throws NullPointerException if {@code topic} is null.
* @see <a href="https:
* @see <a href="https:
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<TopicProperties>> updateTopicWithResponse(TopicProperties topic) {
return withContext(context -> updateTopicWithResponse(topic, context));
}
/**
* Creates a queue with its context.
*
* @param createQueueOptions Queue to create.
* @param context Context to pass into request.
*
* @return A Mono that completes with the created {@link QueueProperties}.
*/
Mono<Response<QueueProperties>> createQueueWithResponse(String queueName, CreateQueueOptions createQueueOptions,
Context context) {
if (queueName == null) {
return monoError(logger, new NullPointerException("'queueName' cannot be null."));
} else if (queueName.isEmpty()) {
return monoError(logger, new IllegalArgumentException("'queueName' cannot be empty."));
}
if (createQueueOptions == null) {
return monoError(logger, new NullPointerException("'createQueueOptions' cannot be null."));
} else if (context == null) {
return monoError(logger, new NullPointerException("'context' cannot be null."));
}
final QueueDescription description = EntityHelper.getQueueDescription(createQueueOptions);
final CreateQueueBodyContent content = new CreateQueueBodyContent()
.setType(CONTENT_TYPE)
.setQueueDescription(description);
final CreateQueueBody createEntity = new CreateQueueBody()
.setContent(content);
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
try {
return entityClient.putWithResponseAsync(queueName, createEntity, null, withTracing)
.onErrorMap(ServiceBusAdministrationAsyncClient::mapException)
.map(this::deserializeQueue);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Creates a rule with its context.
*
* @param ruleOptions Rule to create.
* @param context Context to pass into request.
*
* @return A Mono that completes with the created {@link RuleProperties}.
*/
Mono<Response<RuleProperties>> createRuleWithResponse(String topicName, String subscriptionName, String ruleName,
CreateRuleOptions ruleOptions, Context context) {
if (topicName == null) {
return monoError(logger, new NullPointerException("'topicName' cannot be null."));
} else if (topicName.isEmpty()) {
return monoError(logger, new IllegalArgumentException("'topicName' cannot be empty."));
}
if (subscriptionName == null) {
return monoError(logger, new NullPointerException("'subscriptionName' cannot be null."));
} else if (subscriptionName.isEmpty()) {
return monoError(logger, new IllegalArgumentException("'subscriptionName' cannot be empty."));
}
if (ruleName == null) {
return monoError(logger, new NullPointerException("'ruleName' cannot be null."));
} else if (ruleName.isEmpty()) {
return monoError(logger, new IllegalArgumentException("'ruleName' cannot be empty."));
}
if (ruleOptions == null) {
return monoError(logger, new NullPointerException("'rule' cannot be null."));
}
final RuleActionImpl action = ruleOptions.getAction() != null
? EntityHelper.toImplementation(ruleOptions.getAction())
: null;
final RuleFilterImpl filter = ruleOptions.getFilter() != null
? EntityHelper.toImplementation(ruleOptions.getFilter())
: null;
final RuleDescription rule = new RuleDescription()
.setAction(action)
.setFilter(filter)
.setName(ruleName);
final CreateRuleBodyContent content = new CreateRuleBodyContent()
.setType(CONTENT_TYPE)
.setRuleDescription(rule);
final CreateRuleBody createEntity = new CreateRuleBody().setContent(content);
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
try {
return managementClient.getRules().putWithResponseAsync(topicName, subscriptionName, ruleName, createEntity,
null, withTracing)
.onErrorMap(ServiceBusAdministrationAsyncClient::mapException)
.map(response -> deserializeRule(response));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Creates a subscription with its context.
*
* @param subscriptionOptions Subscription to create.
* @param context Context to pass into request.
*
* @return A Mono that completes with the created {@link SubscriptionProperties}.
*/
Mono<Response<SubscriptionProperties>> createSubscriptionWithResponse(String topicName, String subscriptionName,
CreateSubscriptionOptions subscriptionOptions, Context context) {
if (topicName == null) {
return monoError(logger, new NullPointerException("'topicName' cannot be null."));
} else if (topicName.isEmpty()) {
return monoError(logger, new IllegalArgumentException("'topicName' cannot be empty."));
}
if (subscriptionName == null) {
return monoError(logger, new NullPointerException("'subscriptionName' cannot be null."));
} else if (subscriptionName.isEmpty()) {
return monoError(logger, new IllegalArgumentException("'subscriptionName' cannot be empty."));
}
if (subscriptionOptions == null) {
return monoError(logger, new NullPointerException("'subscription' cannot be null."));
}
final SubscriptionDescription subscription = EntityHelper.getSubscriptionDescription(subscriptionOptions);
final CreateSubscriptionBodyContent content = new CreateSubscriptionBodyContent()
.setType(CONTENT_TYPE)
.setSubscriptionDescription(subscription);
final CreateSubscriptionBody createEntity = new CreateSubscriptionBody().setContent(content);
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
try {
return managementClient.getSubscriptions().putWithResponseAsync(topicName, subscriptionName, createEntity,
null, withTracing)
.onErrorMap(ServiceBusAdministrationAsyncClient::mapException)
.map(response -> deserializeSubscription(topicName, response));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Creates a topicOptions with its context.
*
* @param topicOptions Topic to create.
* @param context Context to pass into request.
*
* @return A Mono that completes with the created {@link TopicProperties}.
*/
Mono<Response<TopicProperties>> createTopicWithResponse(String topicName, CreateTopicOptions topicOptions,
Context context) {
if (topicName == null) {
return monoError(logger, new NullPointerException("'topicName' cannot be null."));
} else if (topicName.isEmpty()) {
return monoError(logger, new IllegalArgumentException("'topicName' cannot be empty."));
}
if (topicOptions == null) {
return monoError(logger, new NullPointerException("'topicOptions' cannot be null"));
} else if (context == null) {
return monoError(logger, new NullPointerException("'context' cannot be null."));
}
final TopicDescription topic = EntityHelper.getTopicDescription(topicOptions);
final CreateTopicBodyContent content = new CreateTopicBodyContent()
.setType(CONTENT_TYPE)
.setTopicDescription(topic);
final CreateTopicBody createEntity = new CreateTopicBody()
.setContent(content);
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
try {
return entityClient.putWithResponseAsync(topicName, createEntity, null, withTracing)
.onErrorMap(ServiceBusAdministrationAsyncClient::mapException)
.map(this::deserializeTopic);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Deletes a queue with its context.
*
* @param queueName Name of queue to delete.
* @param context Context to pass into request.
*
* @return A Mono that completes when the queue is deleted.
*/
Mono<Response<Void>> deleteQueueWithResponse(String queueName, Context context) {
if (queueName == null) {
return monoError(logger, new NullPointerException("'queueName' cannot be null"));
} else if (queueName.isEmpty()) {
return monoError(logger, new IllegalArgumentException("'queueName' cannot be an empty string."));
} else if (context == null) {
return monoError(logger, new NullPointerException("'context' cannot be null."));
}
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
try {
return entityClient.deleteWithResponseAsync(queueName, withTracing)
.onErrorMap(ServiceBusAdministrationAsyncClient::mapException)
.map(response -> {
return new SimpleResponse<>(response.getRequest(), response.getStatusCode(),
response.getHeaders(), null);
});
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Deletes a queue with its context.
*
* @param topicName Name of topic to delete.
* @param subscriptionName Name of the subscription for the rule.
* @param ruleName Name of the rule.
* @param context Context to pass into request.
*
* @return A Mono that completes with the created {@link QueueProperties}.
*/
Mono<Response<Void>> deleteRuleWithResponse(String topicName, String subscriptionName, String ruleName,
Context context) {
if (topicName == null) {
return monoError(logger, new NullPointerException("'topicName' cannot be null"));
} else if (topicName.isEmpty()) {
return monoError(logger, new IllegalArgumentException("'topicName' cannot be an empty string."));
} else if (subscriptionName == null) {
return monoError(logger, new NullPointerException("'subscriptionName' cannot be null"));
} else if (subscriptionName.isEmpty()) {
return monoError(logger, new IllegalArgumentException("'subscriptionName' cannot be an empty string."));
} else if (ruleName == null) {
return monoError(logger, new NullPointerException("'ruleName' cannot be null"));
} else if (ruleName.isEmpty()) {
return monoError(logger, new IllegalArgumentException("'ruleName' cannot be an empty string."));
} else if (context == null) {
return monoError(logger, new NullPointerException("'context' cannot be null."));
}
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
try {
return rulesClient.deleteWithResponseAsync(topicName, subscriptionName, ruleName, withTracing)
.onErrorMap(ServiceBusAdministrationAsyncClient::mapException)
.map(response -> new SimpleResponse<>(response.getRequest(), response.getStatusCode(),
response.getHeaders(), null));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Deletes a subscription with its context.
*
* @param topicName Name of topic associated with subscription to delete.
* @param subscriptionName Name of subscription to delete.
* @param context Context to pass into request.
*
* @return A Mono that completes with the created {@link SubscriptionProperties}.
*/
Mono<Response<Void>> deleteSubscriptionWithResponse(String topicName, String subscriptionName, Context context) {
if (subscriptionName == null) {
return monoError(logger, new NullPointerException("'subscriptionName' cannot be null"));
} else if (subscriptionName.isEmpty()) {
return monoError(logger, new IllegalArgumentException("'subscriptionName' cannot be an empty string."));
} else if (topicName == null) {
return monoError(logger, new NullPointerException("'topicName' cannot be null"));
} else if (topicName.isEmpty()) {
return monoError(logger, new IllegalArgumentException("'topicName' cannot be an empty string."));
} else if (context == null) {
return monoError(logger, new NullPointerException("'context' cannot be null."));
}
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
try {
return managementClient.getSubscriptions().deleteWithResponseAsync(topicName, subscriptionName,
withTracing)
.onErrorMap(ServiceBusAdministrationAsyncClient::mapException)
.map(response -> new SimpleResponse<>(response.getRequest(), response.getStatusCode(),
response.getHeaders(), null));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Deletes a topic with its context.
*
* @param topicName Name of topic to delete.
* @param context Context to pass into request.
*
* @return A Mono that completes with the created {@link TopicProperties}.
*/
Mono<Response<Void>> deleteTopicWithResponse(String topicName, Context context) {
if (topicName == null) {
return monoError(logger, new NullPointerException("'topicName' cannot be null"));
} else if (topicName.isEmpty()) {
return monoError(logger, new IllegalArgumentException("'topicName' cannot be an empty string."));
} else if (context == null) {
return monoError(logger, new NullPointerException("'context' cannot be null."));
}
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
try {
return entityClient.deleteWithResponseAsync(topicName, withTracing)
.onErrorMap(ServiceBusAdministrationAsyncClient::mapException)
.map(response -> new SimpleResponse<>(response.getRequest(), response.getStatusCode(),
response.getHeaders(), null));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Gets whether an entity exists.
*
* @param getEntityOperation Operation to get information about entity. If {@link ResourceNotFoundException} is
* thrown, then it is mapped to false.
* @param <T> Entity type.
*
* @return True if the entity exists, false otherwise.
*/
<T> Mono<Response<Boolean>> getEntityExistsWithResponse(Mono<Response<T>> getEntityOperation) {
return getEntityOperation.map(response -> {
final boolean exists = response.getValue() != null;
return (Response<Boolean>) new SimpleResponse<>(response.getRequest(), response.getStatusCode(),
response.getHeaders(), exists);
})
.onErrorResume(ResourceNotFoundException.class, exception -> {
final HttpResponse response = exception.getResponse();
final Response<Boolean> result = new SimpleResponse<>(response.getRequest(), response.getStatusCode(),
response.getHeaders(), false);
return Mono.just(result);
});
}
/**
* Gets a queue with its context.
*
* @param queueName Name of queue to fetch information for.
* @param context Context to pass into request.
*
* @return A Mono that completes with the {@link QueueProperties}.
*/
<T> Mono<Response<T>> getQueueWithResponse(String queueName, Context context,
Function<QueueProperties, T> mapper) {
if (queueName == null) {
return monoError(logger, new NullPointerException("'queueName' cannot be null"));
} else if (queueName.isEmpty()) {
return monoError(logger, new IllegalArgumentException("'queueName' cannot be empty."));
} else if (context == null) {
return monoError(logger, new NullPointerException("'context' cannot be null."));
}
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
try {
return entityClient.getWithResponseAsync(queueName, true, withTracing)
.onErrorMap(ServiceBusAdministrationAsyncClient::mapException)
.handle((response, sink) -> {
final Response<QueueProperties> deserialize = deserializeQueue(response);
if (deserialize.getValue() == null) {
final HttpResponse notFoundResponse = new EntityNotFoundHttpResponse<>(deserialize);
sink.error(new ResourceNotFoundException(String.format("Queue '%s' does not exist.", queueName),
notFoundResponse));
} else {
final T mapped = mapper.apply(deserialize.getValue());
sink.next(new SimpleResponse<>(response.getRequest(), response.getStatusCode(),
response.getHeaders(), mapped));
}
});
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
Mono<Response<RuleProperties>> getRuleWithResponse(String topicName, String subscriptionName,
String ruleName, Context context) {
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
try {
return rulesClient.getWithResponseAsync(topicName, subscriptionName, ruleName, true, withTracing)
.onErrorMap(ServiceBusAdministrationAsyncClient::mapException)
.map(this::deserializeRule);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Gets a subscription with its context.
*
* @param topicName Name of the topic associated with the subscription.
* @param subscriptionName Name of subscription to fetch information for.
* @param context Context to pass into request.
*
* @return A Mono that completes with the {@link SubscriptionProperties}.
*/
<T> Mono<Response<T>> getSubscriptionWithResponse(String topicName, String subscriptionName, Context context,
Function<SubscriptionProperties, T> mapper) {
if (topicName == null) {
return monoError(logger, new NullPointerException("'topicName' cannot be null."));
} else if (topicName.isEmpty()) {
return monoError(logger, new IllegalArgumentException("'topicName' cannot be an empty string."));
} else if (subscriptionName == null) {
return monoError(logger, new NullPointerException("'subscriptionName' cannot be null."));
} else if (subscriptionName.isEmpty()) {
return monoError(logger, new IllegalArgumentException("'subscriptionName' cannot be an empty string."));
} else if (context == null) {
return monoError(logger, new NullPointerException("'context' cannot be null."));
}
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
try {
return managementClient.getSubscriptions().getWithResponseAsync(topicName, subscriptionName, true,
withTracing)
.onErrorMap(ServiceBusAdministrationAsyncClient::mapException)
.handle((response, sink) -> {
final Response<SubscriptionProperties> deserialize = deserializeSubscription(topicName, response);
if (deserialize.getValue() == null) {
final HttpResponse notFoundResponse = new EntityNotFoundHttpResponse<>(deserialize);
sink.error(new ResourceNotFoundException(String.format(
"Subscription '%s' in topic '%s' does not exist.", topicName, subscriptionName),
notFoundResponse));
} else {
final T mapped = mapper.apply(deserialize.getValue());
sink.next(new SimpleResponse<>(response.getRequest(), response.getStatusCode(),
response.getHeaders(), mapped));
}
});
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Gets the namespace properties with its context.
*
* @param context Context to pass into request.
*
* @return A Mono that completes with the {@link NamespaceProperties}.
*/
Mono<Response<NamespaceProperties>> getNamespacePropertiesWithResponse(Context context) {
return managementClient.getNamespaces().getWithResponseAsync(context).handle((response, sink) -> {
final NamespacePropertiesEntry entry = response.getValue();
if (entry == null || entry.getContent() == null) {
sink.error(new AzureException(
"There was no content inside namespace response. Entry: " + response));
return;
}
final NamespaceProperties namespaceProperties = entry.getContent().getNamespaceProperties();
final Response<NamespaceProperties> result = new SimpleResponse<>(response.getRequest(),
response.getStatusCode(), response.getHeaders(), namespaceProperties);
sink.next(result);
});
}
/**
* Gets a topic with its context.
*
* @param topicName Name of topic to fetch information for.
* @param context Context to pass into request.
*
* @return A Mono that completes with the {@link TopicProperties}.
*/
<T> Mono<Response<T>> getTopicWithResponse(String topicName, Context context,
Function<TopicProperties, T> mapper) {
if (topicName == null) {
return monoError(logger, new NullPointerException("'topicName' cannot be null"));
} else if (topicName.isEmpty()) {
return monoError(logger, new IllegalArgumentException("'topicName' cannot be empty."));
} else if (context == null) {
return monoError(logger, new NullPointerException("'context' cannot be null."));
}
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
try {
return entityClient.getWithResponseAsync(topicName, true, withTracing)
.onErrorMap(ServiceBusAdministrationAsyncClient::mapException)
.handle((response, sink) -> {
final Response<TopicProperties> deserialize = deserializeTopic(response);
if (deserialize.getValue() == null) {
final HttpResponse notFoundResponse = new EntityNotFoundHttpResponse<>(deserialize);
sink.error(new ResourceNotFoundException(String.format("Topic '%s' does not exist.", topicName),
notFoundResponse));
} else {
final T mapped = mapper.apply(deserialize.getValue());
sink.next(new SimpleResponse<>(response.getRequest(), response.getStatusCode(),
response.getHeaders(), mapped));
}
});
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Gets the first page of queues with context.
*
* @param context Context to pass into request.
*
* @return A Mono that completes with a page of queues.
*/
Mono<PagedResponse<QueueProperties>> listQueuesFirstPage(Context context) {
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
try {
return listQueues(0, withTracing);
} catch (RuntimeException e) {
return monoError(logger, e);
}
}
/**
* Gets the next page of queues with context.
*
* @param continuationToken Number of items to skip in feed.
* @param context Context to pass into request.
*
* @return A Mono that completes with a page of queues or empty if there are no items left.
*/
Mono<PagedResponse<QueueProperties>> listQueuesNextPage(String continuationToken, Context context) {
if (continuationToken == null || continuationToken.isEmpty()) {
return Mono.empty();
}
try {
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
final int skip = Integer.parseInt(continuationToken);
return listQueues(skip, withTracing);
} catch (RuntimeException e) {
return monoError(logger, e);
}
}
/**
* Gets the first page of rules with context.
*
* @param context Context to pass into request.
*
* @return A Mono that completes with a page of rules.
*/
Mono<PagedResponse<RuleProperties>> listRulesFirstPage(String topicName, String subscriptionName, Context context) {
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
try {
return listRules(topicName, subscriptionName, 0, withTracing);
} catch (RuntimeException e) {
return monoError(logger, e);
}
}
/**
* Gets the next page of rules with context.
*
* @param continuationToken Number of items to skip in feed.
* @param context Context to pass into request.
*
* @return A Mono that completes with a page of rules or empty if there are no items left.
*/
Mono<PagedResponse<RuleProperties>> listRulesNextPage(String topicName, String subscriptionName,
String continuationToken, Context context) {
if (continuationToken == null || continuationToken.isEmpty()) {
return Mono.empty();
}
try {
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
final int skip = Integer.parseInt(continuationToken);
return listRules(topicName, subscriptionName, skip, withTracing);
} catch (RuntimeException e) {
return monoError(logger, e);
}
}
/**
* Gets the first page of subscriptions with context.
*
* @param context Context to pass into request.
*
* @return A Mono that completes with a page of subscriptions.
*/
Mono<PagedResponse<SubscriptionProperties>> listSubscriptionsFirstPage(String topicName, Context context) {
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
try {
return listSubscriptions(topicName, 0, withTracing);
} catch (RuntimeException e) {
return monoError(logger, e);
}
}
/**
* Gets the next page of subscriptions with context.
*
* @param continuationToken Number of items to skip in feed.
* @param context Context to pass into request.
*
* @return A Mono that completes with a page of subscriptions or empty if there are no items left.
*/
Mono<PagedResponse<SubscriptionProperties>> listSubscriptionsNextPage(String topicName, String continuationToken,
Context context) {
if (continuationToken == null || continuationToken.isEmpty()) {
return Mono.empty();
}
try {
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
final int skip = Integer.parseInt(continuationToken);
return listSubscriptions(topicName, skip, withTracing);
} catch (RuntimeException e) {
return monoError(logger, e);
}
}
/**
* Gets the first page of topics with context.
*
* @param context Context to pass into request.
*
* @return A Mono that completes with a page of topics.
*/
Mono<PagedResponse<TopicProperties>> listTopicsFirstPage(Context context) {
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
try {
return listTopics(0, withTracing);
} catch (RuntimeException e) {
return monoError(logger, e);
}
}
/**
* Gets the next page of topics with context.
*
* @param continuationToken Number of items to skip in feed.
* @param context Context to pass into request.
*
* @return A Mono that completes with a page of topics or empty if there are no items left.
*/
Mono<PagedResponse<TopicProperties>> listTopicsNextPage(String continuationToken, Context context) {
if (continuationToken == null || continuationToken.isEmpty()) {
return Mono.empty();
}
try {
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
final int skip = Integer.parseInt(continuationToken);
return listTopics(skip, withTracing);
} catch (RuntimeException e) {
return monoError(logger, e);
}
}
/**
* Updates a queue with its context.
*
* @param queue Information about the queue to update. You must provide all the property values that are desired
* on the updated entity. Any values not provided are set to the service default values.
* @param context Context to pass into request.
*
* @return A Mono that completes with the updated {@link QueueProperties}.
*/
Mono<Response<QueueProperties>> updateQueueWithResponse(QueueProperties queue, Context context) {
if (queue == null) {
return monoError(logger, new NullPointerException("'queue' cannot be null"));
} else if (context == null) {
return monoError(logger, new NullPointerException("'context' cannot be null."));
}
final QueueDescription queueDescription = EntityHelper.toImplementation(queue);
final CreateQueueBodyContent content = new CreateQueueBodyContent()
.setType(CONTENT_TYPE)
.setQueueDescription(queueDescription);
final CreateQueueBody createEntity = new CreateQueueBody()
.setContent(content);
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
try {
return entityClient.putWithResponseAsync(queue.getName(), createEntity, "*", withTracing)
.onErrorMap(ServiceBusAdministrationAsyncClient::mapException)
.map(response -> deserializeQueue(response));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Updates a rule with its context.
*
* @param rule Information about the rule to update. You must provide all the property values that are desired
* on the updated entity. Any values not provided are set to the service default values.
* @param context Context to pass into request.
*
* @return A Mono that completes with the updated {@link RuleProperties}.
*/
Mono<Response<RuleProperties>> updateRuleWithResponse(String topicName, String subscriptionName,
RuleProperties rule, Context context) {
if (rule == null) {
return monoError(logger, new NullPointerException("'rule' cannot be null"));
} else if (context == null) {
return monoError(logger, new NullPointerException("'context' cannot be null."));
}
final RuleDescription implementation = EntityHelper.toImplementation(rule);
final CreateRuleBodyContent content = new CreateRuleBodyContent()
.setType(CONTENT_TYPE)
.setRuleDescription(implementation);
final CreateRuleBody ruleBody = new CreateRuleBody()
.setContent(content);
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
try {
return managementClient.getRules().putWithResponseAsync(topicName, subscriptionName, rule.getName(),
ruleBody, "*", withTracing)
.onErrorMap(ServiceBusAdministrationAsyncClient::mapException)
.map(response -> deserializeRule(response));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Updates a subscription with its context.
*
* @param subscription Information about the subscription to update. You must provide all the property values
* that are desired on the updated entity. Any values not provided are set to the service default values.
* @param context Context to pass into request.
*
* @return A Mono that completes with the updated {@link SubscriptionProperties}.
*/
Mono<Response<SubscriptionProperties>> updateSubscriptionWithResponse(SubscriptionProperties subscription,
Context context) {
if (subscription == null) {
return monoError(logger, new NullPointerException("'subscription' cannot be null"));
} else if (context == null) {
return monoError(logger, new NullPointerException("'context' cannot be null."));
}
final String topicName = subscription.getTopicName();
final String subscriptionName = subscription.getSubscriptionName();
final SubscriptionDescription implementation = EntityHelper.toImplementation(subscription);
final CreateSubscriptionBodyContent content = new CreateSubscriptionBodyContent()
.setType(CONTENT_TYPE)
.setSubscriptionDescription(implementation);
final CreateSubscriptionBody createEntity = new CreateSubscriptionBody()
.setContent(content);
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
try {
return managementClient.getSubscriptions().putWithResponseAsync(topicName, subscriptionName, createEntity,
"*", withTracing)
.onErrorMap(ServiceBusAdministrationAsyncClient::mapException)
.map(response -> deserializeSubscription(topicName, response));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Updates a topic with its context.
*
* @param topic Information about the topic to update. You must provide all the property values that are desired
* on the updated entity. Any values not provided are set to the service default values.
* @param context Context to pass into request.
*
* @return A Mono that completes with the updated {@link TopicProperties}.
*/
Mono<Response<TopicProperties>> updateTopicWithResponse(TopicProperties topic, Context context) {
if (topic == null) {
return monoError(logger, new NullPointerException("'topic' cannot be null"));
} else if (context == null) {
return monoError(logger, new NullPointerException("'context' cannot be null."));
}
final TopicDescription implementation = EntityHelper.toImplementation(topic);
final CreateTopicBodyContent content = new CreateTopicBodyContent()
.setType(CONTENT_TYPE)
.setTopicDescription(implementation);
final CreateTopicBody createEntity = new CreateTopicBody()
.setContent(content);
final Context withTracing = context.addData(AZ_TRACING_NAMESPACE_KEY, SERVICE_BUS_TRACING_NAMESPACE_VALUE);
try {
return entityClient.putWithResponseAsync(topic.getName(), createEntity, "*", withTracing)
.onErrorMap(ServiceBusAdministrationAsyncClient::mapException)
.map(response -> deserializeTopic(response));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
private <T> T deserialize(Object object, Class<T> clazz) {
if (object == null) {
return null;
}
final String contents = String.valueOf(object);
if (contents.isEmpty()) {
return null;
}
try {
return serializer.deserialize(contents, clazz);
} catch (IOException e) {
throw logger.logExceptionAsError(new RuntimeException(String.format(
"Exception while deserializing. Body: [%s]. Class: %s", contents, clazz), e));
}
}
/**
* Given an HTTP response, will deserialize it into a strongly typed Response object.
*
* @param response HTTP response to deserialize response body from.
* @param clazz Class to deserialize response type into.
* @param <T> Class type to deserialize response into.
*
* @return A Response with a strongly typed response value.
*/
private <T> Response<T> deserialize(Response<Object> response, Class<T> clazz) {
final T deserialize = deserialize(response.getValue(), clazz);
return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(),
deserialize);
}
/**
* Converts a Response into its corresponding {@link QueueDescriptionEntry} then mapped into {@link
* QueueProperties}.
*
* @param response HTTP Response to deserialize.
*
* @return The corresponding HTTP response with convenience properties set.
*/
/**
* Converts a Response into its corresponding {@link RuleDescriptionEntry} then mapped into {@link RuleProperties}.
*
* @param response HTTP Response to deserialize.
*
* @return The corresponding HTTP response with convenience properties set.
*/
private Response<RuleProperties> deserializeRule(Response<Object> response) {
final RuleDescriptionEntry entry = deserialize(response.getValue(), RuleDescriptionEntry.class);
if (entry == null) {
return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null);
} else if (entry.getContent() == null) {
logger.info("entry.getContent() is null. The entity may not exist. {}", entry);
return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null);
}
final RuleDescription description = entry.getContent().getRuleDescription();
final RuleProperties result = EntityHelper.toModel(description);
return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), result);
}
/**
* Converts a Response into its corresponding {@link SubscriptionDescriptionEntry} then mapped into {@link
* SubscriptionProperties}.
*
* @param response HTTP Response to deserialize.
*
* @return The corresponding HTTP response with convenience properties set.
*/
private Response<SubscriptionProperties> deserializeSubscription(String topicName, Response<Object> response) {
final SubscriptionDescriptionEntry entry = deserialize(response.getValue(), SubscriptionDescriptionEntry.class);
if (entry == null) {
return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null);
} else if (entry.getContent() == null) {
logger.warning("entry.getContent() is null. There should have been content returned. Entry: {}", entry);
return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null);
}
final SubscriptionProperties subscription = EntityHelper.toModel(
entry.getContent().getSubscriptionDescription());
final String subscriptionName = getTitleValue(entry.getTitle());
EntityHelper.setSubscriptionName(subscription, subscriptionName);
EntityHelper.setTopicName(subscription, topicName);
return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(),
subscription);
}
/**
* Converts a Response into its corresponding {@link TopicDescriptionEntry} then mapped into {@link
* QueueProperties}.
*
* @param response HTTP Response to deserialize.
*
* @return The corresponding HTTP response with convenience properties set.
*/
private Response<TopicProperties> deserializeTopic(Response<Object> response) {
final TopicDescriptionEntry entry = deserialize(response.getValue(), TopicDescriptionEntry.class);
if (entry == null) {
return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null);
} else if (entry.getContent() == null) {
logger.warning("entry.getContent() is null. There should have been content returned. Entry: {}", entry);
return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null);
} else if (entry.getContent().getTopicDescription() == null) {
final QueueDescriptionEntry entryQueue = deserialize(response.getValue(), QueueDescriptionEntry.class);
if (entryQueue != null && entryQueue.getContent() != null && entryQueue.getContent().getQueueDescription() != null) {
logger.warning("'{}' is not a topic, it is a queue.", entryQueue.getTitle());
return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), null);
}
}
final TopicProperties result = EntityHelper.toModel(entry.getContent().getTopicDescription());
final String topicName = getTitleValue(entry.getTitle());
EntityHelper.setTopicName(result, topicName);
return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), result);
}
/**
* Creates a {@link FeedPage} given the elements and a set of response links to get the next link from.
*
* @param entities Entities in the feed.
* @param responseLinks Links returned from the feed.
* @param <TResult> Type of Service Bus entities in page.
*
* @return A {@link FeedPage} indicating whether this can be continued or not.
* @throws MalformedURLException if the "next" page link does not contain a well-formed URL.
*/
private <TResult, TFeed> FeedPage<TResult> extractPage(Response<TFeed> response, List<TResult> entities,
List<ResponseLink> responseLinks)
throws MalformedURLException, UnsupportedEncodingException {
final Optional<ResponseLink> nextLink = responseLinks.stream()
.filter(link -> link.getRel().equalsIgnoreCase("next"))
.findFirst();
if (!nextLink.isPresent()) {
return new FeedPage<>(response.getStatusCode(), response.getHeaders(), response.getRequest(), entities);
}
final URL url = new URL(nextLink.get().getHref());
final String decode = URLDecoder.decode(url.getQuery(), StandardCharsets.UTF_8.name());
final Optional<Integer> skipParameter = Arrays.stream(decode.split("&|&"))
.map(part -> part.split("=", 2))
.filter(parts -> parts[0].equalsIgnoreCase("$skip") && parts.length == 2)
.map(parts -> Integer.valueOf(parts[1]))
.findFirst();
if (skipParameter.isPresent()) {
return new FeedPage<>(response.getStatusCode(), response.getHeaders(), response.getRequest(), entities,
skipParameter.get());
} else {
logger.warning("There should have been a skip parameter for the next page.");
return new FeedPage<>(response.getStatusCode(), response.getHeaders(), response.getRequest(), entities);
}
}
/**
* Helper method that invokes the service method, extracts the data and translates it to a PagedResponse.
*
* @param skip Number of elements to skip.
* @param context Context for the query.
*
* @return A Mono that completes with a paged response of queues.
*/
private Mono<PagedResponse<QueueProperties>> listQueues(int skip, Context context) {
return managementClient.listEntitiesWithResponseAsync(QUEUES_ENTITY_TYPE, skip, NUMBER_OF_ELEMENTS, context)
.onErrorMap(ServiceBusAdministrationAsyncClient::mapException)
.flatMap(response -> {
final Response<QueueDescriptionFeed> feedResponse = deserialize(response, QueueDescriptionFeed.class);
final QueueDescriptionFeed feed = feedResponse.getValue();
if (feed == null) {
logger.warning("Could not deserialize QueueDescriptionFeed. skip {}, top: {}", skip,
NUMBER_OF_ELEMENTS);
return Mono.empty();
}
final List<QueueProperties> entities = feed.getEntry().stream()
.filter(e -> e.getContent() != null && e.getContent().getQueueDescription() != null)
.map(e -> {
final String queueName = getTitleValue(e.getTitle());
final QueueProperties queueProperties = EntityHelper.toModel(
e.getContent().getQueueDescription());
EntityHelper.setQueueName(queueProperties, queueName);
return queueProperties;
})
.collect(Collectors.toList());
try {
return Mono.just(extractPage(feedResponse, entities, feed.getLink()));
} catch (MalformedURLException | UnsupportedEncodingException error) {
return Mono.error(new RuntimeException("Could not parse response into FeedPage<QueueDescription>",
error));
}
});
}
/**
* Helper method that invokes the service method, extracts the data and translates it to a PagedResponse.
*
* @param skip Number of elements to skip.
* @param context Context for the query.
*
* @return A Mono that completes with a paged response of rules.
*/
private Mono<PagedResponse<RuleProperties>> listRules(String topicName, String subscriptionName, int skip,
Context context) {
return managementClient.listRulesWithResponseAsync(topicName, subscriptionName, skip, NUMBER_OF_ELEMENTS,
context)
.onErrorMap(ServiceBusAdministrationAsyncClient::mapException)
.flatMap(response -> {
final Response<RuleDescriptionFeed> feedResponse = deserialize(response,
RuleDescriptionFeed.class);
final RuleDescriptionFeed feed = feedResponse.getValue();
if (feed == null) {
logger.warning("Could not deserialize RuleDescriptionFeed. skip {}, top: {}", skip,
NUMBER_OF_ELEMENTS);
return Mono.empty();
}
final List<RuleProperties> entities = feed.getEntry().stream()
.filter(e -> e.getContent() != null && e.getContent().getRuleDescription() != null)
.map(e -> {
return EntityHelper.toModel(e.getContent().getRuleDescription());
})
.collect(Collectors.toList());
try {
return Mono.just(extractPage(feedResponse, entities, feed.getLink()));
} catch (MalformedURLException | UnsupportedEncodingException error) {
return Mono.error(new RuntimeException(
"Could not parse response into FeedPage<RuleDescription>", error));
}
});
}
/**
* Helper method that invokes the service method, extracts the data and translates it to a PagedResponse.
*
* @param skip Number of elements to skip.
* @param context Context for the query.
*
* @return A Mono that completes with a paged response of subscriptions.
*/
private Mono<PagedResponse<SubscriptionProperties>> listSubscriptions(String topicName, int skip,
Context context) {
return managementClient.listSubscriptionsWithResponseAsync(topicName, skip, NUMBER_OF_ELEMENTS, context)
.onErrorMap(ServiceBusAdministrationAsyncClient::mapException)
.flatMap(response -> {
final Response<SubscriptionDescriptionFeed> feedResponse = deserialize(response,
SubscriptionDescriptionFeed.class);
final SubscriptionDescriptionFeed feed = feedResponse.getValue();
if (feed == null) {
logger.warning("Could not deserialize SubscriptionDescriptionFeed. skip {}, top: {}", skip,
NUMBER_OF_ELEMENTS);
return Mono.empty();
}
final List<SubscriptionProperties> entities = feed.getEntry().stream()
.filter(e -> e.getContent() != null && e.getContent().getSubscriptionDescription() != null)
.map(e -> {
final String subscriptionName = getTitleValue(e.getTitle());
final SubscriptionProperties description = EntityHelper.toModel(
e.getContent().getSubscriptionDescription());
EntityHelper.setTopicName(description, topicName);
EntityHelper.setSubscriptionName(description, subscriptionName);
return description;
})
.collect(Collectors.toList());
try {
return Mono.just(extractPage(feedResponse, entities, feed.getLink()));
} catch (MalformedURLException | UnsupportedEncodingException error) {
return Mono.error(new RuntimeException(
"Could not parse response into FeedPage<SubscriptionDescription>", error));
}
});
}
/**
* Helper method that invokes the service method, extracts the data and translates it to a PagedResponse.
*
* @param skip Number of elements to skip.
* @param context Context for the query.
*
* @return A Mono that completes with a paged response of topics.
*/
private Mono<PagedResponse<TopicProperties>> listTopics(int skip, Context context) {
return managementClient.listEntitiesWithResponseAsync(TOPICS_ENTITY_TYPE, skip, NUMBER_OF_ELEMENTS, context)
.onErrorMap(ServiceBusAdministrationAsyncClient::mapException)
.flatMap(response -> {
final Response<TopicDescriptionFeed> feedResponse = deserialize(response, TopicDescriptionFeed.class);
final TopicDescriptionFeed feed = feedResponse.getValue();
if (feed == null) {
logger.warning("Could not deserialize TopicDescriptionFeed. skip {}, top: {}", skip,
NUMBER_OF_ELEMENTS);
return Mono.empty();
}
final List<TopicProperties> entities = feed.getEntry().stream()
.filter(e -> e.getContent() != null && e.getContent().getTopicDescription() != null)
.map(e -> {
final String topicName = getTitleValue(e.getTitle());
final TopicProperties topicProperties = EntityHelper.toModel(
e.getContent().getTopicDescription());
EntityHelper.setTopicName(topicProperties, topicName);
return topicProperties;
})
.collect(Collectors.toList());
try {
return Mono.just(extractPage(feedResponse, entities, feed.getLink()));
} catch (MalformedURLException | UnsupportedEncodingException error) {
return Mono.error(new RuntimeException("Could not parse response into FeedPage<TopicDescription>",
error));
}
});
}
/**
* Given an XML title element, returns the XML text inside. Jackson deserializes Objects as LinkedHashMaps. XML text
* is represented as an entry with an empty string as the key.
*
* For example, the text returned from this {@code <title text="text/xml">QueueName</title>} is "QueueName".
*
* @param responseTitle XML title element.
*
* @return The XML text inside the title. {@code null} is returned if there is no value.
*/
@SuppressWarnings("unchecked")
private String getTitleValue(Object responseTitle) {
if (!(responseTitle instanceof Map)) {
return null;
}
final Map<String, String> map;
try {
map = (Map<String, String>) responseTitle;
return map.get("");
} catch (ClassCastException error) {
logger.warning("Unable to cast to Map<String,String>. Title: {}", responseTitle, error);
return null;
}
}
/**
* Maps an exception from the ATOM APIs to its associated {@link HttpResponseException}.
*
* @param exception Exception from the ATOM API.
*
* @return The corresponding {@link HttpResponseException} or {@code throwable} if it is not an instance of {@link
* ServiceBusManagementErrorException}.
*/
private static Throwable mapException(Throwable exception) {
if (!(exception instanceof ServiceBusManagementErrorException)) {
return exception;
}
final ServiceBusManagementErrorException managementError = ((ServiceBusManagementErrorException) exception);
final ServiceBusManagementError error = managementError.getValue();
final HttpResponse errorHttpResponse = managementError.getResponse();
final int statusCode = error != null && error.getCode() != null
? error.getCode()
: errorHttpResponse.getStatusCode();
final String errorDetail = error != null && error.getDetail() != null
? error.getDetail()
: managementError.getMessage();
switch (statusCode) {
case 401:
return new ClientAuthenticationException(errorDetail, managementError.getResponse(), exception);
case 404:
return new ResourceNotFoundException(errorDetail, managementError.getResponse(), exception);
case 409:
return new ResourceExistsException(errorDetail, managementError.getResponse(), exception);
case 412:
return new ResourceModifiedException(errorDetail, managementError.getResponse(), exception);
default:
return new HttpResponseException(errorDetail, managementError.getResponse(), exception);
}
}
/**
* A page of Service Bus entities.
*
* @param <T> The entity description from Service Bus.
*/
private static final class FeedPage<T> implements PagedResponse<T> {
private final int statusCode;
private final HttpHeaders header;
private final HttpRequest request;
private final IterableStream<T> entries;
private final String continuationToken;
/**
* Creates a page that does not have any more pages.
*
* @param entries Items in the page.
*/
private FeedPage(int statusCode, HttpHeaders header, HttpRequest request, List<T> entries) {
this.statusCode = statusCode;
this.header = header;
this.request = request;
this.entries = new IterableStream<>(entries);
this.continuationToken = null;
}
/**
* Creates an instance that has additional pages to fetch.
*
* @param entries Items in the page.
* @param skip Number of elements to "skip".
*/
private FeedPage(int statusCode, HttpHeaders header, HttpRequest request, List<T> entries, int skip) {
this.statusCode = statusCode;
this.header = header;
this.request = request;
this.entries = new IterableStream<>(entries);
this.continuationToken = String.valueOf(skip);
}
@Override
public IterableStream<T> getElements() {
return entries;
}
@Override
public String getContinuationToken() {
return continuationToken;
}
@Override
public int getStatusCode() {
return statusCode;
}
@Override
public HttpHeaders getHeaders() {
return header;
}
@Override
public HttpRequest getRequest() {
return request;
}
@Override
public void close() {
}
}
private static final class EntityNotFoundHttpResponse<T> extends HttpResponse {
private final int statusCode;
private final HttpHeaders headers;
private EntityNotFoundHttpResponse(Response<T> response) {
super(response.getRequest());
this.headers = response.getHeaders();
this.statusCode = response.getStatusCode();
}
@Override
public int getStatusCode() {
return statusCode;
}
@Override
public String getHeaderValue(String name) {
return headers.getValue(name);
}
@Override
public HttpHeaders getHeaders() {
return headers;
}
@Override
public Flux<ByteBuffer> getBody() {
return Flux.empty();
}
@Override
public Mono<byte[]> getBodyAsByteArray() {
return Mono.empty();
}
@Override
public Mono<String> getBodyAsString() {
return Mono.empty();
}
@Override
public Mono<String> getBodyAsString(Charset charset) {
return Mono.empty();
}
}
} |
This is int value , it will round to lower value ,how about rounding to upper value . For e.g. 500000/200000 is 2, but it will be better if we do 3. Just to be extra safe Thoughts? | private void bulkCreateItems(final Map<Key, ObjectNode> records) {
final List<CosmosItemOperation> cosmosItemOperations = mapToCosmosItemOperation(records);
final String containerName = _configuration.getCollectionId();
final CosmosAsyncDatabase database = _client.getDatabase(_configuration.getDatabaseId());
final CosmosAsyncContainer container = database.getContainer(containerName);
LOGGER.info("Bulk loading {} documents in [{}:{}]", cosmosItemOperations.size(),
database.getId(),
containerName);
final Duration blockingWaitTime = Duration.ofSeconds(120 * (_configuration.getBulkloadBatchSize() / 200000));
final BulkProcessingOptions<Object> bulkProcessingOptions = new BulkProcessingOptions<>(Object.class);
bulkProcessingOptions.setMaxMicroBatchSize(MAX_BATCH_SIZE)
.setMaxMicroBatchConcurrency(BULK_OPERATION_CONCURRENCY);
container.processBulkOperations(Flux.fromIterable(cosmosItemOperations), bulkProcessingOptions)
.blockLast(blockingWaitTime);
LOGGER.info("Completed loading {} documents into [{}:{}]", cosmosItemOperations.size(),
database.getId(),
containerName);
} | final Duration blockingWaitTime = Duration.ofSeconds(120 * (_configuration.getBulkloadBatchSize() / 200000)); | private void bulkCreateItems(final Map<Key, ObjectNode> records) {
final List<CosmosItemOperation> cosmosItemOperations = mapToCosmosItemOperation(records);
final String containerName = _configuration.getCollectionId();
final CosmosAsyncDatabase database = _client.getDatabase(_configuration.getDatabaseId());
final CosmosAsyncContainer container = database.getContainer(containerName);
LOGGER.info("Bulk loading {} documents in [{}:{}]", cosmosItemOperations.size(),
database.getId(),
containerName);
final Duration blockingWaitTime = Duration.ofSeconds(120 *
(((_configuration.getBulkloadBatchSize() - 1) / 200000) + 1));
final BulkProcessingOptions<Object> bulkProcessingOptions = new BulkProcessingOptions<>(Object.class);
bulkProcessingOptions.setMaxMicroBatchSize(MAX_BATCH_SIZE)
.setMaxMicroBatchConcurrency(BULK_OPERATION_CONCURRENCY);
container.processBulkOperations(Flux.fromIterable(cosmosItemOperations), bulkProcessingOptions)
.blockLast(blockingWaitTime);
LOGGER.info("Completed loading {} documents into [{}:{}]", cosmosItemOperations.size(),
database.getId(),
containerName);
} | class DataLoader {
private static final Logger LOGGER = LoggerFactory.getLogger(DataLoader.class);
private static final int MAX_BATCH_SIZE = 10000;
private static final int BULK_OPERATION_CONCURRENCY = 10;
private static final Duration VALIDATE_DATA_WAIT_DURATION = Duration.ofSeconds(120);
private static final String COUNT_ALL_QUERY = "SELECT COUNT(1) FROM c";
private static final String COUNT_ALL_QUERY_RESULT_FIELD = "$1";
private final Configuration _configuration;
private final CosmosAsyncClient _client;
private final DataGenerationIterator _dataGenerator;
public DataLoader(final Configuration configuration,
final EntityConfiguration entityConfiguration,
final CosmosAsyncClient client) {
Preconditions.checkNotNull(entityConfiguration, "The test entity configuration can not be null");
_configuration = Preconditions.checkNotNull(configuration,
"The Workload configuration defining the parameters can not be null");
_client = Preconditions.checkNotNull(client,
"The CosmosAsyncClient needed for data loading can not be null");
_dataGenerator = new DataGenerationIterator(entityConfiguration.dataGenerator(),
_configuration.getNumberOfPreCreatedDocuments(),
_configuration.getBulkloadBatchSize());
}
public void loadData() {
LOGGER.info("Starting batched data loading, loading {} documents in each iteration",
_configuration.getBulkloadBatchSize());
while (_dataGenerator.hasNext()) {
final Map<Key, ObjectNode> newDocuments = _dataGenerator.next();
bulkCreateItems(newDocuments);
newDocuments.clear();
}
validateDataCreation(_configuration.getNumberOfPreCreatedDocuments());
}
private void validateDataCreation(int expectedSize) {
final String containerName = _configuration.getCollectionId();
final CosmosAsyncDatabase database = _client.getDatabase(_configuration.getDatabaseId());
final CosmosAsyncContainer container = database.getContainer(containerName);
LOGGER.info("Validating {} documents were loaded into [{}:{}]",
expectedSize, _configuration.getDatabaseId(), containerName);
final List<FeedResponse<ObjectNode>> queryItemsResponseList = container
.queryItems(COUNT_ALL_QUERY, ObjectNode.class)
.byPage()
.collectList()
.block(VALIDATE_DATA_WAIT_DURATION);
final int resultCount = Optional.ofNullable(queryItemsResponseList)
.map(responseList -> responseList.get(0))
.map(FeedResponse::getResults)
.map(list -> list.get(0))
.map(objectNode -> objectNode.get(COUNT_ALL_QUERY_RESULT_FIELD).intValue())
.orElse(0);
if (resultCount < (expectedSize * 0.90)) {
throw new IllegalStateException(
String.format("Number of documents %d in the container %s is less than the expected threshold %f ",
resultCount, containerName, (expectedSize * 0.90)));
}
LOGGER.info("Validated {} out of the {} expected documents were loaded into [{}:{}]",
resultCount, expectedSize, _configuration.getDatabaseId(), containerName);
}
/**
* Map the generated data to createItem requests in the underlying container
*
* @param records Data we want to load into the container
* @return List of CosmosItemOperation, each mapping to a createItem for that record
*/
private List<CosmosItemOperation> mapToCosmosItemOperation(final Map<Key, ObjectNode> records) {
return records.entrySet()
.stream()
.map(record -> {
final String partitionKey = record.getKey().getPartitioningKey();
final ObjectNode value = record.getValue();
return BulkOperations.getCreateItemOperation(value, new PartitionKey(partitionKey));
})
.collect(Collectors.toList());
}
} | class DataLoader {
private static final Logger LOGGER = LoggerFactory.getLogger(DataLoader.class);
private static final int MAX_BATCH_SIZE = 10000;
private static final int BULK_OPERATION_CONCURRENCY = 10;
private static final Duration VALIDATE_DATA_WAIT_DURATION = Duration.ofSeconds(120);
private static final String COUNT_ALL_QUERY = "SELECT COUNT(1) FROM c";
private static final String COUNT_ALL_QUERY_RESULT_FIELD = "$1";
private final Configuration _configuration;
private final CosmosAsyncClient _client;
private final DataGenerationIterator _dataGenerator;
public DataLoader(final Configuration configuration,
final EntityConfiguration entityConfiguration,
final CosmosAsyncClient client) {
Preconditions.checkNotNull(entityConfiguration, "The test entity configuration can not be null");
_configuration = Preconditions.checkNotNull(configuration,
"The Workload configuration defining the parameters can not be null");
_client = Preconditions.checkNotNull(client,
"The CosmosAsyncClient needed for data loading can not be null");
_dataGenerator = new DataGenerationIterator(entityConfiguration.dataGenerator(),
_configuration.getNumberOfPreCreatedDocuments(),
_configuration.getBulkloadBatchSize());
}
public void loadData() {
LOGGER.info("Starting batched data loading, loading {} documents in each iteration",
_configuration.getBulkloadBatchSize());
while (_dataGenerator.hasNext()) {
final Map<Key, ObjectNode> newDocuments = _dataGenerator.next();
bulkCreateItems(newDocuments);
newDocuments.clear();
}
validateDataCreation(_configuration.getNumberOfPreCreatedDocuments());
}
private void validateDataCreation(int expectedSize) {
final String containerName = _configuration.getCollectionId();
final CosmosAsyncDatabase database = _client.getDatabase(_configuration.getDatabaseId());
final CosmosAsyncContainer container = database.getContainer(containerName);
LOGGER.info("Validating {} documents were loaded into [{}:{}]",
expectedSize, _configuration.getDatabaseId(), containerName);
final List<FeedResponse<ObjectNode>> queryItemsResponseList = container
.queryItems(COUNT_ALL_QUERY, ObjectNode.class)
.byPage()
.collectList()
.block(VALIDATE_DATA_WAIT_DURATION);
final int resultCount = Optional.ofNullable(queryItemsResponseList)
.map(responseList -> responseList.get(0))
.map(FeedResponse::getResults)
.map(list -> list.get(0))
.map(objectNode -> objectNode.get(COUNT_ALL_QUERY_RESULT_FIELD).intValue())
.orElse(0);
if (resultCount < (expectedSize * 0.90)) {
throw new IllegalStateException(
String.format("Number of documents %d in the container %s is less than the expected threshold %f ",
resultCount, containerName, (expectedSize * 0.90)));
}
LOGGER.info("Validated {} out of the {} expected documents were loaded into [{}:{}]",
resultCount, expectedSize, _configuration.getDatabaseId(), containerName);
}
/**
* Map the generated data to createItem requests in the underlying container
*
* @param records Data we want to load into the container
* @return List of CosmosItemOperation, each mapping to a createItem for that record
*/
private List<CosmosItemOperation> mapToCosmosItemOperation(final Map<Key, ObjectNode> records) {
return records.entrySet()
.stream()
.map(record -> {
final String partitionKey = record.getKey().getPartitioningKey();
final ObjectNode value = record.getValue();
return BulkOperations.getCreateItemOperation(value, new PartitionKey(partitionKey));
})
.collect(Collectors.toList());
}
} |
Going to go with the -1 and + 1 change. | private void bulkCreateItems(final Map<Key, ObjectNode> records) {
final List<CosmosItemOperation> cosmosItemOperations = mapToCosmosItemOperation(records);
final String containerName = _configuration.getCollectionId();
final CosmosAsyncDatabase database = _client.getDatabase(_configuration.getDatabaseId());
final CosmosAsyncContainer container = database.getContainer(containerName);
LOGGER.info("Bulk loading {} documents in [{}:{}]", cosmosItemOperations.size(),
database.getId(),
containerName);
final Duration blockingWaitTime = Duration.ofSeconds(120 * (_configuration.getBulkloadBatchSize() / 200000));
final BulkProcessingOptions<Object> bulkProcessingOptions = new BulkProcessingOptions<>(Object.class);
bulkProcessingOptions.setMaxMicroBatchSize(MAX_BATCH_SIZE)
.setMaxMicroBatchConcurrency(BULK_OPERATION_CONCURRENCY);
container.processBulkOperations(Flux.fromIterable(cosmosItemOperations), bulkProcessingOptions)
.blockLast(blockingWaitTime);
LOGGER.info("Completed loading {} documents into [{}:{}]", cosmosItemOperations.size(),
database.getId(),
containerName);
} | final Duration blockingWaitTime = Duration.ofSeconds(120 * (_configuration.getBulkloadBatchSize() / 200000)); | private void bulkCreateItems(final Map<Key, ObjectNode> records) {
final List<CosmosItemOperation> cosmosItemOperations = mapToCosmosItemOperation(records);
final String containerName = _configuration.getCollectionId();
final CosmosAsyncDatabase database = _client.getDatabase(_configuration.getDatabaseId());
final CosmosAsyncContainer container = database.getContainer(containerName);
LOGGER.info("Bulk loading {} documents in [{}:{}]", cosmosItemOperations.size(),
database.getId(),
containerName);
final Duration blockingWaitTime = Duration.ofSeconds(120 *
(((_configuration.getBulkloadBatchSize() - 1) / 200000) + 1));
final BulkProcessingOptions<Object> bulkProcessingOptions = new BulkProcessingOptions<>(Object.class);
bulkProcessingOptions.setMaxMicroBatchSize(MAX_BATCH_SIZE)
.setMaxMicroBatchConcurrency(BULK_OPERATION_CONCURRENCY);
container.processBulkOperations(Flux.fromIterable(cosmosItemOperations), bulkProcessingOptions)
.blockLast(blockingWaitTime);
LOGGER.info("Completed loading {} documents into [{}:{}]", cosmosItemOperations.size(),
database.getId(),
containerName);
} | class DataLoader {
private static final Logger LOGGER = LoggerFactory.getLogger(DataLoader.class);
private static final int MAX_BATCH_SIZE = 10000;
private static final int BULK_OPERATION_CONCURRENCY = 10;
private static final Duration VALIDATE_DATA_WAIT_DURATION = Duration.ofSeconds(120);
private static final String COUNT_ALL_QUERY = "SELECT COUNT(1) FROM c";
private static final String COUNT_ALL_QUERY_RESULT_FIELD = "$1";
private final Configuration _configuration;
private final CosmosAsyncClient _client;
private final DataGenerationIterator _dataGenerator;
public DataLoader(final Configuration configuration,
final EntityConfiguration entityConfiguration,
final CosmosAsyncClient client) {
Preconditions.checkNotNull(entityConfiguration, "The test entity configuration can not be null");
_configuration = Preconditions.checkNotNull(configuration,
"The Workload configuration defining the parameters can not be null");
_client = Preconditions.checkNotNull(client,
"The CosmosAsyncClient needed for data loading can not be null");
_dataGenerator = new DataGenerationIterator(entityConfiguration.dataGenerator(),
_configuration.getNumberOfPreCreatedDocuments(),
_configuration.getBulkloadBatchSize());
}
public void loadData() {
LOGGER.info("Starting batched data loading, loading {} documents in each iteration",
_configuration.getBulkloadBatchSize());
while (_dataGenerator.hasNext()) {
final Map<Key, ObjectNode> newDocuments = _dataGenerator.next();
bulkCreateItems(newDocuments);
newDocuments.clear();
}
validateDataCreation(_configuration.getNumberOfPreCreatedDocuments());
}
private void validateDataCreation(int expectedSize) {
final String containerName = _configuration.getCollectionId();
final CosmosAsyncDatabase database = _client.getDatabase(_configuration.getDatabaseId());
final CosmosAsyncContainer container = database.getContainer(containerName);
LOGGER.info("Validating {} documents were loaded into [{}:{}]",
expectedSize, _configuration.getDatabaseId(), containerName);
final List<FeedResponse<ObjectNode>> queryItemsResponseList = container
.queryItems(COUNT_ALL_QUERY, ObjectNode.class)
.byPage()
.collectList()
.block(VALIDATE_DATA_WAIT_DURATION);
final int resultCount = Optional.ofNullable(queryItemsResponseList)
.map(responseList -> responseList.get(0))
.map(FeedResponse::getResults)
.map(list -> list.get(0))
.map(objectNode -> objectNode.get(COUNT_ALL_QUERY_RESULT_FIELD).intValue())
.orElse(0);
if (resultCount < (expectedSize * 0.90)) {
throw new IllegalStateException(
String.format("Number of documents %d in the container %s is less than the expected threshold %f ",
resultCount, containerName, (expectedSize * 0.90)));
}
LOGGER.info("Validated {} out of the {} expected documents were loaded into [{}:{}]",
resultCount, expectedSize, _configuration.getDatabaseId(), containerName);
}
/**
* Map the generated data to createItem requests in the underlying container
*
* @param records Data we want to load into the container
* @return List of CosmosItemOperation, each mapping to a createItem for that record
*/
private List<CosmosItemOperation> mapToCosmosItemOperation(final Map<Key, ObjectNode> records) {
return records.entrySet()
.stream()
.map(record -> {
final String partitionKey = record.getKey().getPartitioningKey();
final ObjectNode value = record.getValue();
return BulkOperations.getCreateItemOperation(value, new PartitionKey(partitionKey));
})
.collect(Collectors.toList());
}
} | class DataLoader {
private static final Logger LOGGER = LoggerFactory.getLogger(DataLoader.class);
private static final int MAX_BATCH_SIZE = 10000;
private static final int BULK_OPERATION_CONCURRENCY = 10;
private static final Duration VALIDATE_DATA_WAIT_DURATION = Duration.ofSeconds(120);
private static final String COUNT_ALL_QUERY = "SELECT COUNT(1) FROM c";
private static final String COUNT_ALL_QUERY_RESULT_FIELD = "$1";
private final Configuration _configuration;
private final CosmosAsyncClient _client;
private final DataGenerationIterator _dataGenerator;
public DataLoader(final Configuration configuration,
final EntityConfiguration entityConfiguration,
final CosmosAsyncClient client) {
Preconditions.checkNotNull(entityConfiguration, "The test entity configuration can not be null");
_configuration = Preconditions.checkNotNull(configuration,
"The Workload configuration defining the parameters can not be null");
_client = Preconditions.checkNotNull(client,
"The CosmosAsyncClient needed for data loading can not be null");
_dataGenerator = new DataGenerationIterator(entityConfiguration.dataGenerator(),
_configuration.getNumberOfPreCreatedDocuments(),
_configuration.getBulkloadBatchSize());
}
public void loadData() {
LOGGER.info("Starting batched data loading, loading {} documents in each iteration",
_configuration.getBulkloadBatchSize());
while (_dataGenerator.hasNext()) {
final Map<Key, ObjectNode> newDocuments = _dataGenerator.next();
bulkCreateItems(newDocuments);
newDocuments.clear();
}
validateDataCreation(_configuration.getNumberOfPreCreatedDocuments());
}
private void validateDataCreation(int expectedSize) {
final String containerName = _configuration.getCollectionId();
final CosmosAsyncDatabase database = _client.getDatabase(_configuration.getDatabaseId());
final CosmosAsyncContainer container = database.getContainer(containerName);
LOGGER.info("Validating {} documents were loaded into [{}:{}]",
expectedSize, _configuration.getDatabaseId(), containerName);
final List<FeedResponse<ObjectNode>> queryItemsResponseList = container
.queryItems(COUNT_ALL_QUERY, ObjectNode.class)
.byPage()
.collectList()
.block(VALIDATE_DATA_WAIT_DURATION);
final int resultCount = Optional.ofNullable(queryItemsResponseList)
.map(responseList -> responseList.get(0))
.map(FeedResponse::getResults)
.map(list -> list.get(0))
.map(objectNode -> objectNode.get(COUNT_ALL_QUERY_RESULT_FIELD).intValue())
.orElse(0);
if (resultCount < (expectedSize * 0.90)) {
throw new IllegalStateException(
String.format("Number of documents %d in the container %s is less than the expected threshold %f ",
resultCount, containerName, (expectedSize * 0.90)));
}
LOGGER.info("Validated {} out of the {} expected documents were loaded into [{}:{}]",
resultCount, expectedSize, _configuration.getDatabaseId(), containerName);
}
/**
* Map the generated data to createItem requests in the underlying container
*
* @param records Data we want to load into the container
* @return List of CosmosItemOperation, each mapping to a createItem for that record
*/
private List<CosmosItemOperation> mapToCosmosItemOperation(final Map<Key, ObjectNode> records) {
return records.entrySet()
.stream()
.map(record -> {
final String partitionKey = record.getKey().getPartitioningKey();
final ObjectNode value = record.getValue();
return BulkOperations.getCreateItemOperation(value, new PartitionKey(partitionKey));
})
.collect(Collectors.toList());
}
} |
why do we need to change the decoder? | private void addStartAndEndKeys(final Map<String, String> headers) {
String value = headers.get(HttpHeaders.READ_FEED_KEY_TYPE);
if (StringUtils.isNotEmpty(value)) {
final ReadFeedKeyType type = EnumUtils.getEnumIgnoreCase(ReadFeedKeyType.class, value);
if (type == null) {
final String reason = String.format(Locale.ROOT, RMResources.InvalidRequestHeaderValue,
HttpHeaders.READ_FEED_KEY_TYPE,
value);
throw new IllegalStateException(reason);
}
switch (type) {
case ResourceId:
this.getReadFeedKeyType().setValue(RntbdReadFeedKeyType.ResourceId.id());
break;
case EffectivePartitionKey:
this.getReadFeedKeyType().setValue(RntbdReadFeedKeyType.EffectivePartitionKey.id());
break;
case EffectivePartitionKeyRange:
this.getReadFeedKeyType().setValue(RntbdReadFeedKeyType.EffectivePartitionKeyRange.id());
break;
default:
throw new IllegalStateException(String.format("Invalid ReadFeed key type '%s'.", type));
}
}
final Base64.Decoder decoder = Base64.getDecoder();
value = headers.get(HttpHeaders.START_ID);
if (StringUtils.isNotEmpty(value)) {
this.getStartId().setValue(decoder.decode(value));
}
value = headers.get(HttpHeaders.END_ID);
if (StringUtils.isNotEmpty(value)) {
this.getEndId().setValue(decoder.decode(value));
}
value = headers.get(HttpHeaders.START_EPK);
if (StringUtils.isNotEmpty(value)) {
this.getStartEpk().setValue(value.getBytes(StandardCharsets.UTF_8));
}
value = headers.get(HttpHeaders.END_EPK);
if (StringUtils.isNotEmpty(value)) {
this.getEndEpk().setValue(value.getBytes(StandardCharsets.UTF_8));
}
} | this.getStartEpk().setValue(value.getBytes(StandardCharsets.UTF_8)); | private void addStartAndEndKeys(final Map<String, String> headers) {
String value = headers.get(HttpHeaders.READ_FEED_KEY_TYPE);
if (StringUtils.isNotEmpty(value)) {
final ReadFeedKeyType type = EnumUtils.getEnumIgnoreCase(ReadFeedKeyType.class, value);
if (type == null) {
final String reason = String.format(Locale.ROOT, RMResources.InvalidRequestHeaderValue,
HttpHeaders.READ_FEED_KEY_TYPE,
value);
throw new IllegalStateException(reason);
}
switch (type) {
case ResourceId:
this.getReadFeedKeyType().setValue(RntbdReadFeedKeyType.ResourceId.id());
break;
case EffectivePartitionKey:
this.getReadFeedKeyType().setValue(RntbdReadFeedKeyType.EffectivePartitionKey.id());
break;
case EffectivePartitionKeyRange:
this.getReadFeedKeyType().setValue(RntbdReadFeedKeyType.EffectivePartitionKeyRange.id());
break;
default:
throw new IllegalStateException(String.format("Invalid ReadFeed key type '%s'.", type));
}
}
final Base64.Decoder decoder = Base64.getDecoder();
value = headers.get(HttpHeaders.START_ID);
if (StringUtils.isNotEmpty(value)) {
this.getStartId().setValue(decoder.decode(value));
}
value = headers.get(HttpHeaders.END_ID);
if (StringUtils.isNotEmpty(value)) {
this.getEndId().setValue(decoder.decode(value));
}
value = headers.get(HttpHeaders.START_EPK);
if (StringUtils.isNotEmpty(value)) {
this.getStartEpk().setValue(value.getBytes(StandardCharsets.UTF_8));
}
value = headers.get(HttpHeaders.END_EPK);
if (StringUtils.isNotEmpty(value)) {
this.getEndEpk().setValue(value.getBytes(StandardCharsets.UTF_8));
}
} | class RntbdRequestHeaders extends RntbdTokenStream<RntbdRequestHeader> {
private static final String URL_TRIM = "/";
RntbdRequestHeaders(final RntbdRequestArgs args, final RntbdRequestFrame frame) {
this(Unpooled.EMPTY_BUFFER);
checkNotNull(args, "args");
checkNotNull(frame, "frame");
final RxDocumentServiceRequest request = args.serviceRequest();
final byte[] content = request.getContentAsByteArray();
this.getPayloadPresent().setValue(content != null && content.length > 0);
this.getReplicaPath().setValue(args.replicaPath());
this.getTransportRequestID().setValue(args.transportRequestId());
final Map<String, String> headers = request.getHeaders();
this.addAimHeader(headers);
this.addAllowScanOnQuery(headers);
this.addBinaryIdIfPresent(headers);
this.addCanCharge(headers);
this.addCanOfferReplaceComplete(headers);
this.addCanThrottle(headers);
this.addCollectionRemoteStorageSecurityIdentifier(headers);
this.addConsistencyLevelHeader(headers);
this.addContentSerializationFormat(headers);
this.addContinuationToken(request);
this.addDateHeader(headers);
this.addDisableRUPerMinuteUsage(headers);
this.addEmitVerboseTracesInQuery(headers);
this.addEnableLogging(headers);
this.addEnableLowPrecisionOrderBy(headers);
this.addEntityId(headers);
this.addEnumerationDirection(headers);
this.addExcludeSystemProperties(headers);
this.addFanoutOperationStateHeader(headers);
this.addIfModifiedSinceHeader(headers);
this.addIndexingDirectiveHeader(headers);
this.addIsAutoScaleRequest(headers);
this.addIsFanout(headers);
this.addIsReadOnlyScript(headers);
this.addIsUserRequest(headers);
this.addMatchHeader(headers, frame.getOperationType());
this.addMigrateCollectionDirectiveHeader(headers);
this.addPageSize(headers);
this.addPopulateCollectionThroughputInfo(headers);
this.addPopulatePartitionStatistics(headers);
this.addPopulateQueryMetrics(headers);
this.addPopulateQuotaInfo(headers);
this.addProfileRequest(headers);
this.addQueryForceScan(headers);
this.addRemoteStorageType(headers);
this.addResourceIdOrPathHeaders(request);
this.addResponseContinuationTokenLimitInKb(headers);
this.addShareThroughput(headers);
this.addStartAndEndKeys(headers);
this.addSupportSpatialLegacyCoordinates(headers);
this.addUsePolygonsSmallerThanAHemisphere(headers);
this.addReturnPreference(headers);
this.fillTokenFromHeader(headers, this::getAllowTentativeWrites, BackendHeaders.ALLOW_TENTATIVE_WRITES);
this.fillTokenFromHeader(headers, this::getAuthorizationToken, HttpHeaders.AUTHORIZATION);
this.fillTokenFromHeader(headers, this::getBinaryPassThroughRequest, BackendHeaders.BINARY_PASSTHROUGH_REQUEST);
this.fillTokenFromHeader(headers, this::getBindReplicaDirective, BackendHeaders.BIND_REPLICA_DIRECTIVE);
this.fillTokenFromHeader(headers, this::getClientRetryAttemptCount, HttpHeaders.CLIENT_RETRY_ATTEMPT_COUNT);
this.fillTokenFromHeader(headers, this::getCollectionPartitionIndex, BackendHeaders.COLLECTION_PARTITION_INDEX);
this.fillTokenFromHeader(headers, this::getCollectionRid, BackendHeaders.COLLECTION_RID);
this.fillTokenFromHeader(headers, this::getCollectionServiceIndex, BackendHeaders.COLLECTION_SERVICE_INDEX);
this.fillTokenFromHeader(headers, this::getEffectivePartitionKey, BackendHeaders.EFFECTIVE_PARTITION_KEY);
this.fillTokenFromHeader(headers, this::getEnableDynamicRidRangeAllocation, BackendHeaders.ENABLE_DYNAMIC_RID_RANGE_ALLOCATION);
this.fillTokenFromHeader(headers, this::getFilterBySchemaRid, HttpHeaders.FILTER_BY_SCHEMA_RESOURCE_ID);
this.fillTokenFromHeader(headers, this::getGatewaySignature, HttpHeaders.GATEWAY_SIGNATURE);
this.fillTokenFromHeader(headers, this::getPartitionCount, BackendHeaders.PARTITION_COUNT);
this.fillTokenFromHeader(headers, this::getPartitionKey, HttpHeaders.PARTITION_KEY);
this.fillTokenFromHeader(headers, this::getPartitionKeyRangeId, HttpHeaders.PARTITION_KEY_RANGE_ID);
this.fillTokenFromHeader(headers, this::getPartitionResourceFilter, BackendHeaders.PARTITION_RESOURCE_FILTER);
this.fillTokenFromHeader(headers, this::getPostTriggerExclude, HttpHeaders.POST_TRIGGER_EXCLUDE);
this.fillTokenFromHeader(headers, this::getPostTriggerInclude, HttpHeaders.POST_TRIGGER_INCLUDE);
this.fillTokenFromHeader(headers, this::getPreTriggerExclude, HttpHeaders.PRE_TRIGGER_EXCLUDE);
this.fillTokenFromHeader(headers, this::getPreTriggerInclude, HttpHeaders.PRE_TRIGGER_INCLUDE);
this.fillTokenFromHeader(headers, this::getPrimaryMasterKey, BackendHeaders.PRIMARY_MASTER_KEY);
this.fillTokenFromHeader(headers, this::getPrimaryReadonlyKey, BackendHeaders.PRIMARY_READONLY_KEY);
this.fillTokenFromHeader(headers, this::getRemainingTimeInMsOnClientRequest, HttpHeaders.REMAINING_TIME_IN_MS_ON_CLIENT_REQUEST);
this.fillTokenFromHeader(headers, this::getResourceSchemaName, BackendHeaders.RESOURCE_SCHEMA_NAME);
this.fillTokenFromHeader(headers, this::getResourceTokenExpiry, HttpHeaders.RESOURCE_TOKEN_EXPIRY);
this.fillTokenFromHeader(headers, this::getRestoreMetadataFilter, HttpHeaders.RESTORE_METADATA_FILTER);
this.fillTokenFromHeader(headers, this::getRestoreParams, BackendHeaders.RESTORE_PARAMS);
this.fillTokenFromHeader(headers, this::getSecondaryMasterKey, BackendHeaders.SECONDARY_MASTER_KEY);
this.fillTokenFromHeader(headers, this::getSecondaryReadonlyKey, BackendHeaders.SECONDARY_READONLY_KEY);
this.fillTokenFromHeader(headers, this::getSessionToken, HttpHeaders.SESSION_TOKEN);
this.fillTokenFromHeader(headers, this::getSharedOfferThroughput, HttpHeaders.SHARED_OFFER_THROUGHPUT);
this.fillTokenFromHeader(headers, this::getTargetGlobalCommittedLsn, HttpHeaders.TARGET_GLOBAL_COMMITTED_LSN);
this.fillTokenFromHeader(headers, this::getTargetLsn, HttpHeaders.TARGET_LSN);
this.fillTokenFromHeader(headers, this::getTimeToLiveInSeconds, BackendHeaders.TIME_TO_LIVE_IN_SECONDS);
this.fillTokenFromHeader(headers, this::getTransportRequestID, HttpHeaders.TRANSPORT_REQUEST_ID);
this.fillTokenFromHeader(headers, this::isBatchAtomic, HttpHeaders.IS_BATCH_ATOMIC);
this.fillTokenFromHeader(headers, this::shouldBatchContinueOnError, HttpHeaders.SHOULD_BATCH_CONTINUE_ON_ERROR);
this.fillTokenFromHeader(headers, this::isBatchOrdered, HttpHeaders.IS_BATCH_ORDERED);
this.fillTokenFromHeader(headers, this::getClientVersion, HttpHeaders.VERSION);
}
private RntbdRequestHeaders(ByteBuf in) {
super(RntbdRequestHeader.set, RntbdRequestHeader.map, in);
}
static RntbdRequestHeaders decode(final ByteBuf in) {
final RntbdRequestHeaders metadata = new RntbdRequestHeaders(in);
return RntbdRequestHeaders.decode(metadata);
}
private RntbdToken getAIM() {
return this.get(RntbdRequestHeader.A_IM);
}
private RntbdToken getAllowTentativeWrites() {
return this.get(RntbdRequestHeader.AllowTentativeWrites);
}
private RntbdToken getAttachmentName() {
return this.get(RntbdRequestHeader.AttachmentName);
}
private RntbdToken getAuthorizationToken() {
return this.get(RntbdRequestHeader.AuthorizationToken);
}
private RntbdToken getBinaryId() {
return this.get(RntbdRequestHeader.BinaryId);
}
private RntbdToken getBinaryPassThroughRequest() {
return this.get(RntbdRequestHeader.BinaryPassthroughRequest);
}
private RntbdToken getBindReplicaDirective() {
return this.get(RntbdRequestHeader.BindReplicaDirective);
}
private RntbdToken getCanCharge() {
return this.get(RntbdRequestHeader.CanCharge);
}
private RntbdToken getCanOfferReplaceComplete() {
return this.get(RntbdRequestHeader.CanOfferReplaceComplete);
}
private RntbdToken getCanThrottle() {
return this.get(RntbdRequestHeader.CanThrottle);
}
private RntbdToken getClientRetryAttemptCount() {
return this.get(RntbdRequestHeader.ClientRetryAttemptCount);
}
private RntbdToken getClientVersion() {
return this.get(RntbdRequestHeader.ClientVersion);
}
private RntbdToken getCollectionName() {
return this.get(RntbdRequestHeader.CollectionName);
}
private RntbdToken getCollectionPartitionIndex() {
return this.get(RntbdRequestHeader.CollectionPartitionIndex);
}
private RntbdToken getCollectionRemoteStorageSecurityIdentifier() {
return this.get(RntbdRequestHeader.CollectionRemoteStorageSecurityIdentifier);
}
private RntbdToken getCollectionRid() {
return this.get(RntbdRequestHeader.CollectionRid);
}
private RntbdToken getCollectionServiceIndex() {
return this.get(RntbdRequestHeader.CollectionServiceIndex);
}
private RntbdToken getConflictName() {
return this.get(RntbdRequestHeader.ConflictName);
}
private RntbdToken getConsistencyLevel() {
return this.get(RntbdRequestHeader.ConsistencyLevel);
}
private RntbdToken getContentSerializationFormat() {
return this.get(RntbdRequestHeader.ContentSerializationFormat);
}
private RntbdToken getContinuationToken() {
return this.get(RntbdRequestHeader.ContinuationToken);
}
private RntbdToken getDatabaseName() {
return this.get(RntbdRequestHeader.DatabaseName);
}
private RntbdToken getDate() {
return this.get(RntbdRequestHeader.Date);
}
private RntbdToken getDisableRUPerMinuteUsage() {
return this.get(RntbdRequestHeader.DisableRUPerMinuteUsage);
}
private RntbdToken getDocumentName() {
return this.get(RntbdRequestHeader.DocumentName);
}
private RntbdToken getEffectivePartitionKey() {
return this.get(RntbdRequestHeader.EffectivePartitionKey);
}
private RntbdToken getReturnPreference() {
return this.get(RntbdRequestHeader.ReturnPreference);
}
private RntbdToken getEmitVerboseTracesInQuery() {
return this.get(RntbdRequestHeader.EmitVerboseTracesInQuery);
}
private RntbdToken getEnableDynamicRidRangeAllocation() {
return this.get(RntbdRequestHeader.EnableDynamicRidRangeAllocation);
}
private RntbdToken getEnableLogging() {
return this.get(RntbdRequestHeader.EnableLogging);
}
private RntbdToken getEnableLowPrecisionOrderBy() {
return this.get(RntbdRequestHeader.EnableLowPrecisionOrderBy);
}
private RntbdToken getEnableScanInQuery() {
return this.get(RntbdRequestHeader.EnableScanInQuery);
}
private RntbdToken getEndEpk() {
return this.get(RntbdRequestHeader.EndEpk);
}
private RntbdToken getEndId() {
return this.get(RntbdRequestHeader.EndId);
}
private RntbdToken getEntityId() {
return this.get(RntbdRequestHeader.EntityId);
}
private RntbdToken getEnumerationDirection() {
return this.get(RntbdRequestHeader.EnumerationDirection);
}
private RntbdToken getExcludeSystemProperties() {
return this.get(RntbdRequestHeader.ExcludeSystemProperties);
}
private RntbdToken getFanoutOperationState() {
return this.get(RntbdRequestHeader.FanoutOperationState);
}
private RntbdToken getFilterBySchemaRid() {
return this.get(RntbdRequestHeader.FilterBySchemaRid);
}
private RntbdToken getForceQueryScan() {
return this.get(RntbdRequestHeader.ForceQueryScan);
}
private RntbdToken getGatewaySignature() {
return this.get(RntbdRequestHeader.GatewaySignature);
}
private RntbdToken getIfModifiedSince() {
return this.get(RntbdRequestHeader.IfModifiedSince);
}
private RntbdToken getIndexingDirective() {
return this.get(RntbdRequestHeader.IndexingDirective);
}
private RntbdToken getIsAutoScaleRequest() {
return this.get(RntbdRequestHeader.IsAutoScaleRequest);
}
private RntbdToken getIsFanout() {
return this.get(RntbdRequestHeader.IsFanout);
}
private RntbdToken getIsReadOnlyScript() {
return this.get(RntbdRequestHeader.IsReadOnlyScript);
}
private RntbdToken getIsUserRequest() {
return this.get(RntbdRequestHeader.IsUserRequest);
}
private RntbdToken getMatch() {
return this.get(RntbdRequestHeader.Match);
}
private RntbdToken getMigrateCollectionDirective() {
return this.get(RntbdRequestHeader.MigrateCollectionDirective);
}
private RntbdToken getPageSize() {
return this.get(RntbdRequestHeader.PageSize);
}
private RntbdToken getPartitionCount() {
return this.get(RntbdRequestHeader.PartitionCount);
}
private RntbdToken getPartitionKey() {
return this.get(RntbdRequestHeader.PartitionKey);
}
private RntbdToken getPartitionKeyRangeId() {
return this.get(RntbdRequestHeader.PartitionKeyRangeId);
}
private RntbdToken getPartitionKeyRangeName() {
return this.get(RntbdRequestHeader.PartitionKeyRangeName);
}
private RntbdToken getPartitionResourceFilter() {
return this.get(RntbdRequestHeader.PartitionResourceFilter);
}
private RntbdToken getPayloadPresent() {
return this.get(RntbdRequestHeader.PayloadPresent);
}
private RntbdToken getPermissionName() {
return this.get(RntbdRequestHeader.PermissionName);
}
private RntbdToken getPopulateCollectionThroughputInfo() {
return this.get(RntbdRequestHeader.PopulateCollectionThroughputInfo);
}
private RntbdToken getPopulatePartitionStatistics() {
return this.get(RntbdRequestHeader.PopulatePartitionStatistics);
}
private RntbdToken getPopulateQueryMetrics() {
return this.get(RntbdRequestHeader.PopulateQueryMetrics);
}
private RntbdToken getPopulateQuotaInfo() {
return this.get(RntbdRequestHeader.PopulateQuotaInfo);
}
private RntbdToken getPostTriggerExclude() {
return this.get(RntbdRequestHeader.PostTriggerExclude);
}
private RntbdToken getPostTriggerInclude() {
return this.get(RntbdRequestHeader.PostTriggerInclude);
}
private RntbdToken getPreTriggerExclude() {
return this.get(RntbdRequestHeader.PreTriggerExclude);
}
private RntbdToken getPreTriggerInclude() {
return this.get(RntbdRequestHeader.PreTriggerInclude);
}
private RntbdToken getPrimaryMasterKey() {
return this.get(RntbdRequestHeader.PrimaryMasterKey);
}
private RntbdToken getPrimaryReadonlyKey() {
return this.get(RntbdRequestHeader.PrimaryReadonlyKey);
}
private RntbdToken getProfileRequest() {
return this.get(RntbdRequestHeader.ProfileRequest);
}
private RntbdToken getReadFeedKeyType() {
return this.get(RntbdRequestHeader.ReadFeedKeyType);
}
private RntbdToken getRemainingTimeInMsOnClientRequest() {
return this.get(RntbdRequestHeader.RemainingTimeInMsOnClientRequest);
}
private RntbdToken getRemoteStorageType() {
return this.get(RntbdRequestHeader.RemoteStorageType);
}
private RntbdToken getReplicaPath() {
return this.get(RntbdRequestHeader.ReplicaPath);
}
private RntbdToken getResourceId() {
return this.get(RntbdRequestHeader.ResourceId);
}
private RntbdToken getResourceSchemaName() {
return this.get(RntbdRequestHeader.ResourceSchemaName);
}
private RntbdToken getResourceTokenExpiry() {
return this.get(RntbdRequestHeader.ResourceTokenExpiry);
}
private RntbdToken getResponseContinuationTokenLimitInKb() {
return this.get(RntbdRequestHeader.ResponseContinuationTokenLimitInKb);
}
private RntbdToken getRestoreMetadataFilter() {
return this.get(RntbdRequestHeader.RestoreMetadaFilter);
}
private RntbdToken getRestoreParams() {
return this.get(RntbdRequestHeader.RestoreParams);
}
private RntbdToken getSchemaName() {
return this.get(RntbdRequestHeader.SchemaName);
}
private RntbdToken getSecondaryMasterKey() {
return this.get(RntbdRequestHeader.SecondaryMasterKey);
}
private RntbdToken getSecondaryReadonlyKey() {
return this.get(RntbdRequestHeader.SecondaryReadonlyKey);
}
private RntbdToken getSessionToken() {
return this.get(RntbdRequestHeader.SessionToken);
}
private RntbdToken getShareThroughput() {
return this.get(RntbdRequestHeader.ShareThroughput);
}
private RntbdToken getSharedOfferThroughput() {
return this.get(RntbdRequestHeader.SharedOfferThroughput);
}
private RntbdToken getStartEpk() {
return this.get(RntbdRequestHeader.StartEpk);
}
private RntbdToken getStartId() {
return this.get(RntbdRequestHeader.StartId);
}
private RntbdToken getStoredProcedureName() {
return this.get(RntbdRequestHeader.StoredProcedureName);
}
private RntbdToken getSupportSpatialLegacyCoordinates() {
return this.get(RntbdRequestHeader.SupportSpatialLegacyCoordinates);
}
private RntbdToken getTargetGlobalCommittedLsn() {
return this.get(RntbdRequestHeader.TargetGlobalCommittedLsn);
}
private RntbdToken getTargetLsn() {
return this.get(RntbdRequestHeader.TargetLsn);
}
private RntbdToken getTimeToLiveInSeconds() {
return this.get(RntbdRequestHeader.TimeToLiveInSeconds);
}
private RntbdToken getTransportRequestID() {
return this.get(RntbdRequestHeader.TransportRequestID);
}
private RntbdToken getTriggerName() {
return this.get(RntbdRequestHeader.TriggerName);
}
private RntbdToken getUsePolygonsSmallerThanAHemisphere() {
return this.get(RntbdRequestHeader.UsePolygonsSmallerThanAHemisphere);
}
private RntbdToken getUserDefinedFunctionName() {
return this.get(RntbdRequestHeader.UserDefinedFunctionName);
}
private RntbdToken getUserDefinedTypeName() {
return this.get(RntbdRequestHeader.UserDefinedTypeName);
}
private RntbdToken getUserName() {
return this.get(RntbdRequestHeader.UserName);
}
private RntbdToken isBatchAtomic() {
return this.get(RntbdRequestHeader.IsBatchAtomic);
}
private RntbdToken shouldBatchContinueOnError() {
return this.get(RntbdRequestHeader.ShouldBatchContinueOnError);
}
private RntbdToken isBatchOrdered() {
return this.get(RntbdRequestHeader.IsBatchOrdered);
}
private void addAimHeader(final Map<String, String> headers) {
final String value = headers.get(HttpHeaders.A_IM);
if (StringUtils.isNotEmpty(value)) {
this.getAIM().setValue(value);
}
}
private void addAllowScanOnQuery(final Map<String, String> headers) {
final String value = headers.get(HttpHeaders.ENABLE_SCAN_IN_QUERY);
if (StringUtils.isNotEmpty(value)) {
this.getEnableScanInQuery().setValue(Boolean.parseBoolean(value));
}
}
private void addBinaryIdIfPresent(final Map<String, String> headers) {
final String value = headers.get(BackendHeaders.BINARY_ID);
if (StringUtils.isNotEmpty(value)) {
this.getBinaryId().setValue(Base64.getDecoder().decode(value));
}
}
private void addCanCharge(final Map<String, String> headers) {
final String value = headers.get(HttpHeaders.CAN_CHARGE);
if (StringUtils.isNotEmpty(value)) {
this.getCanCharge().setValue(Boolean.parseBoolean(value));
}
}
private void addCanOfferReplaceComplete(final Map<String, String> headers) {
final String value = headers.get(HttpHeaders.CAN_OFFER_REPLACE_COMPLETE);
if (StringUtils.isNotEmpty(value)) {
this.getCanOfferReplaceComplete().setValue(Boolean.parseBoolean(value));
}
}
private void addCanThrottle(final Map<String, String> headers) {
final String value = headers.get(HttpHeaders.CAN_THROTTLE);
if (StringUtils.isNotEmpty(value)) {
this.getCanThrottle().setValue(Boolean.parseBoolean(value));
}
}
private void addCollectionRemoteStorageSecurityIdentifier(final Map<String, String> headers) {
final String value = headers.get(HttpHeaders.COLLECTION_REMOTE_STORAGE_SECURITY_IDENTIFIER);
if (StringUtils.isNotEmpty(value)) {
this.getCollectionRemoteStorageSecurityIdentifier().setValue(value);
}
}
private void addConsistencyLevelHeader(final Map<String, String> headers) {
final String value = headers.get(HttpHeaders.CONSISTENCY_LEVEL);
if (StringUtils.isNotEmpty(value)) {
final ConsistencyLevel level = BridgeInternal.fromServiceSerializedFormat(value);
if (level == null) {
final String reason = String.format(Locale.ROOT, RMResources.InvalidRequestHeaderValue,
HttpHeaders.CONSISTENCY_LEVEL,
value);
throw new IllegalStateException(reason);
}
switch (level) {
case STRONG:
this.getConsistencyLevel().setValue(RntbdConsistencyLevel.Strong.id());
break;
case BOUNDED_STALENESS:
this.getConsistencyLevel().setValue(RntbdConsistencyLevel.BoundedStaleness.id());
break;
case SESSION:
this.getConsistencyLevel().setValue(RntbdConsistencyLevel.Session.id());
break;
case EVENTUAL:
this.getConsistencyLevel().setValue(RntbdConsistencyLevel.Eventual.id());
break;
case CONSISTENT_PREFIX:
this.getConsistencyLevel().setValue(RntbdConsistencyLevel.ConsistentPrefix.id());
break;
default:
assert false;
break;
}
}
}
private void addContentSerializationFormat(final Map<String, String> headers) {
final String value = headers.get(HttpHeaders.CONTENT_SERIALIZATION_FORMAT);
if (StringUtils.isNotEmpty(value)) {
final ContentSerializationFormat format = EnumUtils.getEnumIgnoreCase(
ContentSerializationFormat.class,
value);
if (format == null) {
final String reason = String.format(Locale.ROOT, RMResources.InvalidRequestHeaderValue,
HttpHeaders.CONTENT_SERIALIZATION_FORMAT,
value);
throw new IllegalStateException(reason);
}
switch (format) {
case JsonText:
this.getContentSerializationFormat().setValue(RntbdContentSerializationFormat.JsonText.id());
break;
case CosmosBinary:
this.getContentSerializationFormat().setValue(RntbdContentSerializationFormat.CosmosBinary.id());
break;
default:
assert false;
}
}
}
private void addContinuationToken(final RxDocumentServiceRequest request) {
final String value = request.getContinuation();
if (StringUtils.isNotEmpty(value)) {
this.getContinuationToken().setValue(value);
}
}
private void addDateHeader(final Map<String, String> headers) {
String value = headers.get(HttpHeaders.X_DATE);
if (StringUtils.isEmpty(value)) {
value = headers.get(HttpHeaders.HTTP_DATE);
}
if (StringUtils.isNotEmpty(value)) {
this.getDate().setValue(value);
}
}
private void addDisableRUPerMinuteUsage(final Map<String, String> headers) {
final String value = headers.get(HttpHeaders.DISABLE_RU_PER_MINUTE_USAGE);
if (StringUtils.isNotEmpty(value)) {
this.getDisableRUPerMinuteUsage().setValue(Boolean.parseBoolean(value));
}
}
private void addEmitVerboseTracesInQuery(final Map<String, String> headers) {
final String value = headers.get(HttpHeaders.EMIT_VERBOSE_TRACES_IN_QUERY);
if (StringUtils.isNotEmpty(value)) {
this.getEmitVerboseTracesInQuery().setValue(Boolean.parseBoolean(value));
}
}
private void addEnableLogging(final Map<String, String> headers) {
final String value = headers.get(HttpHeaders.ENABLE_LOGGING);
if (StringUtils.isNotEmpty(value)) {
this.getEnableLogging().setValue(Boolean.parseBoolean(value));
}
}
private void addEnableLowPrecisionOrderBy(final Map<String, String> headers) {
final String value = headers.get(HttpHeaders.ENABLE_LOW_PRECISION_ORDER_BY);
if (StringUtils.isNotEmpty(value)) {
this.getEnableLowPrecisionOrderBy().setValue(Boolean.parseBoolean(value));
}
}
private void addEntityId(final Map<String, String> headers) {
final String value = headers.get(BackendHeaders.ENTITY_ID);
if (StringUtils.isNotEmpty(value)) {
this.getEntityId().setValue(value);
}
}
private void addEnumerationDirection(final Map<String, String> headers) {
final String value = headers.get(HttpHeaders.ENUMERATION_DIRECTION);
if (StringUtils.isNotEmpty(value)) {
final EnumerationDirection direction = EnumUtils.getEnumIgnoreCase(EnumerationDirection.class, value);
if (direction == null) {
final String reason = String.format(Locale.ROOT, RMResources.InvalidRequestHeaderValue,
HttpHeaders.ENUMERATION_DIRECTION,
value);
throw new IllegalStateException(reason);
}
switch (direction) {
case Forward:
this.getEnumerationDirection().setValue(RntbdEnumerationDirection.Forward.id());
break;
case Reverse:
this.getEnumerationDirection().setValue(RntbdEnumerationDirection.Reverse.id());
break;
default:
assert false;
}
}
}
private void addExcludeSystemProperties(final Map<String, String> headers) {
final String value = headers.get(BackendHeaders.EXCLUDE_SYSTEM_PROPERTIES);
if (StringUtils.isNotEmpty(value)) {
this.getExcludeSystemProperties().setValue(Boolean.parseBoolean(value));
}
}
private void addFanoutOperationStateHeader(final Map<String, String> headers) {
final String value = headers.get(BackendHeaders.FANOUT_OPERATION_STATE);
if (StringUtils.isNotEmpty(value)) {
final FanoutOperationState format = EnumUtils.getEnumIgnoreCase(FanoutOperationState.class, value);
if (format == null) {
final String reason = String.format(Locale.ROOT, RMResources.InvalidRequestHeaderValue,
BackendHeaders.FANOUT_OPERATION_STATE,
value);
throw new IllegalStateException(reason);
}
switch (format) {
case Started:
this.getFanoutOperationState().setValue(RntbdFanoutOperationState.Started.id());
break;
case Completed:
this.getFanoutOperationState().setValue(RntbdFanoutOperationState.Completed.id());
break;
default:
assert false;
}
}
}
private void addIfModifiedSinceHeader(final Map<String, String> headers) {
final String value = headers.get(HttpHeaders.IF_MODIFIED_SINCE);
if (StringUtils.isNotEmpty(value)) {
this.getIfModifiedSince().setValue(value);
}
}
private void addIndexingDirectiveHeader(final Map<String, String> headers) {
final String value = headers.get(HttpHeaders.INDEXING_DIRECTIVE);
if (StringUtils.isNotEmpty(value)) {
final IndexingDirective directive = EnumUtils.getEnumIgnoreCase(IndexingDirective.class, value);
if (directive == null) {
final String reason = String.format(Locale.ROOT, RMResources.InvalidRequestHeaderValue,
HttpHeaders.INDEXING_DIRECTIVE,
value);
throw new IllegalStateException(reason);
}
switch (directive) {
case DEFAULT:
this.getIndexingDirective().setValue(RntbdIndexingDirective.Default.id());
break;
case EXCLUDE:
this.getIndexingDirective().setValue(RntbdIndexingDirective.Exclude.id());
break;
case INCLUDE:
this.getIndexingDirective().setValue(RntbdIndexingDirective.Include.id());
break;
default:
assert false;
}
}
}
private void addIsAutoScaleRequest(final Map<String, String> headers) {
final String value = headers.get(HttpHeaders.IS_AUTO_SCALE_REQUEST);
if (StringUtils.isNotEmpty(value)) {
this.getIsAutoScaleRequest().setValue(Boolean.parseBoolean(value));
}
}
private void addIsFanout(final Map<String, String> headers) {
final String value = headers.get(BackendHeaders.IS_FANOUT_REQUEST);
if (StringUtils.isNotEmpty(value)) {
this.getIsFanout().setValue(Boolean.parseBoolean(value));
}
}
private void addIsReadOnlyScript(final Map<String, String> headers) {
final String value = headers.get(HttpHeaders.IS_READ_ONLY_SCRIPT);
if (StringUtils.isNotEmpty(value)) {
this.getIsReadOnlyScript().setValue(Boolean.parseBoolean(value));
}
}
private void addIsUserRequest(final Map<String, String> headers) {
final String value = headers.get(BackendHeaders.IS_USER_REQUEST);
if (StringUtils.isNotEmpty(value)) {
this.getIsUserRequest().setValue(Boolean.parseBoolean(value));
}
}
private void addMatchHeader(final Map<String, String> headers, final RntbdOperationType operationType) {
String match = null;
switch (operationType) {
case Read:
case ReadFeed:
match = headers.get(HttpHeaders.IF_NONE_MATCH);
break;
default:
match = headers.get(HttpHeaders.IF_MATCH);
break;
}
if (StringUtils.isNotEmpty(match)) {
this.getMatch().setValue(match);
}
}
private void addMigrateCollectionDirectiveHeader(final Map<String, String> headers) {
final String value = headers.get(HttpHeaders.MIGRATE_COLLECTION_DIRECTIVE);
if (StringUtils.isNotEmpty(value)) {
final MigrateCollectionDirective directive = EnumUtils.getEnumIgnoreCase(MigrateCollectionDirective.class, value);
if (directive == null) {
final String reason = String.format(Locale.ROOT, RMResources.InvalidRequestHeaderValue,
HttpHeaders.MIGRATE_COLLECTION_DIRECTIVE,
value);
throw new IllegalStateException(reason);
}
switch (directive) {
case Freeze:
this.getMigrateCollectionDirective().setValue(RntbdMigrateCollectionDirective.Freeze.id());
break;
case Thaw:
this.getMigrateCollectionDirective().setValue(RntbdMigrateCollectionDirective.Thaw.id());
break;
default:
assert false;
break;
}
}
}
private void addPageSize(final Map<String, String> headers) {
final String value = headers.get(HttpHeaders.PAGE_SIZE);
if (StringUtils.isNotEmpty(value)) {
final long aLong = parseLong(HttpHeaders.PAGE_SIZE, value, -1, 0xFFFFFFFFL);
this.getPageSize().setValue((int)(aLong < 0 ? 0xFFFFFFFFL : aLong));
}
}
private void addPopulateCollectionThroughputInfo(final Map<String, String> headers) {
final String value = headers.get(HttpHeaders.POPULATE_COLLECTION_THROUGHPUT_INFO);
if (StringUtils.isNotEmpty(value)) {
this.getPopulateCollectionThroughputInfo().setValue(Boolean.parseBoolean(value));
}
}
private void addPopulatePartitionStatistics(final Map<String, String> headers) {
final String value = headers.get(HttpHeaders.POPULATE_PARTITION_STATISTICS);
if (StringUtils.isNotEmpty(value)) {
this.getPopulatePartitionStatistics().setValue(Boolean.parseBoolean(value));
}
}
private void addPopulateQueryMetrics(final Map<String, String> headers) {
final String value = headers.get(HttpHeaders.POPULATE_QUERY_METRICS);
if (StringUtils.isNotEmpty(value)) {
this.getPopulateQueryMetrics().setValue(Boolean.parseBoolean(value));
}
}
private void addPopulateQuotaInfo(final Map<String, String> headers) {
final String value = headers.get(HttpHeaders.POPULATE_QUOTA_INFO);
if (StringUtils.isNotEmpty(value)) {
this.getPopulateQuotaInfo().setValue(Boolean.parseBoolean(value));
}
}
private void addProfileRequest(final Map<String, String> headers) {
final String value = headers.get(HttpHeaders.PROFILE_REQUEST);
if (StringUtils.isNotEmpty(value)) {
this.getProfileRequest().setValue(Boolean.parseBoolean(value));
}
}
private void addQueryForceScan(final Map<String, String> headers) {
final String value = headers.get(HttpHeaders.FORCE_QUERY_SCAN);
if (StringUtils.isNotEmpty(value)) {
this.getForceQueryScan().setValue(Boolean.parseBoolean(value));
}
}
private void addRemoteStorageType(final Map<String, String> headers) {
final String value = headers.get(BackendHeaders.REMOTE_STORAGE_TYPE);
if (StringUtils.isNotEmpty(value)) {
final RemoteStorageType type = EnumUtils.getEnumIgnoreCase(RemoteStorageType.class, value);
if (type == null) {
final String reason = String.format(Locale.ROOT, RMResources.InvalidRequestHeaderValue,
BackendHeaders.REMOTE_STORAGE_TYPE,
value);
throw new IllegalStateException(reason);
}
switch (type) {
case Standard:
this.getRemoteStorageType().setValue(RntbdRemoteStorageType.Standard.id());
break;
case Premium:
this.getRemoteStorageType().setValue(RntbdRemoteStorageType.Premium.id());
break;
default:
assert false;
}
}
}
private void addResourceIdOrPathHeaders(final RxDocumentServiceRequest request) {
final String value = request.getResourceId();
if (StringUtils.isNotEmpty(value)) {
this.getResourceId().setValue(ResourceId.parse(request.getResourceType(), value));
}
if (request.getIsNameBased()) {
final String address = request.getResourceAddress();
final String[] fragments = StringUtils.split(address, URL_TRIM);
int count = fragments.length;
if (count >= 2) {
switch (fragments[0]) {
case Paths.DATABASES_PATH_SEGMENT:
this.getDatabaseName().setValue(fragments[1]);
break;
default:
final String reason = String.format(Locale.ROOT, RMResources.InvalidResourceAddress,
value, address);
throw new IllegalStateException(reason);
}
}
if (count >= 4) {
switch (fragments[2]) {
case Paths.COLLECTIONS_PATH_SEGMENT:
this.getCollectionName().setValue(fragments[3]);
break;
case Paths.USERS_PATH_SEGMENT:
this.getUserName().setValue(fragments[3]);
break;
case Paths.USER_DEFINED_TYPES_PATH_SEGMENT:
this.getUserDefinedTypeName().setValue(fragments[3]);
break;
}
}
if (count >= 6) {
switch (fragments[4]) {
case Paths.DOCUMENTS_PATH_SEGMENT:
this.getDocumentName().setValue(fragments[5]);
break;
case Paths.STORED_PROCEDURES_PATH_SEGMENT:
this.getStoredProcedureName().setValue(fragments[5]);
break;
case Paths.PERMISSIONS_PATH_SEGMENT:
this.getPermissionName().setValue(fragments[5]);
break;
case Paths.USER_DEFINED_FUNCTIONS_PATH_SEGMENT:
this.getUserDefinedFunctionName().setValue(fragments[5]);
break;
case Paths.TRIGGERS_PATH_SEGMENT:
this.getTriggerName().setValue(fragments[5]);
break;
case Paths.CONFLICTS_PATH_SEGMENT:
this.getConflictName().setValue(fragments[5]);
break;
case Paths.PARTITION_KEY_RANGES_PATH_SEGMENT:
this.getPartitionKeyRangeName().setValue(fragments[5]);
break;
case Paths.SCHEMAS_PATH_SEGMENT:
this.getSchemaName().setValue(fragments[5]);
break;
}
}
if (count >= 8) {
switch (fragments[6]) {
case Paths.ATTACHMENTS_PATH_SEGMENT:
this.getAttachmentName().setValue(fragments[7]);
break;
}
}
}
}
private void addResponseContinuationTokenLimitInKb(final Map<String, String> headers) {
final String value = headers.get(HttpHeaders.RESPONSE_CONTINUATION_TOKEN_LIMIT_IN_KB);
if (StringUtils.isNotEmpty(value)) {
final long aLong = parseLong(HttpHeaders.RESPONSE_CONTINUATION_TOKEN_LIMIT_IN_KB, value, 0, 0xFFFFFFFFL);
this.getResponseContinuationTokenLimitInKb().setValue((int)(aLong < 0 ? 0xFFFFFFFFL : aLong));
}
}
private void addShareThroughput(final Map<String, String> headers) {
final String value = headers.get(BackendHeaders.SHARE_THROUGHPUT);
if (StringUtils.isNotEmpty(value)) {
this.getShareThroughput().setValue(Boolean.parseBoolean(value));
}
}
private void addSupportSpatialLegacyCoordinates(final Map<String, String> headers) {
final String value = headers.get(HttpHeaders.SUPPORT_SPATIAL_LEGACY_COORDINATES);
if (StringUtils.isNotEmpty(value)) {
this.getSupportSpatialLegacyCoordinates().setValue(Boolean.parseBoolean(value));
}
}
private void addUsePolygonsSmallerThanAHemisphere(final Map<String, String> headers) {
final String value = headers.get(HttpHeaders.USE_POLYGONS_SMALLER_THAN_AHEMISPHERE);
if (StringUtils.isNotEmpty(value)) {
this.getUsePolygonsSmallerThanAHemisphere().setValue(Boolean.parseBoolean(value));
}
}
private void addReturnPreference(final Map<String, String> headers) {
final String value = headers.get(HttpHeaders.PREFER);
if (StringUtils.isNotEmpty(value) && value.contains(HeaderValues.PREFER_RETURN_MINIMAL)) {
this.getReturnPreference().setValue(true);
}
}
private void fillTokenFromHeader(final Map<String, String> headers, final Supplier<RntbdToken> supplier, final String name) {
final String value = headers.get(name);
if (StringUtils.isNotEmpty(value)) {
final RntbdToken token = supplier.get();
switch (token.getTokenType()) {
case SmallString:
case String:
case ULongString: {
token.setValue(value);
break;
}
case Byte: {
token.setValue(Boolean.parseBoolean(value));
break;
}
case Double: {
token.setValue(parseDouble(name, value));
break;
}
case Long: {
final long aLong = parseLong(name, value, Integer.MIN_VALUE, Integer.MAX_VALUE);
token.setValue(aLong);
break;
}
case ULong: {
final long aLong = parseLong(name, value, 0, 0xFFFFFFFFL);
token.setValue(aLong);
break;
}
case LongLong: {
final long aLong = parseLong(name, value);
token.setValue(aLong);
break;
}
default: {
assert false : "Recognized header has neither special-case nor default handling to convert "
+ "from header String to RNTBD token";
break;
}
}
}
}
private static double parseDouble(final String name, final String value) {
final double aDouble;
try {
aDouble = Double.parseDouble(value);
} catch (final NumberFormatException error) {
final String reason = String.format(Locale.ROOT, RMResources.InvalidRequestHeaderValue, name, value);
throw new IllegalStateException(reason);
}
return aDouble;
}
private static long parseLong(final String name, final String value) {
final long aLong;
try {
aLong = Long.parseLong(value);
} catch (final NumberFormatException error) {
final String reason = String.format(Locale.ROOT, RMResources.InvalidRequestHeaderValue, name, value);
throw new IllegalStateException(reason);
}
return aLong;
}
private static long parseLong(final String name, final String value, final long min, final long max) {
final long aLong = parseLong(name, value);
if (!(min <= aLong && aLong <= max)) {
final String reason = String.format(Locale.ROOT, RMResources.InvalidRequestHeaderValue, name, aLong);
throw new IllegalStateException(reason);
}
return aLong;
}
} | class RntbdRequestHeaders extends RntbdTokenStream<RntbdRequestHeader> {
private static final String URL_TRIM = "/";
RntbdRequestHeaders(final RntbdRequestArgs args, final RntbdRequestFrame frame) {
this(Unpooled.EMPTY_BUFFER);
checkNotNull(args, "args");
checkNotNull(frame, "frame");
final RxDocumentServiceRequest request = args.serviceRequest();
final byte[] content = request.getContentAsByteArray();
this.getPayloadPresent().setValue(content != null && content.length > 0);
this.getReplicaPath().setValue(args.replicaPath());
this.getTransportRequestID().setValue(args.transportRequestId());
final Map<String, String> headers = request.getHeaders();
this.addAimHeader(headers);
this.addAllowScanOnQuery(headers);
this.addBinaryIdIfPresent(headers);
this.addCanCharge(headers);
this.addCanOfferReplaceComplete(headers);
this.addCanThrottle(headers);
this.addCollectionRemoteStorageSecurityIdentifier(headers);
this.addConsistencyLevelHeader(headers);
this.addContentSerializationFormat(headers);
this.addContinuationToken(request);
this.addDateHeader(headers);
this.addDisableRUPerMinuteUsage(headers);
this.addEmitVerboseTracesInQuery(headers);
this.addEnableLogging(headers);
this.addEnableLowPrecisionOrderBy(headers);
this.addEntityId(headers);
this.addEnumerationDirection(headers);
this.addExcludeSystemProperties(headers);
this.addFanoutOperationStateHeader(headers);
this.addIfModifiedSinceHeader(headers);
this.addIndexingDirectiveHeader(headers);
this.addIsAutoScaleRequest(headers);
this.addIsFanout(headers);
this.addIsReadOnlyScript(headers);
this.addIsUserRequest(headers);
this.addMatchHeader(headers, frame.getOperationType());
this.addMigrateCollectionDirectiveHeader(headers);
this.addPageSize(headers);
this.addPopulateCollectionThroughputInfo(headers);
this.addPopulatePartitionStatistics(headers);
this.addPopulateQueryMetrics(headers);
this.addPopulateQuotaInfo(headers);
this.addProfileRequest(headers);
this.addQueryForceScan(headers);
this.addRemoteStorageType(headers);
this.addResourceIdOrPathHeaders(request);
this.addResponseContinuationTokenLimitInKb(headers);
this.addShareThroughput(headers);
this.addStartAndEndKeys(headers);
this.addSupportSpatialLegacyCoordinates(headers);
this.addUsePolygonsSmallerThanAHemisphere(headers);
this.addReturnPreference(headers);
this.fillTokenFromHeader(headers, this::getAllowTentativeWrites, BackendHeaders.ALLOW_TENTATIVE_WRITES);
this.fillTokenFromHeader(headers, this::getAuthorizationToken, HttpHeaders.AUTHORIZATION);
this.fillTokenFromHeader(headers, this::getBinaryPassThroughRequest, BackendHeaders.BINARY_PASSTHROUGH_REQUEST);
this.fillTokenFromHeader(headers, this::getBindReplicaDirective, BackendHeaders.BIND_REPLICA_DIRECTIVE);
this.fillTokenFromHeader(headers, this::getClientRetryAttemptCount, HttpHeaders.CLIENT_RETRY_ATTEMPT_COUNT);
this.fillTokenFromHeader(headers, this::getCollectionPartitionIndex, BackendHeaders.COLLECTION_PARTITION_INDEX);
this.fillTokenFromHeader(headers, this::getCollectionRid, BackendHeaders.COLLECTION_RID);
this.fillTokenFromHeader(headers, this::getCollectionServiceIndex, BackendHeaders.COLLECTION_SERVICE_INDEX);
this.fillTokenFromHeader(headers, this::getEffectivePartitionKey, BackendHeaders.EFFECTIVE_PARTITION_KEY);
this.fillTokenFromHeader(headers, this::getEnableDynamicRidRangeAllocation, BackendHeaders.ENABLE_DYNAMIC_RID_RANGE_ALLOCATION);
this.fillTokenFromHeader(headers, this::getFilterBySchemaRid, HttpHeaders.FILTER_BY_SCHEMA_RESOURCE_ID);
this.fillTokenFromHeader(headers, this::getGatewaySignature, HttpHeaders.GATEWAY_SIGNATURE);
this.fillTokenFromHeader(headers, this::getPartitionCount, BackendHeaders.PARTITION_COUNT);
this.fillTokenFromHeader(headers, this::getPartitionKey, HttpHeaders.PARTITION_KEY);
this.fillTokenFromHeader(headers, this::getPartitionKeyRangeId, HttpHeaders.PARTITION_KEY_RANGE_ID);
this.fillTokenFromHeader(headers, this::getPartitionResourceFilter, BackendHeaders.PARTITION_RESOURCE_FILTER);
this.fillTokenFromHeader(headers, this::getPostTriggerExclude, HttpHeaders.POST_TRIGGER_EXCLUDE);
this.fillTokenFromHeader(headers, this::getPostTriggerInclude, HttpHeaders.POST_TRIGGER_INCLUDE);
this.fillTokenFromHeader(headers, this::getPreTriggerExclude, HttpHeaders.PRE_TRIGGER_EXCLUDE);
this.fillTokenFromHeader(headers, this::getPreTriggerInclude, HttpHeaders.PRE_TRIGGER_INCLUDE);
this.fillTokenFromHeader(headers, this::getPrimaryMasterKey, BackendHeaders.PRIMARY_MASTER_KEY);
this.fillTokenFromHeader(headers, this::getPrimaryReadonlyKey, BackendHeaders.PRIMARY_READONLY_KEY);
this.fillTokenFromHeader(headers, this::getRemainingTimeInMsOnClientRequest, HttpHeaders.REMAINING_TIME_IN_MS_ON_CLIENT_REQUEST);
this.fillTokenFromHeader(headers, this::getResourceSchemaName, BackendHeaders.RESOURCE_SCHEMA_NAME);
this.fillTokenFromHeader(headers, this::getResourceTokenExpiry, HttpHeaders.RESOURCE_TOKEN_EXPIRY);
this.fillTokenFromHeader(headers, this::getRestoreMetadataFilter, HttpHeaders.RESTORE_METADATA_FILTER);
this.fillTokenFromHeader(headers, this::getRestoreParams, BackendHeaders.RESTORE_PARAMS);
this.fillTokenFromHeader(headers, this::getSecondaryMasterKey, BackendHeaders.SECONDARY_MASTER_KEY);
this.fillTokenFromHeader(headers, this::getSecondaryReadonlyKey, BackendHeaders.SECONDARY_READONLY_KEY);
this.fillTokenFromHeader(headers, this::getSessionToken, HttpHeaders.SESSION_TOKEN);
this.fillTokenFromHeader(headers, this::getSharedOfferThroughput, HttpHeaders.SHARED_OFFER_THROUGHPUT);
this.fillTokenFromHeader(headers, this::getTargetGlobalCommittedLsn, HttpHeaders.TARGET_GLOBAL_COMMITTED_LSN);
this.fillTokenFromHeader(headers, this::getTargetLsn, HttpHeaders.TARGET_LSN);
this.fillTokenFromHeader(headers, this::getTimeToLiveInSeconds, BackendHeaders.TIME_TO_LIVE_IN_SECONDS);
this.fillTokenFromHeader(headers, this::getTransportRequestID, HttpHeaders.TRANSPORT_REQUEST_ID);
this.fillTokenFromHeader(headers, this::isBatchAtomic, HttpHeaders.IS_BATCH_ATOMIC);
this.fillTokenFromHeader(headers, this::shouldBatchContinueOnError, HttpHeaders.SHOULD_BATCH_CONTINUE_ON_ERROR);
this.fillTokenFromHeader(headers, this::isBatchOrdered, HttpHeaders.IS_BATCH_ORDERED);
this.fillTokenFromHeader(headers, this::getClientVersion, HttpHeaders.VERSION);
}
private RntbdRequestHeaders(ByteBuf in) {
super(RntbdRequestHeader.set, RntbdRequestHeader.map, in);
}
static RntbdRequestHeaders decode(final ByteBuf in) {
final RntbdRequestHeaders metadata = new RntbdRequestHeaders(in);
return RntbdRequestHeaders.decode(metadata);
}
private RntbdToken getAIM() {
return this.get(RntbdRequestHeader.A_IM);
}
private RntbdToken getAllowTentativeWrites() {
return this.get(RntbdRequestHeader.AllowTentativeWrites);
}
private RntbdToken getAttachmentName() {
return this.get(RntbdRequestHeader.AttachmentName);
}
private RntbdToken getAuthorizationToken() {
return this.get(RntbdRequestHeader.AuthorizationToken);
}
private RntbdToken getBinaryId() {
return this.get(RntbdRequestHeader.BinaryId);
}
private RntbdToken getBinaryPassThroughRequest() {
return this.get(RntbdRequestHeader.BinaryPassthroughRequest);
}
private RntbdToken getBindReplicaDirective() {
return this.get(RntbdRequestHeader.BindReplicaDirective);
}
private RntbdToken getCanCharge() {
return this.get(RntbdRequestHeader.CanCharge);
}
private RntbdToken getCanOfferReplaceComplete() {
return this.get(RntbdRequestHeader.CanOfferReplaceComplete);
}
private RntbdToken getCanThrottle() {
return this.get(RntbdRequestHeader.CanThrottle);
}
private RntbdToken getClientRetryAttemptCount() {
return this.get(RntbdRequestHeader.ClientRetryAttemptCount);
}
private RntbdToken getClientVersion() {
return this.get(RntbdRequestHeader.ClientVersion);
}
private RntbdToken getCollectionName() {
return this.get(RntbdRequestHeader.CollectionName);
}
private RntbdToken getCollectionPartitionIndex() {
return this.get(RntbdRequestHeader.CollectionPartitionIndex);
}
private RntbdToken getCollectionRemoteStorageSecurityIdentifier() {
return this.get(RntbdRequestHeader.CollectionRemoteStorageSecurityIdentifier);
}
private RntbdToken getCollectionRid() {
return this.get(RntbdRequestHeader.CollectionRid);
}
private RntbdToken getCollectionServiceIndex() {
return this.get(RntbdRequestHeader.CollectionServiceIndex);
}
private RntbdToken getConflictName() {
return this.get(RntbdRequestHeader.ConflictName);
}
private RntbdToken getConsistencyLevel() {
return this.get(RntbdRequestHeader.ConsistencyLevel);
}
private RntbdToken getContentSerializationFormat() {
return this.get(RntbdRequestHeader.ContentSerializationFormat);
}
private RntbdToken getContinuationToken() {
return this.get(RntbdRequestHeader.ContinuationToken);
}
private RntbdToken getDatabaseName() {
return this.get(RntbdRequestHeader.DatabaseName);
}
private RntbdToken getDate() {
return this.get(RntbdRequestHeader.Date);
}
private RntbdToken getDisableRUPerMinuteUsage() {
return this.get(RntbdRequestHeader.DisableRUPerMinuteUsage);
}
private RntbdToken getDocumentName() {
return this.get(RntbdRequestHeader.DocumentName);
}
private RntbdToken getEffectivePartitionKey() {
return this.get(RntbdRequestHeader.EffectivePartitionKey);
}
private RntbdToken getReturnPreference() {
return this.get(RntbdRequestHeader.ReturnPreference);
}
private RntbdToken getEmitVerboseTracesInQuery() {
return this.get(RntbdRequestHeader.EmitVerboseTracesInQuery);
}
private RntbdToken getEnableDynamicRidRangeAllocation() {
return this.get(RntbdRequestHeader.EnableDynamicRidRangeAllocation);
}
private RntbdToken getEnableLogging() {
return this.get(RntbdRequestHeader.EnableLogging);
}
private RntbdToken getEnableLowPrecisionOrderBy() {
return this.get(RntbdRequestHeader.EnableLowPrecisionOrderBy);
}
private RntbdToken getEnableScanInQuery() {
return this.get(RntbdRequestHeader.EnableScanInQuery);
}
private RntbdToken getEndEpk() {
return this.get(RntbdRequestHeader.EndEpk);
}
private RntbdToken getEndId() {
return this.get(RntbdRequestHeader.EndId);
}
private RntbdToken getEntityId() {
return this.get(RntbdRequestHeader.EntityId);
}
private RntbdToken getEnumerationDirection() {
return this.get(RntbdRequestHeader.EnumerationDirection);
}
private RntbdToken getExcludeSystemProperties() {
return this.get(RntbdRequestHeader.ExcludeSystemProperties);
}
private RntbdToken getFanoutOperationState() {
return this.get(RntbdRequestHeader.FanoutOperationState);
}
private RntbdToken getFilterBySchemaRid() {
return this.get(RntbdRequestHeader.FilterBySchemaRid);
}
private RntbdToken getForceQueryScan() {
return this.get(RntbdRequestHeader.ForceQueryScan);
}
private RntbdToken getGatewaySignature() {
return this.get(RntbdRequestHeader.GatewaySignature);
}
private RntbdToken getIfModifiedSince() {
return this.get(RntbdRequestHeader.IfModifiedSince);
}
private RntbdToken getIndexingDirective() {
return this.get(RntbdRequestHeader.IndexingDirective);
}
private RntbdToken getIsAutoScaleRequest() {
return this.get(RntbdRequestHeader.IsAutoScaleRequest);
}
private RntbdToken getIsFanout() {
return this.get(RntbdRequestHeader.IsFanout);
}
private RntbdToken getIsReadOnlyScript() {
return this.get(RntbdRequestHeader.IsReadOnlyScript);
}
private RntbdToken getIsUserRequest() {
return this.get(RntbdRequestHeader.IsUserRequest);
}
private RntbdToken getMatch() {
return this.get(RntbdRequestHeader.Match);
}
private RntbdToken getMigrateCollectionDirective() {
return this.get(RntbdRequestHeader.MigrateCollectionDirective);
}
private RntbdToken getPageSize() {
return this.get(RntbdRequestHeader.PageSize);
}
private RntbdToken getPartitionCount() {
return this.get(RntbdRequestHeader.PartitionCount);
}
private RntbdToken getPartitionKey() {
return this.get(RntbdRequestHeader.PartitionKey);
}
private RntbdToken getPartitionKeyRangeId() {
return this.get(RntbdRequestHeader.PartitionKeyRangeId);
}
private RntbdToken getPartitionKeyRangeName() {
return this.get(RntbdRequestHeader.PartitionKeyRangeName);
}
private RntbdToken getPartitionResourceFilter() {
return this.get(RntbdRequestHeader.PartitionResourceFilter);
}
private RntbdToken getPayloadPresent() {
return this.get(RntbdRequestHeader.PayloadPresent);
}
private RntbdToken getPermissionName() {
return this.get(RntbdRequestHeader.PermissionName);
}
private RntbdToken getPopulateCollectionThroughputInfo() {
return this.get(RntbdRequestHeader.PopulateCollectionThroughputInfo);
}
private RntbdToken getPopulatePartitionStatistics() {
return this.get(RntbdRequestHeader.PopulatePartitionStatistics);
}
private RntbdToken getPopulateQueryMetrics() {
return this.get(RntbdRequestHeader.PopulateQueryMetrics);
}
private RntbdToken getPopulateQuotaInfo() {
return this.get(RntbdRequestHeader.PopulateQuotaInfo);
}
private RntbdToken getPostTriggerExclude() {
return this.get(RntbdRequestHeader.PostTriggerExclude);
}
private RntbdToken getPostTriggerInclude() {
return this.get(RntbdRequestHeader.PostTriggerInclude);
}
private RntbdToken getPreTriggerExclude() {
return this.get(RntbdRequestHeader.PreTriggerExclude);
}
private RntbdToken getPreTriggerInclude() {
return this.get(RntbdRequestHeader.PreTriggerInclude);
}
private RntbdToken getPrimaryMasterKey() {
return this.get(RntbdRequestHeader.PrimaryMasterKey);
}
private RntbdToken getPrimaryReadonlyKey() {
return this.get(RntbdRequestHeader.PrimaryReadonlyKey);
}
private RntbdToken getProfileRequest() {
return this.get(RntbdRequestHeader.ProfileRequest);
}
private RntbdToken getReadFeedKeyType() {
return this.get(RntbdRequestHeader.ReadFeedKeyType);
}
private RntbdToken getRemainingTimeInMsOnClientRequest() {
return this.get(RntbdRequestHeader.RemainingTimeInMsOnClientRequest);
}
private RntbdToken getRemoteStorageType() {
return this.get(RntbdRequestHeader.RemoteStorageType);
}
private RntbdToken getReplicaPath() {
return this.get(RntbdRequestHeader.ReplicaPath);
}
private RntbdToken getResourceId() {
return this.get(RntbdRequestHeader.ResourceId);
}
private RntbdToken getResourceSchemaName() {
return this.get(RntbdRequestHeader.ResourceSchemaName);
}
private RntbdToken getResourceTokenExpiry() {
return this.get(RntbdRequestHeader.ResourceTokenExpiry);
}
private RntbdToken getResponseContinuationTokenLimitInKb() {
return this.get(RntbdRequestHeader.ResponseContinuationTokenLimitInKb);
}
private RntbdToken getRestoreMetadataFilter() {
return this.get(RntbdRequestHeader.RestoreMetadaFilter);
}
private RntbdToken getRestoreParams() {
return this.get(RntbdRequestHeader.RestoreParams);
}
private RntbdToken getSchemaName() {
return this.get(RntbdRequestHeader.SchemaName);
}
private RntbdToken getSecondaryMasterKey() {
return this.get(RntbdRequestHeader.SecondaryMasterKey);
}
private RntbdToken getSecondaryReadonlyKey() {
return this.get(RntbdRequestHeader.SecondaryReadonlyKey);
}
private RntbdToken getSessionToken() {
return this.get(RntbdRequestHeader.SessionToken);
}
private RntbdToken getShareThroughput() {
return this.get(RntbdRequestHeader.ShareThroughput);
}
private RntbdToken getSharedOfferThroughput() {
return this.get(RntbdRequestHeader.SharedOfferThroughput);
}
private RntbdToken getStartEpk() {
return this.get(RntbdRequestHeader.StartEpk);
}
private RntbdToken getStartId() {
return this.get(RntbdRequestHeader.StartId);
}
private RntbdToken getStoredProcedureName() {
return this.get(RntbdRequestHeader.StoredProcedureName);
}
private RntbdToken getSupportSpatialLegacyCoordinates() {
return this.get(RntbdRequestHeader.SupportSpatialLegacyCoordinates);
}
private RntbdToken getTargetGlobalCommittedLsn() {
return this.get(RntbdRequestHeader.TargetGlobalCommittedLsn);
}
private RntbdToken getTargetLsn() {
return this.get(RntbdRequestHeader.TargetLsn);
}
private RntbdToken getTimeToLiveInSeconds() {
return this.get(RntbdRequestHeader.TimeToLiveInSeconds);
}
private RntbdToken getTransportRequestID() {
return this.get(RntbdRequestHeader.TransportRequestID);
}
private RntbdToken getTriggerName() {
return this.get(RntbdRequestHeader.TriggerName);
}
private RntbdToken getUsePolygonsSmallerThanAHemisphere() {
return this.get(RntbdRequestHeader.UsePolygonsSmallerThanAHemisphere);
}
private RntbdToken getUserDefinedFunctionName() {
return this.get(RntbdRequestHeader.UserDefinedFunctionName);
}
private RntbdToken getUserDefinedTypeName() {
return this.get(RntbdRequestHeader.UserDefinedTypeName);
}
private RntbdToken getUserName() {
return this.get(RntbdRequestHeader.UserName);
}
private RntbdToken isBatchAtomic() {
return this.get(RntbdRequestHeader.IsBatchAtomic);
}
private RntbdToken shouldBatchContinueOnError() {
return this.get(RntbdRequestHeader.ShouldBatchContinueOnError);
}
private RntbdToken isBatchOrdered() {
return this.get(RntbdRequestHeader.IsBatchOrdered);
}
private void addAimHeader(final Map<String, String> headers) {
final String value = headers.get(HttpHeaders.A_IM);
if (StringUtils.isNotEmpty(value)) {
this.getAIM().setValue(value);
}
}
private void addAllowScanOnQuery(final Map<String, String> headers) {
final String value = headers.get(HttpHeaders.ENABLE_SCAN_IN_QUERY);
if (StringUtils.isNotEmpty(value)) {
this.getEnableScanInQuery().setValue(Boolean.parseBoolean(value));
}
}
private void addBinaryIdIfPresent(final Map<String, String> headers) {
final String value = headers.get(BackendHeaders.BINARY_ID);
if (StringUtils.isNotEmpty(value)) {
this.getBinaryId().setValue(Base64.getDecoder().decode(value));
}
}
private void addCanCharge(final Map<String, String> headers) {
final String value = headers.get(HttpHeaders.CAN_CHARGE);
if (StringUtils.isNotEmpty(value)) {
this.getCanCharge().setValue(Boolean.parseBoolean(value));
}
}
private void addCanOfferReplaceComplete(final Map<String, String> headers) {
final String value = headers.get(HttpHeaders.CAN_OFFER_REPLACE_COMPLETE);
if (StringUtils.isNotEmpty(value)) {
this.getCanOfferReplaceComplete().setValue(Boolean.parseBoolean(value));
}
}
private void addCanThrottle(final Map<String, String> headers) {
final String value = headers.get(HttpHeaders.CAN_THROTTLE);
if (StringUtils.isNotEmpty(value)) {
this.getCanThrottle().setValue(Boolean.parseBoolean(value));
}
}
private void addCollectionRemoteStorageSecurityIdentifier(final Map<String, String> headers) {
final String value = headers.get(HttpHeaders.COLLECTION_REMOTE_STORAGE_SECURITY_IDENTIFIER);
if (StringUtils.isNotEmpty(value)) {
this.getCollectionRemoteStorageSecurityIdentifier().setValue(value);
}
}
private void addConsistencyLevelHeader(final Map<String, String> headers) {
final String value = headers.get(HttpHeaders.CONSISTENCY_LEVEL);
if (StringUtils.isNotEmpty(value)) {
final ConsistencyLevel level = BridgeInternal.fromServiceSerializedFormat(value);
if (level == null) {
final String reason = String.format(Locale.ROOT, RMResources.InvalidRequestHeaderValue,
HttpHeaders.CONSISTENCY_LEVEL,
value);
throw new IllegalStateException(reason);
}
switch (level) {
case STRONG:
this.getConsistencyLevel().setValue(RntbdConsistencyLevel.Strong.id());
break;
case BOUNDED_STALENESS:
this.getConsistencyLevel().setValue(RntbdConsistencyLevel.BoundedStaleness.id());
break;
case SESSION:
this.getConsistencyLevel().setValue(RntbdConsistencyLevel.Session.id());
break;
case EVENTUAL:
this.getConsistencyLevel().setValue(RntbdConsistencyLevel.Eventual.id());
break;
case CONSISTENT_PREFIX:
this.getConsistencyLevel().setValue(RntbdConsistencyLevel.ConsistentPrefix.id());
break;
default:
assert false;
break;
}
}
}
private void addContentSerializationFormat(final Map<String, String> headers) {
final String value = headers.get(HttpHeaders.CONTENT_SERIALIZATION_FORMAT);
if (StringUtils.isNotEmpty(value)) {
final ContentSerializationFormat format = EnumUtils.getEnumIgnoreCase(
ContentSerializationFormat.class,
value);
if (format == null) {
final String reason = String.format(Locale.ROOT, RMResources.InvalidRequestHeaderValue,
HttpHeaders.CONTENT_SERIALIZATION_FORMAT,
value);
throw new IllegalStateException(reason);
}
switch (format) {
case JsonText:
this.getContentSerializationFormat().setValue(RntbdContentSerializationFormat.JsonText.id());
break;
case CosmosBinary:
this.getContentSerializationFormat().setValue(RntbdContentSerializationFormat.CosmosBinary.id());
break;
default:
assert false;
}
}
}
private void addContinuationToken(final RxDocumentServiceRequest request) {
final String value = request.getContinuation();
if (StringUtils.isNotEmpty(value)) {
this.getContinuationToken().setValue(value);
}
}
private void addDateHeader(final Map<String, String> headers) {
String value = headers.get(HttpHeaders.X_DATE);
if (StringUtils.isEmpty(value)) {
value = headers.get(HttpHeaders.HTTP_DATE);
}
if (StringUtils.isNotEmpty(value)) {
this.getDate().setValue(value);
}
}
private void addDisableRUPerMinuteUsage(final Map<String, String> headers) {
final String value = headers.get(HttpHeaders.DISABLE_RU_PER_MINUTE_USAGE);
if (StringUtils.isNotEmpty(value)) {
this.getDisableRUPerMinuteUsage().setValue(Boolean.parseBoolean(value));
}
}
private void addEmitVerboseTracesInQuery(final Map<String, String> headers) {
final String value = headers.get(HttpHeaders.EMIT_VERBOSE_TRACES_IN_QUERY);
if (StringUtils.isNotEmpty(value)) {
this.getEmitVerboseTracesInQuery().setValue(Boolean.parseBoolean(value));
}
}
private void addEnableLogging(final Map<String, String> headers) {
final String value = headers.get(HttpHeaders.ENABLE_LOGGING);
if (StringUtils.isNotEmpty(value)) {
this.getEnableLogging().setValue(Boolean.parseBoolean(value));
}
}
private void addEnableLowPrecisionOrderBy(final Map<String, String> headers) {
final String value = headers.get(HttpHeaders.ENABLE_LOW_PRECISION_ORDER_BY);
if (StringUtils.isNotEmpty(value)) {
this.getEnableLowPrecisionOrderBy().setValue(Boolean.parseBoolean(value));
}
}
private void addEntityId(final Map<String, String> headers) {
final String value = headers.get(BackendHeaders.ENTITY_ID);
if (StringUtils.isNotEmpty(value)) {
this.getEntityId().setValue(value);
}
}
private void addEnumerationDirection(final Map<String, String> headers) {
final String value = headers.get(HttpHeaders.ENUMERATION_DIRECTION);
if (StringUtils.isNotEmpty(value)) {
final EnumerationDirection direction = EnumUtils.getEnumIgnoreCase(EnumerationDirection.class, value);
if (direction == null) {
final String reason = String.format(Locale.ROOT, RMResources.InvalidRequestHeaderValue,
HttpHeaders.ENUMERATION_DIRECTION,
value);
throw new IllegalStateException(reason);
}
switch (direction) {
case Forward:
this.getEnumerationDirection().setValue(RntbdEnumerationDirection.Forward.id());
break;
case Reverse:
this.getEnumerationDirection().setValue(RntbdEnumerationDirection.Reverse.id());
break;
default:
assert false;
}
}
}
private void addExcludeSystemProperties(final Map<String, String> headers) {
final String value = headers.get(BackendHeaders.EXCLUDE_SYSTEM_PROPERTIES);
if (StringUtils.isNotEmpty(value)) {
this.getExcludeSystemProperties().setValue(Boolean.parseBoolean(value));
}
}
private void addFanoutOperationStateHeader(final Map<String, String> headers) {
final String value = headers.get(BackendHeaders.FANOUT_OPERATION_STATE);
if (StringUtils.isNotEmpty(value)) {
final FanoutOperationState format = EnumUtils.getEnumIgnoreCase(FanoutOperationState.class, value);
if (format == null) {
final String reason = String.format(Locale.ROOT, RMResources.InvalidRequestHeaderValue,
BackendHeaders.FANOUT_OPERATION_STATE,
value);
throw new IllegalStateException(reason);
}
switch (format) {
case Started:
this.getFanoutOperationState().setValue(RntbdFanoutOperationState.Started.id());
break;
case Completed:
this.getFanoutOperationState().setValue(RntbdFanoutOperationState.Completed.id());
break;
default:
assert false;
}
}
}
private void addIfModifiedSinceHeader(final Map<String, String> headers) {
final String value = headers.get(HttpHeaders.IF_MODIFIED_SINCE);
if (StringUtils.isNotEmpty(value)) {
this.getIfModifiedSince().setValue(value);
}
}
private void addIndexingDirectiveHeader(final Map<String, String> headers) {
final String value = headers.get(HttpHeaders.INDEXING_DIRECTIVE);
if (StringUtils.isNotEmpty(value)) {
final IndexingDirective directive = EnumUtils.getEnumIgnoreCase(IndexingDirective.class, value);
if (directive == null) {
final String reason = String.format(Locale.ROOT, RMResources.InvalidRequestHeaderValue,
HttpHeaders.INDEXING_DIRECTIVE,
value);
throw new IllegalStateException(reason);
}
switch (directive) {
case DEFAULT:
this.getIndexingDirective().setValue(RntbdIndexingDirective.Default.id());
break;
case EXCLUDE:
this.getIndexingDirective().setValue(RntbdIndexingDirective.Exclude.id());
break;
case INCLUDE:
this.getIndexingDirective().setValue(RntbdIndexingDirective.Include.id());
break;
default:
assert false;
}
}
}
private void addIsAutoScaleRequest(final Map<String, String> headers) {
final String value = headers.get(HttpHeaders.IS_AUTO_SCALE_REQUEST);
if (StringUtils.isNotEmpty(value)) {
this.getIsAutoScaleRequest().setValue(Boolean.parseBoolean(value));
}
}
private void addIsFanout(final Map<String, String> headers) {
final String value = headers.get(BackendHeaders.IS_FANOUT_REQUEST);
if (StringUtils.isNotEmpty(value)) {
this.getIsFanout().setValue(Boolean.parseBoolean(value));
}
}
private void addIsReadOnlyScript(final Map<String, String> headers) {
final String value = headers.get(HttpHeaders.IS_READ_ONLY_SCRIPT);
if (StringUtils.isNotEmpty(value)) {
this.getIsReadOnlyScript().setValue(Boolean.parseBoolean(value));
}
}
private void addIsUserRequest(final Map<String, String> headers) {
final String value = headers.get(BackendHeaders.IS_USER_REQUEST);
if (StringUtils.isNotEmpty(value)) {
this.getIsUserRequest().setValue(Boolean.parseBoolean(value));
}
}
private void addMatchHeader(final Map<String, String> headers, final RntbdOperationType operationType) {
String match = null;
switch (operationType) {
case Read:
case ReadFeed:
match = headers.get(HttpHeaders.IF_NONE_MATCH);
break;
default:
match = headers.get(HttpHeaders.IF_MATCH);
break;
}
if (StringUtils.isNotEmpty(match)) {
this.getMatch().setValue(match);
}
}
private void addMigrateCollectionDirectiveHeader(final Map<String, String> headers) {
final String value = headers.get(HttpHeaders.MIGRATE_COLLECTION_DIRECTIVE);
if (StringUtils.isNotEmpty(value)) {
final MigrateCollectionDirective directive = EnumUtils.getEnumIgnoreCase(MigrateCollectionDirective.class, value);
if (directive == null) {
final String reason = String.format(Locale.ROOT, RMResources.InvalidRequestHeaderValue,
HttpHeaders.MIGRATE_COLLECTION_DIRECTIVE,
value);
throw new IllegalStateException(reason);
}
switch (directive) {
case Freeze:
this.getMigrateCollectionDirective().setValue(RntbdMigrateCollectionDirective.Freeze.id());
break;
case Thaw:
this.getMigrateCollectionDirective().setValue(RntbdMigrateCollectionDirective.Thaw.id());
break;
default:
assert false;
break;
}
}
}
private void addPageSize(final Map<String, String> headers) {
final String value = headers.get(HttpHeaders.PAGE_SIZE);
if (StringUtils.isNotEmpty(value)) {
final long aLong = parseLong(HttpHeaders.PAGE_SIZE, value, -1, 0xFFFFFFFFL);
this.getPageSize().setValue((int)(aLong < 0 ? 0xFFFFFFFFL : aLong));
}
}
private void addPopulateCollectionThroughputInfo(final Map<String, String> headers) {
final String value = headers.get(HttpHeaders.POPULATE_COLLECTION_THROUGHPUT_INFO);
if (StringUtils.isNotEmpty(value)) {
this.getPopulateCollectionThroughputInfo().setValue(Boolean.parseBoolean(value));
}
}
private void addPopulatePartitionStatistics(final Map<String, String> headers) {
final String value = headers.get(HttpHeaders.POPULATE_PARTITION_STATISTICS);
if (StringUtils.isNotEmpty(value)) {
this.getPopulatePartitionStatistics().setValue(Boolean.parseBoolean(value));
}
}
private void addPopulateQueryMetrics(final Map<String, String> headers) {
final String value = headers.get(HttpHeaders.POPULATE_QUERY_METRICS);
if (StringUtils.isNotEmpty(value)) {
this.getPopulateQueryMetrics().setValue(Boolean.parseBoolean(value));
}
}
private void addPopulateQuotaInfo(final Map<String, String> headers) {
final String value = headers.get(HttpHeaders.POPULATE_QUOTA_INFO);
if (StringUtils.isNotEmpty(value)) {
this.getPopulateQuotaInfo().setValue(Boolean.parseBoolean(value));
}
}
private void addProfileRequest(final Map<String, String> headers) {
final String value = headers.get(HttpHeaders.PROFILE_REQUEST);
if (StringUtils.isNotEmpty(value)) {
this.getProfileRequest().setValue(Boolean.parseBoolean(value));
}
}
private void addQueryForceScan(final Map<String, String> headers) {
final String value = headers.get(HttpHeaders.FORCE_QUERY_SCAN);
if (StringUtils.isNotEmpty(value)) {
this.getForceQueryScan().setValue(Boolean.parseBoolean(value));
}
}
private void addRemoteStorageType(final Map<String, String> headers) {
final String value = headers.get(BackendHeaders.REMOTE_STORAGE_TYPE);
if (StringUtils.isNotEmpty(value)) {
final RemoteStorageType type = EnumUtils.getEnumIgnoreCase(RemoteStorageType.class, value);
if (type == null) {
final String reason = String.format(Locale.ROOT, RMResources.InvalidRequestHeaderValue,
BackendHeaders.REMOTE_STORAGE_TYPE,
value);
throw new IllegalStateException(reason);
}
switch (type) {
case Standard:
this.getRemoteStorageType().setValue(RntbdRemoteStorageType.Standard.id());
break;
case Premium:
this.getRemoteStorageType().setValue(RntbdRemoteStorageType.Premium.id());
break;
default:
assert false;
}
}
}
private void addResourceIdOrPathHeaders(final RxDocumentServiceRequest request) {
final String value = request.getResourceId();
if (StringUtils.isNotEmpty(value)) {
this.getResourceId().setValue(ResourceId.parse(request.getResourceType(), value));
}
if (request.getIsNameBased()) {
final String address = request.getResourceAddress();
final String[] fragments = StringUtils.split(address, URL_TRIM);
int count = fragments.length;
if (count >= 2) {
switch (fragments[0]) {
case Paths.DATABASES_PATH_SEGMENT:
this.getDatabaseName().setValue(fragments[1]);
break;
default:
final String reason = String.format(Locale.ROOT, RMResources.InvalidResourceAddress,
value, address);
throw new IllegalStateException(reason);
}
}
if (count >= 4) {
switch (fragments[2]) {
case Paths.COLLECTIONS_PATH_SEGMENT:
this.getCollectionName().setValue(fragments[3]);
break;
case Paths.USERS_PATH_SEGMENT:
this.getUserName().setValue(fragments[3]);
break;
case Paths.USER_DEFINED_TYPES_PATH_SEGMENT:
this.getUserDefinedTypeName().setValue(fragments[3]);
break;
}
}
if (count >= 6) {
switch (fragments[4]) {
case Paths.DOCUMENTS_PATH_SEGMENT:
this.getDocumentName().setValue(fragments[5]);
break;
case Paths.STORED_PROCEDURES_PATH_SEGMENT:
this.getStoredProcedureName().setValue(fragments[5]);
break;
case Paths.PERMISSIONS_PATH_SEGMENT:
this.getPermissionName().setValue(fragments[5]);
break;
case Paths.USER_DEFINED_FUNCTIONS_PATH_SEGMENT:
this.getUserDefinedFunctionName().setValue(fragments[5]);
break;
case Paths.TRIGGERS_PATH_SEGMENT:
this.getTriggerName().setValue(fragments[5]);
break;
case Paths.CONFLICTS_PATH_SEGMENT:
this.getConflictName().setValue(fragments[5]);
break;
case Paths.PARTITION_KEY_RANGES_PATH_SEGMENT:
this.getPartitionKeyRangeName().setValue(fragments[5]);
break;
case Paths.SCHEMAS_PATH_SEGMENT:
this.getSchemaName().setValue(fragments[5]);
break;
}
}
if (count >= 8) {
switch (fragments[6]) {
case Paths.ATTACHMENTS_PATH_SEGMENT:
this.getAttachmentName().setValue(fragments[7]);
break;
}
}
}
}
private void addResponseContinuationTokenLimitInKb(final Map<String, String> headers) {
final String value = headers.get(HttpHeaders.RESPONSE_CONTINUATION_TOKEN_LIMIT_IN_KB);
if (StringUtils.isNotEmpty(value)) {
final long aLong = parseLong(HttpHeaders.RESPONSE_CONTINUATION_TOKEN_LIMIT_IN_KB, value, 0, 0xFFFFFFFFL);
this.getResponseContinuationTokenLimitInKb().setValue((int)(aLong < 0 ? 0xFFFFFFFFL : aLong));
}
}
private void addShareThroughput(final Map<String, String> headers) {
final String value = headers.get(BackendHeaders.SHARE_THROUGHPUT);
if (StringUtils.isNotEmpty(value)) {
this.getShareThroughput().setValue(Boolean.parseBoolean(value));
}
}
private void addSupportSpatialLegacyCoordinates(final Map<String, String> headers) {
final String value = headers.get(HttpHeaders.SUPPORT_SPATIAL_LEGACY_COORDINATES);
if (StringUtils.isNotEmpty(value)) {
this.getSupportSpatialLegacyCoordinates().setValue(Boolean.parseBoolean(value));
}
}
private void addUsePolygonsSmallerThanAHemisphere(final Map<String, String> headers) {
final String value = headers.get(HttpHeaders.USE_POLYGONS_SMALLER_THAN_AHEMISPHERE);
if (StringUtils.isNotEmpty(value)) {
this.getUsePolygonsSmallerThanAHemisphere().setValue(Boolean.parseBoolean(value));
}
}
private void addReturnPreference(final Map<String, String> headers) {
final String value = headers.get(HttpHeaders.PREFER);
if (StringUtils.isNotEmpty(value) && value.contains(HeaderValues.PREFER_RETURN_MINIMAL)) {
this.getReturnPreference().setValue(true);
}
}
private void fillTokenFromHeader(final Map<String, String> headers, final Supplier<RntbdToken> supplier, final String name) {
final String value = headers.get(name);
if (StringUtils.isNotEmpty(value)) {
final RntbdToken token = supplier.get();
switch (token.getTokenType()) {
case SmallString:
case String:
case ULongString: {
token.setValue(value);
break;
}
case Byte: {
token.setValue(Boolean.parseBoolean(value));
break;
}
case Double: {
token.setValue(parseDouble(name, value));
break;
}
case Long: {
final long aLong = parseLong(name, value, Integer.MIN_VALUE, Integer.MAX_VALUE);
token.setValue(aLong);
break;
}
case ULong: {
final long aLong = parseLong(name, value, 0, 0xFFFFFFFFL);
token.setValue(aLong);
break;
}
case LongLong: {
final long aLong = parseLong(name, value);
token.setValue(aLong);
break;
}
default: {
assert false : "Recognized header has neither special-case nor default handling to convert "
+ "from header String to RNTBD token";
break;
}
}
}
}
private static double parseDouble(final String name, final String value) {
final double aDouble;
try {
aDouble = Double.parseDouble(value);
} catch (final NumberFormatException error) {
final String reason = String.format(Locale.ROOT, RMResources.InvalidRequestHeaderValue, name, value);
throw new IllegalStateException(reason);
}
return aDouble;
}
private static long parseLong(final String name, final String value) {
final long aLong;
try {
aLong = Long.parseLong(value);
} catch (final NumberFormatException error) {
final String reason = String.format(Locale.ROOT, RMResources.InvalidRequestHeaderValue, name, value);
throw new IllegalStateException(reason);
}
return aLong;
}
private static long parseLong(final String name, final String value, final long min, final long max) {
final long aLong = parseLong(name, value);
if (!(min <= aLong && aLong <= max)) {
final String reason = String.format(Locale.ROOT, RMResources.InvalidRequestHeaderValue, name, aLong);
throw new IllegalStateException(reason);
}
return aLong;
}
} |
discussed offline. | private void addStartAndEndKeys(final Map<String, String> headers) {
String value = headers.get(HttpHeaders.READ_FEED_KEY_TYPE);
if (StringUtils.isNotEmpty(value)) {
final ReadFeedKeyType type = EnumUtils.getEnumIgnoreCase(ReadFeedKeyType.class, value);
if (type == null) {
final String reason = String.format(Locale.ROOT, RMResources.InvalidRequestHeaderValue,
HttpHeaders.READ_FEED_KEY_TYPE,
value);
throw new IllegalStateException(reason);
}
switch (type) {
case ResourceId:
this.getReadFeedKeyType().setValue(RntbdReadFeedKeyType.ResourceId.id());
break;
case EffectivePartitionKey:
this.getReadFeedKeyType().setValue(RntbdReadFeedKeyType.EffectivePartitionKey.id());
break;
case EffectivePartitionKeyRange:
this.getReadFeedKeyType().setValue(RntbdReadFeedKeyType.EffectivePartitionKeyRange.id());
break;
default:
throw new IllegalStateException(String.format("Invalid ReadFeed key type '%s'.", type));
}
}
final Base64.Decoder decoder = Base64.getDecoder();
value = headers.get(HttpHeaders.START_ID);
if (StringUtils.isNotEmpty(value)) {
this.getStartId().setValue(decoder.decode(value));
}
value = headers.get(HttpHeaders.END_ID);
if (StringUtils.isNotEmpty(value)) {
this.getEndId().setValue(decoder.decode(value));
}
value = headers.get(HttpHeaders.START_EPK);
if (StringUtils.isNotEmpty(value)) {
this.getStartEpk().setValue(value.getBytes(StandardCharsets.UTF_8));
}
value = headers.get(HttpHeaders.END_EPK);
if (StringUtils.isNotEmpty(value)) {
this.getEndEpk().setValue(value.getBytes(StandardCharsets.UTF_8));
}
} | this.getStartEpk().setValue(value.getBytes(StandardCharsets.UTF_8)); | private void addStartAndEndKeys(final Map<String, String> headers) {
String value = headers.get(HttpHeaders.READ_FEED_KEY_TYPE);
if (StringUtils.isNotEmpty(value)) {
final ReadFeedKeyType type = EnumUtils.getEnumIgnoreCase(ReadFeedKeyType.class, value);
if (type == null) {
final String reason = String.format(Locale.ROOT, RMResources.InvalidRequestHeaderValue,
HttpHeaders.READ_FEED_KEY_TYPE,
value);
throw new IllegalStateException(reason);
}
switch (type) {
case ResourceId:
this.getReadFeedKeyType().setValue(RntbdReadFeedKeyType.ResourceId.id());
break;
case EffectivePartitionKey:
this.getReadFeedKeyType().setValue(RntbdReadFeedKeyType.EffectivePartitionKey.id());
break;
case EffectivePartitionKeyRange:
this.getReadFeedKeyType().setValue(RntbdReadFeedKeyType.EffectivePartitionKeyRange.id());
break;
default:
throw new IllegalStateException(String.format("Invalid ReadFeed key type '%s'.", type));
}
}
final Base64.Decoder decoder = Base64.getDecoder();
value = headers.get(HttpHeaders.START_ID);
if (StringUtils.isNotEmpty(value)) {
this.getStartId().setValue(decoder.decode(value));
}
value = headers.get(HttpHeaders.END_ID);
if (StringUtils.isNotEmpty(value)) {
this.getEndId().setValue(decoder.decode(value));
}
value = headers.get(HttpHeaders.START_EPK);
if (StringUtils.isNotEmpty(value)) {
this.getStartEpk().setValue(value.getBytes(StandardCharsets.UTF_8));
}
value = headers.get(HttpHeaders.END_EPK);
if (StringUtils.isNotEmpty(value)) {
this.getEndEpk().setValue(value.getBytes(StandardCharsets.UTF_8));
}
} | class RntbdRequestHeaders extends RntbdTokenStream<RntbdRequestHeader> {
private static final String URL_TRIM = "/";
RntbdRequestHeaders(final RntbdRequestArgs args, final RntbdRequestFrame frame) {
this(Unpooled.EMPTY_BUFFER);
checkNotNull(args, "args");
checkNotNull(frame, "frame");
final RxDocumentServiceRequest request = args.serviceRequest();
final byte[] content = request.getContentAsByteArray();
this.getPayloadPresent().setValue(content != null && content.length > 0);
this.getReplicaPath().setValue(args.replicaPath());
this.getTransportRequestID().setValue(args.transportRequestId());
final Map<String, String> headers = request.getHeaders();
this.addAimHeader(headers);
this.addAllowScanOnQuery(headers);
this.addBinaryIdIfPresent(headers);
this.addCanCharge(headers);
this.addCanOfferReplaceComplete(headers);
this.addCanThrottle(headers);
this.addCollectionRemoteStorageSecurityIdentifier(headers);
this.addConsistencyLevelHeader(headers);
this.addContentSerializationFormat(headers);
this.addContinuationToken(request);
this.addDateHeader(headers);
this.addDisableRUPerMinuteUsage(headers);
this.addEmitVerboseTracesInQuery(headers);
this.addEnableLogging(headers);
this.addEnableLowPrecisionOrderBy(headers);
this.addEntityId(headers);
this.addEnumerationDirection(headers);
this.addExcludeSystemProperties(headers);
this.addFanoutOperationStateHeader(headers);
this.addIfModifiedSinceHeader(headers);
this.addIndexingDirectiveHeader(headers);
this.addIsAutoScaleRequest(headers);
this.addIsFanout(headers);
this.addIsReadOnlyScript(headers);
this.addIsUserRequest(headers);
this.addMatchHeader(headers, frame.getOperationType());
this.addMigrateCollectionDirectiveHeader(headers);
this.addPageSize(headers);
this.addPopulateCollectionThroughputInfo(headers);
this.addPopulatePartitionStatistics(headers);
this.addPopulateQueryMetrics(headers);
this.addPopulateQuotaInfo(headers);
this.addProfileRequest(headers);
this.addQueryForceScan(headers);
this.addRemoteStorageType(headers);
this.addResourceIdOrPathHeaders(request);
this.addResponseContinuationTokenLimitInKb(headers);
this.addShareThroughput(headers);
this.addStartAndEndKeys(headers);
this.addSupportSpatialLegacyCoordinates(headers);
this.addUsePolygonsSmallerThanAHemisphere(headers);
this.addReturnPreference(headers);
this.fillTokenFromHeader(headers, this::getAllowTentativeWrites, BackendHeaders.ALLOW_TENTATIVE_WRITES);
this.fillTokenFromHeader(headers, this::getAuthorizationToken, HttpHeaders.AUTHORIZATION);
this.fillTokenFromHeader(headers, this::getBinaryPassThroughRequest, BackendHeaders.BINARY_PASSTHROUGH_REQUEST);
this.fillTokenFromHeader(headers, this::getBindReplicaDirective, BackendHeaders.BIND_REPLICA_DIRECTIVE);
this.fillTokenFromHeader(headers, this::getClientRetryAttemptCount, HttpHeaders.CLIENT_RETRY_ATTEMPT_COUNT);
this.fillTokenFromHeader(headers, this::getCollectionPartitionIndex, BackendHeaders.COLLECTION_PARTITION_INDEX);
this.fillTokenFromHeader(headers, this::getCollectionRid, BackendHeaders.COLLECTION_RID);
this.fillTokenFromHeader(headers, this::getCollectionServiceIndex, BackendHeaders.COLLECTION_SERVICE_INDEX);
this.fillTokenFromHeader(headers, this::getEffectivePartitionKey, BackendHeaders.EFFECTIVE_PARTITION_KEY);
this.fillTokenFromHeader(headers, this::getEnableDynamicRidRangeAllocation, BackendHeaders.ENABLE_DYNAMIC_RID_RANGE_ALLOCATION);
this.fillTokenFromHeader(headers, this::getFilterBySchemaRid, HttpHeaders.FILTER_BY_SCHEMA_RESOURCE_ID);
this.fillTokenFromHeader(headers, this::getGatewaySignature, HttpHeaders.GATEWAY_SIGNATURE);
this.fillTokenFromHeader(headers, this::getPartitionCount, BackendHeaders.PARTITION_COUNT);
this.fillTokenFromHeader(headers, this::getPartitionKey, HttpHeaders.PARTITION_KEY);
this.fillTokenFromHeader(headers, this::getPartitionKeyRangeId, HttpHeaders.PARTITION_KEY_RANGE_ID);
this.fillTokenFromHeader(headers, this::getPartitionResourceFilter, BackendHeaders.PARTITION_RESOURCE_FILTER);
this.fillTokenFromHeader(headers, this::getPostTriggerExclude, HttpHeaders.POST_TRIGGER_EXCLUDE);
this.fillTokenFromHeader(headers, this::getPostTriggerInclude, HttpHeaders.POST_TRIGGER_INCLUDE);
this.fillTokenFromHeader(headers, this::getPreTriggerExclude, HttpHeaders.PRE_TRIGGER_EXCLUDE);
this.fillTokenFromHeader(headers, this::getPreTriggerInclude, HttpHeaders.PRE_TRIGGER_INCLUDE);
this.fillTokenFromHeader(headers, this::getPrimaryMasterKey, BackendHeaders.PRIMARY_MASTER_KEY);
this.fillTokenFromHeader(headers, this::getPrimaryReadonlyKey, BackendHeaders.PRIMARY_READONLY_KEY);
this.fillTokenFromHeader(headers, this::getRemainingTimeInMsOnClientRequest, HttpHeaders.REMAINING_TIME_IN_MS_ON_CLIENT_REQUEST);
this.fillTokenFromHeader(headers, this::getResourceSchemaName, BackendHeaders.RESOURCE_SCHEMA_NAME);
this.fillTokenFromHeader(headers, this::getResourceTokenExpiry, HttpHeaders.RESOURCE_TOKEN_EXPIRY);
this.fillTokenFromHeader(headers, this::getRestoreMetadataFilter, HttpHeaders.RESTORE_METADATA_FILTER);
this.fillTokenFromHeader(headers, this::getRestoreParams, BackendHeaders.RESTORE_PARAMS);
this.fillTokenFromHeader(headers, this::getSecondaryMasterKey, BackendHeaders.SECONDARY_MASTER_KEY);
this.fillTokenFromHeader(headers, this::getSecondaryReadonlyKey, BackendHeaders.SECONDARY_READONLY_KEY);
this.fillTokenFromHeader(headers, this::getSessionToken, HttpHeaders.SESSION_TOKEN);
this.fillTokenFromHeader(headers, this::getSharedOfferThroughput, HttpHeaders.SHARED_OFFER_THROUGHPUT);
this.fillTokenFromHeader(headers, this::getTargetGlobalCommittedLsn, HttpHeaders.TARGET_GLOBAL_COMMITTED_LSN);
this.fillTokenFromHeader(headers, this::getTargetLsn, HttpHeaders.TARGET_LSN);
this.fillTokenFromHeader(headers, this::getTimeToLiveInSeconds, BackendHeaders.TIME_TO_LIVE_IN_SECONDS);
this.fillTokenFromHeader(headers, this::getTransportRequestID, HttpHeaders.TRANSPORT_REQUEST_ID);
this.fillTokenFromHeader(headers, this::isBatchAtomic, HttpHeaders.IS_BATCH_ATOMIC);
this.fillTokenFromHeader(headers, this::shouldBatchContinueOnError, HttpHeaders.SHOULD_BATCH_CONTINUE_ON_ERROR);
this.fillTokenFromHeader(headers, this::isBatchOrdered, HttpHeaders.IS_BATCH_ORDERED);
this.fillTokenFromHeader(headers, this::getClientVersion, HttpHeaders.VERSION);
}
private RntbdRequestHeaders(ByteBuf in) {
super(RntbdRequestHeader.set, RntbdRequestHeader.map, in);
}
static RntbdRequestHeaders decode(final ByteBuf in) {
final RntbdRequestHeaders metadata = new RntbdRequestHeaders(in);
return RntbdRequestHeaders.decode(metadata);
}
private RntbdToken getAIM() {
return this.get(RntbdRequestHeader.A_IM);
}
private RntbdToken getAllowTentativeWrites() {
return this.get(RntbdRequestHeader.AllowTentativeWrites);
}
private RntbdToken getAttachmentName() {
return this.get(RntbdRequestHeader.AttachmentName);
}
private RntbdToken getAuthorizationToken() {
return this.get(RntbdRequestHeader.AuthorizationToken);
}
private RntbdToken getBinaryId() {
return this.get(RntbdRequestHeader.BinaryId);
}
private RntbdToken getBinaryPassThroughRequest() {
return this.get(RntbdRequestHeader.BinaryPassthroughRequest);
}
private RntbdToken getBindReplicaDirective() {
return this.get(RntbdRequestHeader.BindReplicaDirective);
}
private RntbdToken getCanCharge() {
return this.get(RntbdRequestHeader.CanCharge);
}
private RntbdToken getCanOfferReplaceComplete() {
return this.get(RntbdRequestHeader.CanOfferReplaceComplete);
}
private RntbdToken getCanThrottle() {
return this.get(RntbdRequestHeader.CanThrottle);
}
private RntbdToken getClientRetryAttemptCount() {
return this.get(RntbdRequestHeader.ClientRetryAttemptCount);
}
private RntbdToken getClientVersion() {
return this.get(RntbdRequestHeader.ClientVersion);
}
private RntbdToken getCollectionName() {
return this.get(RntbdRequestHeader.CollectionName);
}
private RntbdToken getCollectionPartitionIndex() {
return this.get(RntbdRequestHeader.CollectionPartitionIndex);
}
private RntbdToken getCollectionRemoteStorageSecurityIdentifier() {
return this.get(RntbdRequestHeader.CollectionRemoteStorageSecurityIdentifier);
}
private RntbdToken getCollectionRid() {
return this.get(RntbdRequestHeader.CollectionRid);
}
private RntbdToken getCollectionServiceIndex() {
return this.get(RntbdRequestHeader.CollectionServiceIndex);
}
private RntbdToken getConflictName() {
return this.get(RntbdRequestHeader.ConflictName);
}
private RntbdToken getConsistencyLevel() {
return this.get(RntbdRequestHeader.ConsistencyLevel);
}
private RntbdToken getContentSerializationFormat() {
return this.get(RntbdRequestHeader.ContentSerializationFormat);
}
private RntbdToken getContinuationToken() {
return this.get(RntbdRequestHeader.ContinuationToken);
}
private RntbdToken getDatabaseName() {
return this.get(RntbdRequestHeader.DatabaseName);
}
private RntbdToken getDate() {
return this.get(RntbdRequestHeader.Date);
}
private RntbdToken getDisableRUPerMinuteUsage() {
return this.get(RntbdRequestHeader.DisableRUPerMinuteUsage);
}
private RntbdToken getDocumentName() {
return this.get(RntbdRequestHeader.DocumentName);
}
private RntbdToken getEffectivePartitionKey() {
return this.get(RntbdRequestHeader.EffectivePartitionKey);
}
private RntbdToken getReturnPreference() {
return this.get(RntbdRequestHeader.ReturnPreference);
}
private RntbdToken getEmitVerboseTracesInQuery() {
return this.get(RntbdRequestHeader.EmitVerboseTracesInQuery);
}
private RntbdToken getEnableDynamicRidRangeAllocation() {
return this.get(RntbdRequestHeader.EnableDynamicRidRangeAllocation);
}
private RntbdToken getEnableLogging() {
return this.get(RntbdRequestHeader.EnableLogging);
}
private RntbdToken getEnableLowPrecisionOrderBy() {
return this.get(RntbdRequestHeader.EnableLowPrecisionOrderBy);
}
private RntbdToken getEnableScanInQuery() {
return this.get(RntbdRequestHeader.EnableScanInQuery);
}
private RntbdToken getEndEpk() {
return this.get(RntbdRequestHeader.EndEpk);
}
private RntbdToken getEndId() {
return this.get(RntbdRequestHeader.EndId);
}
private RntbdToken getEntityId() {
return this.get(RntbdRequestHeader.EntityId);
}
private RntbdToken getEnumerationDirection() {
return this.get(RntbdRequestHeader.EnumerationDirection);
}
private RntbdToken getExcludeSystemProperties() {
return this.get(RntbdRequestHeader.ExcludeSystemProperties);
}
private RntbdToken getFanoutOperationState() {
return this.get(RntbdRequestHeader.FanoutOperationState);
}
private RntbdToken getFilterBySchemaRid() {
return this.get(RntbdRequestHeader.FilterBySchemaRid);
}
private RntbdToken getForceQueryScan() {
return this.get(RntbdRequestHeader.ForceQueryScan);
}
private RntbdToken getGatewaySignature() {
return this.get(RntbdRequestHeader.GatewaySignature);
}
private RntbdToken getIfModifiedSince() {
return this.get(RntbdRequestHeader.IfModifiedSince);
}
private RntbdToken getIndexingDirective() {
return this.get(RntbdRequestHeader.IndexingDirective);
}
private RntbdToken getIsAutoScaleRequest() {
return this.get(RntbdRequestHeader.IsAutoScaleRequest);
}
private RntbdToken getIsFanout() {
return this.get(RntbdRequestHeader.IsFanout);
}
private RntbdToken getIsReadOnlyScript() {
return this.get(RntbdRequestHeader.IsReadOnlyScript);
}
private RntbdToken getIsUserRequest() {
return this.get(RntbdRequestHeader.IsUserRequest);
}
private RntbdToken getMatch() {
return this.get(RntbdRequestHeader.Match);
}
private RntbdToken getMigrateCollectionDirective() {
return this.get(RntbdRequestHeader.MigrateCollectionDirective);
}
private RntbdToken getPageSize() {
return this.get(RntbdRequestHeader.PageSize);
}
private RntbdToken getPartitionCount() {
return this.get(RntbdRequestHeader.PartitionCount);
}
private RntbdToken getPartitionKey() {
return this.get(RntbdRequestHeader.PartitionKey);
}
private RntbdToken getPartitionKeyRangeId() {
return this.get(RntbdRequestHeader.PartitionKeyRangeId);
}
private RntbdToken getPartitionKeyRangeName() {
return this.get(RntbdRequestHeader.PartitionKeyRangeName);
}
private RntbdToken getPartitionResourceFilter() {
return this.get(RntbdRequestHeader.PartitionResourceFilter);
}
private RntbdToken getPayloadPresent() {
return this.get(RntbdRequestHeader.PayloadPresent);
}
private RntbdToken getPermissionName() {
return this.get(RntbdRequestHeader.PermissionName);
}
private RntbdToken getPopulateCollectionThroughputInfo() {
return this.get(RntbdRequestHeader.PopulateCollectionThroughputInfo);
}
private RntbdToken getPopulatePartitionStatistics() {
return this.get(RntbdRequestHeader.PopulatePartitionStatistics);
}
private RntbdToken getPopulateQueryMetrics() {
return this.get(RntbdRequestHeader.PopulateQueryMetrics);
}
private RntbdToken getPopulateQuotaInfo() {
return this.get(RntbdRequestHeader.PopulateQuotaInfo);
}
private RntbdToken getPostTriggerExclude() {
return this.get(RntbdRequestHeader.PostTriggerExclude);
}
private RntbdToken getPostTriggerInclude() {
return this.get(RntbdRequestHeader.PostTriggerInclude);
}
private RntbdToken getPreTriggerExclude() {
return this.get(RntbdRequestHeader.PreTriggerExclude);
}
private RntbdToken getPreTriggerInclude() {
return this.get(RntbdRequestHeader.PreTriggerInclude);
}
private RntbdToken getPrimaryMasterKey() {
return this.get(RntbdRequestHeader.PrimaryMasterKey);
}
private RntbdToken getPrimaryReadonlyKey() {
return this.get(RntbdRequestHeader.PrimaryReadonlyKey);
}
private RntbdToken getProfileRequest() {
return this.get(RntbdRequestHeader.ProfileRequest);
}
private RntbdToken getReadFeedKeyType() {
return this.get(RntbdRequestHeader.ReadFeedKeyType);
}
private RntbdToken getRemainingTimeInMsOnClientRequest() {
return this.get(RntbdRequestHeader.RemainingTimeInMsOnClientRequest);
}
private RntbdToken getRemoteStorageType() {
return this.get(RntbdRequestHeader.RemoteStorageType);
}
private RntbdToken getReplicaPath() {
return this.get(RntbdRequestHeader.ReplicaPath);
}
private RntbdToken getResourceId() {
return this.get(RntbdRequestHeader.ResourceId);
}
private RntbdToken getResourceSchemaName() {
return this.get(RntbdRequestHeader.ResourceSchemaName);
}
private RntbdToken getResourceTokenExpiry() {
return this.get(RntbdRequestHeader.ResourceTokenExpiry);
}
private RntbdToken getResponseContinuationTokenLimitInKb() {
return this.get(RntbdRequestHeader.ResponseContinuationTokenLimitInKb);
}
private RntbdToken getRestoreMetadataFilter() {
return this.get(RntbdRequestHeader.RestoreMetadaFilter);
}
private RntbdToken getRestoreParams() {
return this.get(RntbdRequestHeader.RestoreParams);
}
private RntbdToken getSchemaName() {
return this.get(RntbdRequestHeader.SchemaName);
}
private RntbdToken getSecondaryMasterKey() {
return this.get(RntbdRequestHeader.SecondaryMasterKey);
}
private RntbdToken getSecondaryReadonlyKey() {
return this.get(RntbdRequestHeader.SecondaryReadonlyKey);
}
private RntbdToken getSessionToken() {
return this.get(RntbdRequestHeader.SessionToken);
}
private RntbdToken getShareThroughput() {
return this.get(RntbdRequestHeader.ShareThroughput);
}
private RntbdToken getSharedOfferThroughput() {
return this.get(RntbdRequestHeader.SharedOfferThroughput);
}
private RntbdToken getStartEpk() {
return this.get(RntbdRequestHeader.StartEpk);
}
private RntbdToken getStartId() {
return this.get(RntbdRequestHeader.StartId);
}
private RntbdToken getStoredProcedureName() {
return this.get(RntbdRequestHeader.StoredProcedureName);
}
private RntbdToken getSupportSpatialLegacyCoordinates() {
return this.get(RntbdRequestHeader.SupportSpatialLegacyCoordinates);
}
private RntbdToken getTargetGlobalCommittedLsn() {
return this.get(RntbdRequestHeader.TargetGlobalCommittedLsn);
}
private RntbdToken getTargetLsn() {
return this.get(RntbdRequestHeader.TargetLsn);
}
private RntbdToken getTimeToLiveInSeconds() {
return this.get(RntbdRequestHeader.TimeToLiveInSeconds);
}
private RntbdToken getTransportRequestID() {
return this.get(RntbdRequestHeader.TransportRequestID);
}
private RntbdToken getTriggerName() {
return this.get(RntbdRequestHeader.TriggerName);
}
private RntbdToken getUsePolygonsSmallerThanAHemisphere() {
return this.get(RntbdRequestHeader.UsePolygonsSmallerThanAHemisphere);
}
private RntbdToken getUserDefinedFunctionName() {
return this.get(RntbdRequestHeader.UserDefinedFunctionName);
}
private RntbdToken getUserDefinedTypeName() {
return this.get(RntbdRequestHeader.UserDefinedTypeName);
}
private RntbdToken getUserName() {
return this.get(RntbdRequestHeader.UserName);
}
private RntbdToken isBatchAtomic() {
return this.get(RntbdRequestHeader.IsBatchAtomic);
}
private RntbdToken shouldBatchContinueOnError() {
return this.get(RntbdRequestHeader.ShouldBatchContinueOnError);
}
private RntbdToken isBatchOrdered() {
return this.get(RntbdRequestHeader.IsBatchOrdered);
}
private void addAimHeader(final Map<String, String> headers) {
final String value = headers.get(HttpHeaders.A_IM);
if (StringUtils.isNotEmpty(value)) {
this.getAIM().setValue(value);
}
}
private void addAllowScanOnQuery(final Map<String, String> headers) {
final String value = headers.get(HttpHeaders.ENABLE_SCAN_IN_QUERY);
if (StringUtils.isNotEmpty(value)) {
this.getEnableScanInQuery().setValue(Boolean.parseBoolean(value));
}
}
private void addBinaryIdIfPresent(final Map<String, String> headers) {
final String value = headers.get(BackendHeaders.BINARY_ID);
if (StringUtils.isNotEmpty(value)) {
this.getBinaryId().setValue(Base64.getDecoder().decode(value));
}
}
private void addCanCharge(final Map<String, String> headers) {
final String value = headers.get(HttpHeaders.CAN_CHARGE);
if (StringUtils.isNotEmpty(value)) {
this.getCanCharge().setValue(Boolean.parseBoolean(value));
}
}
private void addCanOfferReplaceComplete(final Map<String, String> headers) {
final String value = headers.get(HttpHeaders.CAN_OFFER_REPLACE_COMPLETE);
if (StringUtils.isNotEmpty(value)) {
this.getCanOfferReplaceComplete().setValue(Boolean.parseBoolean(value));
}
}
private void addCanThrottle(final Map<String, String> headers) {
final String value = headers.get(HttpHeaders.CAN_THROTTLE);
if (StringUtils.isNotEmpty(value)) {
this.getCanThrottle().setValue(Boolean.parseBoolean(value));
}
}
private void addCollectionRemoteStorageSecurityIdentifier(final Map<String, String> headers) {
final String value = headers.get(HttpHeaders.COLLECTION_REMOTE_STORAGE_SECURITY_IDENTIFIER);
if (StringUtils.isNotEmpty(value)) {
this.getCollectionRemoteStorageSecurityIdentifier().setValue(value);
}
}
private void addConsistencyLevelHeader(final Map<String, String> headers) {
final String value = headers.get(HttpHeaders.CONSISTENCY_LEVEL);
if (StringUtils.isNotEmpty(value)) {
final ConsistencyLevel level = BridgeInternal.fromServiceSerializedFormat(value);
if (level == null) {
final String reason = String.format(Locale.ROOT, RMResources.InvalidRequestHeaderValue,
HttpHeaders.CONSISTENCY_LEVEL,
value);
throw new IllegalStateException(reason);
}
switch (level) {
case STRONG:
this.getConsistencyLevel().setValue(RntbdConsistencyLevel.Strong.id());
break;
case BOUNDED_STALENESS:
this.getConsistencyLevel().setValue(RntbdConsistencyLevel.BoundedStaleness.id());
break;
case SESSION:
this.getConsistencyLevel().setValue(RntbdConsistencyLevel.Session.id());
break;
case EVENTUAL:
this.getConsistencyLevel().setValue(RntbdConsistencyLevel.Eventual.id());
break;
case CONSISTENT_PREFIX:
this.getConsistencyLevel().setValue(RntbdConsistencyLevel.ConsistentPrefix.id());
break;
default:
assert false;
break;
}
}
}
private void addContentSerializationFormat(final Map<String, String> headers) {
final String value = headers.get(HttpHeaders.CONTENT_SERIALIZATION_FORMAT);
if (StringUtils.isNotEmpty(value)) {
final ContentSerializationFormat format = EnumUtils.getEnumIgnoreCase(
ContentSerializationFormat.class,
value);
if (format == null) {
final String reason = String.format(Locale.ROOT, RMResources.InvalidRequestHeaderValue,
HttpHeaders.CONTENT_SERIALIZATION_FORMAT,
value);
throw new IllegalStateException(reason);
}
switch (format) {
case JsonText:
this.getContentSerializationFormat().setValue(RntbdContentSerializationFormat.JsonText.id());
break;
case CosmosBinary:
this.getContentSerializationFormat().setValue(RntbdContentSerializationFormat.CosmosBinary.id());
break;
default:
assert false;
}
}
}
private void addContinuationToken(final RxDocumentServiceRequest request) {
final String value = request.getContinuation();
if (StringUtils.isNotEmpty(value)) {
this.getContinuationToken().setValue(value);
}
}
private void addDateHeader(final Map<String, String> headers) {
String value = headers.get(HttpHeaders.X_DATE);
if (StringUtils.isEmpty(value)) {
value = headers.get(HttpHeaders.HTTP_DATE);
}
if (StringUtils.isNotEmpty(value)) {
this.getDate().setValue(value);
}
}
private void addDisableRUPerMinuteUsage(final Map<String, String> headers) {
final String value = headers.get(HttpHeaders.DISABLE_RU_PER_MINUTE_USAGE);
if (StringUtils.isNotEmpty(value)) {
this.getDisableRUPerMinuteUsage().setValue(Boolean.parseBoolean(value));
}
}
private void addEmitVerboseTracesInQuery(final Map<String, String> headers) {
final String value = headers.get(HttpHeaders.EMIT_VERBOSE_TRACES_IN_QUERY);
if (StringUtils.isNotEmpty(value)) {
this.getEmitVerboseTracesInQuery().setValue(Boolean.parseBoolean(value));
}
}
private void addEnableLogging(final Map<String, String> headers) {
final String value = headers.get(HttpHeaders.ENABLE_LOGGING);
if (StringUtils.isNotEmpty(value)) {
this.getEnableLogging().setValue(Boolean.parseBoolean(value));
}
}
private void addEnableLowPrecisionOrderBy(final Map<String, String> headers) {
final String value = headers.get(HttpHeaders.ENABLE_LOW_PRECISION_ORDER_BY);
if (StringUtils.isNotEmpty(value)) {
this.getEnableLowPrecisionOrderBy().setValue(Boolean.parseBoolean(value));
}
}
private void addEntityId(final Map<String, String> headers) {
final String value = headers.get(BackendHeaders.ENTITY_ID);
if (StringUtils.isNotEmpty(value)) {
this.getEntityId().setValue(value);
}
}
private void addEnumerationDirection(final Map<String, String> headers) {
final String value = headers.get(HttpHeaders.ENUMERATION_DIRECTION);
if (StringUtils.isNotEmpty(value)) {
final EnumerationDirection direction = EnumUtils.getEnumIgnoreCase(EnumerationDirection.class, value);
if (direction == null) {
final String reason = String.format(Locale.ROOT, RMResources.InvalidRequestHeaderValue,
HttpHeaders.ENUMERATION_DIRECTION,
value);
throw new IllegalStateException(reason);
}
switch (direction) {
case Forward:
this.getEnumerationDirection().setValue(RntbdEnumerationDirection.Forward.id());
break;
case Reverse:
this.getEnumerationDirection().setValue(RntbdEnumerationDirection.Reverse.id());
break;
default:
assert false;
}
}
}
private void addExcludeSystemProperties(final Map<String, String> headers) {
final String value = headers.get(BackendHeaders.EXCLUDE_SYSTEM_PROPERTIES);
if (StringUtils.isNotEmpty(value)) {
this.getExcludeSystemProperties().setValue(Boolean.parseBoolean(value));
}
}
private void addFanoutOperationStateHeader(final Map<String, String> headers) {
final String value = headers.get(BackendHeaders.FANOUT_OPERATION_STATE);
if (StringUtils.isNotEmpty(value)) {
final FanoutOperationState format = EnumUtils.getEnumIgnoreCase(FanoutOperationState.class, value);
if (format == null) {
final String reason = String.format(Locale.ROOT, RMResources.InvalidRequestHeaderValue,
BackendHeaders.FANOUT_OPERATION_STATE,
value);
throw new IllegalStateException(reason);
}
switch (format) {
case Started:
this.getFanoutOperationState().setValue(RntbdFanoutOperationState.Started.id());
break;
case Completed:
this.getFanoutOperationState().setValue(RntbdFanoutOperationState.Completed.id());
break;
default:
assert false;
}
}
}
private void addIfModifiedSinceHeader(final Map<String, String> headers) {
final String value = headers.get(HttpHeaders.IF_MODIFIED_SINCE);
if (StringUtils.isNotEmpty(value)) {
this.getIfModifiedSince().setValue(value);
}
}
private void addIndexingDirectiveHeader(final Map<String, String> headers) {
final String value = headers.get(HttpHeaders.INDEXING_DIRECTIVE);
if (StringUtils.isNotEmpty(value)) {
final IndexingDirective directive = EnumUtils.getEnumIgnoreCase(IndexingDirective.class, value);
if (directive == null) {
final String reason = String.format(Locale.ROOT, RMResources.InvalidRequestHeaderValue,
HttpHeaders.INDEXING_DIRECTIVE,
value);
throw new IllegalStateException(reason);
}
switch (directive) {
case DEFAULT:
this.getIndexingDirective().setValue(RntbdIndexingDirective.Default.id());
break;
case EXCLUDE:
this.getIndexingDirective().setValue(RntbdIndexingDirective.Exclude.id());
break;
case INCLUDE:
this.getIndexingDirective().setValue(RntbdIndexingDirective.Include.id());
break;
default:
assert false;
}
}
}
private void addIsAutoScaleRequest(final Map<String, String> headers) {
final String value = headers.get(HttpHeaders.IS_AUTO_SCALE_REQUEST);
if (StringUtils.isNotEmpty(value)) {
this.getIsAutoScaleRequest().setValue(Boolean.parseBoolean(value));
}
}
private void addIsFanout(final Map<String, String> headers) {
final String value = headers.get(BackendHeaders.IS_FANOUT_REQUEST);
if (StringUtils.isNotEmpty(value)) {
this.getIsFanout().setValue(Boolean.parseBoolean(value));
}
}
private void addIsReadOnlyScript(final Map<String, String> headers) {
final String value = headers.get(HttpHeaders.IS_READ_ONLY_SCRIPT);
if (StringUtils.isNotEmpty(value)) {
this.getIsReadOnlyScript().setValue(Boolean.parseBoolean(value));
}
}
private void addIsUserRequest(final Map<String, String> headers) {
final String value = headers.get(BackendHeaders.IS_USER_REQUEST);
if (StringUtils.isNotEmpty(value)) {
this.getIsUserRequest().setValue(Boolean.parseBoolean(value));
}
}
private void addMatchHeader(final Map<String, String> headers, final RntbdOperationType operationType) {
String match = null;
switch (operationType) {
case Read:
case ReadFeed:
match = headers.get(HttpHeaders.IF_NONE_MATCH);
break;
default:
match = headers.get(HttpHeaders.IF_MATCH);
break;
}
if (StringUtils.isNotEmpty(match)) {
this.getMatch().setValue(match);
}
}
private void addMigrateCollectionDirectiveHeader(final Map<String, String> headers) {
final String value = headers.get(HttpHeaders.MIGRATE_COLLECTION_DIRECTIVE);
if (StringUtils.isNotEmpty(value)) {
final MigrateCollectionDirective directive = EnumUtils.getEnumIgnoreCase(MigrateCollectionDirective.class, value);
if (directive == null) {
final String reason = String.format(Locale.ROOT, RMResources.InvalidRequestHeaderValue,
HttpHeaders.MIGRATE_COLLECTION_DIRECTIVE,
value);
throw new IllegalStateException(reason);
}
switch (directive) {
case Freeze:
this.getMigrateCollectionDirective().setValue(RntbdMigrateCollectionDirective.Freeze.id());
break;
case Thaw:
this.getMigrateCollectionDirective().setValue(RntbdMigrateCollectionDirective.Thaw.id());
break;
default:
assert false;
break;
}
}
}
private void addPageSize(final Map<String, String> headers) {
final String value = headers.get(HttpHeaders.PAGE_SIZE);
if (StringUtils.isNotEmpty(value)) {
final long aLong = parseLong(HttpHeaders.PAGE_SIZE, value, -1, 0xFFFFFFFFL);
this.getPageSize().setValue((int)(aLong < 0 ? 0xFFFFFFFFL : aLong));
}
}
private void addPopulateCollectionThroughputInfo(final Map<String, String> headers) {
final String value = headers.get(HttpHeaders.POPULATE_COLLECTION_THROUGHPUT_INFO);
if (StringUtils.isNotEmpty(value)) {
this.getPopulateCollectionThroughputInfo().setValue(Boolean.parseBoolean(value));
}
}
private void addPopulatePartitionStatistics(final Map<String, String> headers) {
final String value = headers.get(HttpHeaders.POPULATE_PARTITION_STATISTICS);
if (StringUtils.isNotEmpty(value)) {
this.getPopulatePartitionStatistics().setValue(Boolean.parseBoolean(value));
}
}
private void addPopulateQueryMetrics(final Map<String, String> headers) {
final String value = headers.get(HttpHeaders.POPULATE_QUERY_METRICS);
if (StringUtils.isNotEmpty(value)) {
this.getPopulateQueryMetrics().setValue(Boolean.parseBoolean(value));
}
}
private void addPopulateQuotaInfo(final Map<String, String> headers) {
final String value = headers.get(HttpHeaders.POPULATE_QUOTA_INFO);
if (StringUtils.isNotEmpty(value)) {
this.getPopulateQuotaInfo().setValue(Boolean.parseBoolean(value));
}
}
private void addProfileRequest(final Map<String, String> headers) {
final String value = headers.get(HttpHeaders.PROFILE_REQUEST);
if (StringUtils.isNotEmpty(value)) {
this.getProfileRequest().setValue(Boolean.parseBoolean(value));
}
}
private void addQueryForceScan(final Map<String, String> headers) {
final String value = headers.get(HttpHeaders.FORCE_QUERY_SCAN);
if (StringUtils.isNotEmpty(value)) {
this.getForceQueryScan().setValue(Boolean.parseBoolean(value));
}
}
private void addRemoteStorageType(final Map<String, String> headers) {
final String value = headers.get(BackendHeaders.REMOTE_STORAGE_TYPE);
if (StringUtils.isNotEmpty(value)) {
final RemoteStorageType type = EnumUtils.getEnumIgnoreCase(RemoteStorageType.class, value);
if (type == null) {
final String reason = String.format(Locale.ROOT, RMResources.InvalidRequestHeaderValue,
BackendHeaders.REMOTE_STORAGE_TYPE,
value);
throw new IllegalStateException(reason);
}
switch (type) {
case Standard:
this.getRemoteStorageType().setValue(RntbdRemoteStorageType.Standard.id());
break;
case Premium:
this.getRemoteStorageType().setValue(RntbdRemoteStorageType.Premium.id());
break;
default:
assert false;
}
}
}
private void addResourceIdOrPathHeaders(final RxDocumentServiceRequest request) {
final String value = request.getResourceId();
if (StringUtils.isNotEmpty(value)) {
this.getResourceId().setValue(ResourceId.parse(request.getResourceType(), value));
}
if (request.getIsNameBased()) {
final String address = request.getResourceAddress();
final String[] fragments = StringUtils.split(address, URL_TRIM);
int count = fragments.length;
if (count >= 2) {
switch (fragments[0]) {
case Paths.DATABASES_PATH_SEGMENT:
this.getDatabaseName().setValue(fragments[1]);
break;
default:
final String reason = String.format(Locale.ROOT, RMResources.InvalidResourceAddress,
value, address);
throw new IllegalStateException(reason);
}
}
if (count >= 4) {
switch (fragments[2]) {
case Paths.COLLECTIONS_PATH_SEGMENT:
this.getCollectionName().setValue(fragments[3]);
break;
case Paths.USERS_PATH_SEGMENT:
this.getUserName().setValue(fragments[3]);
break;
case Paths.USER_DEFINED_TYPES_PATH_SEGMENT:
this.getUserDefinedTypeName().setValue(fragments[3]);
break;
}
}
if (count >= 6) {
switch (fragments[4]) {
case Paths.DOCUMENTS_PATH_SEGMENT:
this.getDocumentName().setValue(fragments[5]);
break;
case Paths.STORED_PROCEDURES_PATH_SEGMENT:
this.getStoredProcedureName().setValue(fragments[5]);
break;
case Paths.PERMISSIONS_PATH_SEGMENT:
this.getPermissionName().setValue(fragments[5]);
break;
case Paths.USER_DEFINED_FUNCTIONS_PATH_SEGMENT:
this.getUserDefinedFunctionName().setValue(fragments[5]);
break;
case Paths.TRIGGERS_PATH_SEGMENT:
this.getTriggerName().setValue(fragments[5]);
break;
case Paths.CONFLICTS_PATH_SEGMENT:
this.getConflictName().setValue(fragments[5]);
break;
case Paths.PARTITION_KEY_RANGES_PATH_SEGMENT:
this.getPartitionKeyRangeName().setValue(fragments[5]);
break;
case Paths.SCHEMAS_PATH_SEGMENT:
this.getSchemaName().setValue(fragments[5]);
break;
}
}
if (count >= 8) {
switch (fragments[6]) {
case Paths.ATTACHMENTS_PATH_SEGMENT:
this.getAttachmentName().setValue(fragments[7]);
break;
}
}
}
}
private void addResponseContinuationTokenLimitInKb(final Map<String, String> headers) {
final String value = headers.get(HttpHeaders.RESPONSE_CONTINUATION_TOKEN_LIMIT_IN_KB);
if (StringUtils.isNotEmpty(value)) {
final long aLong = parseLong(HttpHeaders.RESPONSE_CONTINUATION_TOKEN_LIMIT_IN_KB, value, 0, 0xFFFFFFFFL);
this.getResponseContinuationTokenLimitInKb().setValue((int)(aLong < 0 ? 0xFFFFFFFFL : aLong));
}
}
private void addShareThroughput(final Map<String, String> headers) {
final String value = headers.get(BackendHeaders.SHARE_THROUGHPUT);
if (StringUtils.isNotEmpty(value)) {
this.getShareThroughput().setValue(Boolean.parseBoolean(value));
}
}
private void addSupportSpatialLegacyCoordinates(final Map<String, String> headers) {
final String value = headers.get(HttpHeaders.SUPPORT_SPATIAL_LEGACY_COORDINATES);
if (StringUtils.isNotEmpty(value)) {
this.getSupportSpatialLegacyCoordinates().setValue(Boolean.parseBoolean(value));
}
}
private void addUsePolygonsSmallerThanAHemisphere(final Map<String, String> headers) {
final String value = headers.get(HttpHeaders.USE_POLYGONS_SMALLER_THAN_AHEMISPHERE);
if (StringUtils.isNotEmpty(value)) {
this.getUsePolygonsSmallerThanAHemisphere().setValue(Boolean.parseBoolean(value));
}
}
private void addReturnPreference(final Map<String, String> headers) {
final String value = headers.get(HttpHeaders.PREFER);
if (StringUtils.isNotEmpty(value) && value.contains(HeaderValues.PREFER_RETURN_MINIMAL)) {
this.getReturnPreference().setValue(true);
}
}
private void fillTokenFromHeader(final Map<String, String> headers, final Supplier<RntbdToken> supplier, final String name) {
final String value = headers.get(name);
if (StringUtils.isNotEmpty(value)) {
final RntbdToken token = supplier.get();
switch (token.getTokenType()) {
case SmallString:
case String:
case ULongString: {
token.setValue(value);
break;
}
case Byte: {
token.setValue(Boolean.parseBoolean(value));
break;
}
case Double: {
token.setValue(parseDouble(name, value));
break;
}
case Long: {
final long aLong = parseLong(name, value, Integer.MIN_VALUE, Integer.MAX_VALUE);
token.setValue(aLong);
break;
}
case ULong: {
final long aLong = parseLong(name, value, 0, 0xFFFFFFFFL);
token.setValue(aLong);
break;
}
case LongLong: {
final long aLong = parseLong(name, value);
token.setValue(aLong);
break;
}
default: {
assert false : "Recognized header has neither special-case nor default handling to convert "
+ "from header String to RNTBD token";
break;
}
}
}
}
private static double parseDouble(final String name, final String value) {
final double aDouble;
try {
aDouble = Double.parseDouble(value);
} catch (final NumberFormatException error) {
final String reason = String.format(Locale.ROOT, RMResources.InvalidRequestHeaderValue, name, value);
throw new IllegalStateException(reason);
}
return aDouble;
}
private static long parseLong(final String name, final String value) {
final long aLong;
try {
aLong = Long.parseLong(value);
} catch (final NumberFormatException error) {
final String reason = String.format(Locale.ROOT, RMResources.InvalidRequestHeaderValue, name, value);
throw new IllegalStateException(reason);
}
return aLong;
}
private static long parseLong(final String name, final String value, final long min, final long max) {
final long aLong = parseLong(name, value);
if (!(min <= aLong && aLong <= max)) {
final String reason = String.format(Locale.ROOT, RMResources.InvalidRequestHeaderValue, name, aLong);
throw new IllegalStateException(reason);
}
return aLong;
}
} | class RntbdRequestHeaders extends RntbdTokenStream<RntbdRequestHeader> {
private static final String URL_TRIM = "/";
RntbdRequestHeaders(final RntbdRequestArgs args, final RntbdRequestFrame frame) {
this(Unpooled.EMPTY_BUFFER);
checkNotNull(args, "args");
checkNotNull(frame, "frame");
final RxDocumentServiceRequest request = args.serviceRequest();
final byte[] content = request.getContentAsByteArray();
this.getPayloadPresent().setValue(content != null && content.length > 0);
this.getReplicaPath().setValue(args.replicaPath());
this.getTransportRequestID().setValue(args.transportRequestId());
final Map<String, String> headers = request.getHeaders();
this.addAimHeader(headers);
this.addAllowScanOnQuery(headers);
this.addBinaryIdIfPresent(headers);
this.addCanCharge(headers);
this.addCanOfferReplaceComplete(headers);
this.addCanThrottle(headers);
this.addCollectionRemoteStorageSecurityIdentifier(headers);
this.addConsistencyLevelHeader(headers);
this.addContentSerializationFormat(headers);
this.addContinuationToken(request);
this.addDateHeader(headers);
this.addDisableRUPerMinuteUsage(headers);
this.addEmitVerboseTracesInQuery(headers);
this.addEnableLogging(headers);
this.addEnableLowPrecisionOrderBy(headers);
this.addEntityId(headers);
this.addEnumerationDirection(headers);
this.addExcludeSystemProperties(headers);
this.addFanoutOperationStateHeader(headers);
this.addIfModifiedSinceHeader(headers);
this.addIndexingDirectiveHeader(headers);
this.addIsAutoScaleRequest(headers);
this.addIsFanout(headers);
this.addIsReadOnlyScript(headers);
this.addIsUserRequest(headers);
this.addMatchHeader(headers, frame.getOperationType());
this.addMigrateCollectionDirectiveHeader(headers);
this.addPageSize(headers);
this.addPopulateCollectionThroughputInfo(headers);
this.addPopulatePartitionStatistics(headers);
this.addPopulateQueryMetrics(headers);
this.addPopulateQuotaInfo(headers);
this.addProfileRequest(headers);
this.addQueryForceScan(headers);
this.addRemoteStorageType(headers);
this.addResourceIdOrPathHeaders(request);
this.addResponseContinuationTokenLimitInKb(headers);
this.addShareThroughput(headers);
this.addStartAndEndKeys(headers);
this.addSupportSpatialLegacyCoordinates(headers);
this.addUsePolygonsSmallerThanAHemisphere(headers);
this.addReturnPreference(headers);
this.fillTokenFromHeader(headers, this::getAllowTentativeWrites, BackendHeaders.ALLOW_TENTATIVE_WRITES);
this.fillTokenFromHeader(headers, this::getAuthorizationToken, HttpHeaders.AUTHORIZATION);
this.fillTokenFromHeader(headers, this::getBinaryPassThroughRequest, BackendHeaders.BINARY_PASSTHROUGH_REQUEST);
this.fillTokenFromHeader(headers, this::getBindReplicaDirective, BackendHeaders.BIND_REPLICA_DIRECTIVE);
this.fillTokenFromHeader(headers, this::getClientRetryAttemptCount, HttpHeaders.CLIENT_RETRY_ATTEMPT_COUNT);
this.fillTokenFromHeader(headers, this::getCollectionPartitionIndex, BackendHeaders.COLLECTION_PARTITION_INDEX);
this.fillTokenFromHeader(headers, this::getCollectionRid, BackendHeaders.COLLECTION_RID);
this.fillTokenFromHeader(headers, this::getCollectionServiceIndex, BackendHeaders.COLLECTION_SERVICE_INDEX);
this.fillTokenFromHeader(headers, this::getEffectivePartitionKey, BackendHeaders.EFFECTIVE_PARTITION_KEY);
this.fillTokenFromHeader(headers, this::getEnableDynamicRidRangeAllocation, BackendHeaders.ENABLE_DYNAMIC_RID_RANGE_ALLOCATION);
this.fillTokenFromHeader(headers, this::getFilterBySchemaRid, HttpHeaders.FILTER_BY_SCHEMA_RESOURCE_ID);
this.fillTokenFromHeader(headers, this::getGatewaySignature, HttpHeaders.GATEWAY_SIGNATURE);
this.fillTokenFromHeader(headers, this::getPartitionCount, BackendHeaders.PARTITION_COUNT);
this.fillTokenFromHeader(headers, this::getPartitionKey, HttpHeaders.PARTITION_KEY);
this.fillTokenFromHeader(headers, this::getPartitionKeyRangeId, HttpHeaders.PARTITION_KEY_RANGE_ID);
this.fillTokenFromHeader(headers, this::getPartitionResourceFilter, BackendHeaders.PARTITION_RESOURCE_FILTER);
this.fillTokenFromHeader(headers, this::getPostTriggerExclude, HttpHeaders.POST_TRIGGER_EXCLUDE);
this.fillTokenFromHeader(headers, this::getPostTriggerInclude, HttpHeaders.POST_TRIGGER_INCLUDE);
this.fillTokenFromHeader(headers, this::getPreTriggerExclude, HttpHeaders.PRE_TRIGGER_EXCLUDE);
this.fillTokenFromHeader(headers, this::getPreTriggerInclude, HttpHeaders.PRE_TRIGGER_INCLUDE);
this.fillTokenFromHeader(headers, this::getPrimaryMasterKey, BackendHeaders.PRIMARY_MASTER_KEY);
this.fillTokenFromHeader(headers, this::getPrimaryReadonlyKey, BackendHeaders.PRIMARY_READONLY_KEY);
this.fillTokenFromHeader(headers, this::getRemainingTimeInMsOnClientRequest, HttpHeaders.REMAINING_TIME_IN_MS_ON_CLIENT_REQUEST);
this.fillTokenFromHeader(headers, this::getResourceSchemaName, BackendHeaders.RESOURCE_SCHEMA_NAME);
this.fillTokenFromHeader(headers, this::getResourceTokenExpiry, HttpHeaders.RESOURCE_TOKEN_EXPIRY);
this.fillTokenFromHeader(headers, this::getRestoreMetadataFilter, HttpHeaders.RESTORE_METADATA_FILTER);
this.fillTokenFromHeader(headers, this::getRestoreParams, BackendHeaders.RESTORE_PARAMS);
this.fillTokenFromHeader(headers, this::getSecondaryMasterKey, BackendHeaders.SECONDARY_MASTER_KEY);
this.fillTokenFromHeader(headers, this::getSecondaryReadonlyKey, BackendHeaders.SECONDARY_READONLY_KEY);
this.fillTokenFromHeader(headers, this::getSessionToken, HttpHeaders.SESSION_TOKEN);
this.fillTokenFromHeader(headers, this::getSharedOfferThroughput, HttpHeaders.SHARED_OFFER_THROUGHPUT);
this.fillTokenFromHeader(headers, this::getTargetGlobalCommittedLsn, HttpHeaders.TARGET_GLOBAL_COMMITTED_LSN);
this.fillTokenFromHeader(headers, this::getTargetLsn, HttpHeaders.TARGET_LSN);
this.fillTokenFromHeader(headers, this::getTimeToLiveInSeconds, BackendHeaders.TIME_TO_LIVE_IN_SECONDS);
this.fillTokenFromHeader(headers, this::getTransportRequestID, HttpHeaders.TRANSPORT_REQUEST_ID);
this.fillTokenFromHeader(headers, this::isBatchAtomic, HttpHeaders.IS_BATCH_ATOMIC);
this.fillTokenFromHeader(headers, this::shouldBatchContinueOnError, HttpHeaders.SHOULD_BATCH_CONTINUE_ON_ERROR);
this.fillTokenFromHeader(headers, this::isBatchOrdered, HttpHeaders.IS_BATCH_ORDERED);
this.fillTokenFromHeader(headers, this::getClientVersion, HttpHeaders.VERSION);
}
private RntbdRequestHeaders(ByteBuf in) {
super(RntbdRequestHeader.set, RntbdRequestHeader.map, in);
}
static RntbdRequestHeaders decode(final ByteBuf in) {
final RntbdRequestHeaders metadata = new RntbdRequestHeaders(in);
return RntbdRequestHeaders.decode(metadata);
}
private RntbdToken getAIM() {
return this.get(RntbdRequestHeader.A_IM);
}
private RntbdToken getAllowTentativeWrites() {
return this.get(RntbdRequestHeader.AllowTentativeWrites);
}
private RntbdToken getAttachmentName() {
return this.get(RntbdRequestHeader.AttachmentName);
}
private RntbdToken getAuthorizationToken() {
return this.get(RntbdRequestHeader.AuthorizationToken);
}
private RntbdToken getBinaryId() {
return this.get(RntbdRequestHeader.BinaryId);
}
private RntbdToken getBinaryPassThroughRequest() {
return this.get(RntbdRequestHeader.BinaryPassthroughRequest);
}
private RntbdToken getBindReplicaDirective() {
return this.get(RntbdRequestHeader.BindReplicaDirective);
}
private RntbdToken getCanCharge() {
return this.get(RntbdRequestHeader.CanCharge);
}
private RntbdToken getCanOfferReplaceComplete() {
return this.get(RntbdRequestHeader.CanOfferReplaceComplete);
}
private RntbdToken getCanThrottle() {
return this.get(RntbdRequestHeader.CanThrottle);
}
private RntbdToken getClientRetryAttemptCount() {
return this.get(RntbdRequestHeader.ClientRetryAttemptCount);
}
private RntbdToken getClientVersion() {
return this.get(RntbdRequestHeader.ClientVersion);
}
private RntbdToken getCollectionName() {
return this.get(RntbdRequestHeader.CollectionName);
}
private RntbdToken getCollectionPartitionIndex() {
return this.get(RntbdRequestHeader.CollectionPartitionIndex);
}
private RntbdToken getCollectionRemoteStorageSecurityIdentifier() {
return this.get(RntbdRequestHeader.CollectionRemoteStorageSecurityIdentifier);
}
private RntbdToken getCollectionRid() {
return this.get(RntbdRequestHeader.CollectionRid);
}
private RntbdToken getCollectionServiceIndex() {
return this.get(RntbdRequestHeader.CollectionServiceIndex);
}
private RntbdToken getConflictName() {
return this.get(RntbdRequestHeader.ConflictName);
}
private RntbdToken getConsistencyLevel() {
return this.get(RntbdRequestHeader.ConsistencyLevel);
}
private RntbdToken getContentSerializationFormat() {
return this.get(RntbdRequestHeader.ContentSerializationFormat);
}
private RntbdToken getContinuationToken() {
return this.get(RntbdRequestHeader.ContinuationToken);
}
private RntbdToken getDatabaseName() {
return this.get(RntbdRequestHeader.DatabaseName);
}
private RntbdToken getDate() {
return this.get(RntbdRequestHeader.Date);
}
private RntbdToken getDisableRUPerMinuteUsage() {
return this.get(RntbdRequestHeader.DisableRUPerMinuteUsage);
}
private RntbdToken getDocumentName() {
return this.get(RntbdRequestHeader.DocumentName);
}
private RntbdToken getEffectivePartitionKey() {
return this.get(RntbdRequestHeader.EffectivePartitionKey);
}
private RntbdToken getReturnPreference() {
return this.get(RntbdRequestHeader.ReturnPreference);
}
private RntbdToken getEmitVerboseTracesInQuery() {
return this.get(RntbdRequestHeader.EmitVerboseTracesInQuery);
}
private RntbdToken getEnableDynamicRidRangeAllocation() {
return this.get(RntbdRequestHeader.EnableDynamicRidRangeAllocation);
}
private RntbdToken getEnableLogging() {
return this.get(RntbdRequestHeader.EnableLogging);
}
private RntbdToken getEnableLowPrecisionOrderBy() {
return this.get(RntbdRequestHeader.EnableLowPrecisionOrderBy);
}
private RntbdToken getEnableScanInQuery() {
return this.get(RntbdRequestHeader.EnableScanInQuery);
}
private RntbdToken getEndEpk() {
return this.get(RntbdRequestHeader.EndEpk);
}
private RntbdToken getEndId() {
return this.get(RntbdRequestHeader.EndId);
}
private RntbdToken getEntityId() {
return this.get(RntbdRequestHeader.EntityId);
}
private RntbdToken getEnumerationDirection() {
return this.get(RntbdRequestHeader.EnumerationDirection);
}
private RntbdToken getExcludeSystemProperties() {
return this.get(RntbdRequestHeader.ExcludeSystemProperties);
}
private RntbdToken getFanoutOperationState() {
return this.get(RntbdRequestHeader.FanoutOperationState);
}
private RntbdToken getFilterBySchemaRid() {
return this.get(RntbdRequestHeader.FilterBySchemaRid);
}
private RntbdToken getForceQueryScan() {
return this.get(RntbdRequestHeader.ForceQueryScan);
}
private RntbdToken getGatewaySignature() {
return this.get(RntbdRequestHeader.GatewaySignature);
}
private RntbdToken getIfModifiedSince() {
return this.get(RntbdRequestHeader.IfModifiedSince);
}
private RntbdToken getIndexingDirective() {
return this.get(RntbdRequestHeader.IndexingDirective);
}
private RntbdToken getIsAutoScaleRequest() {
return this.get(RntbdRequestHeader.IsAutoScaleRequest);
}
private RntbdToken getIsFanout() {
return this.get(RntbdRequestHeader.IsFanout);
}
private RntbdToken getIsReadOnlyScript() {
return this.get(RntbdRequestHeader.IsReadOnlyScript);
}
private RntbdToken getIsUserRequest() {
return this.get(RntbdRequestHeader.IsUserRequest);
}
private RntbdToken getMatch() {
return this.get(RntbdRequestHeader.Match);
}
private RntbdToken getMigrateCollectionDirective() {
return this.get(RntbdRequestHeader.MigrateCollectionDirective);
}
private RntbdToken getPageSize() {
return this.get(RntbdRequestHeader.PageSize);
}
private RntbdToken getPartitionCount() {
return this.get(RntbdRequestHeader.PartitionCount);
}
private RntbdToken getPartitionKey() {
return this.get(RntbdRequestHeader.PartitionKey);
}
private RntbdToken getPartitionKeyRangeId() {
return this.get(RntbdRequestHeader.PartitionKeyRangeId);
}
private RntbdToken getPartitionKeyRangeName() {
return this.get(RntbdRequestHeader.PartitionKeyRangeName);
}
private RntbdToken getPartitionResourceFilter() {
return this.get(RntbdRequestHeader.PartitionResourceFilter);
}
private RntbdToken getPayloadPresent() {
return this.get(RntbdRequestHeader.PayloadPresent);
}
private RntbdToken getPermissionName() {
return this.get(RntbdRequestHeader.PermissionName);
}
private RntbdToken getPopulateCollectionThroughputInfo() {
return this.get(RntbdRequestHeader.PopulateCollectionThroughputInfo);
}
private RntbdToken getPopulatePartitionStatistics() {
return this.get(RntbdRequestHeader.PopulatePartitionStatistics);
}
private RntbdToken getPopulateQueryMetrics() {
return this.get(RntbdRequestHeader.PopulateQueryMetrics);
}
private RntbdToken getPopulateQuotaInfo() {
return this.get(RntbdRequestHeader.PopulateQuotaInfo);
}
private RntbdToken getPostTriggerExclude() {
return this.get(RntbdRequestHeader.PostTriggerExclude);
}
private RntbdToken getPostTriggerInclude() {
return this.get(RntbdRequestHeader.PostTriggerInclude);
}
private RntbdToken getPreTriggerExclude() {
return this.get(RntbdRequestHeader.PreTriggerExclude);
}
private RntbdToken getPreTriggerInclude() {
return this.get(RntbdRequestHeader.PreTriggerInclude);
}
private RntbdToken getPrimaryMasterKey() {
return this.get(RntbdRequestHeader.PrimaryMasterKey);
}
private RntbdToken getPrimaryReadonlyKey() {
return this.get(RntbdRequestHeader.PrimaryReadonlyKey);
}
private RntbdToken getProfileRequest() {
return this.get(RntbdRequestHeader.ProfileRequest);
}
private RntbdToken getReadFeedKeyType() {
return this.get(RntbdRequestHeader.ReadFeedKeyType);
}
private RntbdToken getRemainingTimeInMsOnClientRequest() {
return this.get(RntbdRequestHeader.RemainingTimeInMsOnClientRequest);
}
private RntbdToken getRemoteStorageType() {
return this.get(RntbdRequestHeader.RemoteStorageType);
}
private RntbdToken getReplicaPath() {
return this.get(RntbdRequestHeader.ReplicaPath);
}
private RntbdToken getResourceId() {
return this.get(RntbdRequestHeader.ResourceId);
}
private RntbdToken getResourceSchemaName() {
return this.get(RntbdRequestHeader.ResourceSchemaName);
}
private RntbdToken getResourceTokenExpiry() {
return this.get(RntbdRequestHeader.ResourceTokenExpiry);
}
private RntbdToken getResponseContinuationTokenLimitInKb() {
return this.get(RntbdRequestHeader.ResponseContinuationTokenLimitInKb);
}
private RntbdToken getRestoreMetadataFilter() {
return this.get(RntbdRequestHeader.RestoreMetadaFilter);
}
private RntbdToken getRestoreParams() {
return this.get(RntbdRequestHeader.RestoreParams);
}
private RntbdToken getSchemaName() {
return this.get(RntbdRequestHeader.SchemaName);
}
private RntbdToken getSecondaryMasterKey() {
return this.get(RntbdRequestHeader.SecondaryMasterKey);
}
private RntbdToken getSecondaryReadonlyKey() {
return this.get(RntbdRequestHeader.SecondaryReadonlyKey);
}
private RntbdToken getSessionToken() {
return this.get(RntbdRequestHeader.SessionToken);
}
private RntbdToken getShareThroughput() {
return this.get(RntbdRequestHeader.ShareThroughput);
}
private RntbdToken getSharedOfferThroughput() {
return this.get(RntbdRequestHeader.SharedOfferThroughput);
}
private RntbdToken getStartEpk() {
return this.get(RntbdRequestHeader.StartEpk);
}
private RntbdToken getStartId() {
return this.get(RntbdRequestHeader.StartId);
}
private RntbdToken getStoredProcedureName() {
return this.get(RntbdRequestHeader.StoredProcedureName);
}
private RntbdToken getSupportSpatialLegacyCoordinates() {
return this.get(RntbdRequestHeader.SupportSpatialLegacyCoordinates);
}
private RntbdToken getTargetGlobalCommittedLsn() {
return this.get(RntbdRequestHeader.TargetGlobalCommittedLsn);
}
private RntbdToken getTargetLsn() {
return this.get(RntbdRequestHeader.TargetLsn);
}
private RntbdToken getTimeToLiveInSeconds() {
return this.get(RntbdRequestHeader.TimeToLiveInSeconds);
}
private RntbdToken getTransportRequestID() {
return this.get(RntbdRequestHeader.TransportRequestID);
}
private RntbdToken getTriggerName() {
return this.get(RntbdRequestHeader.TriggerName);
}
private RntbdToken getUsePolygonsSmallerThanAHemisphere() {
return this.get(RntbdRequestHeader.UsePolygonsSmallerThanAHemisphere);
}
private RntbdToken getUserDefinedFunctionName() {
return this.get(RntbdRequestHeader.UserDefinedFunctionName);
}
private RntbdToken getUserDefinedTypeName() {
return this.get(RntbdRequestHeader.UserDefinedTypeName);
}
private RntbdToken getUserName() {
return this.get(RntbdRequestHeader.UserName);
}
private RntbdToken isBatchAtomic() {
return this.get(RntbdRequestHeader.IsBatchAtomic);
}
private RntbdToken shouldBatchContinueOnError() {
return this.get(RntbdRequestHeader.ShouldBatchContinueOnError);
}
private RntbdToken isBatchOrdered() {
return this.get(RntbdRequestHeader.IsBatchOrdered);
}
private void addAimHeader(final Map<String, String> headers) {
final String value = headers.get(HttpHeaders.A_IM);
if (StringUtils.isNotEmpty(value)) {
this.getAIM().setValue(value);
}
}
private void addAllowScanOnQuery(final Map<String, String> headers) {
final String value = headers.get(HttpHeaders.ENABLE_SCAN_IN_QUERY);
if (StringUtils.isNotEmpty(value)) {
this.getEnableScanInQuery().setValue(Boolean.parseBoolean(value));
}
}
private void addBinaryIdIfPresent(final Map<String, String> headers) {
final String value = headers.get(BackendHeaders.BINARY_ID);
if (StringUtils.isNotEmpty(value)) {
this.getBinaryId().setValue(Base64.getDecoder().decode(value));
}
}
private void addCanCharge(final Map<String, String> headers) {
final String value = headers.get(HttpHeaders.CAN_CHARGE);
if (StringUtils.isNotEmpty(value)) {
this.getCanCharge().setValue(Boolean.parseBoolean(value));
}
}
private void addCanOfferReplaceComplete(final Map<String, String> headers) {
final String value = headers.get(HttpHeaders.CAN_OFFER_REPLACE_COMPLETE);
if (StringUtils.isNotEmpty(value)) {
this.getCanOfferReplaceComplete().setValue(Boolean.parseBoolean(value));
}
}
private void addCanThrottle(final Map<String, String> headers) {
final String value = headers.get(HttpHeaders.CAN_THROTTLE);
if (StringUtils.isNotEmpty(value)) {
this.getCanThrottle().setValue(Boolean.parseBoolean(value));
}
}
private void addCollectionRemoteStorageSecurityIdentifier(final Map<String, String> headers) {
final String value = headers.get(HttpHeaders.COLLECTION_REMOTE_STORAGE_SECURITY_IDENTIFIER);
if (StringUtils.isNotEmpty(value)) {
this.getCollectionRemoteStorageSecurityIdentifier().setValue(value);
}
}
private void addConsistencyLevelHeader(final Map<String, String> headers) {
final String value = headers.get(HttpHeaders.CONSISTENCY_LEVEL);
if (StringUtils.isNotEmpty(value)) {
final ConsistencyLevel level = BridgeInternal.fromServiceSerializedFormat(value);
if (level == null) {
final String reason = String.format(Locale.ROOT, RMResources.InvalidRequestHeaderValue,
HttpHeaders.CONSISTENCY_LEVEL,
value);
throw new IllegalStateException(reason);
}
switch (level) {
case STRONG:
this.getConsistencyLevel().setValue(RntbdConsistencyLevel.Strong.id());
break;
case BOUNDED_STALENESS:
this.getConsistencyLevel().setValue(RntbdConsistencyLevel.BoundedStaleness.id());
break;
case SESSION:
this.getConsistencyLevel().setValue(RntbdConsistencyLevel.Session.id());
break;
case EVENTUAL:
this.getConsistencyLevel().setValue(RntbdConsistencyLevel.Eventual.id());
break;
case CONSISTENT_PREFIX:
this.getConsistencyLevel().setValue(RntbdConsistencyLevel.ConsistentPrefix.id());
break;
default:
assert false;
break;
}
}
}
private void addContentSerializationFormat(final Map<String, String> headers) {
final String value = headers.get(HttpHeaders.CONTENT_SERIALIZATION_FORMAT);
if (StringUtils.isNotEmpty(value)) {
final ContentSerializationFormat format = EnumUtils.getEnumIgnoreCase(
ContentSerializationFormat.class,
value);
if (format == null) {
final String reason = String.format(Locale.ROOT, RMResources.InvalidRequestHeaderValue,
HttpHeaders.CONTENT_SERIALIZATION_FORMAT,
value);
throw new IllegalStateException(reason);
}
switch (format) {
case JsonText:
this.getContentSerializationFormat().setValue(RntbdContentSerializationFormat.JsonText.id());
break;
case CosmosBinary:
this.getContentSerializationFormat().setValue(RntbdContentSerializationFormat.CosmosBinary.id());
break;
default:
assert false;
}
}
}
private void addContinuationToken(final RxDocumentServiceRequest request) {
final String value = request.getContinuation();
if (StringUtils.isNotEmpty(value)) {
this.getContinuationToken().setValue(value);
}
}
private void addDateHeader(final Map<String, String> headers) {
String value = headers.get(HttpHeaders.X_DATE);
if (StringUtils.isEmpty(value)) {
value = headers.get(HttpHeaders.HTTP_DATE);
}
if (StringUtils.isNotEmpty(value)) {
this.getDate().setValue(value);
}
}
private void addDisableRUPerMinuteUsage(final Map<String, String> headers) {
final String value = headers.get(HttpHeaders.DISABLE_RU_PER_MINUTE_USAGE);
if (StringUtils.isNotEmpty(value)) {
this.getDisableRUPerMinuteUsage().setValue(Boolean.parseBoolean(value));
}
}
private void addEmitVerboseTracesInQuery(final Map<String, String> headers) {
final String value = headers.get(HttpHeaders.EMIT_VERBOSE_TRACES_IN_QUERY);
if (StringUtils.isNotEmpty(value)) {
this.getEmitVerboseTracesInQuery().setValue(Boolean.parseBoolean(value));
}
}
private void addEnableLogging(final Map<String, String> headers) {
final String value = headers.get(HttpHeaders.ENABLE_LOGGING);
if (StringUtils.isNotEmpty(value)) {
this.getEnableLogging().setValue(Boolean.parseBoolean(value));
}
}
private void addEnableLowPrecisionOrderBy(final Map<String, String> headers) {
final String value = headers.get(HttpHeaders.ENABLE_LOW_PRECISION_ORDER_BY);
if (StringUtils.isNotEmpty(value)) {
this.getEnableLowPrecisionOrderBy().setValue(Boolean.parseBoolean(value));
}
}
private void addEntityId(final Map<String, String> headers) {
final String value = headers.get(BackendHeaders.ENTITY_ID);
if (StringUtils.isNotEmpty(value)) {
this.getEntityId().setValue(value);
}
}
private void addEnumerationDirection(final Map<String, String> headers) {
final String value = headers.get(HttpHeaders.ENUMERATION_DIRECTION);
if (StringUtils.isNotEmpty(value)) {
final EnumerationDirection direction = EnumUtils.getEnumIgnoreCase(EnumerationDirection.class, value);
if (direction == null) {
final String reason = String.format(Locale.ROOT, RMResources.InvalidRequestHeaderValue,
HttpHeaders.ENUMERATION_DIRECTION,
value);
throw new IllegalStateException(reason);
}
switch (direction) {
case Forward:
this.getEnumerationDirection().setValue(RntbdEnumerationDirection.Forward.id());
break;
case Reverse:
this.getEnumerationDirection().setValue(RntbdEnumerationDirection.Reverse.id());
break;
default:
assert false;
}
}
}
private void addExcludeSystemProperties(final Map<String, String> headers) {
final String value = headers.get(BackendHeaders.EXCLUDE_SYSTEM_PROPERTIES);
if (StringUtils.isNotEmpty(value)) {
this.getExcludeSystemProperties().setValue(Boolean.parseBoolean(value));
}
}
private void addFanoutOperationStateHeader(final Map<String, String> headers) {
final String value = headers.get(BackendHeaders.FANOUT_OPERATION_STATE);
if (StringUtils.isNotEmpty(value)) {
final FanoutOperationState format = EnumUtils.getEnumIgnoreCase(FanoutOperationState.class, value);
if (format == null) {
final String reason = String.format(Locale.ROOT, RMResources.InvalidRequestHeaderValue,
BackendHeaders.FANOUT_OPERATION_STATE,
value);
throw new IllegalStateException(reason);
}
switch (format) {
case Started:
this.getFanoutOperationState().setValue(RntbdFanoutOperationState.Started.id());
break;
case Completed:
this.getFanoutOperationState().setValue(RntbdFanoutOperationState.Completed.id());
break;
default:
assert false;
}
}
}
private void addIfModifiedSinceHeader(final Map<String, String> headers) {
final String value = headers.get(HttpHeaders.IF_MODIFIED_SINCE);
if (StringUtils.isNotEmpty(value)) {
this.getIfModifiedSince().setValue(value);
}
}
private void addIndexingDirectiveHeader(final Map<String, String> headers) {
final String value = headers.get(HttpHeaders.INDEXING_DIRECTIVE);
if (StringUtils.isNotEmpty(value)) {
final IndexingDirective directive = EnumUtils.getEnumIgnoreCase(IndexingDirective.class, value);
if (directive == null) {
final String reason = String.format(Locale.ROOT, RMResources.InvalidRequestHeaderValue,
HttpHeaders.INDEXING_DIRECTIVE,
value);
throw new IllegalStateException(reason);
}
switch (directive) {
case DEFAULT:
this.getIndexingDirective().setValue(RntbdIndexingDirective.Default.id());
break;
case EXCLUDE:
this.getIndexingDirective().setValue(RntbdIndexingDirective.Exclude.id());
break;
case INCLUDE:
this.getIndexingDirective().setValue(RntbdIndexingDirective.Include.id());
break;
default:
assert false;
}
}
}
private void addIsAutoScaleRequest(final Map<String, String> headers) {
final String value = headers.get(HttpHeaders.IS_AUTO_SCALE_REQUEST);
if (StringUtils.isNotEmpty(value)) {
this.getIsAutoScaleRequest().setValue(Boolean.parseBoolean(value));
}
}
private void addIsFanout(final Map<String, String> headers) {
final String value = headers.get(BackendHeaders.IS_FANOUT_REQUEST);
if (StringUtils.isNotEmpty(value)) {
this.getIsFanout().setValue(Boolean.parseBoolean(value));
}
}
private void addIsReadOnlyScript(final Map<String, String> headers) {
final String value = headers.get(HttpHeaders.IS_READ_ONLY_SCRIPT);
if (StringUtils.isNotEmpty(value)) {
this.getIsReadOnlyScript().setValue(Boolean.parseBoolean(value));
}
}
private void addIsUserRequest(final Map<String, String> headers) {
final String value = headers.get(BackendHeaders.IS_USER_REQUEST);
if (StringUtils.isNotEmpty(value)) {
this.getIsUserRequest().setValue(Boolean.parseBoolean(value));
}
}
private void addMatchHeader(final Map<String, String> headers, final RntbdOperationType operationType) {
String match = null;
switch (operationType) {
case Read:
case ReadFeed:
match = headers.get(HttpHeaders.IF_NONE_MATCH);
break;
default:
match = headers.get(HttpHeaders.IF_MATCH);
break;
}
if (StringUtils.isNotEmpty(match)) {
this.getMatch().setValue(match);
}
}
private void addMigrateCollectionDirectiveHeader(final Map<String, String> headers) {
final String value = headers.get(HttpHeaders.MIGRATE_COLLECTION_DIRECTIVE);
if (StringUtils.isNotEmpty(value)) {
final MigrateCollectionDirective directive = EnumUtils.getEnumIgnoreCase(MigrateCollectionDirective.class, value);
if (directive == null) {
final String reason = String.format(Locale.ROOT, RMResources.InvalidRequestHeaderValue,
HttpHeaders.MIGRATE_COLLECTION_DIRECTIVE,
value);
throw new IllegalStateException(reason);
}
switch (directive) {
case Freeze:
this.getMigrateCollectionDirective().setValue(RntbdMigrateCollectionDirective.Freeze.id());
break;
case Thaw:
this.getMigrateCollectionDirective().setValue(RntbdMigrateCollectionDirective.Thaw.id());
break;
default:
assert false;
break;
}
}
}
private void addPageSize(final Map<String, String> headers) {
final String value = headers.get(HttpHeaders.PAGE_SIZE);
if (StringUtils.isNotEmpty(value)) {
final long aLong = parseLong(HttpHeaders.PAGE_SIZE, value, -1, 0xFFFFFFFFL);
this.getPageSize().setValue((int)(aLong < 0 ? 0xFFFFFFFFL : aLong));
}
}
private void addPopulateCollectionThroughputInfo(final Map<String, String> headers) {
final String value = headers.get(HttpHeaders.POPULATE_COLLECTION_THROUGHPUT_INFO);
if (StringUtils.isNotEmpty(value)) {
this.getPopulateCollectionThroughputInfo().setValue(Boolean.parseBoolean(value));
}
}
private void addPopulatePartitionStatistics(final Map<String, String> headers) {
final String value = headers.get(HttpHeaders.POPULATE_PARTITION_STATISTICS);
if (StringUtils.isNotEmpty(value)) {
this.getPopulatePartitionStatistics().setValue(Boolean.parseBoolean(value));
}
}
private void addPopulateQueryMetrics(final Map<String, String> headers) {
final String value = headers.get(HttpHeaders.POPULATE_QUERY_METRICS);
if (StringUtils.isNotEmpty(value)) {
this.getPopulateQueryMetrics().setValue(Boolean.parseBoolean(value));
}
}
private void addPopulateQuotaInfo(final Map<String, String> headers) {
final String value = headers.get(HttpHeaders.POPULATE_QUOTA_INFO);
if (StringUtils.isNotEmpty(value)) {
this.getPopulateQuotaInfo().setValue(Boolean.parseBoolean(value));
}
}
private void addProfileRequest(final Map<String, String> headers) {
final String value = headers.get(HttpHeaders.PROFILE_REQUEST);
if (StringUtils.isNotEmpty(value)) {
this.getProfileRequest().setValue(Boolean.parseBoolean(value));
}
}
private void addQueryForceScan(final Map<String, String> headers) {
final String value = headers.get(HttpHeaders.FORCE_QUERY_SCAN);
if (StringUtils.isNotEmpty(value)) {
this.getForceQueryScan().setValue(Boolean.parseBoolean(value));
}
}
private void addRemoteStorageType(final Map<String, String> headers) {
final String value = headers.get(BackendHeaders.REMOTE_STORAGE_TYPE);
if (StringUtils.isNotEmpty(value)) {
final RemoteStorageType type = EnumUtils.getEnumIgnoreCase(RemoteStorageType.class, value);
if (type == null) {
final String reason = String.format(Locale.ROOT, RMResources.InvalidRequestHeaderValue,
BackendHeaders.REMOTE_STORAGE_TYPE,
value);
throw new IllegalStateException(reason);
}
switch (type) {
case Standard:
this.getRemoteStorageType().setValue(RntbdRemoteStorageType.Standard.id());
break;
case Premium:
this.getRemoteStorageType().setValue(RntbdRemoteStorageType.Premium.id());
break;
default:
assert false;
}
}
}
private void addResourceIdOrPathHeaders(final RxDocumentServiceRequest request) {
final String value = request.getResourceId();
if (StringUtils.isNotEmpty(value)) {
this.getResourceId().setValue(ResourceId.parse(request.getResourceType(), value));
}
if (request.getIsNameBased()) {
final String address = request.getResourceAddress();
final String[] fragments = StringUtils.split(address, URL_TRIM);
int count = fragments.length;
if (count >= 2) {
switch (fragments[0]) {
case Paths.DATABASES_PATH_SEGMENT:
this.getDatabaseName().setValue(fragments[1]);
break;
default:
final String reason = String.format(Locale.ROOT, RMResources.InvalidResourceAddress,
value, address);
throw new IllegalStateException(reason);
}
}
if (count >= 4) {
switch (fragments[2]) {
case Paths.COLLECTIONS_PATH_SEGMENT:
this.getCollectionName().setValue(fragments[3]);
break;
case Paths.USERS_PATH_SEGMENT:
this.getUserName().setValue(fragments[3]);
break;
case Paths.USER_DEFINED_TYPES_PATH_SEGMENT:
this.getUserDefinedTypeName().setValue(fragments[3]);
break;
}
}
if (count >= 6) {
switch (fragments[4]) {
case Paths.DOCUMENTS_PATH_SEGMENT:
this.getDocumentName().setValue(fragments[5]);
break;
case Paths.STORED_PROCEDURES_PATH_SEGMENT:
this.getStoredProcedureName().setValue(fragments[5]);
break;
case Paths.PERMISSIONS_PATH_SEGMENT:
this.getPermissionName().setValue(fragments[5]);
break;
case Paths.USER_DEFINED_FUNCTIONS_PATH_SEGMENT:
this.getUserDefinedFunctionName().setValue(fragments[5]);
break;
case Paths.TRIGGERS_PATH_SEGMENT:
this.getTriggerName().setValue(fragments[5]);
break;
case Paths.CONFLICTS_PATH_SEGMENT:
this.getConflictName().setValue(fragments[5]);
break;
case Paths.PARTITION_KEY_RANGES_PATH_SEGMENT:
this.getPartitionKeyRangeName().setValue(fragments[5]);
break;
case Paths.SCHEMAS_PATH_SEGMENT:
this.getSchemaName().setValue(fragments[5]);
break;
}
}
if (count >= 8) {
switch (fragments[6]) {
case Paths.ATTACHMENTS_PATH_SEGMENT:
this.getAttachmentName().setValue(fragments[7]);
break;
}
}
}
}
private void addResponseContinuationTokenLimitInKb(final Map<String, String> headers) {
final String value = headers.get(HttpHeaders.RESPONSE_CONTINUATION_TOKEN_LIMIT_IN_KB);
if (StringUtils.isNotEmpty(value)) {
final long aLong = parseLong(HttpHeaders.RESPONSE_CONTINUATION_TOKEN_LIMIT_IN_KB, value, 0, 0xFFFFFFFFL);
this.getResponseContinuationTokenLimitInKb().setValue((int)(aLong < 0 ? 0xFFFFFFFFL : aLong));
}
}
private void addShareThroughput(final Map<String, String> headers) {
final String value = headers.get(BackendHeaders.SHARE_THROUGHPUT);
if (StringUtils.isNotEmpty(value)) {
this.getShareThroughput().setValue(Boolean.parseBoolean(value));
}
}
private void addSupportSpatialLegacyCoordinates(final Map<String, String> headers) {
final String value = headers.get(HttpHeaders.SUPPORT_SPATIAL_LEGACY_COORDINATES);
if (StringUtils.isNotEmpty(value)) {
this.getSupportSpatialLegacyCoordinates().setValue(Boolean.parseBoolean(value));
}
}
private void addUsePolygonsSmallerThanAHemisphere(final Map<String, String> headers) {
final String value = headers.get(HttpHeaders.USE_POLYGONS_SMALLER_THAN_AHEMISPHERE);
if (StringUtils.isNotEmpty(value)) {
this.getUsePolygonsSmallerThanAHemisphere().setValue(Boolean.parseBoolean(value));
}
}
private void addReturnPreference(final Map<String, String> headers) {
final String value = headers.get(HttpHeaders.PREFER);
if (StringUtils.isNotEmpty(value) && value.contains(HeaderValues.PREFER_RETURN_MINIMAL)) {
this.getReturnPreference().setValue(true);
}
}
private void fillTokenFromHeader(final Map<String, String> headers, final Supplier<RntbdToken> supplier, final String name) {
final String value = headers.get(name);
if (StringUtils.isNotEmpty(value)) {
final RntbdToken token = supplier.get();
switch (token.getTokenType()) {
case SmallString:
case String:
case ULongString: {
token.setValue(value);
break;
}
case Byte: {
token.setValue(Boolean.parseBoolean(value));
break;
}
case Double: {
token.setValue(parseDouble(name, value));
break;
}
case Long: {
final long aLong = parseLong(name, value, Integer.MIN_VALUE, Integer.MAX_VALUE);
token.setValue(aLong);
break;
}
case ULong: {
final long aLong = parseLong(name, value, 0, 0xFFFFFFFFL);
token.setValue(aLong);
break;
}
case LongLong: {
final long aLong = parseLong(name, value);
token.setValue(aLong);
break;
}
default: {
assert false : "Recognized header has neither special-case nor default handling to convert "
+ "from header String to RNTBD token";
break;
}
}
}
}
private static double parseDouble(final String name, final String value) {
final double aDouble;
try {
aDouble = Double.parseDouble(value);
} catch (final NumberFormatException error) {
final String reason = String.format(Locale.ROOT, RMResources.InvalidRequestHeaderValue, name, value);
throw new IllegalStateException(reason);
}
return aDouble;
}
private static long parseLong(final String name, final String value) {
final long aLong;
try {
aLong = Long.parseLong(value);
} catch (final NumberFormatException error) {
final String reason = String.format(Locale.ROOT, RMResources.InvalidRequestHeaderValue, name, value);
throw new IllegalStateException(reason);
}
return aLong;
}
private static long parseLong(final String name, final String value, final long min, final long max) {
final long aLong = parseLong(name, value);
if (!(min <= aLong && aLong <= max)) {
final String reason = String.format(Locale.ROOT, RMResources.InvalidRequestHeaderValue, name, aLong);
throw new IllegalStateException(reason);
}
return aLong;
}
} |
idk if this is ok in the sample, but the fact that `assertion` is not null, doesn't mean that all 3 properties will be populated. it could be one, or 2 or all | public static void main(String[] args) {
TextAnalyticsAsyncClient client =
new TextAnalyticsClientBuilder()
.credential(new AzureKeyCredential("{key}"))
.endpoint("{endpoint}")
.buildAsyncClient();
List<TextDocumentInput> documents = new ArrayList<>();
for (int i = 0; i < 3; i++) {
documents.add(new TextDocumentInput(Integer.toString(i),
"The patient is a 54-year-old gentleman with a history of progressive angina over the past "
+ "several months. "
));
}
AnalyzeHealthcareEntitiesOptions options = new AnalyzeHealthcareEntitiesOptions()
.setIncludeStatistics(true);
client.beginAnalyzeHealthcareEntities(documents, options)
.flatMap(pollResult -> {
AnalyzeHealthcareEntitiesOperationDetail operationResult = pollResult.getValue();
System.out.printf("Operation created time: %s, expiration time: %s.%n",
operationResult.getCreatedAt(), operationResult.getExpiresAt());
return pollResult.getFinalResult();
})
.subscribe(healthcareTaskResultPagedFlux -> healthcareTaskResultPagedFlux.subscribe(
healthcareEntitiesResultCollection -> {
System.out.printf("Results of Azure Text Analytics \"Analyze Healthcare\" Model, version: %s%n",
healthcareEntitiesResultCollection.getModelVersion());
TextDocumentBatchStatistics batchStatistics = healthcareEntitiesResultCollection.getStatistics();
System.out.printf("Documents statistics: document count = %s, erroneous document count = %s,"
+ " transaction count = %s, valid document count = %s.%n",
batchStatistics.getDocumentCount(), batchStatistics.getInvalidDocumentCount(),
batchStatistics.getTransactionCount(), batchStatistics.getValidDocumentCount());
healthcareEntitiesResultCollection.forEach(healthcareEntitiesResult -> {
System.out.println("Document id = " + healthcareEntitiesResult.getId());
System.out.println("Document entities: ");
AtomicInteger ct = new AtomicInteger();
healthcareEntitiesResult.getEntities().forEach(healthcareEntity -> {
System.out.printf(
"\ti = %d, Text: %s, normalized name: %s, category: %s, subcategory: %s, confidence score: %f.%n",
ct.getAndIncrement(), healthcareEntity.getText(),
healthcareEntity.getNormalizedText(), healthcareEntity.getCategory(),
healthcareEntity.getSubcategory(), healthcareEntity.getConfidenceScore());
HealthcareEntityAssertion assertion = healthcareEntity.getAssertion();
if (assertion != null) {
System.out.printf(
"\tEntity assertion: association=%s, certainty=%s, conditionality=%s.%n",
assertion.getAssociation(), assertion.getCertainty(), assertion.getConditionality());
}
IterableStream<EntityDataSource> dataSources = healthcareEntity.getDataSources();
if (dataSources != null) {
dataSources.forEach(dataSource -> System.out.printf(
"\t\tEntity ID in data source: %s, data source: %s.%n",
dataSource.getEntityId(), dataSource.getName()));
}
});
final IterableStream<HealthcareEntityRelation> entityRelations =
healthcareEntitiesResult.getEntityRelations();
if (entityRelations != null) {
entityRelations.forEach(
entityRelation -> {
System.out.printf("Relation type: %s.%n", entityRelation.getRelationType());
entityRelation.getRoles().forEach(role -> {
final HealthcareEntity entity = role.getEntity();
System.out.printf("\tEntity text: %s, category: %s, role: %s.%n",
entity.getText(), entity.getCategory(), role.getName());
});
}
);
}
});
}
));
try {
TimeUnit.MINUTES.sleep(5);
} catch (InterruptedException e) {
e.printStackTrace();
}
} | "\tEntity assertion: association=%s, certainty=%s, conditionality=%s.%n", | public static void main(String[] args) {
TextAnalyticsAsyncClient client =
new TextAnalyticsClientBuilder()
.credential(new AzureKeyCredential("{key}"))
.endpoint("{endpoint}")
.buildAsyncClient();
List<TextDocumentInput> documents = new ArrayList<>();
for (int i = 0; i < 3; i++) {
documents.add(new TextDocumentInput(Integer.toString(i),
"The patient is a 54-year-old gentleman with a history of progressive angina over the past "
+ "several months. "
));
}
AnalyzeHealthcareEntitiesOptions options = new AnalyzeHealthcareEntitiesOptions()
.setIncludeStatistics(true);
client.beginAnalyzeHealthcareEntities(documents, options)
.flatMap(pollResult -> {
AnalyzeHealthcareEntitiesOperationDetail operationResult = pollResult.getValue();
System.out.printf("Operation created time: %s, expiration time: %s.%n",
operationResult.getCreatedAt(), operationResult.getExpiresAt());
return pollResult.getFinalResult();
})
.subscribe(healthcareTaskResultPagedFlux -> healthcareTaskResultPagedFlux.subscribe(
healthcareEntitiesResultCollection -> {
System.out.printf("Results of Azure Text Analytics \"Analyze Healthcare\" Model, version: %s%n",
healthcareEntitiesResultCollection.getModelVersion());
TextDocumentBatchStatistics batchStatistics = healthcareEntitiesResultCollection.getStatistics();
System.out.printf("Documents statistics: document count = %s, erroneous document count = %s,"
+ " transaction count = %s, valid document count = %s.%n",
batchStatistics.getDocumentCount(), batchStatistics.getInvalidDocumentCount(),
batchStatistics.getTransactionCount(), batchStatistics.getValidDocumentCount());
healthcareEntitiesResultCollection.forEach(healthcareEntitiesResult -> {
System.out.println("Document id = " + healthcareEntitiesResult.getId());
System.out.println("Document entities: ");
AtomicInteger ct = new AtomicInteger();
healthcareEntitiesResult.getEntities().forEach(healthcareEntity -> {
System.out.printf(
"\ti = %d, Text: %s, normalized name: %s, category: %s, subcategory: %s, confidence score: %f.%n",
ct.getAndIncrement(), healthcareEntity.getText(),
healthcareEntity.getNormalizedText(), healthcareEntity.getCategory(),
healthcareEntity.getSubcategory(), healthcareEntity.getConfidenceScore());
HealthcareEntityAssertion assertion = healthcareEntity.getAssertion();
if (assertion != null) {
System.out.printf(
"\tEntity assertion: association=%s, certainty=%s, conditionality=%s.%n",
assertion.getAssociation(), assertion.getCertainty(), assertion.getConditionality());
}
IterableStream<EntityDataSource> dataSources = healthcareEntity.getDataSources();
if (dataSources != null) {
dataSources.forEach(dataSource -> System.out.printf(
"\t\tEntity ID in data source: %s, data source: %s.%n",
dataSource.getEntityId(), dataSource.getName()));
}
});
final IterableStream<HealthcareEntityRelation> entityRelations =
healthcareEntitiesResult.getEntityRelations();
if (entityRelations != null) {
entityRelations.forEach(
entityRelation -> {
System.out.printf("Relation type: %s.%n", entityRelation.getRelationType());
entityRelation.getRoles().forEach(role -> {
final HealthcareEntity entity = role.getEntity();
System.out.printf("\tEntity text: %s, category: %s, role: %s.%n",
entity.getText(), entity.getCategory(), role.getName());
});
}
);
}
});
}
));
try {
TimeUnit.MINUTES.sleep(5);
} catch (InterruptedException e) {
e.printStackTrace();
}
} | class AnalyzeHealthcareEntitiesAsync {
/**
* Main method to invoke this demo about how to begin recognizing the healthcare long-running operation.
*
* @param args Unused arguments to the program.
*/
} | class AnalyzeHealthcareEntitiesAsync {
/**
* Main method to invoke this demo about how to begin recognizing the healthcare long-running operation.
*
* @param args Unused arguments to the program.
*/
} |
Yes. Here is more on listing all of properties in the assertion even though some of them are null value. | public static void main(String[] args) {
TextAnalyticsAsyncClient client =
new TextAnalyticsClientBuilder()
.credential(new AzureKeyCredential("{key}"))
.endpoint("{endpoint}")
.buildAsyncClient();
List<TextDocumentInput> documents = new ArrayList<>();
for (int i = 0; i < 3; i++) {
documents.add(new TextDocumentInput(Integer.toString(i),
"The patient is a 54-year-old gentleman with a history of progressive angina over the past "
+ "several months. "
));
}
AnalyzeHealthcareEntitiesOptions options = new AnalyzeHealthcareEntitiesOptions()
.setIncludeStatistics(true);
client.beginAnalyzeHealthcareEntities(documents, options)
.flatMap(pollResult -> {
AnalyzeHealthcareEntitiesOperationDetail operationResult = pollResult.getValue();
System.out.printf("Operation created time: %s, expiration time: %s.%n",
operationResult.getCreatedAt(), operationResult.getExpiresAt());
return pollResult.getFinalResult();
})
.subscribe(healthcareTaskResultPagedFlux -> healthcareTaskResultPagedFlux.subscribe(
healthcareEntitiesResultCollection -> {
System.out.printf("Results of Azure Text Analytics \"Analyze Healthcare\" Model, version: %s%n",
healthcareEntitiesResultCollection.getModelVersion());
TextDocumentBatchStatistics batchStatistics = healthcareEntitiesResultCollection.getStatistics();
System.out.printf("Documents statistics: document count = %s, erroneous document count = %s,"
+ " transaction count = %s, valid document count = %s.%n",
batchStatistics.getDocumentCount(), batchStatistics.getInvalidDocumentCount(),
batchStatistics.getTransactionCount(), batchStatistics.getValidDocumentCount());
healthcareEntitiesResultCollection.forEach(healthcareEntitiesResult -> {
System.out.println("Document id = " + healthcareEntitiesResult.getId());
System.out.println("Document entities: ");
AtomicInteger ct = new AtomicInteger();
healthcareEntitiesResult.getEntities().forEach(healthcareEntity -> {
System.out.printf(
"\ti = %d, Text: %s, normalized name: %s, category: %s, subcategory: %s, confidence score: %f.%n",
ct.getAndIncrement(), healthcareEntity.getText(),
healthcareEntity.getNormalizedText(), healthcareEntity.getCategory(),
healthcareEntity.getSubcategory(), healthcareEntity.getConfidenceScore());
HealthcareEntityAssertion assertion = healthcareEntity.getAssertion();
if (assertion != null) {
System.out.printf(
"\tEntity assertion: association=%s, certainty=%s, conditionality=%s.%n",
assertion.getAssociation(), assertion.getCertainty(), assertion.getConditionality());
}
IterableStream<EntityDataSource> dataSources = healthcareEntity.getDataSources();
if (dataSources != null) {
dataSources.forEach(dataSource -> System.out.printf(
"\t\tEntity ID in data source: %s, data source: %s.%n",
dataSource.getEntityId(), dataSource.getName()));
}
});
final IterableStream<HealthcareEntityRelation> entityRelations =
healthcareEntitiesResult.getEntityRelations();
if (entityRelations != null) {
entityRelations.forEach(
entityRelation -> {
System.out.printf("Relation type: %s.%n", entityRelation.getRelationType());
entityRelation.getRoles().forEach(role -> {
final HealthcareEntity entity = role.getEntity();
System.out.printf("\tEntity text: %s, category: %s, role: %s.%n",
entity.getText(), entity.getCategory(), role.getName());
});
}
);
}
});
}
));
try {
TimeUnit.MINUTES.sleep(5);
} catch (InterruptedException e) {
e.printStackTrace();
}
} | "\tEntity assertion: association=%s, certainty=%s, conditionality=%s.%n", | public static void main(String[] args) {
TextAnalyticsAsyncClient client =
new TextAnalyticsClientBuilder()
.credential(new AzureKeyCredential("{key}"))
.endpoint("{endpoint}")
.buildAsyncClient();
List<TextDocumentInput> documents = new ArrayList<>();
for (int i = 0; i < 3; i++) {
documents.add(new TextDocumentInput(Integer.toString(i),
"The patient is a 54-year-old gentleman with a history of progressive angina over the past "
+ "several months. "
));
}
AnalyzeHealthcareEntitiesOptions options = new AnalyzeHealthcareEntitiesOptions()
.setIncludeStatistics(true);
client.beginAnalyzeHealthcareEntities(documents, options)
.flatMap(pollResult -> {
AnalyzeHealthcareEntitiesOperationDetail operationResult = pollResult.getValue();
System.out.printf("Operation created time: %s, expiration time: %s.%n",
operationResult.getCreatedAt(), operationResult.getExpiresAt());
return pollResult.getFinalResult();
})
.subscribe(healthcareTaskResultPagedFlux -> healthcareTaskResultPagedFlux.subscribe(
healthcareEntitiesResultCollection -> {
System.out.printf("Results of Azure Text Analytics \"Analyze Healthcare\" Model, version: %s%n",
healthcareEntitiesResultCollection.getModelVersion());
TextDocumentBatchStatistics batchStatistics = healthcareEntitiesResultCollection.getStatistics();
System.out.printf("Documents statistics: document count = %s, erroneous document count = %s,"
+ " transaction count = %s, valid document count = %s.%n",
batchStatistics.getDocumentCount(), batchStatistics.getInvalidDocumentCount(),
batchStatistics.getTransactionCount(), batchStatistics.getValidDocumentCount());
healthcareEntitiesResultCollection.forEach(healthcareEntitiesResult -> {
System.out.println("Document id = " + healthcareEntitiesResult.getId());
System.out.println("Document entities: ");
AtomicInteger ct = new AtomicInteger();
healthcareEntitiesResult.getEntities().forEach(healthcareEntity -> {
System.out.printf(
"\ti = %d, Text: %s, normalized name: %s, category: %s, subcategory: %s, confidence score: %f.%n",
ct.getAndIncrement(), healthcareEntity.getText(),
healthcareEntity.getNormalizedText(), healthcareEntity.getCategory(),
healthcareEntity.getSubcategory(), healthcareEntity.getConfidenceScore());
HealthcareEntityAssertion assertion = healthcareEntity.getAssertion();
if (assertion != null) {
System.out.printf(
"\tEntity assertion: association=%s, certainty=%s, conditionality=%s.%n",
assertion.getAssociation(), assertion.getCertainty(), assertion.getConditionality());
}
IterableStream<EntityDataSource> dataSources = healthcareEntity.getDataSources();
if (dataSources != null) {
dataSources.forEach(dataSource -> System.out.printf(
"\t\tEntity ID in data source: %s, data source: %s.%n",
dataSource.getEntityId(), dataSource.getName()));
}
});
final IterableStream<HealthcareEntityRelation> entityRelations =
healthcareEntitiesResult.getEntityRelations();
if (entityRelations != null) {
entityRelations.forEach(
entityRelation -> {
System.out.printf("Relation type: %s.%n", entityRelation.getRelationType());
entityRelation.getRoles().forEach(role -> {
final HealthcareEntity entity = role.getEntity();
System.out.printf("\tEntity text: %s, category: %s, role: %s.%n",
entity.getText(), entity.getCategory(), role.getName());
});
}
);
}
});
}
));
try {
TimeUnit.MINUTES.sleep(5);
} catch (InterruptedException e) {
e.printStackTrace();
}
} | class AnalyzeHealthcareEntitiesAsync {
/**
* Main method to invoke this demo about how to begin recognizing the healthcare long-running operation.
*
* @param args Unused arguments to the program.
*/
} | class AnalyzeHealthcareEntitiesAsync {
/**
* Main method to invoke this demo about how to begin recognizing the healthcare long-running operation.
*
* @param args Unused arguments to the program.
*/
} |
Were these constants removed from SemanticAttributes in the GA release? | private void applySemanticConventions(Attributes attributes, RemoteDependencyData remoteDependencyData, SpanKind spanKind) {
String httpMethod = attributes.get(AttributeKey.stringKey("http.method"));
if (httpMethod != null) {
applyHttpClientSpan(attributes, remoteDependencyData);
return;
}
String rpcSystem = attributes.get(AttributeKey.stringKey("rpc.system"));
if (rpcSystem != null) {
applyRpcClientSpan(attributes, remoteDependencyData, rpcSystem);
return;
}
String dbSystem = attributes.get(AttributeKey.stringKey("db.system"));
if (dbSystem != null) {
applyDatabaseClientSpan(attributes, remoteDependencyData, dbSystem);
return;
}
String messagingSystem = attributes.get(AttributeKey.stringKey("messaging.system"));
if (messagingSystem != null) {
applyMessagingClientSpan(attributes, remoteDependencyData, messagingSystem, spanKind);
return;
}
} | String httpMethod = attributes.get(AttributeKey.stringKey("http.method")); | private void applySemanticConventions(Attributes attributes, RemoteDependencyData remoteDependencyData, SpanKind spanKind) {
String httpMethod = attributes.get(AttributeKey.stringKey("http.method"));
if (httpMethod != null) {
applyHttpClientSpan(attributes, remoteDependencyData);
return;
}
String rpcSystem = attributes.get(AttributeKey.stringKey("rpc.system"));
if (rpcSystem != null) {
applyRpcClientSpan(attributes, remoteDependencyData, rpcSystem);
return;
}
String dbSystem = attributes.get(AttributeKey.stringKey("db.system"));
if (dbSystem != null) {
applyDatabaseClientSpan(attributes, remoteDependencyData, dbSystem);
return;
}
String messagingSystem = attributes.get(AttributeKey.stringKey("messaging.system"));
if (messagingSystem != null) {
applyMessagingClientSpan(attributes, remoteDependencyData, messagingSystem, spanKind);
return;
}
} | class AzureMonitorTraceExporter implements SpanExporter {
private static final Pattern COMPONENT_PATTERN = Pattern
.compile("io\\.opentelemetry\\.javaagent\\.([^0-9]*)(-[0-9.]*)?");
private static final Set<String> SQL_DB_SYSTEMS;
private static final Set<String> STANDARD_ATTRIBUTE_PREFIXES;
private static final AttributeKey<String> AI_SPAN_SOURCE_APP_ID_KEY = AttributeKey.stringKey("applicationinsights.internal.source_app_id");
private static final AttributeKey<String> AI_SPAN_TARGET_APP_ID_KEY = AttributeKey.stringKey("applicationinsights.internal.target_app_id");
private static final AttributeKey<String> AI_SPAN_SOURCE_KEY = AttributeKey.stringKey("applicationinsights.internal.source");
static {
Set<String> dbSystems = new HashSet<>();
dbSystems.add("db2");
dbSystems.add("derby");
dbSystems.add("mariadb");
dbSystems.add("mssql");
dbSystems.add("mysql");
dbSystems.add("oracle");
dbSystems.add("postgresql");
dbSystems.add("sqlite");
dbSystems.add("other_sql");
dbSystems.add("hsqldb");
dbSystems.add("h2");
SQL_DB_SYSTEMS = Collections.unmodifiableSet(dbSystems);
Set<String> standardAttributesPrefix = new HashSet<>();
standardAttributesPrefix.add("http");
standardAttributesPrefix.add("db");
standardAttributesPrefix.add("message");
standardAttributesPrefix.add("messaging");
standardAttributesPrefix.add("rpc");
standardAttributesPrefix.add("enduser");
standardAttributesPrefix.add("net");
standardAttributesPrefix.add("peer");
standardAttributesPrefix.add("exception");
standardAttributesPrefix.add("thread");
standardAttributesPrefix.add("faas");
STANDARD_ATTRIBUTE_PREFIXES = Collections.unmodifiableSet(standardAttributesPrefix);
}
private final MonitorExporterAsyncClient client;
private final ClientLogger logger = new ClientLogger(AzureMonitorTraceExporter.class);
private final String instrumentationKey;
private final String telemetryItemNamePrefix;
/**
* Creates an instance of exporter that is configured with given exporter client that sends telemetry events to
* Application Insights resource identified by the instrumentation key.
* @param client The client used to send data to Azure Monitor.
* @param instrumentationKey The instrumentation key of Application Insights resource.
*/
AzureMonitorTraceExporter(MonitorExporterAsyncClient client, String instrumentationKey) {
this.client = client;
this.instrumentationKey = instrumentationKey;
String formattedInstrumentationKey = instrumentationKey.replaceAll("-", "");
this.telemetryItemNamePrefix = "Microsoft.ApplicationInsights." + formattedInstrumentationKey + ".";
}
/**
* {@inheritDoc}
*/
@Override
public CompletableResultCode export(Collection<SpanData> spans) {
try {
List<TelemetryItem> telemetryItems = new ArrayList<>();
for (SpanData span : spans) {
logger.verbose("exporting span: {}", span);
export(span, telemetryItems);
}
client.export(telemetryItems)
.subscriberContext(Context.of(Tracer.DISABLE_TRACING_KEY, true))
.subscribe();
return CompletableResultCode.ofSuccess();
} catch (Throwable t) {
logger.error(t.getMessage(), t);
return CompletableResultCode.ofFailure();
}
}
/**
* {@inheritDoc}
*/
@Override
public CompletableResultCode flush() {
return CompletableResultCode.ofSuccess();
}
/**
* {@inheritDoc}
*/
@Override
public CompletableResultCode shutdown() {
return CompletableResultCode.ofSuccess();
}
private void export(SpanData span, List<TelemetryItem> telemetryItems) {
SpanKind kind = span.getKind();
String instrumentationName = span.getInstrumentationLibraryInfo().getName();
Matcher matcher = COMPONENT_PATTERN.matcher(instrumentationName);
String stdComponent = matcher.matches() ? matcher.group(1) : null;
if ("jms".equals(stdComponent) && !span.getParentSpanContext().isValid() && kind == SpanKind.CONSUMER) {
return;
}
if (kind == SpanKind.INTERNAL) {
if ("spring-scheduling".equals(stdComponent) && !span.getParentSpanContext().isValid()) {
exportRequest(span, telemetryItems);
} else {
exportRemoteDependency(span, true, telemetryItems);
}
} else if (kind == SpanKind.CLIENT || kind == SpanKind.PRODUCER) {
exportRemoteDependency(span, false, telemetryItems);
} else if (kind == SpanKind.CONSUMER && !span.getParentSpanContext().isRemote()) {
exportRemoteDependency(span, false, telemetryItems);
} else if (kind == SpanKind.SERVER || kind == SpanKind.CONSUMER) {
exportRequest(span, telemetryItems);
} else {
throw logger.logExceptionAsError(new UnsupportedOperationException(kind.name()));
}
}
private static List<TelemetryExceptionDetails> minimalParse(String errorStack) {
TelemetryExceptionDetails details = new TelemetryExceptionDetails();
String line = errorStack.split(System.lineSeparator())[0];
int index = line.indexOf(": ");
if (index != -1) {
details.setTypeName(line.substring(0, index));
details.setMessage(line.substring(index + 2));
} else {
details.setTypeName(line);
}
details.setStack(errorStack);
return Collections.singletonList(details);
}
private void exportRemoteDependency(SpanData span, boolean inProc,
List<TelemetryItem> telemetryItems) {
TelemetryItem telemetryItem = new TelemetryItem();
RemoteDependencyData remoteDependencyData = new RemoteDependencyData();
MonitorBase monitorBase = new MonitorBase();
telemetryItem.setTags(new HashMap<>());
telemetryItem.setName(telemetryItemNamePrefix + "RemoteDependency");
telemetryItem.setVersion(1);
telemetryItem.setInstrumentationKey(instrumentationKey);
telemetryItem.setData(monitorBase);
remoteDependencyData.setProperties(new HashMap<>());
remoteDependencyData.setVersion(2);
monitorBase.setBaseType("RemoteDependencyData");
monitorBase.setBaseData(remoteDependencyData);
addLinks(remoteDependencyData.getProperties(), span.getLinks());
remoteDependencyData.setName(span.getName());
Attributes attributes = span.getAttributes();
if (inProc) {
remoteDependencyData.setType("InProc");
} else {
applySemanticConventions(attributes, remoteDependencyData, span.getKind());
}
remoteDependencyData.setId(span.getSpanId());
telemetryItem.getTags().put(ContextTagKeys.AI_OPERATION_ID.toString(), span.getTraceId());
String parentSpanId = span.getParentSpanId();
if (SpanId.isValid(parentSpanId)) {
telemetryItem.getTags().put(ContextTagKeys.AI_OPERATION_PARENT_ID.toString(), parentSpanId);
}
telemetryItem.setTime(getFormattedTime(span.getStartEpochNanos()));
remoteDependencyData
.setDuration(getFormattedDuration(Duration.ofNanos(span.getEndEpochNanos() - span.getStartEpochNanos())));
remoteDependencyData.setSuccess(span.getStatus().getStatusCode() != StatusCode.ERROR);
setExtraAttributes(telemetryItem, remoteDependencyData.getProperties(), attributes);
Double samplingPercentage = 100.0;
telemetryItem.setSampleRate(samplingPercentage.floatValue());
telemetryItems.add(telemetryItem);
exportEvents(span, samplingPercentage, telemetryItems);
}
private void applyHttpClientSpan(Attributes attributes, RemoteDependencyData telemetry) {
String scheme = attributes.get(AttributeKey.stringKey("http.scheme"));
int defaultPort;
if ("http".equals(scheme)) {
defaultPort = 80;
} else if ("https".equals(scheme)) {
defaultPort = 443;
} else {
defaultPort = 0;
}
String target = getTargetFromPeerAttributes(attributes, defaultPort);
if (target == null) {
target = attributes.get(AttributeKey.stringKey("http.host"));
}
String url = attributes.get(AttributeKey.stringKey("http.url"));
if (target == null && url != null) {
try {
URI uri = new URI(url);
target = uri.getHost();
if (uri.getPort() != 80 && uri.getPort() != 443 && uri.getPort() != -1) {
target += ":" + uri.getPort();
}
} catch (URISyntaxException e) {
logger.error(e.getMessage());
logger.verbose(e.getMessage(), e);
}
}
if (target == null) {
target = "Http";
}
String targetAppId = attributes.get(AI_SPAN_TARGET_APP_ID_KEY);
if (targetAppId == null) {
telemetry.setType("Http");
telemetry.setTarget(target);
} else {
telemetry.setType("Http (tracked component)");
telemetry.setTarget(target + " | " + targetAppId);
}
Long httpStatusCode = attributes.get(AttributeKey.longKey("http.status_code"));
if (httpStatusCode != null) {
telemetry.setResultCode(Long.toString(httpStatusCode));
}
telemetry.setData(url);
}
private static String getTargetFromPeerAttributes(Attributes attributes, int defaultPort) {
String target = attributes.get(AttributeKey.stringKey("peer.service"));
if (target != null) {
return target;
}
target = attributes.get(AttributeKey.stringKey("net.peer.name"));
if (target == null) {
target = attributes.get(AttributeKey.stringKey("net.peer.ip"));
}
if (target == null) {
return null;
}
Long port = attributes.get(AttributeKey.longKey("net.peer.port"));
if (port != null && port != defaultPort) {
return target + ":" + port;
}
return target;
}
private static void applyRpcClientSpan(Attributes attributes, RemoteDependencyData telemetry, String rpcSystem) {
telemetry.setType(rpcSystem);
String target = getTargetFromPeerAttributes(attributes, 0);
if (target == null) {
target = rpcSystem;
}
telemetry.setTarget(target);
}
private static void applyDatabaseClientSpan(Attributes attributes, RemoteDependencyData telemetry, String dbSystem) {
String dbStatement = attributes.get(AttributeKey.stringKey("db.statement"));
String type;
if (SQL_DB_SYSTEMS.contains(dbSystem)) {
type = "SQL";
telemetry.setName(dbStatement);
} else {
type = dbSystem;
}
telemetry.setType(type);
telemetry.setData(dbStatement);
String target = nullAwareConcat(getTargetFromPeerAttributes(attributes, getDefaultPortForDbSystem(dbSystem)),
attributes.get(AttributeKey.stringKey("db.name")), "/");
if (target == null) {
target = dbSystem;
}
telemetry.setTarget(target);
}
private void applyMessagingClientSpan(Attributes attributes, RemoteDependencyData telemetry, String messagingSystem, SpanKind spanKind) {
if (spanKind == SpanKind.PRODUCER) {
telemetry.setType("Queue Message | " + messagingSystem);
} else {
telemetry.setType(messagingSystem);
}
String destination = attributes.get(AttributeKey.stringKey("messaging.destination"));
if (destination != null) {
telemetry.setTarget(destination);
} else {
telemetry.setTarget(messagingSystem);
}
}
private static int getDefaultPortForDbSystem(String dbSystem) {
switch (dbSystem) {
case "mongodb":
return 27017;
case "cassandra":
return 9042;
case "redis":
return 6379;
default:
return 0;
}
}
private void exportRequest(SpanData span, List<TelemetryItem> telemetryItems) {
TelemetryItem telemetryItem = new TelemetryItem();
RequestData requestData = new RequestData();
MonitorBase monitorBase = new MonitorBase();
telemetryItem.setTags(new HashMap<>());
telemetryItem.setName(telemetryItemNamePrefix + "Request");
telemetryItem.setVersion(1);
telemetryItem.setInstrumentationKey(instrumentationKey);
telemetryItem.setData(monitorBase);
requestData.setProperties(new HashMap<>());
requestData.setVersion(2);
monitorBase.setBaseType("RequestData");
monitorBase.setBaseData(requestData);
String source = null;
Attributes attributes = span.getAttributes();
String sourceAppId = attributes.get(AI_SPAN_SOURCE_APP_ID_KEY);
if (sourceAppId != null) {
source = sourceAppId;
}
if (source == null) {
String messagingSystem = attributes.get(AttributeKey.stringKey("messaging.system"));
if (messagingSystem != null) {
source = nullAwareConcat(getTargetFromPeerAttributes(attributes, 0),
attributes.get(AttributeKey.stringKey("messaging.destination")), "/");
if (source == null) {
source = messagingSystem;
}
}
}
if (source == null) {
source = attributes.get(AI_SPAN_SOURCE_KEY);
}
requestData.setSource(source);
addLinks(requestData.getProperties(), span.getLinks());
Long httpStatusCode = attributes.get(AttributeKey.longKey("http.status_code"));
requestData.setResponseCode("200");
if (httpStatusCode != null) {
requestData.setResponseCode(Long.toString(httpStatusCode));
}
String httpUrl = attributes.get(AttributeKey.stringKey("http.url"));
if (httpUrl != null) {
requestData.setUrl(httpUrl);
}
String name = span.getName();
requestData.setName(name);
telemetryItem.getTags().put(ContextTagKeys.AI_OPERATION_NAME.toString(), name);
requestData.setId(span.getSpanId());
telemetryItem.getTags().put(ContextTagKeys.AI_OPERATION_ID.toString(), span.getTraceId());
String aiLegacyParentId = span.getSpanContext().getTraceState().get("ai-legacy-parent-id");
if (aiLegacyParentId != null) {
telemetryItem.getTags().put(ContextTagKeys.AI_OPERATION_PARENT_ID.toString(), aiLegacyParentId);
String aiLegacyOperationId = span.getSpanContext().getTraceState().get("ai-legacy-operation-id");
if (aiLegacyOperationId != null) {
telemetryItem.getTags().putIfAbsent("ai_legacyRootID", aiLegacyOperationId);
}
} else {
String parentSpanId = span.getParentSpanId();
if (SpanId.isValid(parentSpanId)) {
telemetryItem.getTags().put(ContextTagKeys.AI_OPERATION_PARENT_ID.toString(), parentSpanId);
}
}
long startEpochNanos = span.getStartEpochNanos();
telemetryItem.setTime(getFormattedTime(startEpochNanos));
Duration duration = Duration.ofNanos(span.getEndEpochNanos() - startEpochNanos);
requestData.setDuration(getFormattedDuration(duration));
requestData.setSuccess(span.getStatus().getStatusCode() != StatusCode.ERROR);
String description = span.getStatus().getDescription();
if (description != null) {
requestData.getProperties().put("statusDescription", description);
}
Double samplingPercentage = 100.0;
setExtraAttributes(telemetryItem, requestData.getProperties(), attributes);
telemetryItem.setSampleRate(samplingPercentage.floatValue());
telemetryItems.add(telemetryItem);
exportEvents(span, samplingPercentage, telemetryItems);
}
private static String nullAwareConcat(String str1, String str2, String separator) {
if (str1 == null) {
return str2;
}
if (str2 == null) {
return str1;
}
return str1 + separator + str2;
}
private void exportEvents(SpanData span, Double samplingPercentage, List<TelemetryItem> telemetryItems) {
boolean foundException = false;
for (EventData event : span.getEvents()) {
TelemetryItem telemetryItem = new TelemetryItem();
TelemetryEventData eventData = new TelemetryEventData();
MonitorBase monitorBase = new MonitorBase();
telemetryItem.setTags(new HashMap<>());
telemetryItem.setName(telemetryItemNamePrefix + "Event");
telemetryItem.setVersion(1);
telemetryItem.setInstrumentationKey(instrumentationKey);
telemetryItem.setData(monitorBase);
eventData.setProperties(new HashMap<>());
eventData.setVersion(2);
monitorBase.setBaseType("EventData");
monitorBase.setBaseData(eventData);
eventData.setName(event.getName());
String operationId = span.getTraceId();
telemetryItem.getTags().put(ContextTagKeys.AI_OPERATION_ID.toString(), operationId);
telemetryItem.getTags()
.put(ContextTagKeys.AI_OPERATION_PARENT_ID.toString(), span.getSpanId());
telemetryItem.setTime(getFormattedTime(event.getEpochNanos()));
setExtraAttributes(telemetryItem, eventData.getProperties(), event.getAttributes());
if (event.getAttributes().get(AttributeKey.stringKey("exception.type")) != null
|| event.getAttributes().get(AttributeKey.stringKey("exception.message")) != null) {
if (!foundException) {
String stacktrace = event.getAttributes().get(AttributeKey.stringKey("exception.stacktrace"));
if (stacktrace != null) {
trackException(stacktrace, span, operationId, span.getSpanId(), samplingPercentage, telemetryItems);
}
}
foundException = true;
} else {
telemetryItem.setSampleRate(samplingPercentage.floatValue());
telemetryItems.add(telemetryItem);
}
}
}
private void trackException(String errorStack, SpanData span, String operationId,
String id, Double samplingPercentage, List<TelemetryItem> telemetryItems) {
TelemetryItem telemetryItem = new TelemetryItem();
TelemetryExceptionData exceptionData = new TelemetryExceptionData();
MonitorBase monitorBase = new MonitorBase();
telemetryItem.setTags(new HashMap<>());
telemetryItem.setName(telemetryItemNamePrefix + "Exception");
telemetryItem.setVersion(1);
telemetryItem.setInstrumentationKey(instrumentationKey);
telemetryItem.setData(monitorBase);
exceptionData.setProperties(new HashMap<>());
exceptionData.setVersion(2);
monitorBase.setBaseType("ExceptionData");
monitorBase.setBaseData(exceptionData);
telemetryItem.getTags().put(ContextTagKeys.AI_OPERATION_ID.toString(), operationId);
telemetryItem.getTags().put(ContextTagKeys.AI_OPERATION_PARENT_ID.toString(), id);
telemetryItem.setTime(getFormattedTime(span.getEndEpochNanos()));
telemetryItem.setSampleRate(samplingPercentage.floatValue());
exceptionData.setExceptions(minimalParse(errorStack));
telemetryItems.add(telemetryItem);
}
private static String getFormattedDuration(Duration duration) {
return duration.toDays() + "." + duration.toHours() + ":" + duration.toMinutes() + ":" + duration.getSeconds()
+ "." + duration.toMillis();
}
private static String getFormattedTime(long epochNanos) {
return Instant.ofEpochMilli(NANOSECONDS.toMillis(epochNanos))
.atOffset(ZoneOffset.UTC)
.format(DateTimeFormatter.ISO_DATE_TIME);
}
private static void addLinks(Map<String, String> properties, List<LinkData> links) {
if (links.isEmpty()) {
return;
}
StringBuilder sb = new StringBuilder();
sb.append("[");
boolean first = true;
for (LinkData link : links) {
if (!first) {
sb.append(",");
}
sb.append("{\"operation_Id\":\"");
sb.append(link.getSpanContext().getTraceId());
sb.append("\",\"id\":\"");
sb.append(link.getSpanContext().getSpanId());
sb.append("\"}");
first = false;
}
sb.append("]");
properties.put("_MS.links", sb.toString());
}
private String getStringValue(AttributeKey<?> attributeKey, Object value) {
switch (attributeKey.getType()) {
case STRING:
case BOOLEAN:
case LONG:
case DOUBLE:
return String.valueOf(value);
case STRING_ARRAY:
case BOOLEAN_ARRAY:
case LONG_ARRAY:
case DOUBLE_ARRAY:
return join((List<?>) value);
default:
logger.warning("unexpected attribute type: {}", attributeKey.getType());
return null;
}
}
private static <T> String join(List<T> values) {
StringBuilder sb = new StringBuilder();
if (CoreUtils.isNullOrEmpty(values)) {
return sb.toString();
}
for (int i = 0; i < values.size() - 1; i++) {
sb.append(values.get(i));
sb.append(", ");
}
sb.append(values.get(values.size() - 1));
return sb.toString();
}
private void setExtraAttributes(TelemetryItem telemetry, Map<String, String> properties,
Attributes attributes) {
attributes.forEach((key, value) -> {
String stringKey = key.getKey();
if (stringKey.startsWith("applicationinsights.internal.")) {
return;
}
if (key.equals("enduser.id") && value instanceof String) {
telemetry.getTags().put(ContextTagKeys.AI_USER_ID.toString(), (String) value);
return;
}
if (key.equals("http.user_agent") && value instanceof String) {
telemetry.getTags().put("ai.user.userAgent", (String) value);
return;
}
int index = stringKey.indexOf(".");
String prefix = index == -1 ? stringKey : stringKey.substring(0, index);
if (STANDARD_ATTRIBUTE_PREFIXES.contains(prefix)) {
return;
}
String val = getStringValue(key, value);
if (value != null) {
properties.put(key.getKey(), val);
}
});
}
} | class AzureMonitorTraceExporter implements SpanExporter {
private static final Pattern COMPONENT_PATTERN = Pattern
.compile("io\\.opentelemetry\\.javaagent\\.([^0-9]*)(-[0-9.]*)?");
private static final Set<String> SQL_DB_SYSTEMS;
private static final Set<String> STANDARD_ATTRIBUTE_PREFIXES;
private static final AttributeKey<String> AI_SPAN_SOURCE_APP_ID_KEY = AttributeKey.stringKey("applicationinsights.internal.source_app_id");
private static final AttributeKey<String> AI_SPAN_TARGET_APP_ID_KEY = AttributeKey.stringKey("applicationinsights.internal.target_app_id");
private static final AttributeKey<String> AI_SPAN_SOURCE_KEY = AttributeKey.stringKey("applicationinsights.internal.source");
static {
Set<String> dbSystems = new HashSet<>();
dbSystems.add("db2");
dbSystems.add("derby");
dbSystems.add("mariadb");
dbSystems.add("mssql");
dbSystems.add("mysql");
dbSystems.add("oracle");
dbSystems.add("postgresql");
dbSystems.add("sqlite");
dbSystems.add("other_sql");
dbSystems.add("hsqldb");
dbSystems.add("h2");
SQL_DB_SYSTEMS = Collections.unmodifiableSet(dbSystems);
Set<String> standardAttributesPrefix = new HashSet<>();
standardAttributesPrefix.add("http");
standardAttributesPrefix.add("db");
standardAttributesPrefix.add("message");
standardAttributesPrefix.add("messaging");
standardAttributesPrefix.add("rpc");
standardAttributesPrefix.add("enduser");
standardAttributesPrefix.add("net");
standardAttributesPrefix.add("peer");
standardAttributesPrefix.add("exception");
standardAttributesPrefix.add("thread");
standardAttributesPrefix.add("faas");
STANDARD_ATTRIBUTE_PREFIXES = Collections.unmodifiableSet(standardAttributesPrefix);
}
private final MonitorExporterAsyncClient client;
private final ClientLogger logger = new ClientLogger(AzureMonitorTraceExporter.class);
private final String instrumentationKey;
private final String telemetryItemNamePrefix;
/**
* Creates an instance of exporter that is configured with given exporter client that sends telemetry events to
* Application Insights resource identified by the instrumentation key.
* @param client The client used to send data to Azure Monitor.
* @param instrumentationKey The instrumentation key of Application Insights resource.
*/
AzureMonitorTraceExporter(MonitorExporterAsyncClient client, String instrumentationKey) {
this.client = client;
this.instrumentationKey = instrumentationKey;
String formattedInstrumentationKey = instrumentationKey.replaceAll("-", "");
this.telemetryItemNamePrefix = "Microsoft.ApplicationInsights." + formattedInstrumentationKey + ".";
}
/**
* {@inheritDoc}
*/
@Override
public CompletableResultCode export(Collection<SpanData> spans) {
CompletableResultCode completableResultCode = new CompletableResultCode();
try {
List<TelemetryItem> telemetryItems = new ArrayList<>();
for (SpanData span : spans) {
logger.verbose("exporting span: {}", span);
export(span, telemetryItems);
}
client.export(telemetryItems)
.subscriberContext(Context.of(Tracer.DISABLE_TRACING_KEY, true))
.subscribe(ignored -> { }, error -> completableResultCode.fail(), completableResultCode::succeed);
return completableResultCode;
} catch (Throwable t) {
logger.error(t.getMessage(), t);
return completableResultCode.fail();
}
}
/**
* {@inheritDoc}
*/
@Override
public CompletableResultCode flush() {
return CompletableResultCode.ofSuccess();
}
/**
* {@inheritDoc}
*/
@Override
public CompletableResultCode shutdown() {
return CompletableResultCode.ofSuccess();
}
private void export(SpanData span, List<TelemetryItem> telemetryItems) {
SpanKind kind = span.getKind();
String instrumentationName = span.getInstrumentationLibraryInfo().getName();
Matcher matcher = COMPONENT_PATTERN.matcher(instrumentationName);
String stdComponent = matcher.matches() ? matcher.group(1) : null;
if (kind == SpanKind.INTERNAL) {
if ("spring-scheduling".equals(stdComponent) && !span.getParentSpanContext().isValid()) {
exportRequest(span, telemetryItems);
} else {
exportRemoteDependency(span, true, telemetryItems);
}
} else if (kind == SpanKind.CLIENT || kind == SpanKind.PRODUCER) {
exportRemoteDependency(span, false, telemetryItems);
} else if (kind == SpanKind.CONSUMER && !span.getParentSpanContext().isRemote()) {
exportRemoteDependency(span, false, telemetryItems);
} else if (kind == SpanKind.SERVER || kind == SpanKind.CONSUMER) {
exportRequest(span, telemetryItems);
} else {
throw logger.logExceptionAsError(new UnsupportedOperationException(kind.name()));
}
}
private static List<TelemetryExceptionDetails> minimalParse(String errorStack) {
TelemetryExceptionDetails details = new TelemetryExceptionDetails();
String line = errorStack.split(System.lineSeparator())[0];
int index = line.indexOf(": ");
if (index != -1) {
details.setTypeName(line.substring(0, index));
details.setMessage(line.substring(index + 2));
} else {
details.setTypeName(line);
}
details.setStack(errorStack);
return Collections.singletonList(details);
}
private void exportRemoteDependency(SpanData span, boolean inProc,
List<TelemetryItem> telemetryItems) {
TelemetryItem telemetryItem = new TelemetryItem();
RemoteDependencyData remoteDependencyData = new RemoteDependencyData();
MonitorBase monitorBase = new MonitorBase();
telemetryItem.setTags(new HashMap<>());
telemetryItem.setName(telemetryItemNamePrefix + "RemoteDependency");
telemetryItem.setVersion(1);
telemetryItem.setInstrumentationKey(instrumentationKey);
telemetryItem.setData(monitorBase);
remoteDependencyData.setProperties(new HashMap<>());
remoteDependencyData.setVersion(2);
monitorBase.setBaseType("RemoteDependencyData");
monitorBase.setBaseData(remoteDependencyData);
addLinks(remoteDependencyData.getProperties(), span.getLinks());
remoteDependencyData.setName(span.getName());
Attributes attributes = span.getAttributes();
if (inProc) {
remoteDependencyData.setType("InProc");
} else {
applySemanticConventions(attributes, remoteDependencyData, span.getKind());
}
remoteDependencyData.setId(span.getSpanId());
telemetryItem.getTags().put(ContextTagKeys.AI_OPERATION_ID.toString(), span.getTraceId());
String parentSpanId = span.getParentSpanId();
if (SpanId.isValid(parentSpanId)) {
telemetryItem.getTags().put(ContextTagKeys.AI_OPERATION_PARENT_ID.toString(), parentSpanId);
}
telemetryItem.setTime(getFormattedTime(span.getStartEpochNanos()));
remoteDependencyData
.setDuration(getFormattedDuration(Duration.ofNanos(span.getEndEpochNanos() - span.getStartEpochNanos())));
remoteDependencyData.setSuccess(span.getStatus().getStatusCode() != StatusCode.ERROR);
setExtraAttributes(telemetryItem, remoteDependencyData.getProperties(), attributes);
Double samplingPercentage = 100.0;
telemetryItem.setSampleRate(samplingPercentage.floatValue());
telemetryItems.add(telemetryItem);
exportEvents(span, samplingPercentage, telemetryItems);
}
private void applyHttpClientSpan(Attributes attributes, RemoteDependencyData telemetry) {
String scheme = attributes.get(AttributeKey.stringKey("http.scheme"));
int defaultPort;
if ("http".equals(scheme)) {
defaultPort = 80;
} else if ("https".equals(scheme)) {
defaultPort = 443;
} else {
defaultPort = 0;
}
String target = getTargetFromPeerAttributes(attributes, defaultPort);
if (target == null) {
target = attributes.get(AttributeKey.stringKey("http.host"));
}
String url = attributes.get(AttributeKey.stringKey("http.url"));
if (target == null && url != null) {
try {
URI uri = new URI(url);
target = uri.getHost();
if (uri.getPort() != 80 && uri.getPort() != 443 && uri.getPort() != -1) {
target += ":" + uri.getPort();
}
} catch (URISyntaxException e) {
logger.error(e.getMessage());
logger.verbose(e.getMessage(), e);
}
}
if (target == null) {
target = "Http";
}
String targetAppId = attributes.get(AI_SPAN_TARGET_APP_ID_KEY);
if (targetAppId == null) {
telemetry.setType("Http");
telemetry.setTarget(target);
} else {
telemetry.setType("Http (tracked component)");
telemetry.setTarget(target + " | " + targetAppId);
}
Long httpStatusCode = attributes.get(AttributeKey.longKey("http.status_code"));
if (httpStatusCode != null) {
telemetry.setResultCode(Long.toString(httpStatusCode));
}
telemetry.setData(url);
}
private static String getTargetFromPeerAttributes(Attributes attributes, int defaultPort) {
String target = attributes.get(AttributeKey.stringKey("peer.service"));
if (target != null) {
return target;
}
target = attributes.get(AttributeKey.stringKey("net.peer.name"));
if (target == null) {
target = attributes.get(AttributeKey.stringKey("net.peer.ip"));
}
if (target == null) {
return null;
}
Long port = attributes.get(AttributeKey.longKey("net.peer.port"));
if (port != null && port != defaultPort) {
return target + ":" + port;
}
return target;
}
private static void applyRpcClientSpan(Attributes attributes, RemoteDependencyData telemetry, String rpcSystem) {
telemetry.setType(rpcSystem);
String target = getTargetFromPeerAttributes(attributes, 0);
if (target == null) {
target = rpcSystem;
}
telemetry.setTarget(target);
}
private static void applyDatabaseClientSpan(Attributes attributes, RemoteDependencyData telemetry, String dbSystem) {
String dbStatement = attributes.get(AttributeKey.stringKey("db.statement"));
String type;
if (SQL_DB_SYSTEMS.contains(dbSystem)) {
type = "SQL";
telemetry.setName(dbStatement);
} else {
type = dbSystem;
}
telemetry.setType(type);
telemetry.setData(dbStatement);
String target = nullAwareConcat(getTargetFromPeerAttributes(attributes, getDefaultPortForDbSystem(dbSystem)),
attributes.get(AttributeKey.stringKey("db.name")), "/");
if (target == null) {
target = dbSystem;
}
telemetry.setTarget(target);
}
private void applyMessagingClientSpan(Attributes attributes, RemoteDependencyData telemetry, String messagingSystem, SpanKind spanKind) {
if (spanKind == SpanKind.PRODUCER) {
telemetry.setType("Queue Message | " + messagingSystem);
} else {
telemetry.setType(messagingSystem);
}
String destination = attributes.get(AttributeKey.stringKey("messaging.destination"));
if (destination != null) {
telemetry.setTarget(destination);
} else {
telemetry.setTarget(messagingSystem);
}
}
private static int getDefaultPortForDbSystem(String dbSystem) {
switch (dbSystem) {
case "mongodb":
return 27017;
case "cassandra":
return 9042;
case "redis":
return 6379;
default:
return 0;
}
}
private void exportRequest(SpanData span, List<TelemetryItem> telemetryItems) {
TelemetryItem telemetryItem = new TelemetryItem();
RequestData requestData = new RequestData();
MonitorBase monitorBase = new MonitorBase();
telemetryItem.setTags(new HashMap<>());
telemetryItem.setName(telemetryItemNamePrefix + "Request");
telemetryItem.setVersion(1);
telemetryItem.setInstrumentationKey(instrumentationKey);
telemetryItem.setData(monitorBase);
requestData.setProperties(new HashMap<>());
requestData.setVersion(2);
monitorBase.setBaseType("RequestData");
monitorBase.setBaseData(requestData);
String source = null;
Attributes attributes = span.getAttributes();
String sourceAppId = attributes.get(AI_SPAN_SOURCE_APP_ID_KEY);
if (sourceAppId != null) {
source = sourceAppId;
}
if (source == null) {
String messagingSystem = attributes.get(AttributeKey.stringKey("messaging.system"));
if (messagingSystem != null) {
source = nullAwareConcat(getTargetFromPeerAttributes(attributes, 0),
attributes.get(AttributeKey.stringKey("messaging.destination")), "/");
if (source == null) {
source = messagingSystem;
}
}
}
if (source == null) {
source = attributes.get(AI_SPAN_SOURCE_KEY);
}
requestData.setSource(source);
addLinks(requestData.getProperties(), span.getLinks());
Long httpStatusCode = attributes.get(AttributeKey.longKey("http.status_code"));
requestData.setResponseCode("200");
if (httpStatusCode != null) {
requestData.setResponseCode(Long.toString(httpStatusCode));
}
String httpUrl = attributes.get(AttributeKey.stringKey("http.url"));
if (httpUrl != null) {
requestData.setUrl(httpUrl);
}
String name = span.getName();
requestData.setName(name);
telemetryItem.getTags().put(ContextTagKeys.AI_OPERATION_NAME.toString(), name);
requestData.setId(span.getSpanId());
telemetryItem.getTags().put(ContextTagKeys.AI_OPERATION_ID.toString(), span.getTraceId());
String aiLegacyParentId = span.getSpanContext().getTraceState().get("ai-legacy-parent-id");
if (aiLegacyParentId != null) {
telemetryItem.getTags().put(ContextTagKeys.AI_OPERATION_PARENT_ID.toString(), aiLegacyParentId);
String aiLegacyOperationId = span.getSpanContext().getTraceState().get("ai-legacy-operation-id");
if (aiLegacyOperationId != null) {
telemetryItem.getTags().putIfAbsent("ai_legacyRootID", aiLegacyOperationId);
}
} else {
String parentSpanId = span.getParentSpanId();
if (SpanId.isValid(parentSpanId)) {
telemetryItem.getTags().put(ContextTagKeys.AI_OPERATION_PARENT_ID.toString(), parentSpanId);
}
}
long startEpochNanos = span.getStartEpochNanos();
telemetryItem.setTime(getFormattedTime(startEpochNanos));
Duration duration = Duration.ofNanos(span.getEndEpochNanos() - startEpochNanos);
requestData.setDuration(getFormattedDuration(duration));
requestData.setSuccess(span.getStatus().getStatusCode() != StatusCode.ERROR);
String description = span.getStatus().getDescription();
if (description != null) {
requestData.getProperties().put("statusDescription", description);
}
Double samplingPercentage = 100.0;
setExtraAttributes(telemetryItem, requestData.getProperties(), attributes);
telemetryItem.setSampleRate(samplingPercentage.floatValue());
telemetryItems.add(telemetryItem);
exportEvents(span, samplingPercentage, telemetryItems);
}
private static String nullAwareConcat(String str1, String str2, String separator) {
if (str1 == null) {
return str2;
}
if (str2 == null) {
return str1;
}
return str1 + separator + str2;
}
private void exportEvents(SpanData span, Double samplingPercentage, List<TelemetryItem> telemetryItems) {
boolean foundException = false;
for (EventData event : span.getEvents()) {
TelemetryItem telemetryItem = new TelemetryItem();
TelemetryEventData eventData = new TelemetryEventData();
MonitorBase monitorBase = new MonitorBase();
telemetryItem.setTags(new HashMap<>());
telemetryItem.setName(telemetryItemNamePrefix + "Event");
telemetryItem.setVersion(1);
telemetryItem.setInstrumentationKey(instrumentationKey);
telemetryItem.setData(monitorBase);
eventData.setProperties(new HashMap<>());
eventData.setVersion(2);
monitorBase.setBaseType("EventData");
monitorBase.setBaseData(eventData);
eventData.setName(event.getName());
String operationId = span.getTraceId();
telemetryItem.getTags().put(ContextTagKeys.AI_OPERATION_ID.toString(), operationId);
telemetryItem.getTags()
.put(ContextTagKeys.AI_OPERATION_PARENT_ID.toString(), span.getSpanId());
telemetryItem.setTime(getFormattedTime(event.getEpochNanos()));
setExtraAttributes(telemetryItem, eventData.getProperties(), event.getAttributes());
if (event.getAttributes().get(AttributeKey.stringKey("exception.type")) != null
|| event.getAttributes().get(AttributeKey.stringKey("exception.message")) != null) {
String stacktrace = event.getAttributes().get(AttributeKey.stringKey("exception.stacktrace"));
if (stacktrace != null) {
trackException(stacktrace, span, operationId, span.getSpanId(), samplingPercentage, telemetryItems);
}
} else {
telemetryItem.setSampleRate(samplingPercentage.floatValue());
telemetryItems.add(telemetryItem);
}
}
}
private void trackException(String errorStack, SpanData span, String operationId,
String id, Double samplingPercentage, List<TelemetryItem> telemetryItems) {
TelemetryItem telemetryItem = new TelemetryItem();
TelemetryExceptionData exceptionData = new TelemetryExceptionData();
MonitorBase monitorBase = new MonitorBase();
telemetryItem.setTags(new HashMap<>());
telemetryItem.setName(telemetryItemNamePrefix + "Exception");
telemetryItem.setVersion(1);
telemetryItem.setInstrumentationKey(instrumentationKey);
telemetryItem.setData(monitorBase);
exceptionData.setProperties(new HashMap<>());
exceptionData.setVersion(2);
monitorBase.setBaseType("ExceptionData");
monitorBase.setBaseData(exceptionData);
telemetryItem.getTags().put(ContextTagKeys.AI_OPERATION_ID.toString(), operationId);
telemetryItem.getTags().put(ContextTagKeys.AI_OPERATION_PARENT_ID.toString(), id);
telemetryItem.setTime(getFormattedTime(span.getEndEpochNanos()));
telemetryItem.setSampleRate(samplingPercentage.floatValue());
exceptionData.setExceptions(minimalParse(errorStack));
telemetryItems.add(telemetryItem);
}
private static String getFormattedDuration(Duration duration) {
return duration.toDays() + "." + duration.toHours() + ":" + duration.toMinutes() + ":" + duration.getSeconds()
+ "." + duration.toMillis();
}
private static String getFormattedTime(long epochNanos) {
return Instant.ofEpochMilli(NANOSECONDS.toMillis(epochNanos))
.atOffset(ZoneOffset.UTC)
.format(DateTimeFormatter.ISO_DATE_TIME);
}
private static void addLinks(Map<String, String> properties, List<LinkData> links) {
if (links.isEmpty()) {
return;
}
StringBuilder sb = new StringBuilder();
sb.append("[");
boolean first = true;
for (LinkData link : links) {
if (!first) {
sb.append(",");
}
sb.append("{\"operation_Id\":\"");
sb.append(link.getSpanContext().getTraceId());
sb.append("\",\"id\":\"");
sb.append(link.getSpanContext().getSpanId());
sb.append("\"}");
first = false;
}
sb.append("]");
properties.put("_MS.links", sb.toString());
}
private String getStringValue(AttributeKey<?> attributeKey, Object value) {
switch (attributeKey.getType()) {
case STRING:
case BOOLEAN:
case LONG:
case DOUBLE:
return String.valueOf(value);
case STRING_ARRAY:
case BOOLEAN_ARRAY:
case LONG_ARRAY:
case DOUBLE_ARRAY:
return join((List<?>) value);
default:
logger.warning("unexpected attribute type: {}", attributeKey.getType());
return null;
}
}
private static <T> String join(List<T> values) {
StringBuilder sb = new StringBuilder();
if (CoreUtils.isNullOrEmpty(values)) {
return sb.toString();
}
for (int i = 0; i < values.size() - 1; i++) {
sb.append(values.get(i));
sb.append(", ");
}
sb.append(values.get(values.size() - 1));
return sb.toString();
}
private void setExtraAttributes(TelemetryItem telemetry, Map<String, String> properties,
Attributes attributes) {
attributes.forEach((key, value) -> {
String stringKey = key.getKey();
if (stringKey.startsWith("applicationinsights.internal.")) {
return;
}
if (key.getKey().equals("enduser.id") && value instanceof String) {
telemetry.getTags().put(ContextTagKeys.AI_USER_ID.toString(), (String) value);
return;
}
if (key.getKey().equals("http.user_agent") && value instanceof String) {
telemetry.getTags().put("ai.user.userAgent", (String) value);
return;
}
int index = stringKey.indexOf(".");
String prefix = index == -1 ? stringKey : stringKey.substring(0, index);
if (STANDARD_ATTRIBUTE_PREFIXES.contains(prefix)) {
return;
}
String val = getStringValue(key, value);
if (value != null) {
properties.put(key.getKey(), val);
}
});
}
} |
So we removed the dependency on semconv package in this PR https://github.com/Azure/azure-sdk-for-java/pull/18940 since it was moved out of the core oTel lib and was to be managed independently (possible breaking changes). I missed doing these updates to the exporter lib in the last PR so covering them now. | private void applySemanticConventions(Attributes attributes, RemoteDependencyData remoteDependencyData, SpanKind spanKind) {
String httpMethod = attributes.get(AttributeKey.stringKey("http.method"));
if (httpMethod != null) {
applyHttpClientSpan(attributes, remoteDependencyData);
return;
}
String rpcSystem = attributes.get(AttributeKey.stringKey("rpc.system"));
if (rpcSystem != null) {
applyRpcClientSpan(attributes, remoteDependencyData, rpcSystem);
return;
}
String dbSystem = attributes.get(AttributeKey.stringKey("db.system"));
if (dbSystem != null) {
applyDatabaseClientSpan(attributes, remoteDependencyData, dbSystem);
return;
}
String messagingSystem = attributes.get(AttributeKey.stringKey("messaging.system"));
if (messagingSystem != null) {
applyMessagingClientSpan(attributes, remoteDependencyData, messagingSystem, spanKind);
return;
}
} | String httpMethod = attributes.get(AttributeKey.stringKey("http.method")); | private void applySemanticConventions(Attributes attributes, RemoteDependencyData remoteDependencyData, SpanKind spanKind) {
String httpMethod = attributes.get(AttributeKey.stringKey("http.method"));
if (httpMethod != null) {
applyHttpClientSpan(attributes, remoteDependencyData);
return;
}
String rpcSystem = attributes.get(AttributeKey.stringKey("rpc.system"));
if (rpcSystem != null) {
applyRpcClientSpan(attributes, remoteDependencyData, rpcSystem);
return;
}
String dbSystem = attributes.get(AttributeKey.stringKey("db.system"));
if (dbSystem != null) {
applyDatabaseClientSpan(attributes, remoteDependencyData, dbSystem);
return;
}
String messagingSystem = attributes.get(AttributeKey.stringKey("messaging.system"));
if (messagingSystem != null) {
applyMessagingClientSpan(attributes, remoteDependencyData, messagingSystem, spanKind);
return;
}
} | class AzureMonitorTraceExporter implements SpanExporter {
private static final Pattern COMPONENT_PATTERN = Pattern
.compile("io\\.opentelemetry\\.javaagent\\.([^0-9]*)(-[0-9.]*)?");
private static final Set<String> SQL_DB_SYSTEMS;
private static final Set<String> STANDARD_ATTRIBUTE_PREFIXES;
private static final AttributeKey<String> AI_SPAN_SOURCE_APP_ID_KEY = AttributeKey.stringKey("applicationinsights.internal.source_app_id");
private static final AttributeKey<String> AI_SPAN_TARGET_APP_ID_KEY = AttributeKey.stringKey("applicationinsights.internal.target_app_id");
private static final AttributeKey<String> AI_SPAN_SOURCE_KEY = AttributeKey.stringKey("applicationinsights.internal.source");
static {
Set<String> dbSystems = new HashSet<>();
dbSystems.add("db2");
dbSystems.add("derby");
dbSystems.add("mariadb");
dbSystems.add("mssql");
dbSystems.add("mysql");
dbSystems.add("oracle");
dbSystems.add("postgresql");
dbSystems.add("sqlite");
dbSystems.add("other_sql");
dbSystems.add("hsqldb");
dbSystems.add("h2");
SQL_DB_SYSTEMS = Collections.unmodifiableSet(dbSystems);
Set<String> standardAttributesPrefix = new HashSet<>();
standardAttributesPrefix.add("http");
standardAttributesPrefix.add("db");
standardAttributesPrefix.add("message");
standardAttributesPrefix.add("messaging");
standardAttributesPrefix.add("rpc");
standardAttributesPrefix.add("enduser");
standardAttributesPrefix.add("net");
standardAttributesPrefix.add("peer");
standardAttributesPrefix.add("exception");
standardAttributesPrefix.add("thread");
standardAttributesPrefix.add("faas");
STANDARD_ATTRIBUTE_PREFIXES = Collections.unmodifiableSet(standardAttributesPrefix);
}
private final MonitorExporterAsyncClient client;
private final ClientLogger logger = new ClientLogger(AzureMonitorTraceExporter.class);
private final String instrumentationKey;
private final String telemetryItemNamePrefix;
/**
* Creates an instance of exporter that is configured with given exporter client that sends telemetry events to
* Application Insights resource identified by the instrumentation key.
* @param client The client used to send data to Azure Monitor.
* @param instrumentationKey The instrumentation key of Application Insights resource.
*/
AzureMonitorTraceExporter(MonitorExporterAsyncClient client, String instrumentationKey) {
this.client = client;
this.instrumentationKey = instrumentationKey;
String formattedInstrumentationKey = instrumentationKey.replaceAll("-", "");
this.telemetryItemNamePrefix = "Microsoft.ApplicationInsights." + formattedInstrumentationKey + ".";
}
/**
* {@inheritDoc}
*/
@Override
public CompletableResultCode export(Collection<SpanData> spans) {
try {
List<TelemetryItem> telemetryItems = new ArrayList<>();
for (SpanData span : spans) {
logger.verbose("exporting span: {}", span);
export(span, telemetryItems);
}
client.export(telemetryItems)
.subscriberContext(Context.of(Tracer.DISABLE_TRACING_KEY, true))
.subscribe();
return CompletableResultCode.ofSuccess();
} catch (Throwable t) {
logger.error(t.getMessage(), t);
return CompletableResultCode.ofFailure();
}
}
/**
* {@inheritDoc}
*/
@Override
public CompletableResultCode flush() {
return CompletableResultCode.ofSuccess();
}
/**
* {@inheritDoc}
*/
@Override
public CompletableResultCode shutdown() {
return CompletableResultCode.ofSuccess();
}
private void export(SpanData span, List<TelemetryItem> telemetryItems) {
SpanKind kind = span.getKind();
String instrumentationName = span.getInstrumentationLibraryInfo().getName();
Matcher matcher = COMPONENT_PATTERN.matcher(instrumentationName);
String stdComponent = matcher.matches() ? matcher.group(1) : null;
if ("jms".equals(stdComponent) && !span.getParentSpanContext().isValid() && kind == SpanKind.CONSUMER) {
return;
}
if (kind == SpanKind.INTERNAL) {
if ("spring-scheduling".equals(stdComponent) && !span.getParentSpanContext().isValid()) {
exportRequest(span, telemetryItems);
} else {
exportRemoteDependency(span, true, telemetryItems);
}
} else if (kind == SpanKind.CLIENT || kind == SpanKind.PRODUCER) {
exportRemoteDependency(span, false, telemetryItems);
} else if (kind == SpanKind.CONSUMER && !span.getParentSpanContext().isRemote()) {
exportRemoteDependency(span, false, telemetryItems);
} else if (kind == SpanKind.SERVER || kind == SpanKind.CONSUMER) {
exportRequest(span, telemetryItems);
} else {
throw logger.logExceptionAsError(new UnsupportedOperationException(kind.name()));
}
}
private static List<TelemetryExceptionDetails> minimalParse(String errorStack) {
TelemetryExceptionDetails details = new TelemetryExceptionDetails();
String line = errorStack.split(System.lineSeparator())[0];
int index = line.indexOf(": ");
if (index != -1) {
details.setTypeName(line.substring(0, index));
details.setMessage(line.substring(index + 2));
} else {
details.setTypeName(line);
}
details.setStack(errorStack);
return Collections.singletonList(details);
}
private void exportRemoteDependency(SpanData span, boolean inProc,
List<TelemetryItem> telemetryItems) {
TelemetryItem telemetryItem = new TelemetryItem();
RemoteDependencyData remoteDependencyData = new RemoteDependencyData();
MonitorBase monitorBase = new MonitorBase();
telemetryItem.setTags(new HashMap<>());
telemetryItem.setName(telemetryItemNamePrefix + "RemoteDependency");
telemetryItem.setVersion(1);
telemetryItem.setInstrumentationKey(instrumentationKey);
telemetryItem.setData(monitorBase);
remoteDependencyData.setProperties(new HashMap<>());
remoteDependencyData.setVersion(2);
monitorBase.setBaseType("RemoteDependencyData");
monitorBase.setBaseData(remoteDependencyData);
addLinks(remoteDependencyData.getProperties(), span.getLinks());
remoteDependencyData.setName(span.getName());
Attributes attributes = span.getAttributes();
if (inProc) {
remoteDependencyData.setType("InProc");
} else {
applySemanticConventions(attributes, remoteDependencyData, span.getKind());
}
remoteDependencyData.setId(span.getSpanId());
telemetryItem.getTags().put(ContextTagKeys.AI_OPERATION_ID.toString(), span.getTraceId());
String parentSpanId = span.getParentSpanId();
if (SpanId.isValid(parentSpanId)) {
telemetryItem.getTags().put(ContextTagKeys.AI_OPERATION_PARENT_ID.toString(), parentSpanId);
}
telemetryItem.setTime(getFormattedTime(span.getStartEpochNanos()));
remoteDependencyData
.setDuration(getFormattedDuration(Duration.ofNanos(span.getEndEpochNanos() - span.getStartEpochNanos())));
remoteDependencyData.setSuccess(span.getStatus().getStatusCode() != StatusCode.ERROR);
setExtraAttributes(telemetryItem, remoteDependencyData.getProperties(), attributes);
Double samplingPercentage = 100.0;
telemetryItem.setSampleRate(samplingPercentage.floatValue());
telemetryItems.add(telemetryItem);
exportEvents(span, samplingPercentage, telemetryItems);
}
private void applyHttpClientSpan(Attributes attributes, RemoteDependencyData telemetry) {
String scheme = attributes.get(AttributeKey.stringKey("http.scheme"));
int defaultPort;
if ("http".equals(scheme)) {
defaultPort = 80;
} else if ("https".equals(scheme)) {
defaultPort = 443;
} else {
defaultPort = 0;
}
String target = getTargetFromPeerAttributes(attributes, defaultPort);
if (target == null) {
target = attributes.get(AttributeKey.stringKey("http.host"));
}
String url = attributes.get(AttributeKey.stringKey("http.url"));
if (target == null && url != null) {
try {
URI uri = new URI(url);
target = uri.getHost();
if (uri.getPort() != 80 && uri.getPort() != 443 && uri.getPort() != -1) {
target += ":" + uri.getPort();
}
} catch (URISyntaxException e) {
logger.error(e.getMessage());
logger.verbose(e.getMessage(), e);
}
}
if (target == null) {
target = "Http";
}
String targetAppId = attributes.get(AI_SPAN_TARGET_APP_ID_KEY);
if (targetAppId == null) {
telemetry.setType("Http");
telemetry.setTarget(target);
} else {
telemetry.setType("Http (tracked component)");
telemetry.setTarget(target + " | " + targetAppId);
}
Long httpStatusCode = attributes.get(AttributeKey.longKey("http.status_code"));
if (httpStatusCode != null) {
telemetry.setResultCode(Long.toString(httpStatusCode));
}
telemetry.setData(url);
}
private static String getTargetFromPeerAttributes(Attributes attributes, int defaultPort) {
String target = attributes.get(AttributeKey.stringKey("peer.service"));
if (target != null) {
return target;
}
target = attributes.get(AttributeKey.stringKey("net.peer.name"));
if (target == null) {
target = attributes.get(AttributeKey.stringKey("net.peer.ip"));
}
if (target == null) {
return null;
}
Long port = attributes.get(AttributeKey.longKey("net.peer.port"));
if (port != null && port != defaultPort) {
return target + ":" + port;
}
return target;
}
private static void applyRpcClientSpan(Attributes attributes, RemoteDependencyData telemetry, String rpcSystem) {
telemetry.setType(rpcSystem);
String target = getTargetFromPeerAttributes(attributes, 0);
if (target == null) {
target = rpcSystem;
}
telemetry.setTarget(target);
}
private static void applyDatabaseClientSpan(Attributes attributes, RemoteDependencyData telemetry, String dbSystem) {
String dbStatement = attributes.get(AttributeKey.stringKey("db.statement"));
String type;
if (SQL_DB_SYSTEMS.contains(dbSystem)) {
type = "SQL";
telemetry.setName(dbStatement);
} else {
type = dbSystem;
}
telemetry.setType(type);
telemetry.setData(dbStatement);
String target = nullAwareConcat(getTargetFromPeerAttributes(attributes, getDefaultPortForDbSystem(dbSystem)),
attributes.get(AttributeKey.stringKey("db.name")), "/");
if (target == null) {
target = dbSystem;
}
telemetry.setTarget(target);
}
private void applyMessagingClientSpan(Attributes attributes, RemoteDependencyData telemetry, String messagingSystem, SpanKind spanKind) {
if (spanKind == SpanKind.PRODUCER) {
telemetry.setType("Queue Message | " + messagingSystem);
} else {
telemetry.setType(messagingSystem);
}
String destination = attributes.get(AttributeKey.stringKey("messaging.destination"));
if (destination != null) {
telemetry.setTarget(destination);
} else {
telemetry.setTarget(messagingSystem);
}
}
private static int getDefaultPortForDbSystem(String dbSystem) {
switch (dbSystem) {
case "mongodb":
return 27017;
case "cassandra":
return 9042;
case "redis":
return 6379;
default:
return 0;
}
}
private void exportRequest(SpanData span, List<TelemetryItem> telemetryItems) {
TelemetryItem telemetryItem = new TelemetryItem();
RequestData requestData = new RequestData();
MonitorBase monitorBase = new MonitorBase();
telemetryItem.setTags(new HashMap<>());
telemetryItem.setName(telemetryItemNamePrefix + "Request");
telemetryItem.setVersion(1);
telemetryItem.setInstrumentationKey(instrumentationKey);
telemetryItem.setData(monitorBase);
requestData.setProperties(new HashMap<>());
requestData.setVersion(2);
monitorBase.setBaseType("RequestData");
monitorBase.setBaseData(requestData);
String source = null;
Attributes attributes = span.getAttributes();
String sourceAppId = attributes.get(AI_SPAN_SOURCE_APP_ID_KEY);
if (sourceAppId != null) {
source = sourceAppId;
}
if (source == null) {
String messagingSystem = attributes.get(AttributeKey.stringKey("messaging.system"));
if (messagingSystem != null) {
source = nullAwareConcat(getTargetFromPeerAttributes(attributes, 0),
attributes.get(AttributeKey.stringKey("messaging.destination")), "/");
if (source == null) {
source = messagingSystem;
}
}
}
if (source == null) {
source = attributes.get(AI_SPAN_SOURCE_KEY);
}
requestData.setSource(source);
addLinks(requestData.getProperties(), span.getLinks());
Long httpStatusCode = attributes.get(AttributeKey.longKey("http.status_code"));
requestData.setResponseCode("200");
if (httpStatusCode != null) {
requestData.setResponseCode(Long.toString(httpStatusCode));
}
String httpUrl = attributes.get(AttributeKey.stringKey("http.url"));
if (httpUrl != null) {
requestData.setUrl(httpUrl);
}
String name = span.getName();
requestData.setName(name);
telemetryItem.getTags().put(ContextTagKeys.AI_OPERATION_NAME.toString(), name);
requestData.setId(span.getSpanId());
telemetryItem.getTags().put(ContextTagKeys.AI_OPERATION_ID.toString(), span.getTraceId());
String aiLegacyParentId = span.getSpanContext().getTraceState().get("ai-legacy-parent-id");
if (aiLegacyParentId != null) {
telemetryItem.getTags().put(ContextTagKeys.AI_OPERATION_PARENT_ID.toString(), aiLegacyParentId);
String aiLegacyOperationId = span.getSpanContext().getTraceState().get("ai-legacy-operation-id");
if (aiLegacyOperationId != null) {
telemetryItem.getTags().putIfAbsent("ai_legacyRootID", aiLegacyOperationId);
}
} else {
String parentSpanId = span.getParentSpanId();
if (SpanId.isValid(parentSpanId)) {
telemetryItem.getTags().put(ContextTagKeys.AI_OPERATION_PARENT_ID.toString(), parentSpanId);
}
}
long startEpochNanos = span.getStartEpochNanos();
telemetryItem.setTime(getFormattedTime(startEpochNanos));
Duration duration = Duration.ofNanos(span.getEndEpochNanos() - startEpochNanos);
requestData.setDuration(getFormattedDuration(duration));
requestData.setSuccess(span.getStatus().getStatusCode() != StatusCode.ERROR);
String description = span.getStatus().getDescription();
if (description != null) {
requestData.getProperties().put("statusDescription", description);
}
Double samplingPercentage = 100.0;
setExtraAttributes(telemetryItem, requestData.getProperties(), attributes);
telemetryItem.setSampleRate(samplingPercentage.floatValue());
telemetryItems.add(telemetryItem);
exportEvents(span, samplingPercentage, telemetryItems);
}
private static String nullAwareConcat(String str1, String str2, String separator) {
if (str1 == null) {
return str2;
}
if (str2 == null) {
return str1;
}
return str1 + separator + str2;
}
private void exportEvents(SpanData span, Double samplingPercentage, List<TelemetryItem> telemetryItems) {
boolean foundException = false;
for (EventData event : span.getEvents()) {
TelemetryItem telemetryItem = new TelemetryItem();
TelemetryEventData eventData = new TelemetryEventData();
MonitorBase monitorBase = new MonitorBase();
telemetryItem.setTags(new HashMap<>());
telemetryItem.setName(telemetryItemNamePrefix + "Event");
telemetryItem.setVersion(1);
telemetryItem.setInstrumentationKey(instrumentationKey);
telemetryItem.setData(monitorBase);
eventData.setProperties(new HashMap<>());
eventData.setVersion(2);
monitorBase.setBaseType("EventData");
monitorBase.setBaseData(eventData);
eventData.setName(event.getName());
String operationId = span.getTraceId();
telemetryItem.getTags().put(ContextTagKeys.AI_OPERATION_ID.toString(), operationId);
telemetryItem.getTags()
.put(ContextTagKeys.AI_OPERATION_PARENT_ID.toString(), span.getSpanId());
telemetryItem.setTime(getFormattedTime(event.getEpochNanos()));
setExtraAttributes(telemetryItem, eventData.getProperties(), event.getAttributes());
if (event.getAttributes().get(AttributeKey.stringKey("exception.type")) != null
|| event.getAttributes().get(AttributeKey.stringKey("exception.message")) != null) {
if (!foundException) {
String stacktrace = event.getAttributes().get(AttributeKey.stringKey("exception.stacktrace"));
if (stacktrace != null) {
trackException(stacktrace, span, operationId, span.getSpanId(), samplingPercentage, telemetryItems);
}
}
foundException = true;
} else {
telemetryItem.setSampleRate(samplingPercentage.floatValue());
telemetryItems.add(telemetryItem);
}
}
}
private void trackException(String errorStack, SpanData span, String operationId,
String id, Double samplingPercentage, List<TelemetryItem> telemetryItems) {
TelemetryItem telemetryItem = new TelemetryItem();
TelemetryExceptionData exceptionData = new TelemetryExceptionData();
MonitorBase monitorBase = new MonitorBase();
telemetryItem.setTags(new HashMap<>());
telemetryItem.setName(telemetryItemNamePrefix + "Exception");
telemetryItem.setVersion(1);
telemetryItem.setInstrumentationKey(instrumentationKey);
telemetryItem.setData(monitorBase);
exceptionData.setProperties(new HashMap<>());
exceptionData.setVersion(2);
monitorBase.setBaseType("ExceptionData");
monitorBase.setBaseData(exceptionData);
telemetryItem.getTags().put(ContextTagKeys.AI_OPERATION_ID.toString(), operationId);
telemetryItem.getTags().put(ContextTagKeys.AI_OPERATION_PARENT_ID.toString(), id);
telemetryItem.setTime(getFormattedTime(span.getEndEpochNanos()));
telemetryItem.setSampleRate(samplingPercentage.floatValue());
exceptionData.setExceptions(minimalParse(errorStack));
telemetryItems.add(telemetryItem);
}
private static String getFormattedDuration(Duration duration) {
return duration.toDays() + "." + duration.toHours() + ":" + duration.toMinutes() + ":" + duration.getSeconds()
+ "." + duration.toMillis();
}
private static String getFormattedTime(long epochNanos) {
return Instant.ofEpochMilli(NANOSECONDS.toMillis(epochNanos))
.atOffset(ZoneOffset.UTC)
.format(DateTimeFormatter.ISO_DATE_TIME);
}
private static void addLinks(Map<String, String> properties, List<LinkData> links) {
if (links.isEmpty()) {
return;
}
StringBuilder sb = new StringBuilder();
sb.append("[");
boolean first = true;
for (LinkData link : links) {
if (!first) {
sb.append(",");
}
sb.append("{\"operation_Id\":\"");
sb.append(link.getSpanContext().getTraceId());
sb.append("\",\"id\":\"");
sb.append(link.getSpanContext().getSpanId());
sb.append("\"}");
first = false;
}
sb.append("]");
properties.put("_MS.links", sb.toString());
}
private String getStringValue(AttributeKey<?> attributeKey, Object value) {
switch (attributeKey.getType()) {
case STRING:
case BOOLEAN:
case LONG:
case DOUBLE:
return String.valueOf(value);
case STRING_ARRAY:
case BOOLEAN_ARRAY:
case LONG_ARRAY:
case DOUBLE_ARRAY:
return join((List<?>) value);
default:
logger.warning("unexpected attribute type: {}", attributeKey.getType());
return null;
}
}
private static <T> String join(List<T> values) {
StringBuilder sb = new StringBuilder();
if (CoreUtils.isNullOrEmpty(values)) {
return sb.toString();
}
for (int i = 0; i < values.size() - 1; i++) {
sb.append(values.get(i));
sb.append(", ");
}
sb.append(values.get(values.size() - 1));
return sb.toString();
}
private void setExtraAttributes(TelemetryItem telemetry, Map<String, String> properties,
Attributes attributes) {
attributes.forEach((key, value) -> {
String stringKey = key.getKey();
if (stringKey.startsWith("applicationinsights.internal.")) {
return;
}
if (key.equals("enduser.id") && value instanceof String) {
telemetry.getTags().put(ContextTagKeys.AI_USER_ID.toString(), (String) value);
return;
}
if (key.equals("http.user_agent") && value instanceof String) {
telemetry.getTags().put("ai.user.userAgent", (String) value);
return;
}
int index = stringKey.indexOf(".");
String prefix = index == -1 ? stringKey : stringKey.substring(0, index);
if (STANDARD_ATTRIBUTE_PREFIXES.contains(prefix)) {
return;
}
String val = getStringValue(key, value);
if (value != null) {
properties.put(key.getKey(), val);
}
});
}
} | class AzureMonitorTraceExporter implements SpanExporter {
private static final Pattern COMPONENT_PATTERN = Pattern
.compile("io\\.opentelemetry\\.javaagent\\.([^0-9]*)(-[0-9.]*)?");
private static final Set<String> SQL_DB_SYSTEMS;
private static final Set<String> STANDARD_ATTRIBUTE_PREFIXES;
private static final AttributeKey<String> AI_SPAN_SOURCE_APP_ID_KEY = AttributeKey.stringKey("applicationinsights.internal.source_app_id");
private static final AttributeKey<String> AI_SPAN_TARGET_APP_ID_KEY = AttributeKey.stringKey("applicationinsights.internal.target_app_id");
private static final AttributeKey<String> AI_SPAN_SOURCE_KEY = AttributeKey.stringKey("applicationinsights.internal.source");
static {
Set<String> dbSystems = new HashSet<>();
dbSystems.add("db2");
dbSystems.add("derby");
dbSystems.add("mariadb");
dbSystems.add("mssql");
dbSystems.add("mysql");
dbSystems.add("oracle");
dbSystems.add("postgresql");
dbSystems.add("sqlite");
dbSystems.add("other_sql");
dbSystems.add("hsqldb");
dbSystems.add("h2");
SQL_DB_SYSTEMS = Collections.unmodifiableSet(dbSystems);
Set<String> standardAttributesPrefix = new HashSet<>();
standardAttributesPrefix.add("http");
standardAttributesPrefix.add("db");
standardAttributesPrefix.add("message");
standardAttributesPrefix.add("messaging");
standardAttributesPrefix.add("rpc");
standardAttributesPrefix.add("enduser");
standardAttributesPrefix.add("net");
standardAttributesPrefix.add("peer");
standardAttributesPrefix.add("exception");
standardAttributesPrefix.add("thread");
standardAttributesPrefix.add("faas");
STANDARD_ATTRIBUTE_PREFIXES = Collections.unmodifiableSet(standardAttributesPrefix);
}
private final MonitorExporterAsyncClient client;
private final ClientLogger logger = new ClientLogger(AzureMonitorTraceExporter.class);
private final String instrumentationKey;
private final String telemetryItemNamePrefix;
/**
* Creates an instance of exporter that is configured with given exporter client that sends telemetry events to
* Application Insights resource identified by the instrumentation key.
* @param client The client used to send data to Azure Monitor.
* @param instrumentationKey The instrumentation key of Application Insights resource.
*/
AzureMonitorTraceExporter(MonitorExporterAsyncClient client, String instrumentationKey) {
this.client = client;
this.instrumentationKey = instrumentationKey;
String formattedInstrumentationKey = instrumentationKey.replaceAll("-", "");
this.telemetryItemNamePrefix = "Microsoft.ApplicationInsights." + formattedInstrumentationKey + ".";
}
/**
* {@inheritDoc}
*/
@Override
public CompletableResultCode export(Collection<SpanData> spans) {
CompletableResultCode completableResultCode = new CompletableResultCode();
try {
List<TelemetryItem> telemetryItems = new ArrayList<>();
for (SpanData span : spans) {
logger.verbose("exporting span: {}", span);
export(span, telemetryItems);
}
client.export(telemetryItems)
.subscriberContext(Context.of(Tracer.DISABLE_TRACING_KEY, true))
.subscribe(ignored -> { }, error -> completableResultCode.fail(), completableResultCode::succeed);
return completableResultCode;
} catch (Throwable t) {
logger.error(t.getMessage(), t);
return completableResultCode.fail();
}
}
/**
* {@inheritDoc}
*/
@Override
public CompletableResultCode flush() {
return CompletableResultCode.ofSuccess();
}
/**
* {@inheritDoc}
*/
@Override
public CompletableResultCode shutdown() {
return CompletableResultCode.ofSuccess();
}
private void export(SpanData span, List<TelemetryItem> telemetryItems) {
SpanKind kind = span.getKind();
String instrumentationName = span.getInstrumentationLibraryInfo().getName();
Matcher matcher = COMPONENT_PATTERN.matcher(instrumentationName);
String stdComponent = matcher.matches() ? matcher.group(1) : null;
if (kind == SpanKind.INTERNAL) {
if ("spring-scheduling".equals(stdComponent) && !span.getParentSpanContext().isValid()) {
exportRequest(span, telemetryItems);
} else {
exportRemoteDependency(span, true, telemetryItems);
}
} else if (kind == SpanKind.CLIENT || kind == SpanKind.PRODUCER) {
exportRemoteDependency(span, false, telemetryItems);
} else if (kind == SpanKind.CONSUMER && !span.getParentSpanContext().isRemote()) {
exportRemoteDependency(span, false, telemetryItems);
} else if (kind == SpanKind.SERVER || kind == SpanKind.CONSUMER) {
exportRequest(span, telemetryItems);
} else {
throw logger.logExceptionAsError(new UnsupportedOperationException(kind.name()));
}
}
private static List<TelemetryExceptionDetails> minimalParse(String errorStack) {
TelemetryExceptionDetails details = new TelemetryExceptionDetails();
String line = errorStack.split(System.lineSeparator())[0];
int index = line.indexOf(": ");
if (index != -1) {
details.setTypeName(line.substring(0, index));
details.setMessage(line.substring(index + 2));
} else {
details.setTypeName(line);
}
details.setStack(errorStack);
return Collections.singletonList(details);
}
private void exportRemoteDependency(SpanData span, boolean inProc,
List<TelemetryItem> telemetryItems) {
TelemetryItem telemetryItem = new TelemetryItem();
RemoteDependencyData remoteDependencyData = new RemoteDependencyData();
MonitorBase monitorBase = new MonitorBase();
telemetryItem.setTags(new HashMap<>());
telemetryItem.setName(telemetryItemNamePrefix + "RemoteDependency");
telemetryItem.setVersion(1);
telemetryItem.setInstrumentationKey(instrumentationKey);
telemetryItem.setData(monitorBase);
remoteDependencyData.setProperties(new HashMap<>());
remoteDependencyData.setVersion(2);
monitorBase.setBaseType("RemoteDependencyData");
monitorBase.setBaseData(remoteDependencyData);
addLinks(remoteDependencyData.getProperties(), span.getLinks());
remoteDependencyData.setName(span.getName());
Attributes attributes = span.getAttributes();
if (inProc) {
remoteDependencyData.setType("InProc");
} else {
applySemanticConventions(attributes, remoteDependencyData, span.getKind());
}
remoteDependencyData.setId(span.getSpanId());
telemetryItem.getTags().put(ContextTagKeys.AI_OPERATION_ID.toString(), span.getTraceId());
String parentSpanId = span.getParentSpanId();
if (SpanId.isValid(parentSpanId)) {
telemetryItem.getTags().put(ContextTagKeys.AI_OPERATION_PARENT_ID.toString(), parentSpanId);
}
telemetryItem.setTime(getFormattedTime(span.getStartEpochNanos()));
remoteDependencyData
.setDuration(getFormattedDuration(Duration.ofNanos(span.getEndEpochNanos() - span.getStartEpochNanos())));
remoteDependencyData.setSuccess(span.getStatus().getStatusCode() != StatusCode.ERROR);
setExtraAttributes(telemetryItem, remoteDependencyData.getProperties(), attributes);
Double samplingPercentage = 100.0;
telemetryItem.setSampleRate(samplingPercentage.floatValue());
telemetryItems.add(telemetryItem);
exportEvents(span, samplingPercentage, telemetryItems);
}
private void applyHttpClientSpan(Attributes attributes, RemoteDependencyData telemetry) {
String scheme = attributes.get(AttributeKey.stringKey("http.scheme"));
int defaultPort;
if ("http".equals(scheme)) {
defaultPort = 80;
} else if ("https".equals(scheme)) {
defaultPort = 443;
} else {
defaultPort = 0;
}
String target = getTargetFromPeerAttributes(attributes, defaultPort);
if (target == null) {
target = attributes.get(AttributeKey.stringKey("http.host"));
}
String url = attributes.get(AttributeKey.stringKey("http.url"));
if (target == null && url != null) {
try {
URI uri = new URI(url);
target = uri.getHost();
if (uri.getPort() != 80 && uri.getPort() != 443 && uri.getPort() != -1) {
target += ":" + uri.getPort();
}
} catch (URISyntaxException e) {
logger.error(e.getMessage());
logger.verbose(e.getMessage(), e);
}
}
if (target == null) {
target = "Http";
}
String targetAppId = attributes.get(AI_SPAN_TARGET_APP_ID_KEY);
if (targetAppId == null) {
telemetry.setType("Http");
telemetry.setTarget(target);
} else {
telemetry.setType("Http (tracked component)");
telemetry.setTarget(target + " | " + targetAppId);
}
Long httpStatusCode = attributes.get(AttributeKey.longKey("http.status_code"));
if (httpStatusCode != null) {
telemetry.setResultCode(Long.toString(httpStatusCode));
}
telemetry.setData(url);
}
private static String getTargetFromPeerAttributes(Attributes attributes, int defaultPort) {
String target = attributes.get(AttributeKey.stringKey("peer.service"));
if (target != null) {
return target;
}
target = attributes.get(AttributeKey.stringKey("net.peer.name"));
if (target == null) {
target = attributes.get(AttributeKey.stringKey("net.peer.ip"));
}
if (target == null) {
return null;
}
Long port = attributes.get(AttributeKey.longKey("net.peer.port"));
if (port != null && port != defaultPort) {
return target + ":" + port;
}
return target;
}
private static void applyRpcClientSpan(Attributes attributes, RemoteDependencyData telemetry, String rpcSystem) {
telemetry.setType(rpcSystem);
String target = getTargetFromPeerAttributes(attributes, 0);
if (target == null) {
target = rpcSystem;
}
telemetry.setTarget(target);
}
private static void applyDatabaseClientSpan(Attributes attributes, RemoteDependencyData telemetry, String dbSystem) {
String dbStatement = attributes.get(AttributeKey.stringKey("db.statement"));
String type;
if (SQL_DB_SYSTEMS.contains(dbSystem)) {
type = "SQL";
telemetry.setName(dbStatement);
} else {
type = dbSystem;
}
telemetry.setType(type);
telemetry.setData(dbStatement);
String target = nullAwareConcat(getTargetFromPeerAttributes(attributes, getDefaultPortForDbSystem(dbSystem)),
attributes.get(AttributeKey.stringKey("db.name")), "/");
if (target == null) {
target = dbSystem;
}
telemetry.setTarget(target);
}
private void applyMessagingClientSpan(Attributes attributes, RemoteDependencyData telemetry, String messagingSystem, SpanKind spanKind) {
if (spanKind == SpanKind.PRODUCER) {
telemetry.setType("Queue Message | " + messagingSystem);
} else {
telemetry.setType(messagingSystem);
}
String destination = attributes.get(AttributeKey.stringKey("messaging.destination"));
if (destination != null) {
telemetry.setTarget(destination);
} else {
telemetry.setTarget(messagingSystem);
}
}
private static int getDefaultPortForDbSystem(String dbSystem) {
switch (dbSystem) {
case "mongodb":
return 27017;
case "cassandra":
return 9042;
case "redis":
return 6379;
default:
return 0;
}
}
private void exportRequest(SpanData span, List<TelemetryItem> telemetryItems) {
TelemetryItem telemetryItem = new TelemetryItem();
RequestData requestData = new RequestData();
MonitorBase monitorBase = new MonitorBase();
telemetryItem.setTags(new HashMap<>());
telemetryItem.setName(telemetryItemNamePrefix + "Request");
telemetryItem.setVersion(1);
telemetryItem.setInstrumentationKey(instrumentationKey);
telemetryItem.setData(monitorBase);
requestData.setProperties(new HashMap<>());
requestData.setVersion(2);
monitorBase.setBaseType("RequestData");
monitorBase.setBaseData(requestData);
String source = null;
Attributes attributes = span.getAttributes();
String sourceAppId = attributes.get(AI_SPAN_SOURCE_APP_ID_KEY);
if (sourceAppId != null) {
source = sourceAppId;
}
if (source == null) {
String messagingSystem = attributes.get(AttributeKey.stringKey("messaging.system"));
if (messagingSystem != null) {
source = nullAwareConcat(getTargetFromPeerAttributes(attributes, 0),
attributes.get(AttributeKey.stringKey("messaging.destination")), "/");
if (source == null) {
source = messagingSystem;
}
}
}
if (source == null) {
source = attributes.get(AI_SPAN_SOURCE_KEY);
}
requestData.setSource(source);
addLinks(requestData.getProperties(), span.getLinks());
Long httpStatusCode = attributes.get(AttributeKey.longKey("http.status_code"));
requestData.setResponseCode("200");
if (httpStatusCode != null) {
requestData.setResponseCode(Long.toString(httpStatusCode));
}
String httpUrl = attributes.get(AttributeKey.stringKey("http.url"));
if (httpUrl != null) {
requestData.setUrl(httpUrl);
}
String name = span.getName();
requestData.setName(name);
telemetryItem.getTags().put(ContextTagKeys.AI_OPERATION_NAME.toString(), name);
requestData.setId(span.getSpanId());
telemetryItem.getTags().put(ContextTagKeys.AI_OPERATION_ID.toString(), span.getTraceId());
String aiLegacyParentId = span.getSpanContext().getTraceState().get("ai-legacy-parent-id");
if (aiLegacyParentId != null) {
telemetryItem.getTags().put(ContextTagKeys.AI_OPERATION_PARENT_ID.toString(), aiLegacyParentId);
String aiLegacyOperationId = span.getSpanContext().getTraceState().get("ai-legacy-operation-id");
if (aiLegacyOperationId != null) {
telemetryItem.getTags().putIfAbsent("ai_legacyRootID", aiLegacyOperationId);
}
} else {
String parentSpanId = span.getParentSpanId();
if (SpanId.isValid(parentSpanId)) {
telemetryItem.getTags().put(ContextTagKeys.AI_OPERATION_PARENT_ID.toString(), parentSpanId);
}
}
long startEpochNanos = span.getStartEpochNanos();
telemetryItem.setTime(getFormattedTime(startEpochNanos));
Duration duration = Duration.ofNanos(span.getEndEpochNanos() - startEpochNanos);
requestData.setDuration(getFormattedDuration(duration));
requestData.setSuccess(span.getStatus().getStatusCode() != StatusCode.ERROR);
String description = span.getStatus().getDescription();
if (description != null) {
requestData.getProperties().put("statusDescription", description);
}
Double samplingPercentage = 100.0;
setExtraAttributes(telemetryItem, requestData.getProperties(), attributes);
telemetryItem.setSampleRate(samplingPercentage.floatValue());
telemetryItems.add(telemetryItem);
exportEvents(span, samplingPercentage, telemetryItems);
}
private static String nullAwareConcat(String str1, String str2, String separator) {
if (str1 == null) {
return str2;
}
if (str2 == null) {
return str1;
}
return str1 + separator + str2;
}
private void exportEvents(SpanData span, Double samplingPercentage, List<TelemetryItem> telemetryItems) {
boolean foundException = false;
for (EventData event : span.getEvents()) {
TelemetryItem telemetryItem = new TelemetryItem();
TelemetryEventData eventData = new TelemetryEventData();
MonitorBase monitorBase = new MonitorBase();
telemetryItem.setTags(new HashMap<>());
telemetryItem.setName(telemetryItemNamePrefix + "Event");
telemetryItem.setVersion(1);
telemetryItem.setInstrumentationKey(instrumentationKey);
telemetryItem.setData(monitorBase);
eventData.setProperties(new HashMap<>());
eventData.setVersion(2);
monitorBase.setBaseType("EventData");
monitorBase.setBaseData(eventData);
eventData.setName(event.getName());
String operationId = span.getTraceId();
telemetryItem.getTags().put(ContextTagKeys.AI_OPERATION_ID.toString(), operationId);
telemetryItem.getTags()
.put(ContextTagKeys.AI_OPERATION_PARENT_ID.toString(), span.getSpanId());
telemetryItem.setTime(getFormattedTime(event.getEpochNanos()));
setExtraAttributes(telemetryItem, eventData.getProperties(), event.getAttributes());
if (event.getAttributes().get(AttributeKey.stringKey("exception.type")) != null
|| event.getAttributes().get(AttributeKey.stringKey("exception.message")) != null) {
String stacktrace = event.getAttributes().get(AttributeKey.stringKey("exception.stacktrace"));
if (stacktrace != null) {
trackException(stacktrace, span, operationId, span.getSpanId(), samplingPercentage, telemetryItems);
}
} else {
telemetryItem.setSampleRate(samplingPercentage.floatValue());
telemetryItems.add(telemetryItem);
}
}
}
private void trackException(String errorStack, SpanData span, String operationId,
String id, Double samplingPercentage, List<TelemetryItem> telemetryItems) {
TelemetryItem telemetryItem = new TelemetryItem();
TelemetryExceptionData exceptionData = new TelemetryExceptionData();
MonitorBase monitorBase = new MonitorBase();
telemetryItem.setTags(new HashMap<>());
telemetryItem.setName(telemetryItemNamePrefix + "Exception");
telemetryItem.setVersion(1);
telemetryItem.setInstrumentationKey(instrumentationKey);
telemetryItem.setData(monitorBase);
exceptionData.setProperties(new HashMap<>());
exceptionData.setVersion(2);
monitorBase.setBaseType("ExceptionData");
monitorBase.setBaseData(exceptionData);
telemetryItem.getTags().put(ContextTagKeys.AI_OPERATION_ID.toString(), operationId);
telemetryItem.getTags().put(ContextTagKeys.AI_OPERATION_PARENT_ID.toString(), id);
telemetryItem.setTime(getFormattedTime(span.getEndEpochNanos()));
telemetryItem.setSampleRate(samplingPercentage.floatValue());
exceptionData.setExceptions(minimalParse(errorStack));
telemetryItems.add(telemetryItem);
}
private static String getFormattedDuration(Duration duration) {
return duration.toDays() + "." + duration.toHours() + ":" + duration.toMinutes() + ":" + duration.getSeconds()
+ "." + duration.toMillis();
}
private static String getFormattedTime(long epochNanos) {
return Instant.ofEpochMilli(NANOSECONDS.toMillis(epochNanos))
.atOffset(ZoneOffset.UTC)
.format(DateTimeFormatter.ISO_DATE_TIME);
}
private static void addLinks(Map<String, String> properties, List<LinkData> links) {
if (links.isEmpty()) {
return;
}
StringBuilder sb = new StringBuilder();
sb.append("[");
boolean first = true;
for (LinkData link : links) {
if (!first) {
sb.append(",");
}
sb.append("{\"operation_Id\":\"");
sb.append(link.getSpanContext().getTraceId());
sb.append("\",\"id\":\"");
sb.append(link.getSpanContext().getSpanId());
sb.append("\"}");
first = false;
}
sb.append("]");
properties.put("_MS.links", sb.toString());
}
private String getStringValue(AttributeKey<?> attributeKey, Object value) {
switch (attributeKey.getType()) {
case STRING:
case BOOLEAN:
case LONG:
case DOUBLE:
return String.valueOf(value);
case STRING_ARRAY:
case BOOLEAN_ARRAY:
case LONG_ARRAY:
case DOUBLE_ARRAY:
return join((List<?>) value);
default:
logger.warning("unexpected attribute type: {}", attributeKey.getType());
return null;
}
}
private static <T> String join(List<T> values) {
StringBuilder sb = new StringBuilder();
if (CoreUtils.isNullOrEmpty(values)) {
return sb.toString();
}
for (int i = 0; i < values.size() - 1; i++) {
sb.append(values.get(i));
sb.append(", ");
}
sb.append(values.get(values.size() - 1));
return sb.toString();
}
private void setExtraAttributes(TelemetryItem telemetry, Map<String, String> properties,
Attributes attributes) {
attributes.forEach((key, value) -> {
String stringKey = key.getKey();
if (stringKey.startsWith("applicationinsights.internal.")) {
return;
}
if (key.getKey().equals("enduser.id") && value instanceof String) {
telemetry.getTags().put(ContextTagKeys.AI_USER_ID.toString(), (String) value);
return;
}
if (key.getKey().equals("http.user_agent") && value instanceof String) {
telemetry.getTags().put("ai.user.userAgent", (String) value);
return;
}
int index = stringKey.indexOf(".");
String prefix = index == -1 ? stringKey : stringKey.substring(0, index);
if (STANDARD_ATTRIBUTE_PREFIXES.contains(prefix)) {
return;
}
String val = getStringValue(key, value);
if (value != null) {
properties.put(key.getKey(), val);
}
});
}
} |
Can you add a reason why is times(3) and all the other instances? I don't think I'll remember why this is the case.. there are messages+1 in some cases. | void receivesFromFirstLink() {
ServiceBusReceiveLinkProcessor processor = Flux.just(link1).subscribeWith(linkProcessor);
FluxSink<AmqpEndpointState> sink = endpointProcessor.sink();
when(link1.getCredits()).thenReturn(0);
StepVerifier.create(processor)
.then(() -> {
sink.next(AmqpEndpointState.ACTIVE);
messageProcessorSink.next(message1);
messageProcessorSink.next(message2);
})
.expectNext(message1)
.expectNext(message2)
.thenCancel()
.verify();
assertTrue(processor.isTerminated());
assertFalse(processor.hasError());
assertNull(processor.getError());
verify(link1, times(3)).addCredits(eq(PREFETCH));
verify(link1).setEmptyCreditListener(creditSupplierCaptor.capture());
Supplier<Integer> value = creditSupplierCaptor.getValue();
assertNotNull(value);
final Integer creditValue = value.get();
assertEquals(0, creditValue);
} | verify(link1, times(3)).addCredits(eq(PREFETCH)); | void receivesFromFirstLink() {
ServiceBusReceiveLinkProcessor processor = Flux.just(link1).subscribeWith(linkProcessor);
FluxSink<AmqpEndpointState> sink = endpointProcessor.sink();
when(link1.getCredits()).thenReturn(0);
StepVerifier.create(processor)
.then(() -> {
sink.next(AmqpEndpointState.ACTIVE);
messageProcessorSink.next(message1);
messageProcessorSink.next(message2);
})
.expectNext(message1)
.expectNext(message2)
.thenCancel()
.verify();
assertTrue(processor.isTerminated());
assertFalse(processor.hasError());
assertNull(processor.getError());
verify(link1, times(3)).addCredits(eq(PREFETCH));
verify(link1).setEmptyCreditListener(creditSupplierCaptor.capture());
Supplier<Integer> value = creditSupplierCaptor.getValue();
assertNotNull(value);
final Integer creditValue = value.get();
assertEquals(0, creditValue);
} | class ServiceBusReceiveLinkProcessorTest {
private static final int PREFETCH = 5;
@Mock
private ServiceBusReceiveLink link1;
@Mock
private ServiceBusReceiveLink link2;
@Mock
private ServiceBusReceiveLink link3;
@Mock
private AmqpRetryPolicy retryPolicy;
@Mock
private Message message1;
@Mock
private Message message2;
@Captor
private ArgumentCaptor<Supplier<Integer>> creditSupplierCaptor;
private final EmitterProcessor<AmqpEndpointState> endpointProcessor = EmitterProcessor.create();
private final EmitterProcessor<Message> messageProcessor = EmitterProcessor.create();
private final FluxSink<Message> messageProcessorSink = messageProcessor.sink(FluxSink.OverflowStrategy.BUFFER);
private ServiceBusReceiveLinkProcessor linkProcessor;
private ServiceBusReceiveLinkProcessor linkProcessorNoPrefetch;
@BeforeAll
static void beforeAll() {
StepVerifier.setDefaultTimeout(Duration.ofSeconds(10));
}
@AfterAll
static void afterAll() {
StepVerifier.resetDefaultTimeout();
}
@BeforeEach
void setup() {
MockitoAnnotations.initMocks(this);
linkProcessor = new ServiceBusReceiveLinkProcessor(PREFETCH, retryPolicy, ServiceBusReceiveMode.PEEK_LOCK);
linkProcessorNoPrefetch = new ServiceBusReceiveLinkProcessor(0, retryPolicy, ServiceBusReceiveMode.PEEK_LOCK);
when(link1.getEndpointStates()).thenReturn(endpointProcessor);
when(link1.receive()).thenReturn(messageProcessor);
}
@AfterEach
void teardown() {
Mockito.framework().clearInlineMocks();
}
@Test
void constructor() {
assertThrows(NullPointerException.class, () -> new ServiceBusReceiveLinkProcessor(PREFETCH, null,
ServiceBusReceiveMode.PEEK_LOCK));
assertThrows(IllegalArgumentException.class, () -> new ServiceBusReceiveLinkProcessor(-1, retryPolicy,
ServiceBusReceiveMode.PEEK_LOCK));
assertThrows(NullPointerException.class, () -> new ServiceBusReceiveLinkProcessor(PREFETCH, retryPolicy,
null));
}
/**
* Verifies that we can get a new AMQP receive link and fetch a few messages.
*/
@Test
void createNewLink() {
ServiceBusReceiveLinkProcessor processor = Flux.<ServiceBusReceiveLink>create(sink -> sink.next(link1))
.subscribeWith(linkProcessor);
when(link1.getCredits()).thenReturn(1);
StepVerifier.create(processor)
.then(() -> {
messageProcessorSink.next(message1);
messageProcessorSink.next(message2);
})
.expectNext(message1)
.expectNext(message2)
.thenCancel()
.verify();
assertTrue(processor.isTerminated());
assertFalse(processor.hasError());
assertNull(processor.getError());
verify(link1, times(3)).addCredits(eq(PREFETCH - 1));
}
/**
* Verifies that we respect the back pressure request when it is in range 1 - 100.
*/
@Test
void respectsBackpressureInRange() {
final int backpressure = 15;
ServiceBusReceiveLinkProcessor processor = Flux.<ServiceBusReceiveLink>create(sink -> sink.next(link1))
.subscribeWith(linkProcessorNoPrefetch);
StepVerifier.create(processor, backpressure)
.then(() -> messageProcessorSink.next(message1))
.expectNext(message1)
.thenCancel()
.verify();
verify(link1).addCredits(backpressure);
}
/**
* Verifies we don't set the back pressure when it is too low.
*/
@Test
void respectsBackpressureLessThanMinimum() throws InterruptedException {
final Semaphore semaphore = new Semaphore(1);
final int backpressure = -1;
ServiceBusReceiveLinkProcessor processor = Flux.<ServiceBusReceiveLink>create(sink -> sink.next(link1))
.subscribeWith(linkProcessor);
when(link1.getCredits()).thenReturn(1);
semaphore.acquire();
processor.subscribe(
e -> System.out.println("message: " + e),
Assertions::fail,
() -> System.out.println("Complete."),
s -> {
s.request(backpressure);
semaphore.release();
});
assertTrue(semaphore.tryAcquire(10, TimeUnit.SECONDS));
verify(link1, never()).addCredits(anyInt());
verify(link1).setEmptyCreditListener(creditSupplierCaptor.capture());
Supplier<Integer> value = creditSupplierCaptor.getValue();
assertNotNull(value);
final Integer creditValue = value.get();
assertEquals(0, creditValue);
}
/**
* Verifies that we can only subscribe once.
*/
@Test
void onSubscribingTwiceThrowsException() {
ServiceBusReceiveLinkProcessor processor = Flux.<ServiceBusReceiveLink>create(sink -> sink.next(link1))
.subscribeWith(linkProcessor);
processor.subscribe();
StepVerifier.create(processor)
.expectError(IllegalStateException.class)
.verify();
}
/**
* Verifies that we can get subsequent AMQP links when the first one is closed.
*/
@Test
void newLinkOnClose() {
final ServiceBusReceiveLink[] connections = new ServiceBusReceiveLink[]{link1, link2, link3};
final Message message3 = mock(Message.class);
final Message message4 = mock(Message.class);
final ServiceBusReceiveLinkProcessor processor = createSink(connections).subscribeWith(linkProcessor);
final FluxSink<AmqpEndpointState> endpointSink = endpointProcessor.sink();
final DirectProcessor<AmqpEndpointState> connection2EndpointProcessor = DirectProcessor.create();
final FluxSink<AmqpEndpointState> connection2Endpoint =
connection2EndpointProcessor.sink(FluxSink.OverflowStrategy.BUFFER);
final DirectProcessor<Message> link2Receive = DirectProcessor.create();
when(link2.getEndpointStates()).thenReturn(connection2EndpointProcessor);
when(link2.receive()).thenReturn(Flux.create(sink -> sink.next(message2)));
when(link3.getEndpointStates()).thenReturn(Flux.create(sink -> sink.next(AmqpEndpointState.ACTIVE)));
when(link3.receive()).thenReturn(Flux.create(sink -> {
sink.next(message3);
sink.next(message4);
}));
when(link1.getCredits()).thenReturn(1);
when(link2.getCredits()).thenReturn(1);
when(link3.getCredits()).thenReturn(1);
StepVerifier.create(processor)
.then(() -> messageProcessorSink.next(message1))
.expectNext(message1)
.then(() -> {
endpointSink.complete();
})
.expectNext(message2)
.then(() -> {
connection2Endpoint.complete();
})
.expectNext(message3)
.expectNext(message4)
.then(() -> {
processor.cancel();
})
.verifyComplete();
assertTrue(processor.isTerminated());
assertFalse(processor.hasError());
assertNull(processor.getError());
}
/**
* Verifies that we can get the next AMQP link when the first one encounters a retryable error.
*/
@Disabled("Fails on Ubuntu 18")
@Test
void newLinkOnRetryableError() {
final ServiceBusReceiveLink[] connections = new ServiceBusReceiveLink[]{link1, link2};
final ServiceBusReceiveLinkProcessor processor = createSink(connections).subscribeWith(linkProcessor);
final FluxSink<AmqpEndpointState> endpointSink = endpointProcessor.sink();
when(link2.getEndpointStates()).thenReturn(Flux.defer(() -> Flux.create(e -> {
e.next(AmqpEndpointState.ACTIVE);
})));
when(link2.receive()).thenReturn(Flux.just(message2));
final AmqpException amqpException = new AmqpException(true, AmqpErrorCondition.SERVER_BUSY_ERROR, "Test-error",
new AmqpErrorContext("test-namespace"));
when(retryPolicy.calculateRetryDelay(amqpException, 1)).thenReturn(Duration.ofSeconds(1));
StepVerifier.create(processor)
.then(() -> {
endpointSink.next(AmqpEndpointState.ACTIVE);
messageProcessorSink.next(message1);
})
.expectNext(message1)
.then(() -> {
endpointSink.error(amqpException);
})
.expectNext(message2)
.thenCancel()
.verify();
assertTrue(processor.isTerminated());
assertFalse(processor.hasError());
assertNull(processor.getError());
}
/**
* Verifies that an error is propagated when the first connection encounters a non-retryable error.
*/
@Test
void nonRetryableError() {
final ServiceBusReceiveLink[] connections = new ServiceBusReceiveLink[]{link1, link2};
final ServiceBusReceiveLinkProcessor processor = createSink(connections).subscribeWith(linkProcessor);
final FluxSink<AmqpEndpointState> endpointSink = endpointProcessor.sink();
final Message message3 = mock(Message.class);
when(link2.getEndpointStates()).thenReturn(Flux.create(sink -> sink.next(AmqpEndpointState.ACTIVE)));
when(link2.receive()).thenReturn(Flux.just(message2, message3));
final AmqpException amqpException = new AmqpException(false, AmqpErrorCondition.ARGUMENT_ERROR, "Non"
+ "-retryable-error",
new AmqpErrorContext("test-namespace"));
when(retryPolicy.calculateRetryDelay(amqpException, 1)).thenReturn(null);
StepVerifier.create(processor)
.then(() -> {
endpointSink.next(AmqpEndpointState.ACTIVE);
messageProcessorSink.next(message1);
})
.expectNext(message1)
.then(() -> {
endpointSink.error(amqpException);
})
.expectErrorSatisfies(error -> {
assertTrue(error instanceof AmqpException);
AmqpException exception = (AmqpException) error;
assertFalse(exception.isTransient());
assertEquals(amqpException.getErrorCondition(), exception.getErrorCondition());
assertEquals(amqpException.getMessage(), exception.getMessage());
})
.verify();
assertTrue(processor.isTerminated());
assertTrue(processor.hasError());
assertSame(amqpException, processor.getError());
}
/**
* Verifies that when there are no subscribers, one request is fetched up stream.
*/
@Test
void noSubscribers() {
final Subscription subscription = mock(Subscription.class);
linkProcessor.onSubscribe(subscription);
verify(subscription).request(eq(1L));
}
/**
* Verifies that when the instance is terminated, no request is fetched from upstream.
*/
@Test
void noSubscribersWhenTerminated() {
final Subscription subscription = mock(Subscription.class);
linkProcessor.cancel();
linkProcessor.onSubscribe(subscription);
verifyNoInteractions(subscription);
}
/**
* Verifies it keeps trying to get a link and stops after retries are exhausted.
*/
@Disabled("Fails on Ubuntu 18")
@Test
void retriesUntilExhausted() {
final Duration delay = Duration.ofSeconds(1);
final ServiceBusReceiveLink[] connections = new ServiceBusReceiveLink[]{link1, link2, link3};
final ServiceBusReceiveLinkProcessor processor = createSink(connections).subscribeWith(linkProcessor);
final FluxSink<AmqpEndpointState> endpointSink = endpointProcessor.sink();
final DirectProcessor<AmqpEndpointState> link2StateProcessor = DirectProcessor.create();
final FluxSink<AmqpEndpointState> link2StateSink = link2StateProcessor.sink();
when(link2.getEndpointStates()).thenReturn(link2StateProcessor);
when(link2.receive()).thenReturn(Flux.never());
when(link3.getEndpointStates()).thenReturn(Flux.create(sink -> sink.next(AmqpEndpointState.ACTIVE)));
when(link3.receive()).thenReturn(Flux.never());
final AmqpException amqpException = new AmqpException(true, AmqpErrorCondition.SERVER_BUSY_ERROR, "Test-error",
new AmqpErrorContext("test-namespace"));
final AmqpException amqpException2 = new AmqpException(true, AmqpErrorCondition.SERVER_BUSY_ERROR, "Test-error",
new AmqpErrorContext("test-namespace"));
when(retryPolicy.calculateRetryDelay(amqpException, 1)).thenReturn(delay);
when(retryPolicy.calculateRetryDelay(amqpException2, 2)).thenReturn(null);
StepVerifier.create(processor)
.then(() -> {
endpointSink.next(AmqpEndpointState.ACTIVE);
messageProcessorSink.next(message1);
})
.expectNext(message1)
.then(() -> endpointSink.error(amqpException))
.thenAwait(delay)
.then(() -> link2StateSink.error(amqpException2))
.expectErrorSatisfies(error -> assertSame(amqpException2, error))
.verify();
assertTrue(processor.isTerminated());
assertTrue(processor.hasError());
assertSame(amqpException2, processor.getError());
}
/**
* Does not request another link when upstream is closed.
*/
@Test
void doNotRetryWhenParentConnectionIsClosed() {
final TestPublisher<ServiceBusReceiveLink> linkGenerator = TestPublisher.create();
final ServiceBusReceiveLinkProcessor processor = linkGenerator.flux().subscribeWith(linkProcessor);
final TestPublisher<AmqpEndpointState> endpointStates = TestPublisher.create();
final TestPublisher<Message> messages = TestPublisher.create();
when(link1.getEndpointStates()).thenReturn(endpointStates.flux());
when(link1.receive()).thenReturn(messages.flux());
final TestPublisher<AmqpEndpointState> endpointStates2 = TestPublisher.create();
when(link2.getEndpointStates()).thenReturn(endpointStates2.flux());
when(link2.receive()).thenReturn(Flux.never());
StepVerifier.create(processor)
.then(() -> {
linkGenerator.next(link1);
endpointStates.next(AmqpEndpointState.ACTIVE);
messages.next(message1);
})
.expectNext(message1)
.then(linkGenerator::complete)
.then(endpointStates::complete)
.expectComplete()
.verify();
assertTrue(processor.isTerminated());
}
@Test
void requiresNonNull() {
assertThrows(NullPointerException.class,
() -> linkProcessor.onNext(null));
assertThrows(NullPointerException.class,
() -> linkProcessor.onError(null));
}
/**
* Verifies that we respect the back pressure request and stop emitting.
*/
@Test
void stopsEmittingAfterBackPressure() {
final int backpressure = 5;
ServiceBusReceiveLinkProcessor processor = Flux.<ServiceBusReceiveLink>create(sink -> sink.next(link1))
.subscribeWith(linkProcessor);
when(link1.getCredits()).thenReturn(0, 5, 4, 3, 2, 1);
StepVerifier.create(processor, backpressure)
.then(() -> {
for (int i = 0; i < backpressure + 2; i++) {
messageProcessorSink.next(message2);
}
})
.expectNextCount(backpressure)
.thenAwait(Duration.ofSeconds(2))
.thenCancel()
.verify();
}
@Test
void receivesUntilFirstLinkClosed() {
ServiceBusReceiveLinkProcessor processor = Flux.just(link1).subscribeWith(linkProcessor);
FluxSink<AmqpEndpointState> sink = endpointProcessor.sink();
when(link1.getCredits()).thenReturn(0);
StepVerifier.create(processor)
.then(() -> {
sink.next(AmqpEndpointState.ACTIVE);
messageProcessorSink.next(message1);
messageProcessorSink.next(message2);
})
.expectNext(message1)
.expectNext(message2)
.then(() -> sink.complete())
.expectComplete()
.verify();
assertTrue(processor.isTerminated());
assertFalse(processor.hasError());
assertNull(processor.getError());
verify(link1, times(3)).addCredits(eq(PREFETCH));
verify(link1).setEmptyCreditListener(creditSupplierCaptor.capture());
Supplier<Integer> value = creditSupplierCaptor.getValue();
assertNotNull(value);
final Integer creditValue = value.get();
assertEquals(0, creditValue);
}
@Test
/**
* Verifies that when we request back pressure amounts, if it only requests a certain number of events, only that
* number is consumed.
*/
@Test
void backpressureRequestOnlyEmitsThatAmount() {
final int backpressure = PREFETCH;
final int existingCredits = 1;
final int expectedCredits = backpressure - existingCredits;
ServiceBusReceiveLinkProcessor processor = Flux.just(link1).subscribeWith(linkProcessor);
FluxSink<AmqpEndpointState> sink = endpointProcessor.sink();
when(link1.getCredits()).thenReturn(existingCredits);
StepVerifier.create(processor, backpressure)
.then(() -> {
sink.next(AmqpEndpointState.ACTIVE);
final int emitted = backpressure + 5;
for (int i = 0; i < emitted; i++) {
messageProcessorSink.next(mock(Message.class));
}
})
.expectNextCount(backpressure)
.thenAwait(Duration.ofSeconds(1))
.thenCancel()
.verify();
assertTrue(processor.isTerminated());
assertFalse(processor.hasError());
assertNull(processor.getError());
verify(link1, times(backpressure + 1)).addCredits(expectedCredits);
verify(link1).setEmptyCreditListener(any());
}
private static Flux<ServiceBusReceiveLink> createSink(ServiceBusReceiveLink[] links) {
return Flux.create(emitter -> {
final AtomicInteger counter = new AtomicInteger();
emitter.onRequest(request -> {
for (int i = 0; i < request; i++) {
final int index = counter.getAndIncrement();
if (index == links.length) {
emitter.error(new RuntimeException(String.format(
"Cannot emit more. Index: %s.
index, links.length)));
break;
}
emitter.next(links[index]);
}
});
}, FluxSink.OverflowStrategy.BUFFER);
}
@Test
void updateDispositionDoesNotAddCredit() {
ServiceBusReceiveLinkProcessor processor = Flux.<ServiceBusReceiveLink>create(sink -> sink.next(link1))
.subscribeWith(linkProcessor);
final String lockToken = "lockToken";
final DeliveryState deliveryState = mock(DeliveryState.class);
when(link1.getCredits()).thenReturn(0);
when(link1.updateDisposition(eq(lockToken), eq(deliveryState))).thenReturn(Mono.empty());
StepVerifier.create(processor)
.then(() -> processor.updateDisposition(lockToken, deliveryState))
.thenCancel()
.verify();
assertTrue(processor.isTerminated());
assertFalse(processor.hasError());
assertNull(processor.getError());
verify(link1).addCredits(eq(PREFETCH));
verify(link1).updateDisposition(eq(lockToken), eq(deliveryState));
}
} | class ServiceBusReceiveLinkProcessorTest {
private static final int PREFETCH = 5;
@Mock
private ServiceBusReceiveLink link1;
@Mock
private ServiceBusReceiveLink link2;
@Mock
private ServiceBusReceiveLink link3;
@Mock
private AmqpRetryPolicy retryPolicy;
@Mock
private Message message1;
@Mock
private Message message2;
@Captor
private ArgumentCaptor<Supplier<Integer>> creditSupplierCaptor;
private final EmitterProcessor<AmqpEndpointState> endpointProcessor = EmitterProcessor.create();
private final EmitterProcessor<Message> messageProcessor = EmitterProcessor.create();
private final FluxSink<Message> messageProcessorSink = messageProcessor.sink(FluxSink.OverflowStrategy.BUFFER);
private ServiceBusReceiveLinkProcessor linkProcessor;
private ServiceBusReceiveLinkProcessor linkProcessorNoPrefetch;
@BeforeAll
static void beforeAll() {
StepVerifier.setDefaultTimeout(Duration.ofSeconds(10));
}
@AfterAll
static void afterAll() {
StepVerifier.resetDefaultTimeout();
}
@BeforeEach
void setup() {
MockitoAnnotations.initMocks(this);
linkProcessor = new ServiceBusReceiveLinkProcessor(PREFETCH, retryPolicy, ServiceBusReceiveMode.PEEK_LOCK);
linkProcessorNoPrefetch = new ServiceBusReceiveLinkProcessor(0, retryPolicy, ServiceBusReceiveMode.PEEK_LOCK);
when(link1.getEndpointStates()).thenReturn(endpointProcessor);
when(link1.receive()).thenReturn(messageProcessor);
}
@AfterEach
void teardown() {
Mockito.framework().clearInlineMocks();
}
@Test
void constructor() {
assertThrows(NullPointerException.class, () -> new ServiceBusReceiveLinkProcessor(PREFETCH, null,
ServiceBusReceiveMode.PEEK_LOCK));
assertThrows(IllegalArgumentException.class, () -> new ServiceBusReceiveLinkProcessor(-1, retryPolicy,
ServiceBusReceiveMode.PEEK_LOCK));
assertThrows(NullPointerException.class, () -> new ServiceBusReceiveLinkProcessor(PREFETCH, retryPolicy,
null));
}
/**
* Verifies that we can get a new AMQP receive link and fetch a few messages.
*/
@Test
void createNewLink() {
ServiceBusReceiveLinkProcessor processor = Flux.<ServiceBusReceiveLink>create(sink -> sink.next(link1))
.subscribeWith(linkProcessor);
when(link1.getCredits()).thenReturn(1);
StepVerifier.create(processor)
.then(() -> {
messageProcessorSink.next(message1);
messageProcessorSink.next(message2);
})
.expectNext(message1)
.expectNext(message2)
.thenCancel()
.verify();
assertTrue(processor.isTerminated());
assertFalse(processor.hasError());
assertNull(processor.getError());
verify(link1, times(3)).addCredits(eq(PREFETCH - 1));
}
/**
* Verifies that we respect the back pressure request when it is in range 1 - 100.
*/
@Test
void respectsBackpressureInRange() {
final int backpressure = 15;
ServiceBusReceiveLinkProcessor processor = Flux.<ServiceBusReceiveLink>create(sink -> sink.next(link1))
.subscribeWith(linkProcessorNoPrefetch);
StepVerifier.create(processor, backpressure)
.then(() -> messageProcessorSink.next(message1))
.expectNext(message1)
.thenCancel()
.verify();
verify(link1).addCredits(backpressure);
}
/**
* Verifies we don't set the back pressure when it is too low.
*/
@Test
void respectsBackpressureLessThanMinimum() throws InterruptedException {
final Semaphore semaphore = new Semaphore(1);
final int backpressure = -1;
ServiceBusReceiveLinkProcessor processor = Flux.<ServiceBusReceiveLink>create(sink -> sink.next(link1))
.subscribeWith(linkProcessor);
when(link1.getCredits()).thenReturn(1);
semaphore.acquire();
processor.subscribe(
e -> System.out.println("message: " + e),
Assertions::fail,
() -> System.out.println("Complete."),
s -> {
s.request(backpressure);
semaphore.release();
});
assertTrue(semaphore.tryAcquire(10, TimeUnit.SECONDS));
verify(link1, never()).addCredits(anyInt());
verify(link1).setEmptyCreditListener(creditSupplierCaptor.capture());
Supplier<Integer> value = creditSupplierCaptor.getValue();
assertNotNull(value);
final Integer creditValue = value.get();
assertEquals(0, creditValue);
}
/**
* Verifies that we can only subscribe once.
*/
@Test
void onSubscribingTwiceThrowsException() {
ServiceBusReceiveLinkProcessor processor = Flux.<ServiceBusReceiveLink>create(sink -> sink.next(link1))
.subscribeWith(linkProcessor);
processor.subscribe();
StepVerifier.create(processor)
.expectError(IllegalStateException.class)
.verify();
}
/**
* Verifies that we can get subsequent AMQP links when the first one is closed.
*/
@Test
void newLinkOnClose() {
final ServiceBusReceiveLink[] connections = new ServiceBusReceiveLink[]{link1, link2, link3};
final Message message3 = mock(Message.class);
final Message message4 = mock(Message.class);
final ServiceBusReceiveLinkProcessor processor = createSink(connections).subscribeWith(linkProcessor);
final FluxSink<AmqpEndpointState> endpointSink = endpointProcessor.sink();
final DirectProcessor<AmqpEndpointState> connection2EndpointProcessor = DirectProcessor.create();
final FluxSink<AmqpEndpointState> connection2Endpoint =
connection2EndpointProcessor.sink(FluxSink.OverflowStrategy.BUFFER);
final DirectProcessor<Message> link2Receive = DirectProcessor.create();
when(link2.getEndpointStates()).thenReturn(connection2EndpointProcessor);
when(link2.receive()).thenReturn(Flux.create(sink -> sink.next(message2)));
when(link3.getEndpointStates()).thenReturn(Flux.create(sink -> sink.next(AmqpEndpointState.ACTIVE)));
when(link3.receive()).thenReturn(Flux.create(sink -> {
sink.next(message3);
sink.next(message4);
}));
when(link1.getCredits()).thenReturn(1);
when(link2.getCredits()).thenReturn(1);
when(link3.getCredits()).thenReturn(1);
StepVerifier.create(processor)
.then(() -> messageProcessorSink.next(message1))
.expectNext(message1)
.then(() -> {
endpointSink.complete();
})
.expectNext(message2)
.then(() -> {
connection2Endpoint.complete();
})
.expectNext(message3)
.expectNext(message4)
.then(() -> {
processor.cancel();
})
.verifyComplete();
assertTrue(processor.isTerminated());
assertFalse(processor.hasError());
assertNull(processor.getError());
}
/**
* Verifies that we can get the next AMQP link when the first one encounters a retryable error.
*/
@Disabled("Fails on Ubuntu 18")
@Test
void newLinkOnRetryableError() {
final ServiceBusReceiveLink[] connections = new ServiceBusReceiveLink[]{link1, link2};
final ServiceBusReceiveLinkProcessor processor = createSink(connections).subscribeWith(linkProcessor);
final FluxSink<AmqpEndpointState> endpointSink = endpointProcessor.sink();
when(link2.getEndpointStates()).thenReturn(Flux.defer(() -> Flux.create(e -> {
e.next(AmqpEndpointState.ACTIVE);
})));
when(link2.receive()).thenReturn(Flux.just(message2));
final AmqpException amqpException = new AmqpException(true, AmqpErrorCondition.SERVER_BUSY_ERROR, "Test-error",
new AmqpErrorContext("test-namespace"));
when(retryPolicy.calculateRetryDelay(amqpException, 1)).thenReturn(Duration.ofSeconds(1));
StepVerifier.create(processor)
.then(() -> {
endpointSink.next(AmqpEndpointState.ACTIVE);
messageProcessorSink.next(message1);
})
.expectNext(message1)
.then(() -> {
endpointSink.error(amqpException);
})
.expectNext(message2)
.thenCancel()
.verify();
assertTrue(processor.isTerminated());
assertFalse(processor.hasError());
assertNull(processor.getError());
}
/**
* Verifies that an error is propagated when the first connection encounters a non-retryable error.
*/
@Test
void nonRetryableError() {
final ServiceBusReceiveLink[] connections = new ServiceBusReceiveLink[]{link1, link2};
final ServiceBusReceiveLinkProcessor processor = createSink(connections).subscribeWith(linkProcessor);
final FluxSink<AmqpEndpointState> endpointSink = endpointProcessor.sink();
final Message message3 = mock(Message.class);
when(link2.getEndpointStates()).thenReturn(Flux.create(sink -> sink.next(AmqpEndpointState.ACTIVE)));
when(link2.receive()).thenReturn(Flux.just(message2, message3));
final AmqpException amqpException = new AmqpException(false, AmqpErrorCondition.ARGUMENT_ERROR, "Non"
+ "-retryable-error",
new AmqpErrorContext("test-namespace"));
when(retryPolicy.calculateRetryDelay(amqpException, 1)).thenReturn(null);
StepVerifier.create(processor)
.then(() -> {
endpointSink.next(AmqpEndpointState.ACTIVE);
messageProcessorSink.next(message1);
})
.expectNext(message1)
.then(() -> {
endpointSink.error(amqpException);
})
.expectErrorSatisfies(error -> {
assertTrue(error instanceof AmqpException);
AmqpException exception = (AmqpException) error;
assertFalse(exception.isTransient());
assertEquals(amqpException.getErrorCondition(), exception.getErrorCondition());
assertEquals(amqpException.getMessage(), exception.getMessage());
})
.verify();
assertTrue(processor.isTerminated());
assertTrue(processor.hasError());
assertSame(amqpException, processor.getError());
}
/**
* Verifies that when there are no subscribers, one request is fetched up stream.
*/
@Test
void noSubscribers() {
final Subscription subscription = mock(Subscription.class);
linkProcessor.onSubscribe(subscription);
verify(subscription).request(eq(1L));
}
/**
* Verifies that when the instance is terminated, no request is fetched from upstream.
*/
@Test
void noSubscribersWhenTerminated() {
final Subscription subscription = mock(Subscription.class);
linkProcessor.cancel();
linkProcessor.onSubscribe(subscription);
verifyNoInteractions(subscription);
}
/**
* Verifies it keeps trying to get a link and stops after retries are exhausted.
*/
@Disabled("Fails on Ubuntu 18")
@Test
void retriesUntilExhausted() {
final Duration delay = Duration.ofSeconds(1);
final ServiceBusReceiveLink[] connections = new ServiceBusReceiveLink[]{link1, link2, link3};
final ServiceBusReceiveLinkProcessor processor = createSink(connections).subscribeWith(linkProcessor);
final FluxSink<AmqpEndpointState> endpointSink = endpointProcessor.sink();
final DirectProcessor<AmqpEndpointState> link2StateProcessor = DirectProcessor.create();
final FluxSink<AmqpEndpointState> link2StateSink = link2StateProcessor.sink();
when(link2.getEndpointStates()).thenReturn(link2StateProcessor);
when(link2.receive()).thenReturn(Flux.never());
when(link3.getEndpointStates()).thenReturn(Flux.create(sink -> sink.next(AmqpEndpointState.ACTIVE)));
when(link3.receive()).thenReturn(Flux.never());
final AmqpException amqpException = new AmqpException(true, AmqpErrorCondition.SERVER_BUSY_ERROR, "Test-error",
new AmqpErrorContext("test-namespace"));
final AmqpException amqpException2 = new AmqpException(true, AmqpErrorCondition.SERVER_BUSY_ERROR, "Test-error",
new AmqpErrorContext("test-namespace"));
when(retryPolicy.calculateRetryDelay(amqpException, 1)).thenReturn(delay);
when(retryPolicy.calculateRetryDelay(amqpException2, 2)).thenReturn(null);
StepVerifier.create(processor)
.then(() -> {
endpointSink.next(AmqpEndpointState.ACTIVE);
messageProcessorSink.next(message1);
})
.expectNext(message1)
.then(() -> endpointSink.error(amqpException))
.thenAwait(delay)
.then(() -> link2StateSink.error(amqpException2))
.expectErrorSatisfies(error -> assertSame(amqpException2, error))
.verify();
assertTrue(processor.isTerminated());
assertTrue(processor.hasError());
assertSame(amqpException2, processor.getError());
}
/**
* Does not request another link when upstream is closed.
*/
@Test
void doNotRetryWhenParentConnectionIsClosed() {
final TestPublisher<ServiceBusReceiveLink> linkGenerator = TestPublisher.create();
final ServiceBusReceiveLinkProcessor processor = linkGenerator.flux().subscribeWith(linkProcessor);
final TestPublisher<AmqpEndpointState> endpointStates = TestPublisher.create();
final TestPublisher<Message> messages = TestPublisher.create();
when(link1.getEndpointStates()).thenReturn(endpointStates.flux());
when(link1.receive()).thenReturn(messages.flux());
final TestPublisher<AmqpEndpointState> endpointStates2 = TestPublisher.create();
when(link2.getEndpointStates()).thenReturn(endpointStates2.flux());
when(link2.receive()).thenReturn(Flux.never());
StepVerifier.create(processor)
.then(() -> {
linkGenerator.next(link1);
endpointStates.next(AmqpEndpointState.ACTIVE);
messages.next(message1);
})
.expectNext(message1)
.then(linkGenerator::complete)
.then(endpointStates::complete)
.expectComplete()
.verify();
assertTrue(processor.isTerminated());
}
@Test
void requiresNonNull() {
assertThrows(NullPointerException.class,
() -> linkProcessor.onNext(null));
assertThrows(NullPointerException.class,
() -> linkProcessor.onError(null));
}
/**
* Verifies that we respect the back pressure request and stop emitting.
*/
@Test
void stopsEmittingAfterBackPressure() {
final int backpressure = 5;
ServiceBusReceiveLinkProcessor processor = Flux.<ServiceBusReceiveLink>create(sink -> sink.next(link1))
.subscribeWith(linkProcessor);
when(link1.getCredits()).thenReturn(0, 5, 4, 3, 2, 1);
StepVerifier.create(processor, backpressure)
.then(() -> {
for (int i = 0; i < backpressure + 2; i++) {
messageProcessorSink.next(message2);
}
})
.expectNextCount(backpressure)
.thenAwait(Duration.ofSeconds(2))
.thenCancel()
.verify();
}
@Test
void receivesUntilFirstLinkClosed() {
ServiceBusReceiveLinkProcessor processor = Flux.just(link1).subscribeWith(linkProcessor);
FluxSink<AmqpEndpointState> sink = endpointProcessor.sink();
when(link1.getCredits()).thenReturn(0);
StepVerifier.create(processor)
.then(() -> {
sink.next(AmqpEndpointState.ACTIVE);
messageProcessorSink.next(message1);
messageProcessorSink.next(message2);
})
.expectNext(message1)
.expectNext(message2)
.then(() -> sink.complete())
.expectComplete()
.verify();
assertTrue(processor.isTerminated());
assertFalse(processor.hasError());
assertNull(processor.getError());
verify(link1, times(3)).addCredits(eq(PREFETCH));
verify(link1).setEmptyCreditListener(creditSupplierCaptor.capture());
Supplier<Integer> value = creditSupplierCaptor.getValue();
assertNotNull(value);
final Integer creditValue = value.get();
assertEquals(0, creditValue);
}
@Test
/**
* Verifies that when we request back pressure amounts, if it only requests a certain number of events, only that
* number is consumed.
*/
@Test
void backpressureRequestOnlyEmitsThatAmount() {
final int backpressure = PREFETCH;
final int existingCredits = 1;
final int expectedCredits = backpressure - existingCredits;
ServiceBusReceiveLinkProcessor processor = Flux.just(link1).subscribeWith(linkProcessor);
FluxSink<AmqpEndpointState> sink = endpointProcessor.sink();
when(link1.getCredits()).thenReturn(existingCredits);
StepVerifier.create(processor, backpressure)
.then(() -> {
sink.next(AmqpEndpointState.ACTIVE);
final int emitted = backpressure + 5;
for (int i = 0; i < emitted; i++) {
messageProcessorSink.next(mock(Message.class));
}
})
.expectNextCount(backpressure)
.thenAwait(Duration.ofSeconds(1))
.thenCancel()
.verify();
assertTrue(processor.isTerminated());
assertFalse(processor.hasError());
assertNull(processor.getError());
verify(link1, times(backpressure + 1)).addCredits(expectedCredits);
verify(link1).setEmptyCreditListener(any());
}
private static Flux<ServiceBusReceiveLink> createSink(ServiceBusReceiveLink[] links) {
return Flux.create(emitter -> {
final AtomicInteger counter = new AtomicInteger();
emitter.onRequest(request -> {
for (int i = 0; i < request; i++) {
final int index = counter.getAndIncrement();
if (index == links.length) {
emitter.error(new RuntimeException(String.format(
"Cannot emit more. Index: %s.
index, links.length)));
break;
}
emitter.next(links[index]);
}
});
}, FluxSink.OverflowStrategy.BUFFER);
}
@Test
void updateDispositionDoesNotAddCredit() {
ServiceBusReceiveLinkProcessor processor = Flux.<ServiceBusReceiveLink>create(sink -> sink.next(link1))
.subscribeWith(linkProcessor);
final String lockToken = "lockToken";
final DeliveryState deliveryState = mock(DeliveryState.class);
when(link1.getCredits()).thenReturn(0);
when(link1.updateDisposition(eq(lockToken), eq(deliveryState))).thenReturn(Mono.empty());
StepVerifier.create(processor)
.then(() -> processor.updateDisposition(lockToken, deliveryState))
.thenCancel()
.verify();
assertTrue(processor.isTerminated());
assertFalse(processor.hasError());
assertNull(processor.getError());
verify(link1).addCredits(eq(PREFETCH));
verify(link1).updateDisposition(eq(lockToken), eq(deliveryState));
}
} |
I'm curious why there isn't any sort of TokenCredential or AzureSasCredential policy here. Does this service not have any sort of authentication? I can't find it in the .NET repo either | public ModelsRepositoryAsyncClient buildAsyncClient() {
Objects.requireNonNull(endpoint, "'endpoint' cannot be null");
Configuration buildConfiguration = this.configuration;
if (buildConfiguration == null)
{
buildConfiguration = Configuration.getGlobalConfiguration().clone();
}
ModelsRepositoryServiceVersion serviceVersion = this.serviceVersion;
if (serviceVersion == null)
{
serviceVersion = ModelsRepositoryServiceVersion.getLatest();
}
RetryPolicy retryPolicy = this.retryPolicy;
if (retryPolicy == null)
{
retryPolicy = DEFAULT_RETRY_POLICY;
}
if (this.httpPipeline == null) {
this.httpPipeline = buildPipeline(
this.endpoint,
this.httpLogOptions,
this.clientOptions,
this.httpClient,
this.additionalPolicies,
retryPolicy,
buildConfiguration,
this.properties);
}
return new ModelsRepositoryAsyncClient(this.endpoint, this.httpPipeline, serviceVersion, this.jsonSerializer);
} | Objects.requireNonNull(endpoint, "'endpoint' cannot be null"); | public ModelsRepositoryAsyncClient buildAsyncClient() {
Objects.requireNonNull(endpoint, "'endpoint' cannot be null");
Configuration buildConfiguration = this.configuration;
if (buildConfiguration == null)
{
buildConfiguration = Configuration.getGlobalConfiguration().clone();
}
ModelsRepositoryServiceVersion serviceVersion = this.serviceVersion;
if (serviceVersion == null)
{
serviceVersion = ModelsRepositoryServiceVersion.getLatest();
}
RetryPolicy retryPolicy = this.retryPolicy;
if (retryPolicy == null)
{
retryPolicy = DEFAULT_RETRY_POLICY;
}
if (this.httpPipeline == null) {
this.httpPipeline = buildPipeline(
this.endpoint,
this.httpLogOptions,
this.clientOptions,
this.httpClient,
this.additionalPolicies,
retryPolicy,
buildConfiguration,
this.properties);
}
return new ModelsRepositoryAsyncClient(this.endpoint, this.httpPipeline, serviceVersion, this.jsonSerializer);
} | class ModelsRepositoryClientBuilder {
private static final String MODELS_REPOSITORY_PROPERTIES = "azure-iot-modelsrepository.properties";
private static final String SDK_NAME = "name";
private static final String SDK_VERSION = "version";
private final List<HttpPipelinePolicy> additionalPolicies;
private String endpoint;
private ModelsRepositoryServiceVersion serviceVersion;
private ClientOptions clientOptions;
private HttpPipeline httpPipeline;
private HttpClient httpClient;
private HttpLogOptions httpLogOptions;
private RetryPolicy retryPolicy;
private JsonSerializer jsonSerializer;
private static final String retryAfterHeader = null;
private static final ChronoUnit retryAfterTimeUnit = null;
private static final RetryPolicy DEFAULT_RETRY_POLICY = new RetryPolicy(retryAfterHeader, retryAfterTimeUnit);
private final Map<String, String> properties;
private Configuration configuration;
/**
* The public constructor for ModelsRepositoryClientBuilder
*/
public ModelsRepositoryClientBuilder()
{
additionalPolicies = new ArrayList<>();
properties = CoreUtils.getProperties(MODELS_REPOSITORY_PROPERTIES);
httpLogOptions = new HttpLogOptions();
}
private static HttpPipeline buildPipeline(String endpoint,
HttpLogOptions httpLogOptions,
ClientOptions clientOptions,
HttpClient httpClient,
List<HttpPipelinePolicy> additionalPolicies,
RetryPolicy retryPolicy,
Configuration configuration,
Map<String, String> properties) {
List<HttpPipelinePolicy> policies = new ArrayList<>();
String clientName = properties.getOrDefault(SDK_NAME, "UnknownName");
String clientVersion = properties.getOrDefault(SDK_VERSION, "UnknownVersion");
String applicationId = clientOptions == null
? httpLogOptions.getApplicationId()
: clientOptions.getApplicationId();
policies.add(new UserAgentPolicy(applicationId, clientName, clientVersion, configuration));
policies.add(new RequestIdPolicy());
HttpPolicyProviders.addBeforeRetryPolicies(policies);
policies.add(retryPolicy);
policies.add(new AddDatePolicy());
policies.addAll(additionalPolicies);
if (clientOptions != null) {
List<HttpHeader> httpHeaderList = new ArrayList<>();
clientOptions.getHeaders().forEach(header ->
httpHeaderList.add(new HttpHeader(header.getName(), header.getValue())));
policies.add(new AddHeadersPolicy(new HttpHeaders(httpHeaderList)));
}
HttpPolicyProviders.addAfterRetryPolicies(policies);
policies.add(new HttpLoggingPolicy(httpLogOptions));
return new HttpPipelineBuilder()
.policies(policies.toArray(new HttpPipelinePolicy[0]))
.httpClient(httpClient)
.build();
}
/**
* Create a {@link ModelsRepotioryClient} based on the builder settings.
*
* @return the created synchronous ModelsRepotioryClient
*/
public ModelsRepotioryClient buildClient() {
return new ModelsRepotioryClient(buildAsyncClient());
}
/**
* Create a {@link ModelsRepositoryAsyncClient} based on the builder settings.
*
* @return the created asynchronous ModelsRepositoryAsyncClient
*/
/**
* Set the service endpoint that the built client will communicate with. This field is mandatory to set.
*
* @param endpoint URL of the service.
* @return the updated ModelsRepositoryClientBuilder instance for fluent building.
*/
public ModelsRepositoryClientBuilder endpoint(String endpoint) {
this.endpoint = endpoint;
return this;
}
/**
* Sets the {@link ModelsRepositoryServiceVersion} that is used when making API requests.
* <p>
* If a service version is not provided, the service version that will be used will be the latest known service
* version based on the version of the client library being used. If no service version is specified, updating to a
* newer version of the client library will have the result of potentially moving to a newer service version.
* <p>
* Targeting a specific service version may also mean that the service will return an error for newer APIs.
*
* @param serviceVersion The service API version to use.
* @return the updated ModelsRepositoryClientBuilder instance for fluent building.
*/
public ModelsRepositoryClientBuilder serviceVersion(ModelsRepositoryServiceVersion serviceVersion) {
this.serviceVersion = serviceVersion;
return this;
}
/**
* Sets the {@link HttpClient} to use for sending a receiving requests to and from the service.
*
* @param httpClient HttpClient to use for requests.
* @return the updated ModelsRepositoryClientBuilder instance for fluent building.
*/
public ModelsRepositoryClientBuilder httpClient(HttpClient httpClient) {
this.httpClient = httpClient;
return this;
}
/**
* Sets the {@link HttpLogOptions} for service requests.
*
* @param logOptions The logging configuration to use when sending and receiving HTTP requests/responses.
* @return the updated ModelsRepositoryClientBuilder instance for fluent building.
* @throws NullPointerException If {@code httpLogOptions} is {@code null}.
*/
public ModelsRepositoryClientBuilder httpLogOptions(HttpLogOptions logOptions) {
this.httpLogOptions = logOptions;
return this;
}
/**
* Adds a pipeline policy to apply on each request sent. The policy will be added after the retry policy. If
* the method is called multiple times, all policies will be added and their order preserved.
*
* @param pipelinePolicy a pipeline policy
* @return the updated ModelsRepositoryClientBuilder instance for fluent building.
* @throws NullPointerException If {@code pipelinePolicy} is {@code null}.
*/
public ModelsRepositoryClientBuilder addPolicy(HttpPipelinePolicy pipelinePolicy) {
this.additionalPolicies.add(Objects.requireNonNull(pipelinePolicy, "'pipelinePolicy' cannot be null"));
return this;
}
/**
* Sets the {@link HttpPipelinePolicy} that is used as the retry policy for each request that is sent.
*
* The default retry policy will be used if not provided. The default retry policy is {@link RetryPolicy
* For implementing custom retry logic, see {@link RetryPolicy} as an example.
*
* @param retryPolicy the retry policy applied to each request.
* @return The updated ConfigurationClientBuilder object.
*/
public ModelsRepositoryClientBuilder retryPolicy(RetryPolicy retryPolicy) {
this.retryPolicy = retryPolicy;
return this;
}
/**
* Sets the {@link HttpPipeline} to use for the service client.
* <p>
* If {@code pipeline} is set, all other settings are ignored, aside from {@link
*
* @param httpPipeline HttpPipeline to use for sending service requests and receiving responses.
* @return the updated ModelsRepositoryClientBuilder instance for fluent building.
*/
public ModelsRepositoryClientBuilder pipeline(HttpPipeline httpPipeline) {
this.httpPipeline = httpPipeline;
return this;
}
/**
* Sets the configuration store that is used during construction of the service client.
*
* The default configuration store is a clone of the {@link Configuration
* configuration store}, use {@link Configuration
*
* @param configuration The configuration store used to
* @return The updated ModelsRepositoryClientBuilder object for fluent building.
*/
public ModelsRepositoryClientBuilder configuration(Configuration configuration) {
this.configuration = configuration;
return this;
}
/**
* Custom JSON serializer that is used to handle model types that are not contained in the Azure Models Repository library.
*
* @param jsonSerializer The serializer to deserialize response payloads into user defined models.
* @return The updated ModelsRepositoryClientBuilder object.
*/
public ModelsRepositoryClientBuilder serializer(JsonSerializer jsonSerializer) {
this.jsonSerializer = jsonSerializer;
return this;
}
/**
* Sets the {@link ClientOptions} which enables various options to be set on the client. For example setting an
* {@code applicationId} using {@link ClientOptions
* the {@link UserAgentPolicy} for telemetry/monitoring purposes.
*
* <p>More About <a href="https:
*
* @param clientOptions the {@link ClientOptions} to be set on the client.
* @return The updated KeyClientBuilder object.
*/
public ModelsRepositoryClientBuilder clientOptions(ClientOptions clientOptions) {
this.clientOptions = clientOptions;
return this;
}
} | class ModelsRepositoryClientBuilder {
private static final String MODELS_REPOSITORY_PROPERTIES = "azure-iot-modelsrepository.properties";
private static final String SDK_NAME = "name";
private static final String SDK_VERSION = "version";
private final List<HttpPipelinePolicy> additionalPolicies;
private String endpoint;
private ModelsRepositoryServiceVersion serviceVersion;
private ClientOptions clientOptions;
private HttpPipeline httpPipeline;
private HttpClient httpClient;
private HttpLogOptions httpLogOptions;
private RetryPolicy retryPolicy;
private JsonSerializer jsonSerializer;
private static final String retryAfterHeader = null;
private static final ChronoUnit retryAfterTimeUnit = null;
private static final RetryPolicy DEFAULT_RETRY_POLICY = new RetryPolicy(retryAfterHeader, retryAfterTimeUnit);
private final Map<String, String> properties;
private Configuration configuration;
/**
* The public constructor for ModelsRepositoryClientBuilder
*/
public ModelsRepositoryClientBuilder()
{
additionalPolicies = new ArrayList<>();
properties = CoreUtils.getProperties(MODELS_REPOSITORY_PROPERTIES);
httpLogOptions = new HttpLogOptions();
}
private static HttpPipeline buildPipeline(String endpoint,
HttpLogOptions httpLogOptions,
ClientOptions clientOptions,
HttpClient httpClient,
List<HttpPipelinePolicy> additionalPolicies,
RetryPolicy retryPolicy,
Configuration configuration,
Map<String, String> properties) {
List<HttpPipelinePolicy> policies = new ArrayList<>();
String clientName = properties.getOrDefault(SDK_NAME, "UnknownName");
String clientVersion = properties.getOrDefault(SDK_VERSION, "UnknownVersion");
String applicationId = clientOptions == null
? httpLogOptions.getApplicationId()
: clientOptions.getApplicationId();
policies.add(new UserAgentPolicy(applicationId, clientName, clientVersion, configuration));
policies.add(new RequestIdPolicy());
HttpPolicyProviders.addBeforeRetryPolicies(policies);
policies.add(retryPolicy);
policies.add(new AddDatePolicy());
policies.addAll(additionalPolicies);
if (clientOptions != null) {
List<HttpHeader> httpHeaderList = new ArrayList<>();
clientOptions.getHeaders().forEach(header ->
httpHeaderList.add(new HttpHeader(header.getName(), header.getValue())));
policies.add(new AddHeadersPolicy(new HttpHeaders(httpHeaderList)));
}
HttpPolicyProviders.addAfterRetryPolicies(policies);
policies.add(new HttpLoggingPolicy(httpLogOptions));
return new HttpPipelineBuilder()
.policies(policies.toArray(new HttpPipelinePolicy[0]))
.httpClient(httpClient)
.build();
}
/**
* Create a {@link ModelsRepotioryClient} based on the builder settings.
*
* @return the created synchronous ModelsRepotioryClient
*/
public ModelsRepotioryClient buildClient() {
return new ModelsRepotioryClient(buildAsyncClient());
}
/**
* Create a {@link ModelsRepositoryAsyncClient} based on the builder settings.
*
* @return the created asynchronous ModelsRepositoryAsyncClient
*/
/**
* Set the service endpoint that the built client will communicate with. This field is mandatory to set.
*
* @param endpoint URL of the service.
* @return the updated ModelsRepositoryClientBuilder instance for fluent building.
*/
public ModelsRepositoryClientBuilder endpoint(String endpoint) {
this.endpoint = endpoint;
return this;
}
/**
* Sets the {@link ModelsRepositoryServiceVersion} that is used when making API requests.
* <p>
* If a service version is not provided, the service version that will be used will be the latest known service
* version based on the version of the client library being used. If no service version is specified, updating to a
* newer version of the client library will have the result of potentially moving to a newer service version.
* <p>
* Targeting a specific service version may also mean that the service will return an error for newer APIs.
*
* @param serviceVersion The service API version to use.
* @return the updated ModelsRepositoryClientBuilder instance for fluent building.
*/
public ModelsRepositoryClientBuilder serviceVersion(ModelsRepositoryServiceVersion serviceVersion) {
this.serviceVersion = serviceVersion;
return this;
}
/**
* Sets the {@link HttpClient} to use for sending a receiving requests to and from the service.
*
* @param httpClient HttpClient to use for requests.
* @return the updated ModelsRepositoryClientBuilder instance for fluent building.
*/
public ModelsRepositoryClientBuilder httpClient(HttpClient httpClient) {
this.httpClient = httpClient;
return this;
}
/**
* Sets the {@link HttpLogOptions} for service requests.
*
* @param logOptions The logging configuration to use when sending and receiving HTTP requests/responses.
* @return the updated ModelsRepositoryClientBuilder instance for fluent building.
* @throws NullPointerException If {@code httpLogOptions} is {@code null}.
*/
public ModelsRepositoryClientBuilder httpLogOptions(HttpLogOptions logOptions) {
this.httpLogOptions = logOptions;
return this;
}
/**
* Adds a pipeline policy to apply on each request sent. The policy will be added after the retry policy. If
* the method is called multiple times, all policies will be added and their order preserved.
*
* @param pipelinePolicy a pipeline policy
* @return the updated ModelsRepositoryClientBuilder instance for fluent building.
* @throws NullPointerException If {@code pipelinePolicy} is {@code null}.
*/
public ModelsRepositoryClientBuilder addPolicy(HttpPipelinePolicy pipelinePolicy) {
this.additionalPolicies.add(Objects.requireNonNull(pipelinePolicy, "'pipelinePolicy' cannot be null"));
return this;
}
/**
* Sets the {@link HttpPipelinePolicy} that is used as the retry policy for each request that is sent.
*
* The default retry policy will be used if not provided. The default retry policy is {@link RetryPolicy
* For implementing custom retry logic, see {@link RetryPolicy} as an example.
*
* @param retryPolicy the retry policy applied to each request.
* @return The updated ConfigurationClientBuilder object.
*/
public ModelsRepositoryClientBuilder retryPolicy(RetryPolicy retryPolicy) {
this.retryPolicy = retryPolicy;
return this;
}
/**
* Sets the {@link HttpPipeline} to use for the service client.
* <p>
* If {@code pipeline} is set, all other settings are ignored, aside from {@link
*
* @param httpPipeline HttpPipeline to use for sending service requests and receiving responses.
* @return the updated ModelsRepositoryClientBuilder instance for fluent building.
*/
public ModelsRepositoryClientBuilder pipeline(HttpPipeline httpPipeline) {
this.httpPipeline = httpPipeline;
return this;
}
/**
* Sets the configuration store that is used during construction of the service client.
*
* The default configuration store is a clone of the {@link Configuration
* configuration store}, use {@link Configuration
*
* @param configuration The configuration store used to
* @return The updated ModelsRepositoryClientBuilder object for fluent building.
*/
public ModelsRepositoryClientBuilder configuration(Configuration configuration) {
this.configuration = configuration;
return this;
}
/**
* Custom JSON serializer that is used to handle model types that are not contained in the Azure Models Repository library.
*
* @param jsonSerializer The serializer to deserialize response payloads into user defined models.
* @return The updated ModelsRepositoryClientBuilder object.
*/
public ModelsRepositoryClientBuilder serializer(JsonSerializer jsonSerializer) {
this.jsonSerializer = jsonSerializer;
return this;
}
/**
* Sets the {@link ClientOptions} which enables various options to be set on the client. For example setting an
* {@code applicationId} using {@link ClientOptions
* the {@link UserAgentPolicy} for telemetry/monitoring purposes.
*
* <p>More About <a href="https:
*
* @param clientOptions the {@link ClientOptions} to be set on the client.
* @return The updated KeyClientBuilder object.
*/
public ModelsRepositoryClientBuilder clientOptions(ClientOptions clientOptions) {
this.clientOptions = clientOptions;
return this;
}
} |
There is no authentication support as of today. The global repository is also public and no credentials. | public ModelsRepositoryAsyncClient buildAsyncClient() {
Objects.requireNonNull(endpoint, "'endpoint' cannot be null");
Configuration buildConfiguration = this.configuration;
if (buildConfiguration == null)
{
buildConfiguration = Configuration.getGlobalConfiguration().clone();
}
ModelsRepositoryServiceVersion serviceVersion = this.serviceVersion;
if (serviceVersion == null)
{
serviceVersion = ModelsRepositoryServiceVersion.getLatest();
}
RetryPolicy retryPolicy = this.retryPolicy;
if (retryPolicy == null)
{
retryPolicy = DEFAULT_RETRY_POLICY;
}
if (this.httpPipeline == null) {
this.httpPipeline = buildPipeline(
this.endpoint,
this.httpLogOptions,
this.clientOptions,
this.httpClient,
this.additionalPolicies,
retryPolicy,
buildConfiguration,
this.properties);
}
return new ModelsRepositoryAsyncClient(this.endpoint, this.httpPipeline, serviceVersion, this.jsonSerializer);
} | Objects.requireNonNull(endpoint, "'endpoint' cannot be null"); | public ModelsRepositoryAsyncClient buildAsyncClient() {
Objects.requireNonNull(endpoint, "'endpoint' cannot be null");
Configuration buildConfiguration = this.configuration;
if (buildConfiguration == null)
{
buildConfiguration = Configuration.getGlobalConfiguration().clone();
}
ModelsRepositoryServiceVersion serviceVersion = this.serviceVersion;
if (serviceVersion == null)
{
serviceVersion = ModelsRepositoryServiceVersion.getLatest();
}
RetryPolicy retryPolicy = this.retryPolicy;
if (retryPolicy == null)
{
retryPolicy = DEFAULT_RETRY_POLICY;
}
if (this.httpPipeline == null) {
this.httpPipeline = buildPipeline(
this.endpoint,
this.httpLogOptions,
this.clientOptions,
this.httpClient,
this.additionalPolicies,
retryPolicy,
buildConfiguration,
this.properties);
}
return new ModelsRepositoryAsyncClient(this.endpoint, this.httpPipeline, serviceVersion, this.jsonSerializer);
} | class ModelsRepositoryClientBuilder {
private static final String MODELS_REPOSITORY_PROPERTIES = "azure-iot-modelsrepository.properties";
private static final String SDK_NAME = "name";
private static final String SDK_VERSION = "version";
private final List<HttpPipelinePolicy> additionalPolicies;
private String endpoint;
private ModelsRepositoryServiceVersion serviceVersion;
private ClientOptions clientOptions;
private HttpPipeline httpPipeline;
private HttpClient httpClient;
private HttpLogOptions httpLogOptions;
private RetryPolicy retryPolicy;
private JsonSerializer jsonSerializer;
private static final String retryAfterHeader = null;
private static final ChronoUnit retryAfterTimeUnit = null;
private static final RetryPolicy DEFAULT_RETRY_POLICY = new RetryPolicy(retryAfterHeader, retryAfterTimeUnit);
private final Map<String, String> properties;
private Configuration configuration;
/**
* The public constructor for ModelsRepositoryClientBuilder
*/
public ModelsRepositoryClientBuilder()
{
additionalPolicies = new ArrayList<>();
properties = CoreUtils.getProperties(MODELS_REPOSITORY_PROPERTIES);
httpLogOptions = new HttpLogOptions();
}
private static HttpPipeline buildPipeline(String endpoint,
HttpLogOptions httpLogOptions,
ClientOptions clientOptions,
HttpClient httpClient,
List<HttpPipelinePolicy> additionalPolicies,
RetryPolicy retryPolicy,
Configuration configuration,
Map<String, String> properties) {
List<HttpPipelinePolicy> policies = new ArrayList<>();
String clientName = properties.getOrDefault(SDK_NAME, "UnknownName");
String clientVersion = properties.getOrDefault(SDK_VERSION, "UnknownVersion");
String applicationId = clientOptions == null
? httpLogOptions.getApplicationId()
: clientOptions.getApplicationId();
policies.add(new UserAgentPolicy(applicationId, clientName, clientVersion, configuration));
policies.add(new RequestIdPolicy());
HttpPolicyProviders.addBeforeRetryPolicies(policies);
policies.add(retryPolicy);
policies.add(new AddDatePolicy());
policies.addAll(additionalPolicies);
if (clientOptions != null) {
List<HttpHeader> httpHeaderList = new ArrayList<>();
clientOptions.getHeaders().forEach(header ->
httpHeaderList.add(new HttpHeader(header.getName(), header.getValue())));
policies.add(new AddHeadersPolicy(new HttpHeaders(httpHeaderList)));
}
HttpPolicyProviders.addAfterRetryPolicies(policies);
policies.add(new HttpLoggingPolicy(httpLogOptions));
return new HttpPipelineBuilder()
.policies(policies.toArray(new HttpPipelinePolicy[0]))
.httpClient(httpClient)
.build();
}
/**
* Create a {@link ModelsRepotioryClient} based on the builder settings.
*
* @return the created synchronous ModelsRepotioryClient
*/
public ModelsRepotioryClient buildClient() {
return new ModelsRepotioryClient(buildAsyncClient());
}
/**
* Create a {@link ModelsRepositoryAsyncClient} based on the builder settings.
*
* @return the created asynchronous ModelsRepositoryAsyncClient
*/
/**
* Set the service endpoint that the built client will communicate with. This field is mandatory to set.
*
* @param endpoint URL of the service.
* @return the updated ModelsRepositoryClientBuilder instance for fluent building.
*/
public ModelsRepositoryClientBuilder endpoint(String endpoint) {
this.endpoint = endpoint;
return this;
}
/**
* Sets the {@link ModelsRepositoryServiceVersion} that is used when making API requests.
* <p>
* If a service version is not provided, the service version that will be used will be the latest known service
* version based on the version of the client library being used. If no service version is specified, updating to a
* newer version of the client library will have the result of potentially moving to a newer service version.
* <p>
* Targeting a specific service version may also mean that the service will return an error for newer APIs.
*
* @param serviceVersion The service API version to use.
* @return the updated ModelsRepositoryClientBuilder instance for fluent building.
*/
public ModelsRepositoryClientBuilder serviceVersion(ModelsRepositoryServiceVersion serviceVersion) {
this.serviceVersion = serviceVersion;
return this;
}
/**
* Sets the {@link HttpClient} to use for sending a receiving requests to and from the service.
*
* @param httpClient HttpClient to use for requests.
* @return the updated ModelsRepositoryClientBuilder instance for fluent building.
*/
public ModelsRepositoryClientBuilder httpClient(HttpClient httpClient) {
this.httpClient = httpClient;
return this;
}
/**
* Sets the {@link HttpLogOptions} for service requests.
*
* @param logOptions The logging configuration to use when sending and receiving HTTP requests/responses.
* @return the updated ModelsRepositoryClientBuilder instance for fluent building.
* @throws NullPointerException If {@code httpLogOptions} is {@code null}.
*/
public ModelsRepositoryClientBuilder httpLogOptions(HttpLogOptions logOptions) {
this.httpLogOptions = logOptions;
return this;
}
/**
* Adds a pipeline policy to apply on each request sent. The policy will be added after the retry policy. If
* the method is called multiple times, all policies will be added and their order preserved.
*
* @param pipelinePolicy a pipeline policy
* @return the updated ModelsRepositoryClientBuilder instance for fluent building.
* @throws NullPointerException If {@code pipelinePolicy} is {@code null}.
*/
public ModelsRepositoryClientBuilder addPolicy(HttpPipelinePolicy pipelinePolicy) {
this.additionalPolicies.add(Objects.requireNonNull(pipelinePolicy, "'pipelinePolicy' cannot be null"));
return this;
}
/**
* Sets the {@link HttpPipelinePolicy} that is used as the retry policy for each request that is sent.
*
* The default retry policy will be used if not provided. The default retry policy is {@link RetryPolicy
* For implementing custom retry logic, see {@link RetryPolicy} as an example.
*
* @param retryPolicy the retry policy applied to each request.
* @return The updated ConfigurationClientBuilder object.
*/
public ModelsRepositoryClientBuilder retryPolicy(RetryPolicy retryPolicy) {
this.retryPolicy = retryPolicy;
return this;
}
/**
* Sets the {@link HttpPipeline} to use for the service client.
* <p>
* If {@code pipeline} is set, all other settings are ignored, aside from {@link
*
* @param httpPipeline HttpPipeline to use for sending service requests and receiving responses.
* @return the updated ModelsRepositoryClientBuilder instance for fluent building.
*/
public ModelsRepositoryClientBuilder pipeline(HttpPipeline httpPipeline) {
this.httpPipeline = httpPipeline;
return this;
}
/**
* Sets the configuration store that is used during construction of the service client.
*
* The default configuration store is a clone of the {@link Configuration
* configuration store}, use {@link Configuration
*
* @param configuration The configuration store used to
* @return The updated ModelsRepositoryClientBuilder object for fluent building.
*/
public ModelsRepositoryClientBuilder configuration(Configuration configuration) {
this.configuration = configuration;
return this;
}
/**
* Custom JSON serializer that is used to handle model types that are not contained in the Azure Models Repository library.
*
* @param jsonSerializer The serializer to deserialize response payloads into user defined models.
* @return The updated ModelsRepositoryClientBuilder object.
*/
public ModelsRepositoryClientBuilder serializer(JsonSerializer jsonSerializer) {
this.jsonSerializer = jsonSerializer;
return this;
}
/**
* Sets the {@link ClientOptions} which enables various options to be set on the client. For example setting an
* {@code applicationId} using {@link ClientOptions
* the {@link UserAgentPolicy} for telemetry/monitoring purposes.
*
* <p>More About <a href="https:
*
* @param clientOptions the {@link ClientOptions} to be set on the client.
* @return The updated KeyClientBuilder object.
*/
public ModelsRepositoryClientBuilder clientOptions(ClientOptions clientOptions) {
this.clientOptions = clientOptions;
return this;
}
} | class ModelsRepositoryClientBuilder {
private static final String MODELS_REPOSITORY_PROPERTIES = "azure-iot-modelsrepository.properties";
private static final String SDK_NAME = "name";
private static final String SDK_VERSION = "version";
private final List<HttpPipelinePolicy> additionalPolicies;
private String endpoint;
private ModelsRepositoryServiceVersion serviceVersion;
private ClientOptions clientOptions;
private HttpPipeline httpPipeline;
private HttpClient httpClient;
private HttpLogOptions httpLogOptions;
private RetryPolicy retryPolicy;
private JsonSerializer jsonSerializer;
private static final String retryAfterHeader = null;
private static final ChronoUnit retryAfterTimeUnit = null;
private static final RetryPolicy DEFAULT_RETRY_POLICY = new RetryPolicy(retryAfterHeader, retryAfterTimeUnit);
private final Map<String, String> properties;
private Configuration configuration;
/**
* The public constructor for ModelsRepositoryClientBuilder
*/
public ModelsRepositoryClientBuilder()
{
additionalPolicies = new ArrayList<>();
properties = CoreUtils.getProperties(MODELS_REPOSITORY_PROPERTIES);
httpLogOptions = new HttpLogOptions();
}
private static HttpPipeline buildPipeline(String endpoint,
HttpLogOptions httpLogOptions,
ClientOptions clientOptions,
HttpClient httpClient,
List<HttpPipelinePolicy> additionalPolicies,
RetryPolicy retryPolicy,
Configuration configuration,
Map<String, String> properties) {
List<HttpPipelinePolicy> policies = new ArrayList<>();
String clientName = properties.getOrDefault(SDK_NAME, "UnknownName");
String clientVersion = properties.getOrDefault(SDK_VERSION, "UnknownVersion");
String applicationId = clientOptions == null
? httpLogOptions.getApplicationId()
: clientOptions.getApplicationId();
policies.add(new UserAgentPolicy(applicationId, clientName, clientVersion, configuration));
policies.add(new RequestIdPolicy());
HttpPolicyProviders.addBeforeRetryPolicies(policies);
policies.add(retryPolicy);
policies.add(new AddDatePolicy());
policies.addAll(additionalPolicies);
if (clientOptions != null) {
List<HttpHeader> httpHeaderList = new ArrayList<>();
clientOptions.getHeaders().forEach(header ->
httpHeaderList.add(new HttpHeader(header.getName(), header.getValue())));
policies.add(new AddHeadersPolicy(new HttpHeaders(httpHeaderList)));
}
HttpPolicyProviders.addAfterRetryPolicies(policies);
policies.add(new HttpLoggingPolicy(httpLogOptions));
return new HttpPipelineBuilder()
.policies(policies.toArray(new HttpPipelinePolicy[0]))
.httpClient(httpClient)
.build();
}
/**
* Create a {@link ModelsRepotioryClient} based on the builder settings.
*
* @return the created synchronous ModelsRepotioryClient
*/
public ModelsRepotioryClient buildClient() {
return new ModelsRepotioryClient(buildAsyncClient());
}
/**
* Create a {@link ModelsRepositoryAsyncClient} based on the builder settings.
*
* @return the created asynchronous ModelsRepositoryAsyncClient
*/
/**
* Set the service endpoint that the built client will communicate with. This field is mandatory to set.
*
* @param endpoint URL of the service.
* @return the updated ModelsRepositoryClientBuilder instance for fluent building.
*/
public ModelsRepositoryClientBuilder endpoint(String endpoint) {
this.endpoint = endpoint;
return this;
}
/**
* Sets the {@link ModelsRepositoryServiceVersion} that is used when making API requests.
* <p>
* If a service version is not provided, the service version that will be used will be the latest known service
* version based on the version of the client library being used. If no service version is specified, updating to a
* newer version of the client library will have the result of potentially moving to a newer service version.
* <p>
* Targeting a specific service version may also mean that the service will return an error for newer APIs.
*
* @param serviceVersion The service API version to use.
* @return the updated ModelsRepositoryClientBuilder instance for fluent building.
*/
public ModelsRepositoryClientBuilder serviceVersion(ModelsRepositoryServiceVersion serviceVersion) {
this.serviceVersion = serviceVersion;
return this;
}
/**
* Sets the {@link HttpClient} to use for sending a receiving requests to and from the service.
*
* @param httpClient HttpClient to use for requests.
* @return the updated ModelsRepositoryClientBuilder instance for fluent building.
*/
public ModelsRepositoryClientBuilder httpClient(HttpClient httpClient) {
this.httpClient = httpClient;
return this;
}
/**
* Sets the {@link HttpLogOptions} for service requests.
*
* @param logOptions The logging configuration to use when sending and receiving HTTP requests/responses.
* @return the updated ModelsRepositoryClientBuilder instance for fluent building.
* @throws NullPointerException If {@code httpLogOptions} is {@code null}.
*/
public ModelsRepositoryClientBuilder httpLogOptions(HttpLogOptions logOptions) {
this.httpLogOptions = logOptions;
return this;
}
/**
* Adds a pipeline policy to apply on each request sent. The policy will be added after the retry policy. If
* the method is called multiple times, all policies will be added and their order preserved.
*
* @param pipelinePolicy a pipeline policy
* @return the updated ModelsRepositoryClientBuilder instance for fluent building.
* @throws NullPointerException If {@code pipelinePolicy} is {@code null}.
*/
public ModelsRepositoryClientBuilder addPolicy(HttpPipelinePolicy pipelinePolicy) {
this.additionalPolicies.add(Objects.requireNonNull(pipelinePolicy, "'pipelinePolicy' cannot be null"));
return this;
}
/**
* Sets the {@link HttpPipelinePolicy} that is used as the retry policy for each request that is sent.
*
* The default retry policy will be used if not provided. The default retry policy is {@link RetryPolicy
* For implementing custom retry logic, see {@link RetryPolicy} as an example.
*
* @param retryPolicy the retry policy applied to each request.
* @return The updated ConfigurationClientBuilder object.
*/
public ModelsRepositoryClientBuilder retryPolicy(RetryPolicy retryPolicy) {
this.retryPolicy = retryPolicy;
return this;
}
/**
* Sets the {@link HttpPipeline} to use for the service client.
* <p>
* If {@code pipeline} is set, all other settings are ignored, aside from {@link
*
* @param httpPipeline HttpPipeline to use for sending service requests and receiving responses.
* @return the updated ModelsRepositoryClientBuilder instance for fluent building.
*/
public ModelsRepositoryClientBuilder pipeline(HttpPipeline httpPipeline) {
this.httpPipeline = httpPipeline;
return this;
}
/**
* Sets the configuration store that is used during construction of the service client.
*
* The default configuration store is a clone of the {@link Configuration
* configuration store}, use {@link Configuration
*
* @param configuration The configuration store used to
* @return The updated ModelsRepositoryClientBuilder object for fluent building.
*/
public ModelsRepositoryClientBuilder configuration(Configuration configuration) {
this.configuration = configuration;
return this;
}
/**
* Custom JSON serializer that is used to handle model types that are not contained in the Azure Models Repository library.
*
* @param jsonSerializer The serializer to deserialize response payloads into user defined models.
* @return The updated ModelsRepositoryClientBuilder object.
*/
public ModelsRepositoryClientBuilder serializer(JsonSerializer jsonSerializer) {
this.jsonSerializer = jsonSerializer;
return this;
}
/**
* Sets the {@link ClientOptions} which enables various options to be set on the client. For example setting an
* {@code applicationId} using {@link ClientOptions
* the {@link UserAgentPolicy} for telemetry/monitoring purposes.
*
* <p>More About <a href="https:
*
* @param clientOptions the {@link ClientOptions} to be set on the client.
* @return The updated KeyClientBuilder object.
*/
public ModelsRepositoryClientBuilder clientOptions(ClientOptions clientOptions) {
this.clientOptions = clientOptions;
return this;
}
} |
Interesting. Got it! | public ModelsRepositoryAsyncClient buildAsyncClient() {
Objects.requireNonNull(endpoint, "'endpoint' cannot be null");
Configuration buildConfiguration = this.configuration;
if (buildConfiguration == null)
{
buildConfiguration = Configuration.getGlobalConfiguration().clone();
}
ModelsRepositoryServiceVersion serviceVersion = this.serviceVersion;
if (serviceVersion == null)
{
serviceVersion = ModelsRepositoryServiceVersion.getLatest();
}
RetryPolicy retryPolicy = this.retryPolicy;
if (retryPolicy == null)
{
retryPolicy = DEFAULT_RETRY_POLICY;
}
if (this.httpPipeline == null) {
this.httpPipeline = buildPipeline(
this.endpoint,
this.httpLogOptions,
this.clientOptions,
this.httpClient,
this.additionalPolicies,
retryPolicy,
buildConfiguration,
this.properties);
}
return new ModelsRepositoryAsyncClient(this.endpoint, this.httpPipeline, serviceVersion, this.jsonSerializer);
} | Objects.requireNonNull(endpoint, "'endpoint' cannot be null"); | public ModelsRepositoryAsyncClient buildAsyncClient() {
Objects.requireNonNull(endpoint, "'endpoint' cannot be null");
Configuration buildConfiguration = this.configuration;
if (buildConfiguration == null)
{
buildConfiguration = Configuration.getGlobalConfiguration().clone();
}
ModelsRepositoryServiceVersion serviceVersion = this.serviceVersion;
if (serviceVersion == null)
{
serviceVersion = ModelsRepositoryServiceVersion.getLatest();
}
RetryPolicy retryPolicy = this.retryPolicy;
if (retryPolicy == null)
{
retryPolicy = DEFAULT_RETRY_POLICY;
}
if (this.httpPipeline == null) {
this.httpPipeline = buildPipeline(
this.endpoint,
this.httpLogOptions,
this.clientOptions,
this.httpClient,
this.additionalPolicies,
retryPolicy,
buildConfiguration,
this.properties);
}
return new ModelsRepositoryAsyncClient(this.endpoint, this.httpPipeline, serviceVersion, this.jsonSerializer);
} | class ModelsRepositoryClientBuilder {
private static final String MODELS_REPOSITORY_PROPERTIES = "azure-iot-modelsrepository.properties";
private static final String SDK_NAME = "name";
private static final String SDK_VERSION = "version";
private final List<HttpPipelinePolicy> additionalPolicies;
private String endpoint;
private ModelsRepositoryServiceVersion serviceVersion;
private ClientOptions clientOptions;
private HttpPipeline httpPipeline;
private HttpClient httpClient;
private HttpLogOptions httpLogOptions;
private RetryPolicy retryPolicy;
private JsonSerializer jsonSerializer;
private static final String retryAfterHeader = null;
private static final ChronoUnit retryAfterTimeUnit = null;
private static final RetryPolicy DEFAULT_RETRY_POLICY = new RetryPolicy(retryAfterHeader, retryAfterTimeUnit);
private final Map<String, String> properties;
private Configuration configuration;
/**
* The public constructor for ModelsRepositoryClientBuilder
*/
public ModelsRepositoryClientBuilder()
{
additionalPolicies = new ArrayList<>();
properties = CoreUtils.getProperties(MODELS_REPOSITORY_PROPERTIES);
httpLogOptions = new HttpLogOptions();
}
private static HttpPipeline buildPipeline(String endpoint,
HttpLogOptions httpLogOptions,
ClientOptions clientOptions,
HttpClient httpClient,
List<HttpPipelinePolicy> additionalPolicies,
RetryPolicy retryPolicy,
Configuration configuration,
Map<String, String> properties) {
List<HttpPipelinePolicy> policies = new ArrayList<>();
String clientName = properties.getOrDefault(SDK_NAME, "UnknownName");
String clientVersion = properties.getOrDefault(SDK_VERSION, "UnknownVersion");
String applicationId = clientOptions == null
? httpLogOptions.getApplicationId()
: clientOptions.getApplicationId();
policies.add(new UserAgentPolicy(applicationId, clientName, clientVersion, configuration));
policies.add(new RequestIdPolicy());
HttpPolicyProviders.addBeforeRetryPolicies(policies);
policies.add(retryPolicy);
policies.add(new AddDatePolicy());
policies.addAll(additionalPolicies);
if (clientOptions != null) {
List<HttpHeader> httpHeaderList = new ArrayList<>();
clientOptions.getHeaders().forEach(header ->
httpHeaderList.add(new HttpHeader(header.getName(), header.getValue())));
policies.add(new AddHeadersPolicy(new HttpHeaders(httpHeaderList)));
}
HttpPolicyProviders.addAfterRetryPolicies(policies);
policies.add(new HttpLoggingPolicy(httpLogOptions));
return new HttpPipelineBuilder()
.policies(policies.toArray(new HttpPipelinePolicy[0]))
.httpClient(httpClient)
.build();
}
/**
* Create a {@link ModelsRepotioryClient} based on the builder settings.
*
* @return the created synchronous ModelsRepotioryClient
*/
public ModelsRepotioryClient buildClient() {
return new ModelsRepotioryClient(buildAsyncClient());
}
/**
* Create a {@link ModelsRepositoryAsyncClient} based on the builder settings.
*
* @return the created asynchronous ModelsRepositoryAsyncClient
*/
/**
* Set the service endpoint that the built client will communicate with. This field is mandatory to set.
*
* @param endpoint URL of the service.
* @return the updated ModelsRepositoryClientBuilder instance for fluent building.
*/
public ModelsRepositoryClientBuilder endpoint(String endpoint) {
this.endpoint = endpoint;
return this;
}
/**
* Sets the {@link ModelsRepositoryServiceVersion} that is used when making API requests.
* <p>
* If a service version is not provided, the service version that will be used will be the latest known service
* version based on the version of the client library being used. If no service version is specified, updating to a
* newer version of the client library will have the result of potentially moving to a newer service version.
* <p>
* Targeting a specific service version may also mean that the service will return an error for newer APIs.
*
* @param serviceVersion The service API version to use.
* @return the updated ModelsRepositoryClientBuilder instance for fluent building.
*/
public ModelsRepositoryClientBuilder serviceVersion(ModelsRepositoryServiceVersion serviceVersion) {
this.serviceVersion = serviceVersion;
return this;
}
/**
* Sets the {@link HttpClient} to use for sending a receiving requests to and from the service.
*
* @param httpClient HttpClient to use for requests.
* @return the updated ModelsRepositoryClientBuilder instance for fluent building.
*/
public ModelsRepositoryClientBuilder httpClient(HttpClient httpClient) {
this.httpClient = httpClient;
return this;
}
/**
* Sets the {@link HttpLogOptions} for service requests.
*
* @param logOptions The logging configuration to use when sending and receiving HTTP requests/responses.
* @return the updated ModelsRepositoryClientBuilder instance for fluent building.
* @throws NullPointerException If {@code httpLogOptions} is {@code null}.
*/
public ModelsRepositoryClientBuilder httpLogOptions(HttpLogOptions logOptions) {
this.httpLogOptions = logOptions;
return this;
}
/**
* Adds a pipeline policy to apply on each request sent. The policy will be added after the retry policy. If
* the method is called multiple times, all policies will be added and their order preserved.
*
* @param pipelinePolicy a pipeline policy
* @return the updated ModelsRepositoryClientBuilder instance for fluent building.
* @throws NullPointerException If {@code pipelinePolicy} is {@code null}.
*/
public ModelsRepositoryClientBuilder addPolicy(HttpPipelinePolicy pipelinePolicy) {
this.additionalPolicies.add(Objects.requireNonNull(pipelinePolicy, "'pipelinePolicy' cannot be null"));
return this;
}
/**
* Sets the {@link HttpPipelinePolicy} that is used as the retry policy for each request that is sent.
*
* The default retry policy will be used if not provided. The default retry policy is {@link RetryPolicy
* For implementing custom retry logic, see {@link RetryPolicy} as an example.
*
* @param retryPolicy the retry policy applied to each request.
* @return The updated ConfigurationClientBuilder object.
*/
public ModelsRepositoryClientBuilder retryPolicy(RetryPolicy retryPolicy) {
this.retryPolicy = retryPolicy;
return this;
}
/**
* Sets the {@link HttpPipeline} to use for the service client.
* <p>
* If {@code pipeline} is set, all other settings are ignored, aside from {@link
*
* @param httpPipeline HttpPipeline to use for sending service requests and receiving responses.
* @return the updated ModelsRepositoryClientBuilder instance for fluent building.
*/
public ModelsRepositoryClientBuilder pipeline(HttpPipeline httpPipeline) {
this.httpPipeline = httpPipeline;
return this;
}
/**
* Sets the configuration store that is used during construction of the service client.
*
* The default configuration store is a clone of the {@link Configuration
* configuration store}, use {@link Configuration
*
* @param configuration The configuration store used to
* @return The updated ModelsRepositoryClientBuilder object for fluent building.
*/
public ModelsRepositoryClientBuilder configuration(Configuration configuration) {
this.configuration = configuration;
return this;
}
/**
* Custom JSON serializer that is used to handle model types that are not contained in the Azure Models Repository library.
*
* @param jsonSerializer The serializer to deserialize response payloads into user defined models.
* @return The updated ModelsRepositoryClientBuilder object.
*/
public ModelsRepositoryClientBuilder serializer(JsonSerializer jsonSerializer) {
this.jsonSerializer = jsonSerializer;
return this;
}
/**
* Sets the {@link ClientOptions} which enables various options to be set on the client. For example setting an
* {@code applicationId} using {@link ClientOptions
* the {@link UserAgentPolicy} for telemetry/monitoring purposes.
*
* <p>More About <a href="https:
*
* @param clientOptions the {@link ClientOptions} to be set on the client.
* @return The updated KeyClientBuilder object.
*/
public ModelsRepositoryClientBuilder clientOptions(ClientOptions clientOptions) {
this.clientOptions = clientOptions;
return this;
}
} | class ModelsRepositoryClientBuilder {
private static final String MODELS_REPOSITORY_PROPERTIES = "azure-iot-modelsrepository.properties";
private static final String SDK_NAME = "name";
private static final String SDK_VERSION = "version";
private final List<HttpPipelinePolicy> additionalPolicies;
private String endpoint;
private ModelsRepositoryServiceVersion serviceVersion;
private ClientOptions clientOptions;
private HttpPipeline httpPipeline;
private HttpClient httpClient;
private HttpLogOptions httpLogOptions;
private RetryPolicy retryPolicy;
private JsonSerializer jsonSerializer;
private static final String retryAfterHeader = null;
private static final ChronoUnit retryAfterTimeUnit = null;
private static final RetryPolicy DEFAULT_RETRY_POLICY = new RetryPolicy(retryAfterHeader, retryAfterTimeUnit);
private final Map<String, String> properties;
private Configuration configuration;
/**
* The public constructor for ModelsRepositoryClientBuilder
*/
public ModelsRepositoryClientBuilder()
{
additionalPolicies = new ArrayList<>();
properties = CoreUtils.getProperties(MODELS_REPOSITORY_PROPERTIES);
httpLogOptions = new HttpLogOptions();
}
private static HttpPipeline buildPipeline(String endpoint,
HttpLogOptions httpLogOptions,
ClientOptions clientOptions,
HttpClient httpClient,
List<HttpPipelinePolicy> additionalPolicies,
RetryPolicy retryPolicy,
Configuration configuration,
Map<String, String> properties) {
List<HttpPipelinePolicy> policies = new ArrayList<>();
String clientName = properties.getOrDefault(SDK_NAME, "UnknownName");
String clientVersion = properties.getOrDefault(SDK_VERSION, "UnknownVersion");
String applicationId = clientOptions == null
? httpLogOptions.getApplicationId()
: clientOptions.getApplicationId();
policies.add(new UserAgentPolicy(applicationId, clientName, clientVersion, configuration));
policies.add(new RequestIdPolicy());
HttpPolicyProviders.addBeforeRetryPolicies(policies);
policies.add(retryPolicy);
policies.add(new AddDatePolicy());
policies.addAll(additionalPolicies);
if (clientOptions != null) {
List<HttpHeader> httpHeaderList = new ArrayList<>();
clientOptions.getHeaders().forEach(header ->
httpHeaderList.add(new HttpHeader(header.getName(), header.getValue())));
policies.add(new AddHeadersPolicy(new HttpHeaders(httpHeaderList)));
}
HttpPolicyProviders.addAfterRetryPolicies(policies);
policies.add(new HttpLoggingPolicy(httpLogOptions));
return new HttpPipelineBuilder()
.policies(policies.toArray(new HttpPipelinePolicy[0]))
.httpClient(httpClient)
.build();
}
/**
* Create a {@link ModelsRepotioryClient} based on the builder settings.
*
* @return the created synchronous ModelsRepotioryClient
*/
public ModelsRepotioryClient buildClient() {
return new ModelsRepotioryClient(buildAsyncClient());
}
/**
* Create a {@link ModelsRepositoryAsyncClient} based on the builder settings.
*
* @return the created asynchronous ModelsRepositoryAsyncClient
*/
/**
* Set the service endpoint that the built client will communicate with. This field is mandatory to set.
*
* @param endpoint URL of the service.
* @return the updated ModelsRepositoryClientBuilder instance for fluent building.
*/
public ModelsRepositoryClientBuilder endpoint(String endpoint) {
this.endpoint = endpoint;
return this;
}
/**
* Sets the {@link ModelsRepositoryServiceVersion} that is used when making API requests.
* <p>
* If a service version is not provided, the service version that will be used will be the latest known service
* version based on the version of the client library being used. If no service version is specified, updating to a
* newer version of the client library will have the result of potentially moving to a newer service version.
* <p>
* Targeting a specific service version may also mean that the service will return an error for newer APIs.
*
* @param serviceVersion The service API version to use.
* @return the updated ModelsRepositoryClientBuilder instance for fluent building.
*/
public ModelsRepositoryClientBuilder serviceVersion(ModelsRepositoryServiceVersion serviceVersion) {
this.serviceVersion = serviceVersion;
return this;
}
/**
* Sets the {@link HttpClient} to use for sending a receiving requests to and from the service.
*
* @param httpClient HttpClient to use for requests.
* @return the updated ModelsRepositoryClientBuilder instance for fluent building.
*/
public ModelsRepositoryClientBuilder httpClient(HttpClient httpClient) {
this.httpClient = httpClient;
return this;
}
/**
* Sets the {@link HttpLogOptions} for service requests.
*
* @param logOptions The logging configuration to use when sending and receiving HTTP requests/responses.
* @return the updated ModelsRepositoryClientBuilder instance for fluent building.
* @throws NullPointerException If {@code httpLogOptions} is {@code null}.
*/
public ModelsRepositoryClientBuilder httpLogOptions(HttpLogOptions logOptions) {
this.httpLogOptions = logOptions;
return this;
}
/**
* Adds a pipeline policy to apply on each request sent. The policy will be added after the retry policy. If
* the method is called multiple times, all policies will be added and their order preserved.
*
* @param pipelinePolicy a pipeline policy
* @return the updated ModelsRepositoryClientBuilder instance for fluent building.
* @throws NullPointerException If {@code pipelinePolicy} is {@code null}.
*/
public ModelsRepositoryClientBuilder addPolicy(HttpPipelinePolicy pipelinePolicy) {
this.additionalPolicies.add(Objects.requireNonNull(pipelinePolicy, "'pipelinePolicy' cannot be null"));
return this;
}
/**
* Sets the {@link HttpPipelinePolicy} that is used as the retry policy for each request that is sent.
*
* The default retry policy will be used if not provided. The default retry policy is {@link RetryPolicy
* For implementing custom retry logic, see {@link RetryPolicy} as an example.
*
* @param retryPolicy the retry policy applied to each request.
* @return The updated ConfigurationClientBuilder object.
*/
public ModelsRepositoryClientBuilder retryPolicy(RetryPolicy retryPolicy) {
this.retryPolicy = retryPolicy;
return this;
}
/**
* Sets the {@link HttpPipeline} to use for the service client.
* <p>
* If {@code pipeline} is set, all other settings are ignored, aside from {@link
*
* @param httpPipeline HttpPipeline to use for sending service requests and receiving responses.
* @return the updated ModelsRepositoryClientBuilder instance for fluent building.
*/
public ModelsRepositoryClientBuilder pipeline(HttpPipeline httpPipeline) {
this.httpPipeline = httpPipeline;
return this;
}
/**
* Sets the configuration store that is used during construction of the service client.
*
* The default configuration store is a clone of the {@link Configuration
* configuration store}, use {@link Configuration
*
* @param configuration The configuration store used to
* @return The updated ModelsRepositoryClientBuilder object for fluent building.
*/
public ModelsRepositoryClientBuilder configuration(Configuration configuration) {
this.configuration = configuration;
return this;
}
/**
* Custom JSON serializer that is used to handle model types that are not contained in the Azure Models Repository library.
*
* @param jsonSerializer The serializer to deserialize response payloads into user defined models.
* @return The updated ModelsRepositoryClientBuilder object.
*/
public ModelsRepositoryClientBuilder serializer(JsonSerializer jsonSerializer) {
this.jsonSerializer = jsonSerializer;
return this;
}
/**
* Sets the {@link ClientOptions} which enables various options to be set on the client. For example setting an
* {@code applicationId} using {@link ClientOptions
* the {@link UserAgentPolicy} for telemetry/monitoring purposes.
*
* <p>More About <a href="https:
*
* @param clientOptions the {@link ClientOptions} to be set on the client.
* @return The updated KeyClientBuilder object.
*/
public ModelsRepositoryClientBuilder clientOptions(ClientOptions clientOptions) {
this.clientOptions = clientOptions;
return this;
}
} |
this comment was moved to `minimalParse` method which is a better place ```suggestion ``` | private void export(SpanData span, List<TelemetryItem> telemetryItems) {
SpanKind kind = span.getKind();
String instrumentationName = span.getInstrumentationLibraryInfo().getName();
Matcher matcher = COMPONENT_PATTERN.matcher(instrumentationName);
String stdComponent = matcher.matches() ? matcher.group(1) : null;
if (kind == SpanKind.INTERNAL) {
if ("spring-scheduling".equals(stdComponent) && !span.getParentSpanContext().isValid()) {
exportRequest(span, telemetryItems);
} else {
exportRemoteDependency(span, true, telemetryItems);
}
} else if (kind == SpanKind.CLIENT || kind == SpanKind.PRODUCER) {
exportRemoteDependency(span, false, telemetryItems);
} else if (kind == SpanKind.CONSUMER && !span.getParentSpanContext().isRemote()) {
exportRemoteDependency(span, false, telemetryItems);
} else if (kind == SpanKind.SERVER || kind == SpanKind.CONSUMER) {
exportRequest(span, telemetryItems);
} else {
throw logger.logExceptionAsError(new UnsupportedOperationException(kind.name()));
}
}
private static List<TelemetryExceptionDetails> minimalParse(String errorStack) {
TelemetryExceptionDetails details = new TelemetryExceptionDetails();
String line = errorStack.split(System.lineSeparator())[0];
int index = line.indexOf(": ");
if (index != -1) {
details.setTypeName(line.substring(0, index));
details.setMessage(line.substring(index + 2));
} else {
details.setTypeName(line);
}
details.setStack(errorStack);
return Collections.singletonList(details);
}
private void exportRemoteDependency(SpanData span, boolean inProc,
List<TelemetryItem> telemetryItems) {
TelemetryItem telemetryItem = new TelemetryItem();
RemoteDependencyData remoteDependencyData = new RemoteDependencyData();
MonitorBase monitorBase = new MonitorBase();
telemetryItem.setTags(new HashMap<>());
telemetryItem.setName(telemetryItemNamePrefix + "RemoteDependency");
telemetryItem.setVersion(1);
telemetryItem.setInstrumentationKey(instrumentationKey);
telemetryItem.setData(monitorBase);
remoteDependencyData.setProperties(new HashMap<>());
remoteDependencyData.setVersion(2);
monitorBase.setBaseType("RemoteDependencyData");
monitorBase.setBaseData(remoteDependencyData);
addLinks(remoteDependencyData.getProperties(), span.getLinks());
remoteDependencyData.setName(span.getName());
Attributes attributes = span.getAttributes();
if (inProc) {
remoteDependencyData.setType("InProc");
} else {
applySemanticConventions(attributes, remoteDependencyData, span.getKind());
}
remoteDependencyData.setId(span.getSpanId());
telemetryItem.getTags().put(ContextTagKeys.AI_OPERATION_ID.toString(), span.getTraceId());
String parentSpanId = span.getParentSpanId();
if (SpanId.isValid(parentSpanId)) {
telemetryItem.getTags().put(ContextTagKeys.AI_OPERATION_PARENT_ID.toString(), parentSpanId);
}
telemetryItem.setTime(getFormattedTime(span.getStartEpochNanos()));
remoteDependencyData
.setDuration(getFormattedDuration(Duration.ofNanos(span.getEndEpochNanos() - span.getStartEpochNanos())));
remoteDependencyData.setSuccess(span.getStatus().getStatusCode() != StatusCode.ERROR);
setExtraAttributes(telemetryItem, remoteDependencyData.getProperties(), attributes);
Double samplingPercentage = 100.0;
telemetryItem.setSampleRate(samplingPercentage.floatValue());
telemetryItems.add(telemetryItem);
exportEvents(span, samplingPercentage, telemetryItems);
}
private void applySemanticConventions(Attributes attributes, RemoteDependencyData remoteDependencyData, SpanKind spanKind) {
String httpMethod = attributes.get(SemanticAttributes.HTTP_METHOD);
if (httpMethod != null) {
applyHttpClientSpan(attributes, remoteDependencyData);
return;
}
String rpcSystem = attributes.get(SemanticAttributes.RPC_SYSTEM);
if (rpcSystem != null) {
applyRpcClientSpan(attributes, remoteDependencyData, rpcSystem);
return;
}
String dbSystem = attributes.get(SemanticAttributes.DB_SYSTEM);
if (dbSystem != null) {
applyDatabaseClientSpan(attributes, remoteDependencyData, dbSystem);
return;
}
String messagingSystem = attributes.get(SemanticAttributes.MESSAGING_SYSTEM);
if (messagingSystem != null) {
applyMessagingClientSpan(attributes, remoteDependencyData, messagingSystem, spanKind);
return;
}
}
private void applyHttpClientSpan(Attributes attributes, RemoteDependencyData telemetry) {
String scheme = attributes.get(SemanticAttributes.HTTP_SCHEME);
int defaultPort;
if ("http".equals(scheme)) {
defaultPort = 80;
} else if ("https".equals(scheme)) {
defaultPort = 443;
} else {
defaultPort = 0;
}
String target = getTargetFromPeerAttributes(attributes, defaultPort);
if (target == null) {
target = attributes.get(SemanticAttributes.HTTP_HOST);
}
String url = attributes.get(SemanticAttributes.HTTP_URL);
if (target == null && url != null) {
try {
URI uri = new URI(url);
target = uri.getHost();
if (uri.getPort() != 80 && uri.getPort() != 443 && uri.getPort() != -1) {
target += ":" + uri.getPort();
}
} catch (URISyntaxException e) {
logger.error(e.getMessage());
logger.verbose(e.getMessage(), e);
}
}
if (target == null) {
target = "Http";
}
String targetAppId = attributes.get(AI_SPAN_TARGET_APP_ID_KEY);
if (targetAppId == null) {
telemetry.setType("Http");
telemetry.setTarget(target);
} else {
telemetry.setType("Http (tracked component)");
telemetry.setTarget(target + " | " + targetAppId);
}
Long httpStatusCode = attributes.get(SemanticAttributes.HTTP_STATUS_CODE);
if (httpStatusCode != null) {
telemetry.setResultCode(Long.toString(httpStatusCode));
}
telemetry.setData(url);
}
private static String getTargetFromPeerAttributes(Attributes attributes, int defaultPort) {
String target = attributes.get(SemanticAttributes.PEER_SERVICE);
if (target != null) {
return target;
}
target = attributes.get(SemanticAttributes.NET_PEER_NAME);
if (target == null) {
target = attributes.get(SemanticAttributes.NET_PEER_IP);
}
if (target == null) {
return null;
}
Long port = attributes.get(SemanticAttributes.NET_PEER_PORT);
if (port != null && port != defaultPort) {
return target + ":" + port;
}
return target;
}
private static void applyRpcClientSpan(Attributes attributes, RemoteDependencyData telemetry, String rpcSystem) {
telemetry.setType(rpcSystem);
String target = getTargetFromPeerAttributes(attributes, 0);
if (target == null) {
target = rpcSystem;
}
telemetry.setTarget(target);
}
private static void applyDatabaseClientSpan(Attributes attributes, RemoteDependencyData telemetry, String dbSystem) {
String dbStatement = attributes.get(SemanticAttributes.DB_STATEMENT);
String type;
if (SQL_DB_SYSTEMS.contains(dbSystem)) {
type = "SQL";
telemetry.setName(dbStatement);
} else {
type = dbSystem;
}
telemetry.setType(type);
telemetry.setData(dbStatement);
String target = nullAwareConcat(getTargetFromPeerAttributes(attributes, getDefaultPortForDbSystem(dbSystem)),
attributes.get(SemanticAttributes.DB_NAME), "/");
if (target == null) {
target = dbSystem;
}
telemetry.setTarget(target);
}
private void applyMessagingClientSpan(Attributes attributes, RemoteDependencyData telemetry, String messagingSystem, SpanKind spanKind) {
if (spanKind == SpanKind.PRODUCER) {
telemetry.setType("Queue Message | " + messagingSystem);
} else {
telemetry.setType(messagingSystem);
}
String destination = attributes.get(SemanticAttributes.MESSAGING_DESTINATION);
if (destination != null) {
telemetry.setTarget(destination);
} else {
telemetry.setTarget(messagingSystem);
}
}
private static int getDefaultPortForDbSystem(String dbSystem) {
switch (dbSystem) {
case "mongodb":
return 27017;
case "cassandra":
return 9042;
case "redis":
return 6379;
default:
return 0;
}
}
private void exportRequest(SpanData span, List<TelemetryItem> telemetryItems) {
TelemetryItem telemetryItem = new TelemetryItem();
RequestData requestData = new RequestData();
MonitorBase monitorBase = new MonitorBase();
telemetryItem.setTags(new HashMap<>());
telemetryItem.setName(telemetryItemNamePrefix + "Request");
telemetryItem.setVersion(1);
telemetryItem.setInstrumentationKey(instrumentationKey);
telemetryItem.setData(monitorBase);
requestData.setProperties(new HashMap<>());
requestData.setVersion(2);
monitorBase.setBaseType("RequestData");
monitorBase.setBaseData(requestData);
String source = null;
Attributes attributes = span.getAttributes();
String sourceAppId = attributes.get(AI_SPAN_SOURCE_APP_ID_KEY);
if (sourceAppId != null) {
source = sourceAppId;
}
if (source == null) {
String messagingSystem = attributes.get(SemanticAttributes.MESSAGING_SYSTEM);
if (messagingSystem != null) {
source = nullAwareConcat(getTargetFromPeerAttributes(attributes, 0),
attributes.get(SemanticAttributes.MESSAGING_DESTINATION), "/");
if (source == null) {
source = messagingSystem;
}
}
}
if (source == null) {
source = attributes.get(AI_SPAN_SOURCE_KEY);
}
requestData.setSource(source);
addLinks(requestData.getProperties(), span.getLinks());
Long httpStatusCode = attributes.get(SemanticAttributes.HTTP_STATUS_CODE);
requestData.setResponseCode("200");
if (httpStatusCode != null) {
requestData.setResponseCode(Long.toString(httpStatusCode));
}
String httpUrl = attributes.get(SemanticAttributes.HTTP_URL);
if (httpUrl != null) {
requestData.setUrl(httpUrl);
}
String name = span.getName();
requestData.setName(name);
telemetryItem.getTags().put(ContextTagKeys.AI_OPERATION_NAME.toString(), name);
requestData.setId(span.getSpanId());
telemetryItem.getTags().put(ContextTagKeys.AI_OPERATION_ID.toString(), span.getTraceId());
String aiLegacyParentId = span.getSpanContext().getTraceState().get("ai-legacy-parent-id");
if (aiLegacyParentId != null) {
telemetryItem.getTags().put(ContextTagKeys.AI_OPERATION_PARENT_ID.toString(), aiLegacyParentId);
String aiLegacyOperationId = span.getSpanContext().getTraceState().get("ai-legacy-operation-id");
if (aiLegacyOperationId != null) {
telemetryItem.getTags().putIfAbsent("ai_legacyRootID", aiLegacyOperationId);
}
} else {
String parentSpanId = span.getParentSpanId();
if (SpanId.isValid(parentSpanId)) {
telemetryItem.getTags().put(ContextTagKeys.AI_OPERATION_PARENT_ID.toString(), parentSpanId);
}
}
long startEpochNanos = span.getStartEpochNanos();
telemetryItem.setTime(getFormattedTime(startEpochNanos));
Duration duration = Duration.ofNanos(span.getEndEpochNanos() - startEpochNanos);
requestData.setDuration(getFormattedDuration(duration));
requestData.setSuccess(span.getStatus().getStatusCode() != StatusCode.ERROR);
String description = span.getStatus().getDescription();
if (description != null) {
requestData.getProperties().put("statusDescription", description);
}
Double samplingPercentage = 100.0;
setExtraAttributes(telemetryItem, requestData.getProperties(), attributes);
telemetryItem.setSampleRate(samplingPercentage.floatValue());
telemetryItems.add(telemetryItem);
exportEvents(span, samplingPercentage, telemetryItems);
}
private static String nullAwareConcat(String str1, String str2, String separator) {
if (str1 == null) {
return str2;
}
if (str2 == null) {
return str1;
}
return str1 + separator + str2;
}
private void exportEvents(SpanData span, Double samplingPercentage, List<TelemetryItem> telemetryItems) {
boolean foundException = false;
for (EventData event : span.getEvents()) {
TelemetryItem telemetryItem = new TelemetryItem();
TelemetryEventData eventData = new TelemetryEventData();
MonitorBase monitorBase = new MonitorBase();
telemetryItem.setTags(new HashMap<>());
telemetryItem.setName(telemetryItemNamePrefix + "Event");
telemetryItem.setVersion(1);
telemetryItem.setInstrumentationKey(instrumentationKey);
telemetryItem.setData(monitorBase);
eventData.setProperties(new HashMap<>());
eventData.setVersion(2);
monitorBase.setBaseType("EventData");
monitorBase.setBaseData(eventData);
eventData.setName(event.getName());
String operationId = span.getTraceId();
telemetryItem.getTags().put(ContextTagKeys.AI_OPERATION_ID.toString(), operationId);
telemetryItem.getTags()
.put(ContextTagKeys.AI_OPERATION_PARENT_ID.toString(), span.getSpanId());
telemetryItem.setTime(getFormattedTime(event.getEpochNanos()));
setExtraAttributes(telemetryItem, eventData.getProperties(), event.getAttributes());
if (event.getAttributes().get(SemanticAttributes.EXCEPTION_TYPE) != null
|| event.getAttributes().get(SemanticAttributes.EXCEPTION_MESSAGE) != null) {
String stacktrace = event.getAttributes().get(SemanticAttributes.EXCEPTION_STACKTRACE);
if (stacktrace != null) {
trackException(stacktrace, span, operationId, span.getSpanId(), samplingPercentage, telemetryItems);
}
} else {
telemetryItem.setSampleRate(samplingPercentage.floatValue());
telemetryItems.add(telemetryItem);
}
}
}
private void trackException(String errorStack, SpanData span, String operationId,
String id, Double samplingPercentage, List<TelemetryItem> telemetryItems) {
TelemetryItem telemetryItem = new TelemetryItem();
TelemetryExceptionData exceptionData = new TelemetryExceptionData();
MonitorBase monitorBase = new MonitorBase();
telemetryItem.setTags(new HashMap<>());
telemetryItem.setName(telemetryItemNamePrefix + "Exception");
telemetryItem.setVersion(1);
telemetryItem.setInstrumentationKey(instrumentationKey);
telemetryItem.setData(monitorBase);
exceptionData.setProperties(new HashMap<>());
exceptionData.setVersion(2);
monitorBase.setBaseType("ExceptionData");
monitorBase.setBaseData(exceptionData);
telemetryItem.getTags().put(ContextTagKeys.AI_OPERATION_ID.toString(), operationId);
telemetryItem.getTags().put(ContextTagKeys.AI_OPERATION_PARENT_ID.toString(), id);
telemetryItem.setTime(getFormattedTime(span.getEndEpochNanos()));
telemetryItem.setSampleRate(samplingPercentage.floatValue());
exceptionData.setExceptions(minimalParse(errorStack));
telemetryItems.add(telemetryItem);
}
private static String getFormattedDuration(Duration duration) {
return duration.toDays() + "." + duration.toHours() + ":" + duration.toMinutes() + ":" + duration.getSeconds()
+ "." + duration.toMillis();
}
private static String getFormattedTime(long epochNanos) {
return Instant.ofEpochMilli(NANOSECONDS.toMillis(epochNanos))
.atOffset(ZoneOffset.UTC)
.format(DateTimeFormatter.ISO_DATE_TIME);
}
private static void addLinks(Map<String, String> properties, List<LinkData> links) {
if (links.isEmpty()) {
return;
}
StringBuilder sb = new StringBuilder();
sb.append("[");
boolean first = true;
for (LinkData link : links) {
if (!first) {
sb.append(",");
}
sb.append("{\"operation_Id\":\"");
sb.append(link.getSpanContext().getTraceId());
sb.append("\",\"id\":\"");
sb.append(link.getSpanContext().getSpanId());
sb.append("\"}");
first = false;
}
sb.append("]");
properties.put("_MS.links", sb.toString());
}
private String getStringValue(AttributeKey<?> attributeKey, Object value) {
switch (attributeKey.getType()) {
case STRING:
case BOOLEAN:
case LONG:
case DOUBLE:
return String.valueOf(value);
case STRING_ARRAY:
case BOOLEAN_ARRAY:
case LONG_ARRAY:
case DOUBLE_ARRAY:
return join((List<?>) value);
default:
logger.warning("unexpected attribute type: {}", attributeKey.getType());
return null;
}
}
private static <T> String join(List<T> values) {
StringBuilder sb = new StringBuilder();
if (CoreUtils.isNullOrEmpty(values)) {
return sb.toString();
}
for (int i = 0; i < values.size() - 1; i++) {
sb.append(values.get(i));
sb.append(", ");
}
sb.append(values.get(values.size() - 1));
return sb.toString();
}
private void setExtraAttributes(TelemetryItem telemetry, Map<String, String> properties,
Attributes attributes) {
attributes.forEach((key, value) -> {
String stringKey = key.getKey();
if (stringKey.startsWith("applicationinsights.internal.")) {
return;
}
if (key.equals(SemanticAttributes.ENDUSER_ID) && value instanceof String) {
telemetry.getTags().put(ContextTagKeys.AI_USER_ID.toString(), (String) value);
return;
}
if (key.equals(SemanticAttributes.HTTP_USER_AGENT) && value instanceof String) {
telemetry.getTags().put("ai.user.userAgent", (String) value);
return;
}
int index = stringKey.indexOf(".");
String prefix = index == -1 ? stringKey : stringKey.substring(0, index);
if (STANDARD_ATTRIBUTE_PREFIXES.contains(prefix)) {
return;
}
String val = getStringValue(key, value);
if (value != null) {
properties.put(key.getKey(), val);
}
});
}
} | private void export(SpanData span, List<TelemetryItem> telemetryItems) {
SpanKind kind = span.getKind();
String instrumentationName = span.getInstrumentationLibraryInfo().getName();
Matcher matcher = COMPONENT_PATTERN.matcher(instrumentationName);
String stdComponent = matcher.matches() ? matcher.group(1) : null;
if (kind == SpanKind.INTERNAL) {
if ("spring-scheduling".equals(stdComponent) && !span.getParentSpanContext().isValid()) {
exportRequest(span, telemetryItems);
} else {
exportRemoteDependency(span, true, telemetryItems);
}
} else if (kind == SpanKind.CLIENT || kind == SpanKind.PRODUCER) {
exportRemoteDependency(span, false, telemetryItems);
} else if (kind == SpanKind.CONSUMER && !span.getParentSpanContext().isRemote()) {
exportRemoteDependency(span, false, telemetryItems);
} else if (kind == SpanKind.SERVER || kind == SpanKind.CONSUMER) {
exportRequest(span, telemetryItems);
} else {
throw logger.logExceptionAsError(new UnsupportedOperationException(kind.name()));
}
}
private static List<TelemetryExceptionDetails> minimalParse(String errorStack) {
TelemetryExceptionDetails details = new TelemetryExceptionDetails();
String line = errorStack.split(System.lineSeparator())[0];
int index = line.indexOf(": ");
if (index != -1) {
details.setTypeName(line.substring(0, index));
details.setMessage(line.substring(index + 2));
} else {
details.setTypeName(line);
}
details.setStack(errorStack);
return Collections.singletonList(details);
}
private void exportRemoteDependency(SpanData span, boolean inProc,
List<TelemetryItem> telemetryItems) {
TelemetryItem telemetryItem = new TelemetryItem();
RemoteDependencyData remoteDependencyData = new RemoteDependencyData();
MonitorBase monitorBase = new MonitorBase();
telemetryItem.setTags(new HashMap<>());
telemetryItem.setName(telemetryItemNamePrefix + "RemoteDependency");
telemetryItem.setVersion(1);
telemetryItem.setInstrumentationKey(instrumentationKey);
telemetryItem.setData(monitorBase);
remoteDependencyData.setProperties(new HashMap<>());
remoteDependencyData.setVersion(2);
monitorBase.setBaseType("RemoteDependencyData");
monitorBase.setBaseData(remoteDependencyData);
addLinks(remoteDependencyData.getProperties(), span.getLinks());
remoteDependencyData.setName(span.getName());
Attributes attributes = span.getAttributes();
if (inProc) {
remoteDependencyData.setType("InProc");
} else {
applySemanticConventions(attributes, remoteDependencyData, span.getKind());
}
remoteDependencyData.setId(span.getSpanId());
telemetryItem.getTags().put(ContextTagKeys.AI_OPERATION_ID.toString(), span.getTraceId());
String parentSpanId = span.getParentSpanId();
if (SpanId.isValid(parentSpanId)) {
telemetryItem.getTags().put(ContextTagKeys.AI_OPERATION_PARENT_ID.toString(), parentSpanId);
}
telemetryItem.setTime(getFormattedTime(span.getStartEpochNanos()));
remoteDependencyData
.setDuration(getFormattedDuration(Duration.ofNanos(span.getEndEpochNanos() - span.getStartEpochNanos())));
remoteDependencyData.setSuccess(span.getStatus().getStatusCode() != StatusCode.ERROR);
setExtraAttributes(telemetryItem, remoteDependencyData.getProperties(), attributes);
Double samplingPercentage = 100.0;
telemetryItem.setSampleRate(samplingPercentage.floatValue());
telemetryItems.add(telemetryItem);
exportEvents(span, samplingPercentage, telemetryItems);
}
private void applySemanticConventions(Attributes attributes, RemoteDependencyData remoteDependencyData, SpanKind spanKind) {
String httpMethod = attributes.get(SemanticAttributes.HTTP_METHOD);
if (httpMethod != null) {
applyHttpClientSpan(attributes, remoteDependencyData);
return;
}
String rpcSystem = attributes.get(SemanticAttributes.RPC_SYSTEM);
if (rpcSystem != null) {
applyRpcClientSpan(attributes, remoteDependencyData, rpcSystem);
return;
}
String dbSystem = attributes.get(SemanticAttributes.DB_SYSTEM);
if (dbSystem != null) {
applyDatabaseClientSpan(attributes, remoteDependencyData, dbSystem);
return;
}
String messagingSystem = attributes.get(SemanticAttributes.MESSAGING_SYSTEM);
if (messagingSystem != null) {
applyMessagingClientSpan(attributes, remoteDependencyData, messagingSystem, spanKind);
return;
}
}
private void applyHttpClientSpan(Attributes attributes, RemoteDependencyData telemetry) {
String scheme = attributes.get(SemanticAttributes.HTTP_SCHEME);
int defaultPort;
if ("http".equals(scheme)) {
defaultPort = 80;
} else if ("https".equals(scheme)) {
defaultPort = 443;
} else {
defaultPort = 0;
}
String target = getTargetFromPeerAttributes(attributes, defaultPort);
if (target == null) {
target = attributes.get(SemanticAttributes.HTTP_HOST);
}
String url = attributes.get(SemanticAttributes.HTTP_URL);
if (target == null && url != null) {
try {
URI uri = new URI(url);
target = uri.getHost();
if (uri.getPort() != 80 && uri.getPort() != 443 && uri.getPort() != -1) {
target += ":" + uri.getPort();
}
} catch (URISyntaxException e) {
logger.error(e.getMessage());
logger.verbose(e.getMessage(), e);
}
}
if (target == null) {
target = "Http";
}
String targetAppId = attributes.get(AI_SPAN_TARGET_APP_ID_KEY);
if (targetAppId == null) {
telemetry.setType("Http");
telemetry.setTarget(target);
} else {
telemetry.setType("Http (tracked component)");
telemetry.setTarget(target + " | " + targetAppId);
}
Long httpStatusCode = attributes.get(SemanticAttributes.HTTP_STATUS_CODE);
if (httpStatusCode != null) {
telemetry.setResultCode(Long.toString(httpStatusCode));
}
telemetry.setData(url);
}
private static String getTargetFromPeerAttributes(Attributes attributes, int defaultPort) {
String target = attributes.get(SemanticAttributes.PEER_SERVICE);
if (target != null) {
return target;
}
target = attributes.get(SemanticAttributes.NET_PEER_NAME);
if (target == null) {
target = attributes.get(SemanticAttributes.NET_PEER_IP);
}
if (target == null) {
return null;
}
Long port = attributes.get(SemanticAttributes.NET_PEER_PORT);
if (port != null && port != defaultPort) {
return target + ":" + port;
}
return target;
}
private static void applyRpcClientSpan(Attributes attributes, RemoteDependencyData telemetry, String rpcSystem) {
telemetry.setType(rpcSystem);
String target = getTargetFromPeerAttributes(attributes, 0);
if (target == null) {
target = rpcSystem;
}
telemetry.setTarget(target);
}
private static void applyDatabaseClientSpan(Attributes attributes, RemoteDependencyData telemetry, String dbSystem) {
String dbStatement = attributes.get(SemanticAttributes.DB_STATEMENT);
String type;
if (SQL_DB_SYSTEMS.contains(dbSystem)) {
type = "SQL";
telemetry.setName(dbStatement);
} else {
type = dbSystem;
}
telemetry.setType(type);
telemetry.setData(dbStatement);
String target = nullAwareConcat(getTargetFromPeerAttributes(attributes, getDefaultPortForDbSystem(dbSystem)),
attributes.get(SemanticAttributes.DB_NAME), "/");
if (target == null) {
target = dbSystem;
}
telemetry.setTarget(target);
}
private void applyMessagingClientSpan(Attributes attributes, RemoteDependencyData telemetry, String messagingSystem, SpanKind spanKind) {
if (spanKind == SpanKind.PRODUCER) {
telemetry.setType("Queue Message | " + messagingSystem);
} else {
telemetry.setType(messagingSystem);
}
String destination = attributes.get(SemanticAttributes.MESSAGING_DESTINATION);
if (destination != null) {
telemetry.setTarget(destination);
} else {
telemetry.setTarget(messagingSystem);
}
}
private static int getDefaultPortForDbSystem(String dbSystem) {
switch (dbSystem) {
case "mongodb":
return 27017;
case "cassandra":
return 9042;
case "redis":
return 6379;
default:
return 0;
}
}
private void exportRequest(SpanData span, List<TelemetryItem> telemetryItems) {
TelemetryItem telemetryItem = new TelemetryItem();
RequestData requestData = new RequestData();
MonitorBase monitorBase = new MonitorBase();
telemetryItem.setTags(new HashMap<>());
telemetryItem.setName(telemetryItemNamePrefix + "Request");
telemetryItem.setVersion(1);
telemetryItem.setInstrumentationKey(instrumentationKey);
telemetryItem.setData(monitorBase);
requestData.setProperties(new HashMap<>());
requestData.setVersion(2);
monitorBase.setBaseType("RequestData");
monitorBase.setBaseData(requestData);
String source = null;
Attributes attributes = span.getAttributes();
String sourceAppId = attributes.get(AI_SPAN_SOURCE_APP_ID_KEY);
if (sourceAppId != null) {
source = sourceAppId;
}
if (source == null) {
String messagingSystem = attributes.get(SemanticAttributes.MESSAGING_SYSTEM);
if (messagingSystem != null) {
source = nullAwareConcat(getTargetFromPeerAttributes(attributes, 0),
attributes.get(SemanticAttributes.MESSAGING_DESTINATION), "/");
if (source == null) {
source = messagingSystem;
}
}
}
if (source == null) {
source = attributes.get(AI_SPAN_SOURCE_KEY);
}
requestData.setSource(source);
addLinks(requestData.getProperties(), span.getLinks());
Long httpStatusCode = attributes.get(SemanticAttributes.HTTP_STATUS_CODE);
requestData.setResponseCode("200");
if (httpStatusCode != null) {
requestData.setResponseCode(Long.toString(httpStatusCode));
}
String httpUrl = attributes.get(SemanticAttributes.HTTP_URL);
if (httpUrl != null) {
requestData.setUrl(httpUrl);
}
String name = span.getName();
requestData.setName(name);
telemetryItem.getTags().put(ContextTagKeys.AI_OPERATION_NAME.toString(), name);
requestData.setId(span.getSpanId());
telemetryItem.getTags().put(ContextTagKeys.AI_OPERATION_ID.toString(), span.getTraceId());
String aiLegacyParentId = span.getSpanContext().getTraceState().get("ai-legacy-parent-id");
if (aiLegacyParentId != null) {
telemetryItem.getTags().put(ContextTagKeys.AI_OPERATION_PARENT_ID.toString(), aiLegacyParentId);
String aiLegacyOperationId = span.getSpanContext().getTraceState().get("ai-legacy-operation-id");
if (aiLegacyOperationId != null) {
telemetryItem.getTags().putIfAbsent("ai_legacyRootID", aiLegacyOperationId);
}
} else {
String parentSpanId = span.getParentSpanId();
if (SpanId.isValid(parentSpanId)) {
telemetryItem.getTags().put(ContextTagKeys.AI_OPERATION_PARENT_ID.toString(), parentSpanId);
}
}
long startEpochNanos = span.getStartEpochNanos();
telemetryItem.setTime(getFormattedTime(startEpochNanos));
Duration duration = Duration.ofNanos(span.getEndEpochNanos() - startEpochNanos);
requestData.setDuration(getFormattedDuration(duration));
requestData.setSuccess(span.getStatus().getStatusCode() != StatusCode.ERROR);
String description = span.getStatus().getDescription();
if (description != null) {
requestData.getProperties().put("statusDescription", description);
}
Double samplingPercentage = 100.0;
setExtraAttributes(telemetryItem, requestData.getProperties(), attributes);
telemetryItem.setSampleRate(samplingPercentage.floatValue());
telemetryItems.add(telemetryItem);
exportEvents(span, samplingPercentage, telemetryItems);
}
private static String nullAwareConcat(String str1, String str2, String separator) {
if (str1 == null) {
return str2;
}
if (str2 == null) {
return str1;
}
return str1 + separator + str2;
}
private void exportEvents(SpanData span, Double samplingPercentage, List<TelemetryItem> telemetryItems) {
boolean foundException = false;
for (EventData event : span.getEvents()) {
TelemetryItem telemetryItem = new TelemetryItem();
TelemetryEventData eventData = new TelemetryEventData();
MonitorBase monitorBase = new MonitorBase();
telemetryItem.setTags(new HashMap<>());
telemetryItem.setName(telemetryItemNamePrefix + "Event");
telemetryItem.setVersion(1);
telemetryItem.setInstrumentationKey(instrumentationKey);
telemetryItem.setData(monitorBase);
eventData.setProperties(new HashMap<>());
eventData.setVersion(2);
monitorBase.setBaseType("EventData");
monitorBase.setBaseData(eventData);
eventData.setName(event.getName());
String operationId = span.getTraceId();
telemetryItem.getTags().put(ContextTagKeys.AI_OPERATION_ID.toString(), operationId);
telemetryItem.getTags()
.put(ContextTagKeys.AI_OPERATION_PARENT_ID.toString(), span.getSpanId());
telemetryItem.setTime(getFormattedTime(event.getEpochNanos()));
setExtraAttributes(telemetryItem, eventData.getProperties(), event.getAttributes());
if (event.getAttributes().get(SemanticAttributes.EXCEPTION_TYPE) != null
|| event.getAttributes().get(SemanticAttributes.EXCEPTION_MESSAGE) != null) {
String stacktrace = event.getAttributes().get(SemanticAttributes.EXCEPTION_STACKTRACE);
if (stacktrace != null) {
trackException(stacktrace, span, operationId, span.getSpanId(), samplingPercentage, telemetryItems);
}
} else {
telemetryItem.setSampleRate(samplingPercentage.floatValue());
telemetryItems.add(telemetryItem);
}
}
}
private void trackException(String errorStack, SpanData span, String operationId,
String id, Double samplingPercentage, List<TelemetryItem> telemetryItems) {
TelemetryItem telemetryItem = new TelemetryItem();
TelemetryExceptionData exceptionData = new TelemetryExceptionData();
MonitorBase monitorBase = new MonitorBase();
telemetryItem.setTags(new HashMap<>());
telemetryItem.setName(telemetryItemNamePrefix + "Exception");
telemetryItem.setVersion(1);
telemetryItem.setInstrumentationKey(instrumentationKey);
telemetryItem.setData(monitorBase);
exceptionData.setProperties(new HashMap<>());
exceptionData.setVersion(2);
monitorBase.setBaseType("ExceptionData");
monitorBase.setBaseData(exceptionData);
telemetryItem.getTags().put(ContextTagKeys.AI_OPERATION_ID.toString(), operationId);
telemetryItem.getTags().put(ContextTagKeys.AI_OPERATION_PARENT_ID.toString(), id);
telemetryItem.setTime(getFormattedTime(span.getEndEpochNanos()));
telemetryItem.setSampleRate(samplingPercentage.floatValue());
exceptionData.setExceptions(minimalParse(errorStack));
telemetryItems.add(telemetryItem);
}
private static String getFormattedDuration(Duration duration) {
return duration.toDays() + "." + duration.toHours() + ":" + duration.toMinutes() + ":" + duration.getSeconds()
+ "." + duration.toMillis();
}
private static String getFormattedTime(long epochNanos) {
return Instant.ofEpochMilli(NANOSECONDS.toMillis(epochNanos))
.atOffset(ZoneOffset.UTC)
.format(DateTimeFormatter.ISO_DATE_TIME);
}
private static void addLinks(Map<String, String> properties, List<LinkData> links) {
if (links.isEmpty()) {
return;
}
StringBuilder sb = new StringBuilder();
sb.append("[");
boolean first = true;
for (LinkData link : links) {
if (!first) {
sb.append(",");
}
sb.append("{\"operation_Id\":\"");
sb.append(link.getSpanContext().getTraceId());
sb.append("\",\"id\":\"");
sb.append(link.getSpanContext().getSpanId());
sb.append("\"}");
first = false;
}
sb.append("]");
properties.put("_MS.links", sb.toString());
}
private String getStringValue(AttributeKey<?> attributeKey, Object value) {
switch (attributeKey.getType()) {
case STRING:
case BOOLEAN:
case LONG:
case DOUBLE:
return String.valueOf(value);
case STRING_ARRAY:
case BOOLEAN_ARRAY:
case LONG_ARRAY:
case DOUBLE_ARRAY:
return join((List<?>) value);
default:
logger.warning("unexpected attribute type: {}", attributeKey.getType());
return null;
}
}
private static <T> String join(List<T> values) {
StringBuilder sb = new StringBuilder();
if (CoreUtils.isNullOrEmpty(values)) {
return sb.toString();
}
for (int i = 0; i < values.size() - 1; i++) {
sb.append(values.get(i));
sb.append(", ");
}
sb.append(values.get(values.size() - 1));
return sb.toString();
}
private void setExtraAttributes(TelemetryItem telemetry, Map<String, String> properties,
Attributes attributes) {
attributes.forEach((key, value) -> {
String stringKey = key.getKey();
if (stringKey.startsWith("applicationinsights.internal.")) {
return;
}
if (key.equals(SemanticAttributes.ENDUSER_ID) && value instanceof String) {
telemetry.getTags().put(ContextTagKeys.AI_USER_ID.toString(), (String) value);
return;
}
if (key.equals(SemanticAttributes.HTTP_USER_AGENT) && value instanceof String) {
telemetry.getTags().put("ai.user.userAgent", (String) value);
return;
}
int index = stringKey.indexOf(".");
String prefix = index == -1 ? stringKey : stringKey.substring(0, index);
if (STANDARD_ATTRIBUTE_PREFIXES.contains(prefix)) {
return;
}
String val = getStringValue(key, value);
if (value != null) {
properties.put(key.getKey(), val);
}
});
}
} | class AzureMonitorTraceExporter implements SpanExporter {
private static final Pattern COMPONENT_PATTERN = Pattern
.compile("io\\.opentelemetry\\.javaagent\\.([^0-9]*)(-[0-9.]*)?");
private static final Set<String> SQL_DB_SYSTEMS;
private static final Set<String> STANDARD_ATTRIBUTE_PREFIXES;
private static final AttributeKey<String> AI_SPAN_SOURCE_APP_ID_KEY = AttributeKey.stringKey("applicationinsights.internal.source_app_id");
private static final AttributeKey<String> AI_SPAN_TARGET_APP_ID_KEY = AttributeKey.stringKey("applicationinsights.internal.target_app_id");
private static final AttributeKey<String> AI_SPAN_SOURCE_KEY = AttributeKey.stringKey("applicationinsights.internal.source");
static {
Set<String> dbSystems = new HashSet<>();
dbSystems.add("db2");
dbSystems.add("derby");
dbSystems.add("mariadb");
dbSystems.add("mssql");
dbSystems.add("mysql");
dbSystems.add("oracle");
dbSystems.add("postgresql");
dbSystems.add("sqlite");
dbSystems.add("other_sql");
dbSystems.add("hsqldb");
dbSystems.add("h2");
SQL_DB_SYSTEMS = Collections.unmodifiableSet(dbSystems);
Set<String> standardAttributesPrefix = new HashSet<>();
standardAttributesPrefix.add("http");
standardAttributesPrefix.add("db");
standardAttributesPrefix.add("message");
standardAttributesPrefix.add("messaging");
standardAttributesPrefix.add("rpc");
standardAttributesPrefix.add("enduser");
standardAttributesPrefix.add("net");
standardAttributesPrefix.add("peer");
standardAttributesPrefix.add("exception");
standardAttributesPrefix.add("thread");
standardAttributesPrefix.add("faas");
STANDARD_ATTRIBUTE_PREFIXES = Collections.unmodifiableSet(standardAttributesPrefix);
}
private final MonitorExporterAsyncClient client;
private final ClientLogger logger = new ClientLogger(AzureMonitorTraceExporter.class);
private final String instrumentationKey;
private final String telemetryItemNamePrefix;
/**
* Creates an instance of exporter that is configured with given exporter client that sends telemetry events to
* Application Insights resource identified by the instrumentation key.
* @param client The client used to send data to Azure Monitor.
* @param instrumentationKey The instrumentation key of Application Insights resource.
*/
AzureMonitorTraceExporter(MonitorExporterAsyncClient client, String instrumentationKey) {
this.client = client;
this.instrumentationKey = instrumentationKey;
String formattedInstrumentationKey = instrumentationKey.replaceAll("-", "");
this.telemetryItemNamePrefix = "Microsoft.ApplicationInsights." + formattedInstrumentationKey + ".";
}
/**
* {@inheritDoc}
*/
@Override
public CompletableResultCode export(Collection<SpanData> spans) {
CompletableResultCode completableResultCode = new CompletableResultCode();
try {
List<TelemetryItem> telemetryItems = new ArrayList<>();
for (SpanData span : spans) {
logger.verbose("exporting span: {}", span);
export(span, telemetryItems);
}
client.export(telemetryItems)
.subscriberContext(Context.of(Tracer.DISABLE_TRACING_KEY, true))
.subscribe(ignored -> { }, error -> completableResultCode.fail(), completableResultCode::succeed);
return completableResultCode;
} catch (Throwable t) {
logger.error(t.getMessage(), t);
return completableResultCode.fail();
}
}
/**
* {@inheritDoc}
*/
@Override
public CompletableResultCode flush() {
return CompletableResultCode.ofSuccess();
}
/**
* {@inheritDoc}
*/
@Override
public CompletableResultCode shutdown() {
return CompletableResultCode.ofSuccess();
} | class AzureMonitorTraceExporter implements SpanExporter {
private static final Pattern COMPONENT_PATTERN = Pattern
.compile("io\\.opentelemetry\\.javaagent\\.([^0-9]*)(-[0-9.]*)?");
private static final Set<String> SQL_DB_SYSTEMS;
private static final Set<String> STANDARD_ATTRIBUTE_PREFIXES;
private static final AttributeKey<String> AI_SPAN_SOURCE_APP_ID_KEY = AttributeKey.stringKey("applicationinsights.internal.source_app_id");
private static final AttributeKey<String> AI_SPAN_TARGET_APP_ID_KEY = AttributeKey.stringKey("applicationinsights.internal.target_app_id");
private static final AttributeKey<String> AI_SPAN_SOURCE_KEY = AttributeKey.stringKey("applicationinsights.internal.source");
static {
Set<String> dbSystems = new HashSet<>();
dbSystems.add("db2");
dbSystems.add("derby");
dbSystems.add("mariadb");
dbSystems.add("mssql");
dbSystems.add("mysql");
dbSystems.add("oracle");
dbSystems.add("postgresql");
dbSystems.add("sqlite");
dbSystems.add("other_sql");
dbSystems.add("hsqldb");
dbSystems.add("h2");
SQL_DB_SYSTEMS = Collections.unmodifiableSet(dbSystems);
Set<String> standardAttributesPrefix = new HashSet<>();
standardAttributesPrefix.add("http");
standardAttributesPrefix.add("db");
standardAttributesPrefix.add("message");
standardAttributesPrefix.add("messaging");
standardAttributesPrefix.add("rpc");
standardAttributesPrefix.add("enduser");
standardAttributesPrefix.add("net");
standardAttributesPrefix.add("peer");
standardAttributesPrefix.add("exception");
standardAttributesPrefix.add("thread");
standardAttributesPrefix.add("faas");
STANDARD_ATTRIBUTE_PREFIXES = Collections.unmodifiableSet(standardAttributesPrefix);
}
private final MonitorExporterAsyncClient client;
private final ClientLogger logger = new ClientLogger(AzureMonitorTraceExporter.class);
private final String instrumentationKey;
private final String telemetryItemNamePrefix;
/**
* Creates an instance of exporter that is configured with given exporter client that sends telemetry events to
* Application Insights resource identified by the instrumentation key.
* @param client The client used to send data to Azure Monitor.
* @param instrumentationKey The instrumentation key of Application Insights resource.
*/
AzureMonitorTraceExporter(MonitorExporterAsyncClient client, String instrumentationKey) {
this.client = client;
this.instrumentationKey = instrumentationKey;
String formattedInstrumentationKey = instrumentationKey.replaceAll("-", "");
this.telemetryItemNamePrefix = "Microsoft.ApplicationInsights." + formattedInstrumentationKey + ".";
}
/**
* {@inheritDoc}
*/
@Override
public CompletableResultCode export(Collection<SpanData> spans) {
CompletableResultCode completableResultCode = new CompletableResultCode();
try {
List<TelemetryItem> telemetryItems = new ArrayList<>();
for (SpanData span : spans) {
logger.verbose("exporting span: {}", span);
export(span, telemetryItems);
}
client.export(telemetryItems)
.subscriberContext(Context.of(Tracer.DISABLE_TRACING_KEY, true))
.subscribe(ignored -> { }, error -> completableResultCode.fail(), completableResultCode::succeed);
return completableResultCode;
} catch (Throwable t) {
logger.error(t.getMessage(), t);
return completableResultCode.fail();
}
}
/**
* {@inheritDoc}
*/
@Override
public CompletableResultCode flush() {
return CompletableResultCode.ofSuccess();
}
/**
* {@inheritDoc}
*/
@Override
public CompletableResultCode shutdown() {
return CompletableResultCode.ofSuccess();
} | |
Thank you for picking on small problems :) | public CommunicationIdentityClient createCommunicationIdentityClient() {
String endpoint = "https:
AzureKeyCredential keyCredential = new AzureKeyCredential("<access-key>");
HttpClient httpClient = new NettyAsyncHttpClientBuilder().build();
CommunicationIdentityClient communicationIdentityClient = new CommunicationIdentityClientBuilder()
.endpoint(endpoint)
.credential(keyCredential)
.httpClient(httpClient)
.buildClient();
return communicationIdentityClient;
} | AzureKeyCredential keyCredential = new AzureKeyCredential("<access-key>"); | public CommunicationIdentityClient createCommunicationIdentityClient() {
String endpoint = "https:
AzureKeyCredential keyCredential = new AzureKeyCredential("<access-key>");
HttpClient httpClient = new NettyAsyncHttpClientBuilder().build();
CommunicationIdentityClient communicationIdentityClient = new CommunicationIdentityClientBuilder()
.endpoint(endpoint)
.credential(keyCredential)
.httpClient(httpClient)
.buildClient();
return communicationIdentityClient;
} | class ReadmeSamples {
/**
* Sample code for creating a sync Communication Identity Client.
*
* @return the Communication Identity Client.
*/
/**
* Sample code for creating a sync Communication Identity Client using connection string.
*
* @return the Communication Identity Client.
*/
public CommunicationIdentityClient createCommunicationIdentityClientWithConnectionString() {
HttpClient httpClient = new NettyAsyncHttpClientBuilder().build();
String connectionString = "<connection_string>";
CommunicationIdentityClient communicationIdentityClient = new CommunicationIdentityClientBuilder()
.connectionString(connectionString)
.httpClient(httpClient)
.buildClient();
return communicationIdentityClient;
}
/**
* Sample code for creating a sync Communication Identity Client using AAD authentication.
*
* @return the Communication Identity Client.
*/
public CommunicationIdentityClient createCommunicationIdentityClientWithAAD() {
String endpoint = "https:
HttpClient httpClient = new NettyAsyncHttpClientBuilder().build();
CommunicationIdentityClient communicationIdentityClient = new CommunicationIdentityClientBuilder()
.endpoint(endpoint)
.credential(new DefaultAzureCredentialBuilder().build())
.httpClient(httpClient)
.buildClient();
return communicationIdentityClient;
}
/**
* Sample code for creating a user
*
* @return the created user
*/
public CommunicationUserIdentifier createNewUser() {
CommunicationIdentityClient communicationIdentityClient = createCommunicationIdentityClient();
CommunicationUserIdentifier user = communicationIdentityClient.createUser();
System.out.println("User id: " + user.getId());
return user;
}
/**
* Sample code for creating a user with token
*
* @return the result with the created user and token
*/
public CommunicationUserIdentifierAndTokenResult createNewUserAndToken() {
CommunicationIdentityClient communicationIdentityClient = createCommunicationIdentityClient();
List<CommunicationTokenScope> scopes =
new ArrayList<>(Arrays.asList(CommunicationTokenScope.CHAT));
CommunicationUserIdentifierAndTokenResult result = communicationIdentityClient.createUserAndToken(scopes);
System.out.println("User id: " + result.getUser().getId());
System.out.println("User token value: " + result.getUserToken().getToken());
return result;
}
/**
* Sample code for issuing a user token
*
* @return the issued user token
*/
public AccessToken issueUserToken() {
CommunicationIdentityClient communicationIdentityClient = createCommunicationIdentityClient();
CommunicationUserIdentifier user = communicationIdentityClient.createUser();
List<CommunicationTokenScope> scopes =
new ArrayList<>(Arrays.asList(CommunicationTokenScope.CHAT));
AccessToken userToken = communicationIdentityClient.getToken(user, scopes);
System.out.println("User token value: " + userToken.getToken());
System.out.println("Expires at: " + userToken.getExpiresAt());
return userToken;
}
/**
* Sample code for revoking user token
*/
public void revokeUserToken() {
CommunicationIdentityClient communicationIdentityClient = createCommunicationIdentityClient();
CommunicationUserIdentifier user = createNewUser();
List<CommunicationTokenScope> scopes = Arrays.asList(CommunicationTokenScope.CHAT);
communicationIdentityClient.getToken(user, scopes);
communicationIdentityClient.revokeTokens(user);
}
/**
* Sample code for deleting user
*/
public void deleteUser() {
CommunicationIdentityClient communicationIdentityClient = createCommunicationIdentityClient();
CommunicationUserIdentifier user = communicationIdentityClient.createUser();
communicationIdentityClient.deleteUser(user);
}
/**
* Sample code for troubleshooting
*/
public void createUserTroubleshooting() {
CommunicationIdentityClient communicationIdentityClient = createCommunicationIdentityClient();
try {
CommunicationUserIdentifier user = communicationIdentityClient.createUser();
} catch (RuntimeException ex) {
System.out.println(ex.getMessage());
}
}
} | class ReadmeSamples {
/**
* Sample code for creating a sync Communication Identity Client.
*
* @return the Communication Identity Client.
*/
/**
* Sample code for creating a sync Communication Identity Client using connection string.
*
* @return the Communication Identity Client.
*/
public CommunicationIdentityClient createCommunicationIdentityClientWithConnectionString() {
HttpClient httpClient = new NettyAsyncHttpClientBuilder().build();
String connectionString = "<connection_string>";
CommunicationIdentityClient communicationIdentityClient = new CommunicationIdentityClientBuilder()
.connectionString(connectionString)
.httpClient(httpClient)
.buildClient();
return communicationIdentityClient;
}
/**
* Sample code for creating a sync Communication Identity Client using AAD authentication.
*
* @return the Communication Identity Client.
*/
public CommunicationIdentityClient createCommunicationIdentityClientWithAAD() {
String endpoint = "https:
HttpClient httpClient = new NettyAsyncHttpClientBuilder().build();
CommunicationIdentityClient communicationIdentityClient = new CommunicationIdentityClientBuilder()
.endpoint(endpoint)
.credential(new DefaultAzureCredentialBuilder().build())
.httpClient(httpClient)
.buildClient();
return communicationIdentityClient;
}
/**
* Sample code for creating a user
*
* @return the created user
*/
public CommunicationUserIdentifier createNewUser() {
CommunicationIdentityClient communicationIdentityClient = createCommunicationIdentityClient();
CommunicationUserIdentifier user = communicationIdentityClient.createUser();
System.out.println("User id: " + user.getId());
return user;
}
/**
* Sample code for creating a user with token
*
* @return the result with the created user and token
*/
public CommunicationUserIdentifierAndToken createNewUserAndToken() {
CommunicationIdentityClient communicationIdentityClient = createCommunicationIdentityClient();
List<CommunicationTokenScope> scopes = Arrays.asList(CommunicationTokenScope.CHAT);
CommunicationUserIdentifierAndToken result = communicationIdentityClient.createUserAndToken(scopes);
System.out.println("User id: " + result.getUser().getId());
System.out.println("User token value: " + result.getUserToken().getToken());
return result;
}
/**
* Sample code for issuing a user token
*
* @return the issued user token
*/
public AccessToken issueUserToken() {
CommunicationIdentityClient communicationIdentityClient = createCommunicationIdentityClient();
CommunicationUserIdentifier user = communicationIdentityClient.createUser();
List<CommunicationTokenScope> scopes = Arrays.asList(CommunicationTokenScope.CHAT);
AccessToken userToken = communicationIdentityClient.getToken(user, scopes);
System.out.println("User token value: " + userToken.getToken());
System.out.println("Expires at: " + userToken.getExpiresAt());
return userToken;
}
/**
* Sample code for revoking user token
*/
public void revokeUserToken() {
CommunicationIdentityClient communicationIdentityClient = createCommunicationIdentityClient();
CommunicationUserIdentifier user = createNewUser();
List<CommunicationTokenScope> scopes = Arrays.asList(CommunicationTokenScope.CHAT);
communicationIdentityClient.getToken(user, scopes);
communicationIdentityClient.revokeTokens(user);
}
/**
* Sample code for deleting user
*/
public void deleteUser() {
CommunicationIdentityClient communicationIdentityClient = createCommunicationIdentityClient();
CommunicationUserIdentifier user = communicationIdentityClient.createUser();
communicationIdentityClient.deleteUser(user);
}
/**
* Sample code for troubleshooting
*/
public void createUserTroubleshooting() {
CommunicationIdentityClient communicationIdentityClient = createCommunicationIdentityClient();
try {
CommunicationUserIdentifier user = communicationIdentityClient.createUser();
} catch (RuntimeException ex) {
System.out.println(ex.getMessage());
}
}
} |
We should consider making this configurable as these numbers may not work for all customers. | void startPartitionPump(PartitionOwnership claimedOwnership, Checkpoint checkpoint) {
if (partitionPumps.containsKey(claimedOwnership.getPartitionId())) {
logger.verbose("Consumer is already running for this partition {}", claimedOwnership.getPartitionId());
return;
}
try {
PartitionContext partitionContext = new PartitionContext(claimedOwnership.getFullyQualifiedNamespace(),
claimedOwnership.getEventHubName(), claimedOwnership.getConsumerGroup(),
claimedOwnership.getPartitionId());
PartitionProcessor partitionProcessor = this.partitionProcessorFactory.get();
InitializationContext initializationContext = new InitializationContext(partitionContext);
partitionProcessor.initialize(initializationContext);
EventPosition startFromEventPosition = null;
if (checkpoint != null && checkpoint.getOffset() != null) {
startFromEventPosition = EventPosition.fromOffset(checkpoint.getOffset());
} else if (checkpoint != null && checkpoint.getSequenceNumber() != null) {
startFromEventPosition = EventPosition.fromSequenceNumber(checkpoint.getSequenceNumber());
} else if (initialPartitionEventPosition.containsKey(claimedOwnership.getPartitionId())) {
startFromEventPosition = initialPartitionEventPosition.get(claimedOwnership.getPartitionId());
} else {
startFromEventPosition = EventPosition.latest();
}
logger.info("Starting event processing from {} for partition {}", startFromEventPosition,
claimedOwnership.getPartitionId());
ReceiveOptions receiveOptions = new ReceiveOptions().setOwnerLevel(0L)
.setTrackLastEnqueuedEventProperties(trackLastEnqueuedEventProperties);
Scheduler scheduler = Schedulers.newBoundedElastic(Runtime.getRuntime().availableProcessors(),
10000, "partition-pump-" + claimedOwnership.getPartitionId());
EventHubConsumerAsyncClient eventHubConsumer = eventHubClientBuilder.buildAsyncClient()
.createConsumer(claimedOwnership.getConsumerGroup(), PREFETCH);
PartitionPump partitionPump = new PartitionPump(claimedOwnership.getPartitionId(), eventHubConsumer,
scheduler);
partitionPumps.put(claimedOwnership.getPartitionId(), partitionPump);
Flux<Flux<PartitionEvent>> partitionEventFlux;
Flux<PartitionEvent> receiver = eventHubConsumer
.receiveFromPartition(claimedOwnership.getPartitionId(), startFromEventPosition, receiveOptions)
.doOnNext(partitionEvent -> {
if (logger.canLogAtLevel(LogLevel.VERBOSE)) {
logger.verbose("On next {}, {}, {}",
partitionContext.getEventHubName(), partitionContext.getPartitionId(),
partitionEvent.getData().getSequenceNumber());
}
});
if (maxWaitTime != null) {
partitionEventFlux = receiver
.windowTimeout(maxBatchSize, maxWaitTime);
} else {
partitionEventFlux = receiver
.window(maxBatchSize);
}
partitionEventFlux
.concatMap(Flux::collectList)
.publishOn(scheduler, false, PREFETCH)
.contextWrite(context -> {
return Operators.enableOnDiscard(context, new OnDropped(claimedOwnership.getPartitionId()));
})
.subscribe(partitionEventBatch -> {
processEvents(partitionContext, partitionProcessor,
eventHubConsumer, partitionEventBatch);
},
/* EventHubConsumer receive() returned an error */
ex -> handleError(claimedOwnership, partitionPump, partitionProcessor, ex, partitionContext),
() -> {
partitionProcessor.close(new CloseContext(partitionContext,
CloseReason.EVENT_PROCESSOR_SHUTDOWN));
cleanup(claimedOwnership, partitionPump);
});
} catch (Exception ex) {
if (partitionPumps.containsKey(claimedOwnership.getPartitionId())) {
cleanup(claimedOwnership, partitionPumps.get(claimedOwnership.getPartitionId()));
}
throw logger.logExceptionAsError(
new PartitionProcessorException(
"Error occurred while starting partition pump for partition " + claimedOwnership.getPartitionId(),
ex));
}
} | 10000, "partition-pump-" + claimedOwnership.getPartitionId()); | void startPartitionPump(PartitionOwnership claimedOwnership, Checkpoint checkpoint) {
if (partitionPumps.containsKey(claimedOwnership.getPartitionId())) {
logger.verbose("Consumer is already running for this partition {}", claimedOwnership.getPartitionId());
return;
}
try {
PartitionContext partitionContext = new PartitionContext(claimedOwnership.getFullyQualifiedNamespace(),
claimedOwnership.getEventHubName(), claimedOwnership.getConsumerGroup(),
claimedOwnership.getPartitionId());
PartitionProcessor partitionProcessor = this.partitionProcessorFactory.get();
InitializationContext initializationContext = new InitializationContext(partitionContext);
partitionProcessor.initialize(initializationContext);
EventPosition startFromEventPosition;
if (checkpoint != null && checkpoint.getOffset() != null) {
startFromEventPosition = EventPosition.fromOffset(checkpoint.getOffset());
} else if (checkpoint != null && checkpoint.getSequenceNumber() != null) {
startFromEventPosition = EventPosition.fromSequenceNumber(checkpoint.getSequenceNumber());
} else if (initialPartitionEventPosition.containsKey(claimedOwnership.getPartitionId())) {
startFromEventPosition = initialPartitionEventPosition.get(claimedOwnership.getPartitionId());
} else {
startFromEventPosition = EventPosition.latest();
}
logger.info("Starting event processing from {} for partition {}", startFromEventPosition,
claimedOwnership.getPartitionId());
ReceiveOptions receiveOptions = new ReceiveOptions().setOwnerLevel(0L)
.setTrackLastEnqueuedEventProperties(trackLastEnqueuedEventProperties);
Scheduler scheduler = Schedulers.newBoundedElastic(schedulerSize,
MAXIMUM_QUEUE_SIZE, "partition-pump-" + claimedOwnership.getPartitionId());
EventHubConsumerAsyncClient eventHubConsumer = eventHubClientBuilder.buildAsyncClient()
.createConsumer(claimedOwnership.getConsumerGroup(), PREFETCH);
PartitionPump partitionPump = new PartitionPump(claimedOwnership.getPartitionId(), eventHubConsumer,
scheduler);
partitionPumps.put(claimedOwnership.getPartitionId(), partitionPump);
Flux<Flux<PartitionEvent>> partitionEventFlux;
Flux<PartitionEvent> receiver = eventHubConsumer
.receiveFromPartition(claimedOwnership.getPartitionId(), startFromEventPosition, receiveOptions)
.doOnNext(partitionEvent -> {
if (logger.canLogAtLevel(LogLevel.VERBOSE)) {
logger.verbose("On next {}, {}, {}",
partitionContext.getEventHubName(), partitionContext.getPartitionId(),
partitionEvent.getData().getSequenceNumber());
}
});
if (maxWaitTime != null) {
partitionEventFlux = receiver
.windowTimeout(maxBatchSize, maxWaitTime);
} else {
partitionEventFlux = receiver
.window(maxBatchSize);
}
partitionEventFlux
.concatMap(Flux::collectList)
.publishOn(scheduler, false, PREFETCH)
.subscribe(partitionEventBatch -> {
processEvents(partitionContext, partitionProcessor,
eventHubConsumer, partitionEventBatch);
},
/* EventHubConsumer receive() returned an error */
ex -> handleError(claimedOwnership, partitionPump, partitionProcessor, ex, partitionContext),
() -> {
partitionProcessor.close(new CloseContext(partitionContext,
CloseReason.EVENT_PROCESSOR_SHUTDOWN));
cleanup(claimedOwnership, partitionPump);
});
} catch (Exception ex) {
if (partitionPumps.containsKey(claimedOwnership.getPartitionId())) {
cleanup(claimedOwnership, partitionPumps.get(claimedOwnership.getPartitionId()));
}
throw logger.logExceptionAsError(
new PartitionProcessorException(
"Error occurred while starting partition pump for partition " + claimedOwnership.getPartitionId(),
ex));
}
} | class PartitionPumpManager {
private static final int PREFETCH = EventHubClientBuilder.DEFAULT_PREFETCH_COUNT;
private final ClientLogger logger = new ClientLogger(PartitionPumpManager.class);
private final CheckpointStore checkpointStore;
private final Map<String, PartitionPump> partitionPumps = new ConcurrentHashMap<>();
private final Supplier<PartitionProcessor> partitionProcessorFactory;
private final EventHubClientBuilder eventHubClientBuilder;
private final TracerProvider tracerProvider;
private final boolean trackLastEnqueuedEventProperties;
private final Map<String, EventPosition> initialPartitionEventPosition;
private final Duration maxWaitTime;
private final int maxBatchSize;
private final boolean batchReceiveMode;
/**
* Creates an instance of partition pump manager.
*
* @param checkpointStore The partition manager that is used to store and update checkpoints.
* @param partitionProcessorFactory The partition processor factory that is used to create new instances of {@link
* PartitionProcessor} when new partition pumps are started.
* @param eventHubClientBuilder The client builder used to create new clients (and new connections) for each
* partition processed by this {@link EventProcessorClient}.
* @param trackLastEnqueuedEventProperties If set to {@code true}, all events received by this EventProcessorClient
* will also include the last enqueued event properties for it's respective partitions.
* @param tracerProvider The tracer implementation.
* @param initialPartitionEventPosition Map of initial event positions for partition ids.
* @param maxBatchSize The maximum batch size to receive per users' process handler invocation.
* @param maxWaitTime The maximum time to wait to receive a batch or a single event.
* @param batchReceiveMode The boolean value indicating if this processor is configured to receive in batches or
* single events.
*/
PartitionPumpManager(CheckpointStore checkpointStore,
Supplier<PartitionProcessor> partitionProcessorFactory, EventHubClientBuilder eventHubClientBuilder,
boolean trackLastEnqueuedEventProperties, TracerProvider tracerProvider,
Map<String, EventPosition> initialPartitionEventPosition, int maxBatchSize, Duration maxWaitTime,
boolean batchReceiveMode) {
this.checkpointStore = checkpointStore;
this.partitionProcessorFactory = partitionProcessorFactory;
this.eventHubClientBuilder = eventHubClientBuilder;
this.trackLastEnqueuedEventProperties = trackLastEnqueuedEventProperties;
this.tracerProvider = tracerProvider;
this.initialPartitionEventPosition = initialPartitionEventPosition;
this.maxBatchSize = maxBatchSize;
this.maxWaitTime = maxWaitTime;
this.batchReceiveMode = batchReceiveMode;
}
/**
* Stops all partition pumps that are actively consuming events. This method is invoked when the {@link
* EventProcessorClient} is requested to stop.
*/
void stopAllPartitionPumps() {
this.partitionPumps.forEach((partitionId, eventHubConsumer) -> {
try {
eventHubConsumer.close();
} catch (Exception ex) {
logger.warning(Messages.FAILED_CLOSE_CONSUMER_PARTITION, partitionId, ex);
} finally {
partitionPumps.remove(partitionId);
}
});
}
/**
* Checks the state of the connection for the given partition. If the connection is closed, then this method will
* remove the partition from the list of partition pumps.
*
* @param ownership The partition ownership information for which the connection state will be verified.
*/
void verifyPartitionConnection(PartitionOwnership ownership) {
String partitionId = ownership.getPartitionId();
if (partitionPumps.containsKey(partitionId)) {
PartitionPump partitionPump = partitionPumps.get(partitionId);
EventHubConsumerAsyncClient consumerClient = partitionPump.getClient();
if (consumerClient.isConnectionClosed()) {
logger.info("Connection closed for {}, partition {}. Removing the consumer.",
ownership.getEventHubName(), partitionId);
try {
partitionPumps.get(partitionId).close();
} catch (Exception ex) {
logger.warning(Messages.FAILED_CLOSE_CONSUMER_PARTITION, partitionId, ex);
} finally {
partitionPumps.remove(partitionId);
}
}
}
}
/**
* Starts a new partition pump for the newly claimed partition. If the partition already has an active partition
* pump, this will not create a new consumer.
*
* @param claimedOwnership The details of partition ownership for which new partition pump is requested to start.
*/
private void processEvent(PartitionContext partitionContext, PartitionProcessor partitionProcessor,
EventHubConsumerAsyncClient eventHubConsumer, EventContext eventContext) {
Context processSpanContext = null;
EventData eventData = eventContext.getEventData();
if (eventData != null) {
processSpanContext = startProcessTracingSpan(eventData, eventHubConsumer.getEventHubName(),
eventHubConsumer.getFullyQualifiedNamespace());
if (processSpanContext.getData(SPAN_CONTEXT_KEY).isPresent()) {
eventData.addContext(SPAN_CONTEXT_KEY, processSpanContext);
}
}
try {
if (logger.canLogAtLevel(LogLevel.VERBOSE)) {
logger.verbose("Processing event {}, {}", partitionContext.getEventHubName(),
partitionContext.getPartitionId());
}
partitionProcessor.processEvent(new EventContext(partitionContext, eventData, checkpointStore,
eventContext.getLastEnqueuedEventProperties()));
if (logger.canLogAtLevel(LogLevel.VERBOSE)) {
logger.verbose("Completed processing event {}, {}", partitionContext.getEventHubName(),
partitionContext.getPartitionId());
}
endProcessTracingSpan(processSpanContext, Signal.complete());
} catch (Throwable throwable) {
/* user code for event processing threw an exception - log and bubble up */
endProcessTracingSpan(processSpanContext, Signal.error(throwable));
throw logger.logExceptionAsError(new PartitionProcessorException("Error in event processing callback",
throwable));
}
}
private void processEvents(PartitionContext partitionContext, PartitionProcessor partitionProcessor,
EventHubConsumerAsyncClient eventHubConsumer, List<PartitionEvent> partitionEventBatch) {
try {
if (batchReceiveMode) {
LastEnqueuedEventProperties[] lastEnqueuedEventProperties = new LastEnqueuedEventProperties[1];
List<EventData> eventDataList = partitionEventBatch.stream()
.map(partitionEvent -> {
lastEnqueuedEventProperties[0] = partitionEvent.getLastEnqueuedEventProperties();
return partitionEvent.getData();
})
.collect(Collectors.toList());
EventBatchContext eventBatchContext = new EventBatchContext(partitionContext, eventDataList,
checkpointStore, lastEnqueuedEventProperties[0]);
if (logger.canLogAtLevel(LogLevel.VERBOSE)) {
logger.verbose("Processing event batch {}, {}", partitionContext.getEventHubName(),
partitionContext.getPartitionId());
}
partitionProcessor.processEventBatch(eventBatchContext);
if (logger.canLogAtLevel(LogLevel.VERBOSE)) {
logger.verbose("Completed processing event batch{}, {}", partitionContext.getEventHubName(),
partitionContext.getPartitionId());
}
} else {
EventData eventData = (partitionEventBatch.size() == 1
? partitionEventBatch.get(0).getData() : null);
LastEnqueuedEventProperties lastEnqueuedEventProperties = (partitionEventBatch.size() == 1
? partitionEventBatch.get(0).getLastEnqueuedEventProperties() : null);
EventContext eventContext = new EventContext(partitionContext, eventData, checkpointStore,
lastEnqueuedEventProperties);
processEvent(partitionContext, partitionProcessor, eventHubConsumer, eventContext);
}
} catch (Throwable throwable) {
/* user code for event processing threw an exception - log and bubble up */
throw logger.logExceptionAsError(new PartitionProcessorException("Error in event processing callback",
throwable));
}
}
Map<String, PartitionPump> getPartitionPumps() {
return this.partitionPumps;
}
class OnDropped implements Consumer<Object> {
private final String partitionId;
OnDropped(String partitionId) {
this.partitionId = partitionId;
}
@Override
public void accept(Object o) {
logger.warning("partitionId[{}] Dropped object: {}", partitionId, o);
}
}
private void handleError(PartitionOwnership claimedOwnership, PartitionPump partitionPump,
PartitionProcessor partitionProcessor, Throwable throwable, PartitionContext partitionContext) {
boolean shouldRethrow = true;
if (!(throwable instanceof PartitionProcessorException)) {
shouldRethrow = false;
logger.warning("Error receiving events from partition {}", partitionContext.getPartitionId(), throwable);
partitionProcessor.processError(new ErrorContext(partitionContext, throwable));
}
CloseReason closeReason = CloseReason.LOST_PARTITION_OWNERSHIP;
partitionProcessor.close(new CloseContext(partitionContext, closeReason));
cleanup(claimedOwnership, partitionPump);
if (shouldRethrow) {
PartitionProcessorException exception = (PartitionProcessorException) throwable;
throw logger.logExceptionAsError(exception);
}
}
private void cleanup(PartitionOwnership claimedOwnership, PartitionPump partitionPump) {
try {
logger.info("Closing consumer for partition id {}", claimedOwnership.getPartitionId());
partitionPump.close();
} finally {
logger.info("Removing partition id {} from list of processing partitions",
claimedOwnership.getPartitionId());
partitionPumps.remove(claimedOwnership.getPartitionId());
}
}
/*
* Starts a new process tracing span and attaches the returned context to the EventData object for users.
*/
private Context startProcessTracingSpan(EventData eventData, String eventHubName, String fullyQualifiedNamespace) {
Object diagnosticId = eventData.getProperties().get(DIAGNOSTIC_ID_KEY);
if (diagnosticId == null || !tracerProvider.isEnabled()) {
return Context.NONE;
}
Context spanContext = tracerProvider.extractContext(diagnosticId.toString(), Context.NONE)
.addData(ENTITY_PATH_KEY, eventHubName)
.addData(HOST_NAME_KEY, fullyQualifiedNamespace)
.addData(AZ_TRACING_NAMESPACE_KEY, AZ_NAMESPACE_VALUE);
spanContext = eventData.getEnqueuedTime() == null
? spanContext
: spanContext.addData(MESSAGE_ENQUEUED_TIME, eventData.getEnqueuedTime().getEpochSecond());
return tracerProvider.startSpan(AZ_TRACING_SERVICE_NAME, spanContext, ProcessKind.PROCESS);
}
/*
* Ends the process tracing span and the scope of that span.
*/
private void endProcessTracingSpan(Context processSpanContext, Signal<Void> signal) {
if (processSpanContext == null) {
return;
}
Optional<Object> spanScope = processSpanContext.getData(SCOPE_KEY);
if (!spanScope.isPresent() || !tracerProvider.isEnabled()) {
return;
}
Object spanObject = spanScope.get();
if (spanObject instanceof AutoCloseable) {
AutoCloseable close = (AutoCloseable) spanObject;
try {
close.close();
} catch (Exception exception) {
logger.error(Messages.EVENT_PROCESSOR_RUN_END, exception);
}
} else {
logger.verbose(String.format(Locale.US, Messages.PROCESS_SPAN_SCOPE_TYPE_ERROR,
spanObject != null ? spanObject.getClass() : "null"));
}
tracerProvider.endSpan(processSpanContext, signal);
}
} | class PartitionPumpManager {
private static final int PREFETCH = EventHubClientBuilder.DEFAULT_PREFETCH_COUNT;
private static final int MAXIMUM_QUEUE_SIZE = 10000;
private final int schedulerSize = Runtime.getRuntime().availableProcessors() * 4;
private final ClientLogger logger = new ClientLogger(PartitionPumpManager.class);
private final CheckpointStore checkpointStore;
private final Map<String, PartitionPump> partitionPumps = new ConcurrentHashMap<>();
private final Supplier<PartitionProcessor> partitionProcessorFactory;
private final EventHubClientBuilder eventHubClientBuilder;
private final TracerProvider tracerProvider;
private final boolean trackLastEnqueuedEventProperties;
private final Map<String, EventPosition> initialPartitionEventPosition;
private final Duration maxWaitTime;
private final int maxBatchSize;
private final boolean batchReceiveMode;
/**
* Creates an instance of partition pump manager.
*
* @param checkpointStore The partition manager that is used to store and update checkpoints.
* @param partitionProcessorFactory The partition processor factory that is used to create new instances of {@link
* PartitionProcessor} when new partition pumps are started.
* @param eventHubClientBuilder The client builder used to create new clients (and new connections) for each
* partition processed by this {@link EventProcessorClient}.
* @param trackLastEnqueuedEventProperties If set to {@code true}, all events received by this EventProcessorClient
* will also include the last enqueued event properties for it's respective partitions.
* @param tracerProvider The tracer implementation.
* @param initialPartitionEventPosition Map of initial event positions for partition ids.
* @param maxBatchSize The maximum batch size to receive per users' process handler invocation.
* @param maxWaitTime The maximum time to wait to receive a batch or a single event.
* @param batchReceiveMode The boolean value indicating if this processor is configured to receive in batches or
* single events.
*/
PartitionPumpManager(CheckpointStore checkpointStore,
Supplier<PartitionProcessor> partitionProcessorFactory, EventHubClientBuilder eventHubClientBuilder,
boolean trackLastEnqueuedEventProperties, TracerProvider tracerProvider,
Map<String, EventPosition> initialPartitionEventPosition, int maxBatchSize, Duration maxWaitTime,
boolean batchReceiveMode) {
this.checkpointStore = checkpointStore;
this.partitionProcessorFactory = partitionProcessorFactory;
this.eventHubClientBuilder = eventHubClientBuilder;
this.trackLastEnqueuedEventProperties = trackLastEnqueuedEventProperties;
this.tracerProvider = tracerProvider;
this.initialPartitionEventPosition = initialPartitionEventPosition;
this.maxBatchSize = maxBatchSize;
this.maxWaitTime = maxWaitTime;
this.batchReceiveMode = batchReceiveMode;
}
/**
* Stops all partition pumps that are actively consuming events. This method is invoked when the {@link
* EventProcessorClient} is requested to stop.
*/
void stopAllPartitionPumps() {
this.partitionPumps.forEach((partitionId, eventHubConsumer) -> {
try {
eventHubConsumer.close();
} catch (Exception ex) {
logger.warning(Messages.FAILED_CLOSE_CONSUMER_PARTITION, partitionId, ex);
} finally {
partitionPumps.remove(partitionId);
}
});
}
/**
* Checks the state of the connection for the given partition. If the connection is closed, then this method will
* remove the partition from the list of partition pumps.
*
* @param ownership The partition ownership information for which the connection state will be verified.
*/
void verifyPartitionConnection(PartitionOwnership ownership) {
final String partitionId = ownership.getPartitionId();
final PartitionPump partitionPump = partitionPumps.get(partitionId);
if (partitionPump == null) {
logger.info("eventHubName[{}] partitionId[{}] No partition pump found for ownership record.",
ownership.getEventHubName(), partitionId);
return;
}
final EventHubConsumerAsyncClient consumerClient = partitionPump.getClient();
if (consumerClient.isConnectionClosed()) {
logger.info("eventHubName[{}] partitionId[{}] Connection closed for partition. Removing the consumer.",
ownership.getEventHubName(), partitionId);
try {
partitionPump.close();
} catch (Exception ex) {
logger.warning(Messages.FAILED_CLOSE_CONSUMER_PARTITION, partitionId, ex);
} finally {
partitionPumps.remove(partitionId);
}
}
}
/**
* Starts a new partition pump for the newly claimed partition. If the partition already has an active partition
* pump, this will not create a new consumer.
*
* @param claimedOwnership The details of partition ownership for which new partition pump is requested to start.
*/
private void processEvent(PartitionContext partitionContext, PartitionProcessor partitionProcessor,
EventHubConsumerAsyncClient eventHubConsumer, EventContext eventContext) {
Context processSpanContext = null;
EventData eventData = eventContext.getEventData();
if (eventData != null) {
processSpanContext = startProcessTracingSpan(eventData, eventHubConsumer.getEventHubName(),
eventHubConsumer.getFullyQualifiedNamespace());
if (processSpanContext.getData(SPAN_CONTEXT_KEY).isPresent()) {
eventData.addContext(SPAN_CONTEXT_KEY, processSpanContext);
}
}
try {
if (logger.canLogAtLevel(LogLevel.VERBOSE)) {
logger.verbose("Processing event {}, {}", partitionContext.getEventHubName(),
partitionContext.getPartitionId());
}
partitionProcessor.processEvent(new EventContext(partitionContext, eventData, checkpointStore,
eventContext.getLastEnqueuedEventProperties()));
if (logger.canLogAtLevel(LogLevel.VERBOSE)) {
logger.verbose("Completed processing event {}, {}", partitionContext.getEventHubName(),
partitionContext.getPartitionId());
}
endProcessTracingSpan(processSpanContext, Signal.complete());
} catch (Throwable throwable) {
/* user code for event processing threw an exception - log and bubble up */
endProcessTracingSpan(processSpanContext, Signal.error(throwable));
throw logger.logExceptionAsError(new PartitionProcessorException("Error in event processing callback",
throwable));
}
}
private void processEvents(PartitionContext partitionContext, PartitionProcessor partitionProcessor,
EventHubConsumerAsyncClient eventHubConsumer, List<PartitionEvent> partitionEventBatch) {
try {
if (batchReceiveMode) {
LastEnqueuedEventProperties[] lastEnqueuedEventProperties = new LastEnqueuedEventProperties[1];
List<EventData> eventDataList = partitionEventBatch.stream()
.map(partitionEvent -> {
lastEnqueuedEventProperties[0] = partitionEvent.getLastEnqueuedEventProperties();
return partitionEvent.getData();
})
.collect(Collectors.toList());
EventBatchContext eventBatchContext = new EventBatchContext(partitionContext, eventDataList,
checkpointStore, lastEnqueuedEventProperties[0]);
if (logger.canLogAtLevel(LogLevel.VERBOSE)) {
logger.verbose("Processing event batch {}, {}", partitionContext.getEventHubName(),
partitionContext.getPartitionId());
}
partitionProcessor.processEventBatch(eventBatchContext);
if (logger.canLogAtLevel(LogLevel.VERBOSE)) {
logger.verbose("Completed processing event batch{}, {}", partitionContext.getEventHubName(),
partitionContext.getPartitionId());
}
} else {
EventData eventData = (partitionEventBatch.size() == 1
? partitionEventBatch.get(0).getData() : null);
LastEnqueuedEventProperties lastEnqueuedEventProperties = (partitionEventBatch.size() == 1
? partitionEventBatch.get(0).getLastEnqueuedEventProperties() : null);
EventContext eventContext = new EventContext(partitionContext, eventData, checkpointStore,
lastEnqueuedEventProperties);
processEvent(partitionContext, partitionProcessor, eventHubConsumer, eventContext);
}
} catch (Throwable throwable) {
/* user code for event processing threw an exception - log and bubble up */
throw logger.logExceptionAsError(new PartitionProcessorException("Error in event processing callback",
throwable));
}
}
Map<String, PartitionPump> getPartitionPumps() {
return this.partitionPumps;
}
private void handleError(PartitionOwnership claimedOwnership, PartitionPump partitionPump,
PartitionProcessor partitionProcessor, Throwable throwable, PartitionContext partitionContext) {
boolean shouldRethrow = true;
if (!(throwable instanceof PartitionProcessorException)) {
shouldRethrow = false;
logger.warning("Error receiving events from partition {}", partitionContext.getPartitionId(), throwable);
partitionProcessor.processError(new ErrorContext(partitionContext, throwable));
}
CloseReason closeReason = CloseReason.LOST_PARTITION_OWNERSHIP;
partitionProcessor.close(new CloseContext(partitionContext, closeReason));
cleanup(claimedOwnership, partitionPump);
if (shouldRethrow) {
PartitionProcessorException exception = (PartitionProcessorException) throwable;
throw logger.logExceptionAsError(exception);
}
}
private void cleanup(PartitionOwnership claimedOwnership, PartitionPump partitionPump) {
try {
logger.info("Closing consumer for partition id {}", claimedOwnership.getPartitionId());
partitionPump.close();
} finally {
logger.info("Removing partition id {} from list of processing partitions",
claimedOwnership.getPartitionId());
partitionPumps.remove(claimedOwnership.getPartitionId());
}
}
/*
* Starts a new process tracing span and attaches the returned context to the EventData object for users.
*/
private Context startProcessTracingSpan(EventData eventData, String eventHubName, String fullyQualifiedNamespace) {
Object diagnosticId = eventData.getProperties().get(DIAGNOSTIC_ID_KEY);
if (diagnosticId == null || !tracerProvider.isEnabled()) {
return Context.NONE;
}
Context spanContext = tracerProvider.extractContext(diagnosticId.toString(), Context.NONE)
.addData(ENTITY_PATH_KEY, eventHubName)
.addData(HOST_NAME_KEY, fullyQualifiedNamespace)
.addData(AZ_TRACING_NAMESPACE_KEY, AZ_NAMESPACE_VALUE);
spanContext = eventData.getEnqueuedTime() == null
? spanContext
: spanContext.addData(MESSAGE_ENQUEUED_TIME, eventData.getEnqueuedTime().getEpochSecond());
return tracerProvider.startSpan(AZ_TRACING_SERVICE_NAME, spanContext, ProcessKind.PROCESS);
}
/*
* Ends the process tracing span and the scope of that span.
*/
private void endProcessTracingSpan(Context processSpanContext, Signal<Void> signal) {
if (processSpanContext == null) {
return;
}
Optional<Object> spanScope = processSpanContext.getData(SCOPE_KEY);
if (!spanScope.isPresent() || !tracerProvider.isEnabled()) {
return;
}
Object spanObject = spanScope.get();
if (spanObject instanceof AutoCloseable) {
AutoCloseable close = (AutoCloseable) spanObject;
try {
close.close();
} catch (Exception exception) {
logger.error(Messages.EVENT_PROCESSOR_RUN_END, exception);
}
} else {
logger.verbose(String.format(Locale.US, Messages.PROCESS_SPAN_SCOPE_TYPE_ERROR,
spanObject != null ? spanObject.getClass() : "null"));
}
tracerProvider.endSpan(processSpanContext, signal);
}
} |
Don't we want to record the new data when running in LIVE mode? | public Mono<HttpResponse> process(HttpPipelineCallContext context, HttpPipelineNextPolicy next) {
if (TestBase.getTestMode() == TestMode.LIVE) {
return next.process();
}
final NetworkCallRecord networkCallRecord = new NetworkCallRecord();
Map<String, String> headers = new HashMap<>();
captureRequestHeaders(context.getHttpRequest().getHeaders(), headers,
X_MS_CLIENT_REQUEST_ID,
CONTENT_TYPE,
X_MS_VERSION,
USER_AGENT);
networkCallRecord.setHeaders(headers);
networkCallRecord.setMethod(context.getHttpRequest().getHttpMethod().toString());
UrlBuilder urlBuilder = UrlBuilder.parse(context.getHttpRequest().getUrl());
redactedAccountName(urlBuilder);
if (urlBuilder.getQuery().containsKey(SIG)) {
urlBuilder.setQueryParameter(SIG, "REDACTED");
}
networkCallRecord.setUri(urlBuilder.toString().replaceAll("\\?$", ""));
return next.process()
.doOnError(throwable -> {
networkCallRecord.setException(new NetworkCallError(throwable));
recordedData.addNetworkCall(networkCallRecord);
throw logger.logExceptionAsWarning(Exceptions.propagate(throwable));
}).flatMap(httpResponse -> {
final HttpResponse bufferedResponse = httpResponse.buffer();
return extractResponseData(bufferedResponse, redactor, logger).map(responseData -> {
networkCallRecord.setResponse(responseData);
String body = responseData.get(BODY);
if (body != null && body.contains("<Status>InProgress</Status>")
|| Integer.parseInt(responseData.get(STATUS_CODE)) == HttpURLConnection.HTTP_MOVED_TEMP) {
logger.info("Waiting for a response or redirection.");
} else {
recordedData.addNetworkCall(networkCallRecord);
}
return bufferedResponse;
});
});
} | if (TestBase.getTestMode() == TestMode.LIVE) { | public Mono<HttpResponse> process(HttpPipelineCallContext context, HttpPipelineNextPolicy next) {
if (TEST_MODE == TestMode.LIVE) {
return next.process();
}
final NetworkCallRecord networkCallRecord = new NetworkCallRecord();
Map<String, String> headers = new HashMap<>();
captureRequestHeaders(context.getHttpRequest().getHeaders(), headers,
X_MS_CLIENT_REQUEST_ID,
CONTENT_TYPE,
X_MS_VERSION,
USER_AGENT);
networkCallRecord.setHeaders(headers);
networkCallRecord.setMethod(context.getHttpRequest().getHttpMethod().toString());
UrlBuilder urlBuilder = UrlBuilder.parse(context.getHttpRequest().getUrl());
redactedAccountName(urlBuilder);
if (urlBuilder.getQuery().containsKey(SIG)) {
urlBuilder.setQueryParameter(SIG, "REDACTED");
}
networkCallRecord.setUri(urlBuilder.toString().replaceAll("\\?$", ""));
return next.process()
.doOnError(throwable -> {
networkCallRecord.setException(new NetworkCallError(throwable));
recordedData.addNetworkCall(networkCallRecord);
throw logger.logExceptionAsWarning(Exceptions.propagate(throwable));
}).flatMap(httpResponse -> {
final HttpResponse bufferedResponse = httpResponse.buffer();
return extractResponseData(bufferedResponse, redactor, logger).map(responseData -> {
networkCallRecord.setResponse(responseData);
String body = responseData.get(BODY);
if (body != null && body.contains("<Status>InProgress</Status>")
|| Integer.parseInt(responseData.get(STATUS_CODE)) == HttpURLConnection.HTTP_MOVED_TEMP) {
logger.info("Waiting for a response or redirection.");
} else {
recordedData.addNetworkCall(networkCallRecord);
}
return bufferedResponse;
});
});
} | class RecordNetworkCallPolicy implements HttpPipelinePolicy {
private static final int DEFAULT_BUFFER_LENGTH = 1024;
private static final String CONTENT_TYPE = "Content-Type";
private static final String CONTENT_ENCODING = "Content-Encoding";
private static final String CONTENT_LENGTH = "Content-Length";
private static final String X_MS_CLIENT_REQUEST_ID = "x-ms-client-request-id";
private static final String X_MS_ENCRYPTION_KEY_SHA256 = "x-ms-encryption-key-sha256";
private static final String X_MS_VERSION = "x-ms-version";
private static final String USER_AGENT = "User-Agent";
private static final String STATUS_CODE = "StatusCode";
private static final String BODY = "Body";
private static final String SIG = "sig";
private final ClientLogger logger = new ClientLogger(RecordNetworkCallPolicy.class);
private final RecordedData recordedData;
private final RecordingRedactor redactor;
/**
* Creates a policy that records network calls into {@code recordedData}.
*
* @param recordedData The record to persist network calls into.
*/
public RecordNetworkCallPolicy(RecordedData recordedData) {
this(recordedData, Collections.emptyList());
}
/**
* Creates a policy that records network calls into {@code recordedData} by redacting sensitive information by
* applying the provided redactor functions.
* @param recordedData The record to persist network calls into.
* @param redactors The custom redactor functions to apply to redact sensitive information from recorded data.
*/
public RecordNetworkCallPolicy(RecordedData recordedData, List<Function<String, String>> redactors) {
this.recordedData = recordedData;
redactor = new RecordingRedactor(redactors);
}
@Override
private static void redactedAccountName(UrlBuilder urlBuilder) {
String[] hostParts = urlBuilder.getHost().split("\\.");
hostParts[0] = "REDACTED";
urlBuilder.setHost(String.join(".", hostParts));
}
private static void captureRequestHeaders(HttpHeaders requestHeaders, Map<String, String> captureHeaders,
String... headerNames) {
for (String headerName : headerNames) {
if (requestHeaders.getValue(headerName) != null) {
captureHeaders.put(headerName, requestHeaders.getValue(headerName));
}
}
}
private static Mono<Map<String, String>> extractResponseData(final HttpResponse response,
final RecordingRedactor redactor, final ClientLogger logger) {
final Map<String, String> responseData = new HashMap<>();
responseData.put(STATUS_CODE, Integer.toString(response.getStatusCode()));
boolean addedRetryAfter = false;
for (HttpHeader header : response.getHeaders()) {
String headerValueToStore = header.getValue();
if (header.getName().equalsIgnoreCase("retry-after")) {
headerValueToStore = "0";
addedRetryAfter = true;
} else if (header.getName().equalsIgnoreCase(X_MS_ENCRYPTION_KEY_SHA256)) {
headerValueToStore = "REDACTED";
}
responseData.put(header.getName(), headerValueToStore);
}
if (!addedRetryAfter) {
responseData.put("retry-after", "0");
}
String contentType = response.getHeaderValue(CONTENT_TYPE);
if (contentType == null) {
return response.getBodyAsByteArray().switchIfEmpty(Mono.just(new byte[0])).map(bytes -> {
if (bytes.length == 0) {
return responseData;
}
String content = new String(bytes, StandardCharsets.UTF_8);
responseData.put(CONTENT_LENGTH, Integer.toString(content.length()));
responseData.put(BODY, content);
return responseData;
});
} else if (contentType.equalsIgnoreCase(ContentType.APPLICATION_OCTET_STREAM)
|| contentType.equalsIgnoreCase("avro/binary")) {
return response.getBodyAsByteArray().switchIfEmpty(Mono.just(new byte[0])).map(bytes -> {
if (bytes.length == 0) {
return responseData;
}
responseData.put(BODY, Base64.getEncoder().encodeToString(bytes));
return responseData;
});
} else if (contentType.contains("json") || response.getHeaderValue(CONTENT_ENCODING) == null) {
return response.getBodyAsString(StandardCharsets.UTF_8).switchIfEmpty(Mono.just("")).map(content -> {
responseData.put(BODY, redactor.redact(content));
return responseData;
});
} else {
return response.getBodyAsByteArray().switchIfEmpty(Mono.just(new byte[0])).map(bytes -> {
if (bytes.length == 0) {
return responseData;
}
String content;
if ("gzip".equalsIgnoreCase(response.getHeaderValue(CONTENT_ENCODING))) {
try (GZIPInputStream gis = new GZIPInputStream(new ByteArrayInputStream(bytes));
ByteArrayOutputStream output = new ByteArrayOutputStream()) {
byte[] buffer = new byte[DEFAULT_BUFFER_LENGTH];
int position = 0;
int bytesRead = gis.read(buffer, position, buffer.length);
while (bytesRead != -1) {
output.write(buffer, 0, bytesRead);
position += bytesRead;
bytesRead = gis.read(buffer, position, buffer.length);
}
content = output.toString("UTF-8");
} catch (IOException e) {
throw logger.logExceptionAsWarning(Exceptions.propagate(e));
}
} else {
content = new String(bytes, StandardCharsets.UTF_8);
}
responseData.remove(CONTENT_ENCODING);
responseData.put(CONTENT_LENGTH, Integer.toString(content.length()));
responseData.put(BODY, content);
return responseData;
});
}
}
} | class RecordNetworkCallPolicy implements HttpPipelinePolicy {
private static final int DEFAULT_BUFFER_LENGTH = 1024;
private static final String CONTENT_TYPE = "Content-Type";
private static final String CONTENT_ENCODING = "Content-Encoding";
private static final String CONTENT_LENGTH = "Content-Length";
private static final String X_MS_CLIENT_REQUEST_ID = "x-ms-client-request-id";
private static final String X_MS_ENCRYPTION_KEY_SHA256 = "x-ms-encryption-key-sha256";
private static final String X_MS_VERSION = "x-ms-version";
private static final String USER_AGENT = "User-Agent";
private static final String STATUS_CODE = "StatusCode";
private static final String BODY = "Body";
private static final String SIG = "sig";
private static final TestMode TEST_MODE = ImplUtils.getTestMode();
private final ClientLogger logger = new ClientLogger(RecordNetworkCallPolicy.class);
private final RecordedData recordedData;
private final RecordingRedactor redactor;
/**
* Creates a policy that records network calls into {@code recordedData}.
*
* @param recordedData The record to persist network calls into.
*/
public RecordNetworkCallPolicy(RecordedData recordedData) {
this(recordedData, Collections.emptyList());
}
/**
* Creates a policy that records network calls into {@code recordedData} by redacting sensitive information by
* applying the provided redactor functions.
* @param recordedData The record to persist network calls into.
* @param redactors The custom redactor functions to apply to redact sensitive information from recorded data.
*/
public RecordNetworkCallPolicy(RecordedData recordedData, List<Function<String, String>> redactors) {
this.recordedData = recordedData;
redactor = new RecordingRedactor(redactors);
}
@Override
private static void redactedAccountName(UrlBuilder urlBuilder) {
String[] hostParts = urlBuilder.getHost().split("\\.");
hostParts[0] = "REDACTED";
urlBuilder.setHost(String.join(".", hostParts));
}
private static void captureRequestHeaders(HttpHeaders requestHeaders, Map<String, String> captureHeaders,
String... headerNames) {
for (String headerName : headerNames) {
if (requestHeaders.getValue(headerName) != null) {
captureHeaders.put(headerName, requestHeaders.getValue(headerName));
}
}
}
private static Mono<Map<String, String>> extractResponseData(final HttpResponse response,
final RecordingRedactor redactor, final ClientLogger logger) {
final Map<String, String> responseData = new HashMap<>();
responseData.put(STATUS_CODE, Integer.toString(response.getStatusCode()));
boolean addedRetryAfter = false;
for (HttpHeader header : response.getHeaders()) {
String headerValueToStore = header.getValue();
if (header.getName().equalsIgnoreCase("retry-after")) {
headerValueToStore = "0";
addedRetryAfter = true;
} else if (header.getName().equalsIgnoreCase(X_MS_ENCRYPTION_KEY_SHA256)) {
headerValueToStore = "REDACTED";
}
responseData.put(header.getName(), headerValueToStore);
}
if (!addedRetryAfter) {
responseData.put("retry-after", "0");
}
String contentType = response.getHeaderValue(CONTENT_TYPE);
if (contentType == null) {
return response.getBodyAsByteArray().switchIfEmpty(Mono.just(new byte[0])).map(bytes -> {
if (bytes.length == 0) {
return responseData;
}
String content = new String(bytes, StandardCharsets.UTF_8);
responseData.put(CONTENT_LENGTH, Integer.toString(content.length()));
responseData.put(BODY, content);
return responseData;
});
} else if (contentType.equalsIgnoreCase(ContentType.APPLICATION_OCTET_STREAM)
|| contentType.equalsIgnoreCase("avro/binary")) {
return response.getBodyAsByteArray().switchIfEmpty(Mono.just(new byte[0])).map(bytes -> {
if (bytes.length == 0) {
return responseData;
}
responseData.put(BODY, Base64.getEncoder().encodeToString(bytes));
return responseData;
});
} else if (contentType.contains("json") || response.getHeaderValue(CONTENT_ENCODING) == null) {
return response.getBodyAsString(StandardCharsets.UTF_8).switchIfEmpty(Mono.just("")).map(content -> {
responseData.put(BODY, redactor.redact(content));
return responseData;
});
} else {
return response.getBodyAsByteArray().switchIfEmpty(Mono.just(new byte[0])).map(bytes -> {
if (bytes.length == 0) {
return responseData;
}
String content;
if ("gzip".equalsIgnoreCase(response.getHeaderValue(CONTENT_ENCODING))) {
try (GZIPInputStream gis = new GZIPInputStream(new ByteArrayInputStream(bytes));
ByteArrayOutputStream output = new ByteArrayOutputStream()) {
byte[] buffer = new byte[DEFAULT_BUFFER_LENGTH];
int position = 0;
int bytesRead = gis.read(buffer, position, buffer.length);
while (bytesRead != -1) {
output.write(buffer, 0, bytesRead);
position += bytesRead;
bytesRead = gis.read(buffer, position, buffer.length);
}
content = output.toString("UTF-8");
} catch (IOException e) {
throw logger.logExceptionAsWarning(Exceptions.propagate(e));
}
} else {
content = new String(bytes, StandardCharsets.UTF_8);
}
responseData.remove(CONTENT_ENCODING);
responseData.put(CONTENT_LENGTH, Integer.toString(content.length()));
responseData.put(BODY, content);
return responseData;
});
}
}
} |
We record when in `TestMode.RECORD` 😃 | public Mono<HttpResponse> process(HttpPipelineCallContext context, HttpPipelineNextPolicy next) {
if (TestBase.getTestMode() == TestMode.LIVE) {
return next.process();
}
final NetworkCallRecord networkCallRecord = new NetworkCallRecord();
Map<String, String> headers = new HashMap<>();
captureRequestHeaders(context.getHttpRequest().getHeaders(), headers,
X_MS_CLIENT_REQUEST_ID,
CONTENT_TYPE,
X_MS_VERSION,
USER_AGENT);
networkCallRecord.setHeaders(headers);
networkCallRecord.setMethod(context.getHttpRequest().getHttpMethod().toString());
UrlBuilder urlBuilder = UrlBuilder.parse(context.getHttpRequest().getUrl());
redactedAccountName(urlBuilder);
if (urlBuilder.getQuery().containsKey(SIG)) {
urlBuilder.setQueryParameter(SIG, "REDACTED");
}
networkCallRecord.setUri(urlBuilder.toString().replaceAll("\\?$", ""));
return next.process()
.doOnError(throwable -> {
networkCallRecord.setException(new NetworkCallError(throwable));
recordedData.addNetworkCall(networkCallRecord);
throw logger.logExceptionAsWarning(Exceptions.propagate(throwable));
}).flatMap(httpResponse -> {
final HttpResponse bufferedResponse = httpResponse.buffer();
return extractResponseData(bufferedResponse, redactor, logger).map(responseData -> {
networkCallRecord.setResponse(responseData);
String body = responseData.get(BODY);
if (body != null && body.contains("<Status>InProgress</Status>")
|| Integer.parseInt(responseData.get(STATUS_CODE)) == HttpURLConnection.HTTP_MOVED_TEMP) {
logger.info("Waiting for a response or redirection.");
} else {
recordedData.addNetworkCall(networkCallRecord);
}
return bufferedResponse;
});
});
} | if (TestBase.getTestMode() == TestMode.LIVE) { | public Mono<HttpResponse> process(HttpPipelineCallContext context, HttpPipelineNextPolicy next) {
if (TEST_MODE == TestMode.LIVE) {
return next.process();
}
final NetworkCallRecord networkCallRecord = new NetworkCallRecord();
Map<String, String> headers = new HashMap<>();
captureRequestHeaders(context.getHttpRequest().getHeaders(), headers,
X_MS_CLIENT_REQUEST_ID,
CONTENT_TYPE,
X_MS_VERSION,
USER_AGENT);
networkCallRecord.setHeaders(headers);
networkCallRecord.setMethod(context.getHttpRequest().getHttpMethod().toString());
UrlBuilder urlBuilder = UrlBuilder.parse(context.getHttpRequest().getUrl());
redactedAccountName(urlBuilder);
if (urlBuilder.getQuery().containsKey(SIG)) {
urlBuilder.setQueryParameter(SIG, "REDACTED");
}
networkCallRecord.setUri(urlBuilder.toString().replaceAll("\\?$", ""));
return next.process()
.doOnError(throwable -> {
networkCallRecord.setException(new NetworkCallError(throwable));
recordedData.addNetworkCall(networkCallRecord);
throw logger.logExceptionAsWarning(Exceptions.propagate(throwable));
}).flatMap(httpResponse -> {
final HttpResponse bufferedResponse = httpResponse.buffer();
return extractResponseData(bufferedResponse, redactor, logger).map(responseData -> {
networkCallRecord.setResponse(responseData);
String body = responseData.get(BODY);
if (body != null && body.contains("<Status>InProgress</Status>")
|| Integer.parseInt(responseData.get(STATUS_CODE)) == HttpURLConnection.HTTP_MOVED_TEMP) {
logger.info("Waiting for a response or redirection.");
} else {
recordedData.addNetworkCall(networkCallRecord);
}
return bufferedResponse;
});
});
} | class RecordNetworkCallPolicy implements HttpPipelinePolicy {
private static final int DEFAULT_BUFFER_LENGTH = 1024;
private static final String CONTENT_TYPE = "Content-Type";
private static final String CONTENT_ENCODING = "Content-Encoding";
private static final String CONTENT_LENGTH = "Content-Length";
private static final String X_MS_CLIENT_REQUEST_ID = "x-ms-client-request-id";
private static final String X_MS_ENCRYPTION_KEY_SHA256 = "x-ms-encryption-key-sha256";
private static final String X_MS_VERSION = "x-ms-version";
private static final String USER_AGENT = "User-Agent";
private static final String STATUS_CODE = "StatusCode";
private static final String BODY = "Body";
private static final String SIG = "sig";
private final ClientLogger logger = new ClientLogger(RecordNetworkCallPolicy.class);
private final RecordedData recordedData;
private final RecordingRedactor redactor;
/**
* Creates a policy that records network calls into {@code recordedData}.
*
* @param recordedData The record to persist network calls into.
*/
public RecordNetworkCallPolicy(RecordedData recordedData) {
this(recordedData, Collections.emptyList());
}
/**
* Creates a policy that records network calls into {@code recordedData} by redacting sensitive information by
* applying the provided redactor functions.
* @param recordedData The record to persist network calls into.
* @param redactors The custom redactor functions to apply to redact sensitive information from recorded data.
*/
public RecordNetworkCallPolicy(RecordedData recordedData, List<Function<String, String>> redactors) {
this.recordedData = recordedData;
redactor = new RecordingRedactor(redactors);
}
@Override
private static void redactedAccountName(UrlBuilder urlBuilder) {
String[] hostParts = urlBuilder.getHost().split("\\.");
hostParts[0] = "REDACTED";
urlBuilder.setHost(String.join(".", hostParts));
}
private static void captureRequestHeaders(HttpHeaders requestHeaders, Map<String, String> captureHeaders,
String... headerNames) {
for (String headerName : headerNames) {
if (requestHeaders.getValue(headerName) != null) {
captureHeaders.put(headerName, requestHeaders.getValue(headerName));
}
}
}
private static Mono<Map<String, String>> extractResponseData(final HttpResponse response,
final RecordingRedactor redactor, final ClientLogger logger) {
final Map<String, String> responseData = new HashMap<>();
responseData.put(STATUS_CODE, Integer.toString(response.getStatusCode()));
boolean addedRetryAfter = false;
for (HttpHeader header : response.getHeaders()) {
String headerValueToStore = header.getValue();
if (header.getName().equalsIgnoreCase("retry-after")) {
headerValueToStore = "0";
addedRetryAfter = true;
} else if (header.getName().equalsIgnoreCase(X_MS_ENCRYPTION_KEY_SHA256)) {
headerValueToStore = "REDACTED";
}
responseData.put(header.getName(), headerValueToStore);
}
if (!addedRetryAfter) {
responseData.put("retry-after", "0");
}
String contentType = response.getHeaderValue(CONTENT_TYPE);
if (contentType == null) {
return response.getBodyAsByteArray().switchIfEmpty(Mono.just(new byte[0])).map(bytes -> {
if (bytes.length == 0) {
return responseData;
}
String content = new String(bytes, StandardCharsets.UTF_8);
responseData.put(CONTENT_LENGTH, Integer.toString(content.length()));
responseData.put(BODY, content);
return responseData;
});
} else if (contentType.equalsIgnoreCase(ContentType.APPLICATION_OCTET_STREAM)
|| contentType.equalsIgnoreCase("avro/binary")) {
return response.getBodyAsByteArray().switchIfEmpty(Mono.just(new byte[0])).map(bytes -> {
if (bytes.length == 0) {
return responseData;
}
responseData.put(BODY, Base64.getEncoder().encodeToString(bytes));
return responseData;
});
} else if (contentType.contains("json") || response.getHeaderValue(CONTENT_ENCODING) == null) {
return response.getBodyAsString(StandardCharsets.UTF_8).switchIfEmpty(Mono.just("")).map(content -> {
responseData.put(BODY, redactor.redact(content));
return responseData;
});
} else {
return response.getBodyAsByteArray().switchIfEmpty(Mono.just(new byte[0])).map(bytes -> {
if (bytes.length == 0) {
return responseData;
}
String content;
if ("gzip".equalsIgnoreCase(response.getHeaderValue(CONTENT_ENCODING))) {
try (GZIPInputStream gis = new GZIPInputStream(new ByteArrayInputStream(bytes));
ByteArrayOutputStream output = new ByteArrayOutputStream()) {
byte[] buffer = new byte[DEFAULT_BUFFER_LENGTH];
int position = 0;
int bytesRead = gis.read(buffer, position, buffer.length);
while (bytesRead != -1) {
output.write(buffer, 0, bytesRead);
position += bytesRead;
bytesRead = gis.read(buffer, position, buffer.length);
}
content = output.toString("UTF-8");
} catch (IOException e) {
throw logger.logExceptionAsWarning(Exceptions.propagate(e));
}
} else {
content = new String(bytes, StandardCharsets.UTF_8);
}
responseData.remove(CONTENT_ENCODING);
responseData.put(CONTENT_LENGTH, Integer.toString(content.length()));
responseData.put(BODY, content);
return responseData;
});
}
}
} | class RecordNetworkCallPolicy implements HttpPipelinePolicy {
private static final int DEFAULT_BUFFER_LENGTH = 1024;
private static final String CONTENT_TYPE = "Content-Type";
private static final String CONTENT_ENCODING = "Content-Encoding";
private static final String CONTENT_LENGTH = "Content-Length";
private static final String X_MS_CLIENT_REQUEST_ID = "x-ms-client-request-id";
private static final String X_MS_ENCRYPTION_KEY_SHA256 = "x-ms-encryption-key-sha256";
private static final String X_MS_VERSION = "x-ms-version";
private static final String USER_AGENT = "User-Agent";
private static final String STATUS_CODE = "StatusCode";
private static final String BODY = "Body";
private static final String SIG = "sig";
private static final TestMode TEST_MODE = ImplUtils.getTestMode();
private final ClientLogger logger = new ClientLogger(RecordNetworkCallPolicy.class);
private final RecordedData recordedData;
private final RecordingRedactor redactor;
/**
* Creates a policy that records network calls into {@code recordedData}.
*
* @param recordedData The record to persist network calls into.
*/
public RecordNetworkCallPolicy(RecordedData recordedData) {
this(recordedData, Collections.emptyList());
}
/**
* Creates a policy that records network calls into {@code recordedData} by redacting sensitive information by
* applying the provided redactor functions.
* @param recordedData The record to persist network calls into.
* @param redactors The custom redactor functions to apply to redact sensitive information from recorded data.
*/
public RecordNetworkCallPolicy(RecordedData recordedData, List<Function<String, String>> redactors) {
this.recordedData = recordedData;
redactor = new RecordingRedactor(redactors);
}
@Override
private static void redactedAccountName(UrlBuilder urlBuilder) {
String[] hostParts = urlBuilder.getHost().split("\\.");
hostParts[0] = "REDACTED";
urlBuilder.setHost(String.join(".", hostParts));
}
private static void captureRequestHeaders(HttpHeaders requestHeaders, Map<String, String> captureHeaders,
String... headerNames) {
for (String headerName : headerNames) {
if (requestHeaders.getValue(headerName) != null) {
captureHeaders.put(headerName, requestHeaders.getValue(headerName));
}
}
}
private static Mono<Map<String, String>> extractResponseData(final HttpResponse response,
final RecordingRedactor redactor, final ClientLogger logger) {
final Map<String, String> responseData = new HashMap<>();
responseData.put(STATUS_CODE, Integer.toString(response.getStatusCode()));
boolean addedRetryAfter = false;
for (HttpHeader header : response.getHeaders()) {
String headerValueToStore = header.getValue();
if (header.getName().equalsIgnoreCase("retry-after")) {
headerValueToStore = "0";
addedRetryAfter = true;
} else if (header.getName().equalsIgnoreCase(X_MS_ENCRYPTION_KEY_SHA256)) {
headerValueToStore = "REDACTED";
}
responseData.put(header.getName(), headerValueToStore);
}
if (!addedRetryAfter) {
responseData.put("retry-after", "0");
}
String contentType = response.getHeaderValue(CONTENT_TYPE);
if (contentType == null) {
return response.getBodyAsByteArray().switchIfEmpty(Mono.just(new byte[0])).map(bytes -> {
if (bytes.length == 0) {
return responseData;
}
String content = new String(bytes, StandardCharsets.UTF_8);
responseData.put(CONTENT_LENGTH, Integer.toString(content.length()));
responseData.put(BODY, content);
return responseData;
});
} else if (contentType.equalsIgnoreCase(ContentType.APPLICATION_OCTET_STREAM)
|| contentType.equalsIgnoreCase("avro/binary")) {
return response.getBodyAsByteArray().switchIfEmpty(Mono.just(new byte[0])).map(bytes -> {
if (bytes.length == 0) {
return responseData;
}
responseData.put(BODY, Base64.getEncoder().encodeToString(bytes));
return responseData;
});
} else if (contentType.contains("json") || response.getHeaderValue(CONTENT_ENCODING) == null) {
return response.getBodyAsString(StandardCharsets.UTF_8).switchIfEmpty(Mono.just("")).map(content -> {
responseData.put(BODY, redactor.redact(content));
return responseData;
});
} else {
return response.getBodyAsByteArray().switchIfEmpty(Mono.just(new byte[0])).map(bytes -> {
if (bytes.length == 0) {
return responseData;
}
String content;
if ("gzip".equalsIgnoreCase(response.getHeaderValue(CONTENT_ENCODING))) {
try (GZIPInputStream gis = new GZIPInputStream(new ByteArrayInputStream(bytes));
ByteArrayOutputStream output = new ByteArrayOutputStream()) {
byte[] buffer = new byte[DEFAULT_BUFFER_LENGTH];
int position = 0;
int bytesRead = gis.read(buffer, position, buffer.length);
while (bytesRead != -1) {
output.write(buffer, 0, bytesRead);
position += bytesRead;
bytesRead = gis.read(buffer, position, buffer.length);
}
content = output.toString("UTF-8");
} catch (IOException e) {
throw logger.logExceptionAsWarning(Exceptions.propagate(e));
}
} else {
content = new String(bytes, StandardCharsets.UTF_8);
}
responseData.remove(CONTENT_ENCODING);
responseData.put(CONTENT_LENGTH, Integer.toString(content.length()));
responseData.put(BODY, content);
return responseData;
});
}
}
} |
I don't think we should be using `ClientOptions` to set producet and version information. `ClientOptions` is provided by the user and we should try not to add headers that they don't specify. | private ConnectionOptions getConnectionOptions() {
configuration = configuration == null ? Configuration.getGlobalConfiguration().clone() : configuration;
if (credentials == null) {
final String connectionString = configuration.get(AZURE_EVENT_HUBS_CONNECTION_STRING);
if (CoreUtils.isNullOrEmpty(connectionString)) {
throw logger.logExceptionAsError(new IllegalArgumentException("Credentials have not been set. "
+ "They can be set using: connectionString(String), connectionString(String, String), "
+ "credentials(String, String, TokenCredential), or setting the environment variable '"
+ AZURE_EVENT_HUBS_CONNECTION_STRING + "' with a connection string"));
}
connectionString(connectionString);
}
if (proxyOptions == null) {
proxyOptions = getDefaultProxyConfiguration(configuration);
}
if (proxyOptions != null && proxyOptions.isProxyAddressConfigured()
&& transport != AmqpTransportType.AMQP_WEB_SOCKETS) {
throw logger.logExceptionAsError(new IllegalArgumentException(
"Cannot use a proxy when TransportType is not AMQP Web Sockets."));
}
final CbsAuthorizationType authorizationType = credentials instanceof EventHubSharedKeyCredential
? CbsAuthorizationType.SHARED_ACCESS_SIGNATURE
: CbsAuthorizationType.JSON_WEB_TOKEN;
final SslDomain.VerifyMode verificationMode = verifyMode != null
? verifyMode
: SslDomain.VerifyMode.VERIFY_PEER_NAME;
final ClientOptions options = new ClientOptions();
if (clientOptions != null) {
options.setApplicationId(clientOptions.getApplicationId())
.setHeaders(clientOptions.getHeaders());
}
final Map<String, String> properties = CoreUtils.getProperties(EVENTHUBS_PROPERTIES_FILE);
final String product = properties.getOrDefault(NAME_KEY, UNKNOWN);
final String clientVersion = properties.getOrDefault(VERSION_KEY, UNKNOWN);
final List<Header> headers = new ArrayList<>();
boolean foundName = false;
boolean foundVersion = false;
for (Header header : options.getHeaders()) {
if (NAME_KEY.equals(header.getName())) {
foundName = true;
} else if (VERSION_KEY.equals(header.getName())) {
foundVersion = true;
}
headers.add(header);
}
if (!foundName) {
headers.add(new Header(NAME_KEY, product));
}
if (!foundVersion) {
headers.add(new Header(VERSION_KEY, clientVersion));
}
options.setHeaders(headers);
if (customEndpointAddress == null) {
return new ConnectionOptions(fullyQualifiedNamespace, credentials, authorizationType, transport,
retryOptions, proxyOptions, scheduler, options, verificationMode);
} else {
return new ConnectionOptions(fullyQualifiedNamespace, credentials, authorizationType, transport,
retryOptions, proxyOptions, scheduler, options, verificationMode, customEndpointAddress.getHost(),
customEndpointAddress.getPort());
}
} | headers.add(new Header(NAME_KEY, product)); | private ConnectionOptions getConnectionOptions() {
configuration = configuration == null ? Configuration.getGlobalConfiguration().clone() : configuration;
if (credentials == null) {
final String connectionString = configuration.get(AZURE_EVENT_HUBS_CONNECTION_STRING);
if (CoreUtils.isNullOrEmpty(connectionString)) {
throw logger.logExceptionAsError(new IllegalArgumentException("Credentials have not been set. "
+ "They can be set using: connectionString(String), connectionString(String, String), "
+ "credentials(String, String, TokenCredential), or setting the environment variable '"
+ AZURE_EVENT_HUBS_CONNECTION_STRING + "' with a connection string"));
}
connectionString(connectionString);
}
if (proxyOptions == null) {
proxyOptions = getDefaultProxyConfiguration(configuration);
}
if (proxyOptions != null && proxyOptions.isProxyAddressConfigured()
&& transport != AmqpTransportType.AMQP_WEB_SOCKETS) {
throw logger.logExceptionAsError(new IllegalArgumentException(
"Cannot use a proxy when TransportType is not AMQP Web Sockets."));
}
final CbsAuthorizationType authorizationType = credentials instanceof EventHubSharedKeyCredential
? CbsAuthorizationType.SHARED_ACCESS_SIGNATURE
: CbsAuthorizationType.JSON_WEB_TOKEN;
final SslDomain.VerifyMode verificationMode = verifyMode != null
? verifyMode
: SslDomain.VerifyMode.VERIFY_PEER_NAME;
final ClientOptions options = clientOptions != null ? clientOptions : new ClientOptions();
final Map<String, String> properties = CoreUtils.getProperties(EVENTHUBS_PROPERTIES_FILE);
final String product = properties.getOrDefault(NAME_KEY, UNKNOWN);
final String clientVersion = properties.getOrDefault(VERSION_KEY, UNKNOWN);
if (customEndpointAddress == null) {
return new ConnectionOptions(fullyQualifiedNamespace, credentials, authorizationType, transport,
retryOptions, proxyOptions, scheduler, options, verificationMode, product, clientVersion);
} else {
return new ConnectionOptions(fullyQualifiedNamespace, credentials, authorizationType, transport,
retryOptions, proxyOptions, scheduler, options, verificationMode, product, clientVersion,
customEndpointAddress.getHost(), customEndpointAddress.getPort());
}
} | class EventHubClientBuilder {
static final int DEFAULT_PREFETCH_COUNT = 500;
static final int DEFAULT_PREFETCH_COUNT_FOR_SYNC_CLIENT = 1;
/**
* The name of the default consumer group in the Event Hubs service.
*/
public static final String DEFAULT_CONSUMER_GROUP_NAME = "$Default";
/**
* The minimum value allowed for the prefetch count of the consumer.
*/
private static final int MINIMUM_PREFETCH_COUNT = 1;
/**
* The maximum value allowed for the prefetch count of the consumer.
*/
private static final int MAXIMUM_PREFETCH_COUNT = 8000;
private static final String EVENTHUBS_PROPERTIES_FILE = "azure-messaging-eventhubs.properties";
private static final String NAME_KEY = "name";
private static final String VERSION_KEY = "version";
private static final String UNKNOWN = "UNKNOWN";
private static final String AZURE_EVENT_HUBS_CONNECTION_STRING = "AZURE_EVENT_HUBS_CONNECTION_STRING";
private static final AmqpRetryOptions DEFAULT_RETRY = new AmqpRetryOptions()
.setTryTimeout(ClientConstants.OPERATION_TIMEOUT);
private static final Pattern HOST_PORT_PATTERN = Pattern.compile("^[^:]+:\\d+");
private final ClientLogger logger = new ClientLogger(EventHubClientBuilder.class);
private final Object connectionLock = new Object();
private final AtomicBoolean isSharedConnection = new AtomicBoolean();
private TokenCredential credentials;
private Configuration configuration;
private ProxyOptions proxyOptions;
private AmqpRetryOptions retryOptions;
private Scheduler scheduler;
private AmqpTransportType transport;
private String fullyQualifiedNamespace;
private String eventHubName;
private String consumerGroup;
private EventHubConnectionProcessor eventHubConnectionProcessor;
private Integer prefetchCount;
private ClientOptions clientOptions;
private SslDomain.VerifyMode verifyMode;
private URL customEndpointAddress;
/**
* Keeps track of the open clients that were created from this builder when there is a shared connection.
*/
private final AtomicInteger openClients = new AtomicInteger();
/**
* Creates a new instance with the default transport {@link AmqpTransportType
* non-shared connection means that a dedicated AMQP connection is created for every Event Hub consumer or producer
* created using the builder.
*/
public EventHubClientBuilder() {
transport = AmqpTransportType.AMQP;
}
/**
* Sets the credential information given a connection string to the Event Hub instance.
*
* <p>
* If the connection string is copied from the Event Hubs namespace, it will likely not contain the name to the
* desired Event Hub, which is needed. In this case, the name can be added manually by adding {@literal
* "EntityPath=EVENT_HUB_NAME"} to the end of the connection string. For example, "EntityPath=telemetry-hub".
* </p>
*
* <p>
* If you have defined a shared access policy directly on the Event Hub itself, then copying the connection string
* from that Event Hub will result in a connection string that contains the name.
* </p>
*
* @param connectionString The connection string to use for connecting to the Event Hub instance. It is expected
* that the Event Hub name and the shared access key properties are contained in this connection string.
*
* @return The updated {@link EventHubClientBuilder} object.
* @throws IllegalArgumentException if {@code connectionString} is null or empty. Or, the {@code
* connectionString} does not contain the "EntityPath" key, which is the name of the Event Hub instance.
* @throws AzureException If the shared access signature token credential could not be created using the
* connection string.
*/
public EventHubClientBuilder connectionString(String connectionString) {
ConnectionStringProperties properties = new ConnectionStringProperties(connectionString);
TokenCredential tokenCredential = getTokenCredential(properties);
return credential(properties.getEndpoint().getHost(), properties.getEntityPath(), tokenCredential);
}
private TokenCredential getTokenCredential(ConnectionStringProperties properties) {
TokenCredential tokenCredential;
if (properties.getSharedAccessSignature() == null) {
tokenCredential = new EventHubSharedKeyCredential(properties.getSharedAccessKeyName(),
properties.getSharedAccessKey(), ClientConstants.TOKEN_VALIDITY);
} else {
tokenCredential = new EventHubSharedKeyCredential(properties.getSharedAccessSignature());
}
return tokenCredential;
}
/**
* Sets the client options.
*
* @param clientOptions The client options.
* @return The updated {@link EventHubClientBuilder} object.
*/
public EventHubClientBuilder clientOptions(ClientOptions clientOptions) {
this.clientOptions = clientOptions;
return this;
}
/**
* Sets the credential information given a connection string to the Event Hubs namespace and name to a specific
* Event Hub instance.
*
* @param connectionString The connection string to use for connecting to the Event Hubs namespace; it is
* expected that the shared access key properties are contained in this connection string, but not the Event Hub
* name.
* @param eventHubName The name of the Event Hub to connect the client to.
*
* @return The updated {@link EventHubClientBuilder} object.
* @throws NullPointerException if {@code connectionString} or {@code eventHubName} is null.
* @throws IllegalArgumentException if {@code connectionString} or {@code eventHubName} is an empty string. Or,
* if the {@code connectionString} contains the Event Hub name.
* @throws AzureException If the shared access signature token credential could not be created using the
* connection string.
*/
public EventHubClientBuilder connectionString(String connectionString, String eventHubName) {
Objects.requireNonNull(connectionString, "'connectionString' cannot be null.");
Objects.requireNonNull(eventHubName, "'eventHubName' cannot be null.");
if (connectionString.isEmpty()) {
throw logger.logExceptionAsError(new IllegalArgumentException(
"'connectionString' cannot be an empty string."));
} else if (eventHubName.isEmpty()) {
throw logger.logExceptionAsError(new IllegalArgumentException("'eventHubName' cannot be an empty string."));
}
final ConnectionStringProperties properties = new ConnectionStringProperties(connectionString);
TokenCredential tokenCredential = getTokenCredential(properties);
if (!CoreUtils.isNullOrEmpty(properties.getEntityPath())
&& !eventHubName.equals(properties.getEntityPath())) {
throw logger.logExceptionAsError(new IllegalArgumentException(String.format(Locale.US,
"'connectionString' contains an Event Hub name [%s] and it does not match the given "
+ "'eventHubName' parameter [%s]. Please use the credentials(String connectionString) overload. "
+ "Or supply a 'connectionString' without 'EntityPath' in it.",
properties.getEntityPath(), eventHubName)));
}
return credential(properties.getEndpoint().getHost(), eventHubName, tokenCredential);
}
/**
* Sets the configuration store that is used during construction of the service client.
*
* If not specified, the default configuration store is used to configure the {@link EventHubAsyncClient}. Use
* {@link Configuration
*
* @param configuration The configuration store used to configure the {@link EventHubAsyncClient}.
*
* @return The updated {@link EventHubClientBuilder} object.
*/
public EventHubClientBuilder configuration(Configuration configuration) {
this.configuration = configuration;
return this;
}
/**
* Sets a custom endpoint address when connecting to the Event Hubs service. This can be useful when your network
* does not allow connecting to the standard Azure Event Hubs endpoint address, but does allow connecting through
* an intermediary. For example: {@literal https:
* <p>
* If no port is specified, the default port for the {@link
* used.
*
* @param customEndpointAddress The custom endpoint address.
* @return The updated {@link EventHubClientBuilder} object.
* @throws IllegalArgumentException if {@code customEndpointAddress} cannot be parsed into a valid {@link URL}.
*/
public EventHubClientBuilder customEndpointAddress(String customEndpointAddress) {
if (customEndpointAddress == null) {
this.customEndpointAddress = null;
return this;
}
try {
this.customEndpointAddress = new URL(customEndpointAddress);
} catch (MalformedURLException e) {
throw logger.logExceptionAsError(
new IllegalArgumentException(customEndpointAddress + " : is not a valid URL.", e));
}
return this;
}
/**
* Toggles the builder to use the same connection for producers or consumers that are built from this instance. By
* default, a new connection is constructed and used created for each Event Hub consumer or producer created.
*
* @return The updated {@link EventHubClientBuilder} object.
*/
public EventHubClientBuilder shareConnection() {
this.isSharedConnection.set(true);
return this;
}
/**
* Sets the credential information for which Event Hub instance to connect to, and how to authorize against it.
*
* @param fullyQualifiedNamespace The fully qualified name for the Event Hubs namespace. This is likely to be
* similar to <strong>{@literal "{your-namespace}.servicebus.windows.net}"</strong>.
* @param eventHubName The name of the Event Hub to connect the client to.
* @param credential The token credential to use for authorization. Access controls may be specified by the
* Event Hubs namespace or the requested Event Hub, depending on Azure configuration.
*
* @return The updated {@link EventHubClientBuilder} object.
* @throws IllegalArgumentException if {@code fullyQualifiedNamespace} or {@code eventHubName} is an empty
* string.
* @throws NullPointerException if {@code fullyQualifiedNamespace}, {@code eventHubName}, {@code credentials} is
* null.
*/
public EventHubClientBuilder credential(String fullyQualifiedNamespace, String eventHubName,
TokenCredential credential) {
this.fullyQualifiedNamespace = Objects.requireNonNull(fullyQualifiedNamespace,
"'fullyQualifiedNamespace' cannot be null.");
this.credentials = Objects.requireNonNull(credential, "'credential' cannot be null.");
this.eventHubName = Objects.requireNonNull(eventHubName, "'eventHubName' cannot be null.");
if (CoreUtils.isNullOrEmpty(fullyQualifiedNamespace)) {
throw logger.logExceptionAsError(new IllegalArgumentException("'host' cannot be an empty string."));
} else if (CoreUtils.isNullOrEmpty(eventHubName)) {
throw logger.logExceptionAsError(new IllegalArgumentException("'eventHubName' cannot be an empty string."));
}
return this;
}
/**
* Sets the proxy configuration to use for {@link EventHubAsyncClient}. When a proxy is configured, {@link
* AmqpTransportType
*
* @param proxyOptions The proxy configuration to use.
*
* @return The updated {@link EventHubClientBuilder} object.
*/
public EventHubClientBuilder proxyOptions(ProxyOptions proxyOptions) {
this.proxyOptions = proxyOptions;
return this;
}
/**
* Sets the transport type by which all the communication with Azure Event Hubs occurs. Default value is {@link
* AmqpTransportType
*
* @param transport The transport type to use.
*
* @return The updated {@link EventHubClientBuilder} object.
*/
public EventHubClientBuilder transportType(AmqpTransportType transport) {
this.transport = transport;
return this;
}
/**
* Sets the retry policy for {@link EventHubAsyncClient}. If not specified, the default retry options are used.
*
* @param retryOptions The retry policy to use.
*
* @return The updated {@link EventHubClientBuilder} object.
*/
public EventHubClientBuilder retry(AmqpRetryOptions retryOptions) {
this.retryOptions = retryOptions;
return this;
}
/**
* Sets the name of the consumer group this consumer is associated with. Events are read in the context of this
* group. The name of the consumer group that is created by default is {@link
* "$Default"}.
*
* @param consumerGroup The name of the consumer group this consumer is associated with. Events are read in the
* context of this group. The name of the consumer group that is created by default is {@link
*
*
* @return The updated {@link EventHubClientBuilder} object.
*/
public EventHubClientBuilder consumerGroup(String consumerGroup) {
this.consumerGroup = consumerGroup;
return this;
}
/**
* Sets the count used by the receiver to control the number of events the Event Hub consumer will actively receive
* and queue locally without regard to whether a receive operation is currently active.
*
* @param prefetchCount The amount of events to queue locally.
*
* @return The updated {@link EventHubClientBuilder} object.
* @throws IllegalArgumentException if {@code prefetchCount} is less than {@link
* greater than {@link
*/
public EventHubClientBuilder prefetchCount(int prefetchCount) {
if (prefetchCount < MINIMUM_PREFETCH_COUNT) {
throw logger.logExceptionAsError(new IllegalArgumentException(String.format(Locale.US,
"PrefetchCount, '%s' has to be above %s", prefetchCount, MINIMUM_PREFETCH_COUNT)));
}
if (prefetchCount > MAXIMUM_PREFETCH_COUNT) {
throw logger.logExceptionAsError(new IllegalArgumentException(String.format(Locale.US,
"PrefetchCount, '%s', has to be below %s", prefetchCount, MAXIMUM_PREFETCH_COUNT)));
}
this.prefetchCount = prefetchCount;
return this;
}
/**
* Package-private method that sets the scheduler for the created Event Hub client.
*
* @param scheduler Scheduler to set.
*
* @return The updated {@link EventHubClientBuilder} object.
*/
EventHubClientBuilder scheduler(Scheduler scheduler) {
this.scheduler = scheduler;
return this;
}
/**
* Package-private method that sets the verify mode for this connection.
*
* @param verifyMode The verification mode.
* @return The updated {@link EventHubClientBuilder} object.
*/
EventHubClientBuilder verifyMode(SslDomain.VerifyMode verifyMode) {
this.verifyMode = verifyMode;
return this;
}
/**
* Creates a new {@link EventHubConsumerAsyncClient} based on the options set on this builder. Every time {@code
* buildAsyncConsumer()} is invoked, a new instance of {@link EventHubConsumerAsyncClient} is created.
*
* @return A new {@link EventHubConsumerAsyncClient} with the configured options.
* @throws IllegalArgumentException If shared connection is not used and the credentials have not been set using
* either {@link
* {@link
* {@link AmqpTransportType
*/
public EventHubConsumerAsyncClient buildAsyncConsumerClient() {
if (CoreUtils.isNullOrEmpty(consumerGroup)) {
throw logger.logExceptionAsError(new IllegalArgumentException("'consumerGroup' cannot be null or an empty "
+ "string. using EventHubClientBuilder.consumerGroup(String)"));
}
return buildAsyncClient().createConsumer(consumerGroup, prefetchCount);
}
/**
* Creates a new {@link EventHubConsumerClient} based on the options set on this builder. Every time {@code
* buildConsumer()} is invoked, a new instance of {@link EventHubConsumerClient} is created.
*
* @return A new {@link EventHubConsumerClient} with the configured options.
* @throws IllegalArgumentException If shared connection is not used and the credentials have not been set using
* either {@link
* {@link
* {@link AmqpTransportType
*/
public EventHubConsumerClient buildConsumerClient() {
return buildClient().createConsumer(consumerGroup, prefetchCount);
}
/**
* Creates a new {@link EventHubProducerAsyncClient} based on options set on this builder. Every time {@code
* buildAsyncProducer()} is invoked, a new instance of {@link EventHubProducerAsyncClient} is created.
*
* @return A new {@link EventHubProducerAsyncClient} instance with all the configured options.
* @throws IllegalArgumentException If shared connection is not used and the credentials have not been set using
* either {@link
* proxy is specified but the transport type is not {@link AmqpTransportType
*/
public EventHubProducerAsyncClient buildAsyncProducerClient() {
return buildAsyncClient().createProducer();
}
/**
* Creates a new {@link EventHubProducerClient} based on options set on this builder. Every time {@code
* buildAsyncProducer()} is invoked, a new instance of {@link EventHubProducerClient} is created.
*
* @return A new {@link EventHubProducerClient} instance with all the configured options.
* @throws IllegalArgumentException If shared connection is not used and the credentials have not been set using
* either {@link
* proxy is specified but the transport type is not {@link AmqpTransportType
*/
public EventHubProducerClient buildProducerClient() {
return buildClient().createProducer();
}
/**
* Creates a new {@link EventHubAsyncClient} based on options set on this builder. Every time {@code
* buildAsyncClient()} is invoked, a new instance of {@link EventHubAsyncClient} is created.
*
* <p>
* The following options are used if ones are not specified in the builder:
*
* <ul>
* <li>If no configuration is specified, the {@link Configuration
* is used to provide any shared configuration values. The configuration values read are the {@link
* Configuration
* ProxyOptions
* <li>If no retry is specified, the default retry options are used.</li>
* <li>If no proxy is specified, the builder checks the {@link Configuration
* configuration} for a configured proxy, then it checks to see if a system proxy is configured.</li>
* <li>If no timeout is specified, a {@link ClientConstants
* <li>If no scheduler is specified, an {@link Schedulers
* </ul>
*
* @return A new {@link EventHubAsyncClient} instance with all the configured options.
* @throws IllegalArgumentException if the credentials have not been set using either {@link
*
* specified but the transport type is not {@link AmqpTransportType
*/
EventHubAsyncClient buildAsyncClient() {
if (retryOptions == null) {
retryOptions = DEFAULT_RETRY;
}
if (scheduler == null) {
scheduler = Schedulers.elastic();
}
if (prefetchCount == null) {
prefetchCount = DEFAULT_PREFETCH_COUNT;
}
final MessageSerializer messageSerializer = new EventHubMessageSerializer();
final EventHubConnectionProcessor processor;
if (isSharedConnection.get()) {
synchronized (connectionLock) {
if (eventHubConnectionProcessor == null) {
eventHubConnectionProcessor = buildConnectionProcessor(messageSerializer);
}
}
processor = eventHubConnectionProcessor;
final int numberOfOpenClients = openClients.incrementAndGet();
logger.info("
} else {
processor = buildConnectionProcessor(messageSerializer);
}
final TracerProvider tracerProvider = new TracerProvider(ServiceLoader.load(Tracer.class));
return new EventHubAsyncClient(processor, tracerProvider, messageSerializer, scheduler,
isSharedConnection.get(), this::onClientClose);
}
/**
* Creates a new {@link EventHubClient} based on options set on this builder. Every time {@code buildClient()} is
* invoked, a new instance of {@link EventHubClient} is created.
*
* <p>
* The following options are used if ones are not specified in the builder:
*
* <ul>
* <li>If no configuration is specified, the {@link Configuration
* is used to provide any shared configuration values. The configuration values read are the {@link
* Configuration
* ProxyOptions
* <li>If no retry is specified, the default retry options are used.</li>
* <li>If no proxy is specified, the builder checks the {@link Configuration
* configuration} for a configured proxy, then it checks to see if a system proxy is configured.</li>
* <li>If no timeout is specified, a {@link ClientConstants
* <li>If no scheduler is specified, an {@link Schedulers
* </ul>
*
* @return A new {@link EventHubClient} instance with all the configured options.
* @throws IllegalArgumentException if the credentials have not been set using either {@link
*
* specified but the transport type is not {@link AmqpTransportType
*/
EventHubClient buildClient() {
if (prefetchCount == null) {
prefetchCount = DEFAULT_PREFETCH_COUNT_FOR_SYNC_CLIENT;
}
final EventHubAsyncClient client = buildAsyncClient();
return new EventHubClient(client, retryOptions);
}
void onClientClose() {
synchronized (connectionLock) {
final int numberOfOpenClients = openClients.decrementAndGet();
logger.info("Closing a dependent client.
if (numberOfOpenClients > 0) {
return;
}
if (numberOfOpenClients < 0) {
logger.warning("There should not be less than 0 clients. actual: {}", numberOfOpenClients);
}
logger.info("No more open clients, closing shared connection.");
if (eventHubConnectionProcessor != null) {
eventHubConnectionProcessor.dispose();
eventHubConnectionProcessor = null;
} else {
logger.warning("Shared EventHubConnectionProcessor was already disposed.");
}
}
}
private EventHubConnectionProcessor buildConnectionProcessor(MessageSerializer messageSerializer) {
final ConnectionOptions connectionOptions = getConnectionOptions();
final TokenManagerProvider tokenManagerProvider = new AzureTokenManagerProvider(
connectionOptions.getAuthorizationType(), connectionOptions.getFullyQualifiedNamespace(),
ClientConstants.AZURE_ACTIVE_DIRECTORY_SCOPE);
final ReactorProvider provider = new ReactorProvider();
final ReactorHandlerProvider handlerProvider = new ReactorHandlerProvider(provider);
final Flux<EventHubAmqpConnection> connectionFlux = Flux.create(sink -> {
sink.onRequest(request -> {
if (request == 0) {
return;
} else if (request > 1) {
sink.error(logger.logExceptionAsWarning(new IllegalArgumentException(
"Requested more than one connection. Only emitting one. Request: " + request)));
return;
}
final String connectionId = StringUtil.getRandomString("MF");
logger.info("connectionId[{}]: Emitting a single connection.", connectionId);
final EventHubAmqpConnection connection = new EventHubReactorAmqpConnection(connectionId,
connectionOptions, eventHubName, provider, handlerProvider, tokenManagerProvider,
messageSerializer);
sink.next(connection);
});
});
return connectionFlux.subscribeWith(new EventHubConnectionProcessor(
connectionOptions.getFullyQualifiedNamespace(), eventHubName, connectionOptions.getRetry()));
}
private ProxyOptions getDefaultProxyConfiguration(Configuration configuration) {
ProxyAuthenticationType authentication = ProxyAuthenticationType.NONE;
if (proxyOptions != null) {
authentication = proxyOptions.getAuthentication();
}
String proxyAddress = configuration.get(Configuration.PROPERTY_HTTP_PROXY);
if (CoreUtils.isNullOrEmpty(proxyAddress)) {
return ProxyOptions.SYSTEM_DEFAULTS;
}
return getProxyOptions(authentication, proxyAddress);
}
private ProxyOptions getProxyOptions(ProxyAuthenticationType authentication, String proxyAddress) {
String host;
int port;
if (HOST_PORT_PATTERN.matcher(proxyAddress.trim()).find()) {
final String[] hostPort = proxyAddress.split(":");
host = hostPort[0];
port = Integer.parseInt(hostPort[1]);
final Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(host, port));
final String username = configuration.get(ProxyOptions.PROXY_USERNAME);
final String password = configuration.get(ProxyOptions.PROXY_PASSWORD);
return new ProxyOptions(authentication, proxy, username, password);
} else {
com.azure.core.http.ProxyOptions coreProxyOptions = com.azure.core.http.ProxyOptions
.fromConfiguration(configuration);
return new ProxyOptions(authentication, new Proxy(coreProxyOptions.getType().toProxyType(),
coreProxyOptions.getAddress()), coreProxyOptions.getUsername(), coreProxyOptions.getPassword());
}
}
} | class EventHubClientBuilder {
static final int DEFAULT_PREFETCH_COUNT = 500;
static final int DEFAULT_PREFETCH_COUNT_FOR_SYNC_CLIENT = 1;
/**
* The name of the default consumer group in the Event Hubs service.
*/
public static final String DEFAULT_CONSUMER_GROUP_NAME = "$Default";
/**
* The minimum value allowed for the prefetch count of the consumer.
*/
private static final int MINIMUM_PREFETCH_COUNT = 1;
/**
* The maximum value allowed for the prefetch count of the consumer.
*/
private static final int MAXIMUM_PREFETCH_COUNT = 8000;
private static final String EVENTHUBS_PROPERTIES_FILE = "azure-messaging-eventhubs.properties";
private static final String NAME_KEY = "name";
private static final String VERSION_KEY = "version";
private static final String UNKNOWN = "UNKNOWN";
private static final String AZURE_EVENT_HUBS_CONNECTION_STRING = "AZURE_EVENT_HUBS_CONNECTION_STRING";
private static final AmqpRetryOptions DEFAULT_RETRY = new AmqpRetryOptions()
.setTryTimeout(ClientConstants.OPERATION_TIMEOUT);
private static final Pattern HOST_PORT_PATTERN = Pattern.compile("^[^:]+:\\d+");
private final ClientLogger logger = new ClientLogger(EventHubClientBuilder.class);
private final Object connectionLock = new Object();
private final AtomicBoolean isSharedConnection = new AtomicBoolean();
private TokenCredential credentials;
private Configuration configuration;
private ProxyOptions proxyOptions;
private AmqpRetryOptions retryOptions;
private Scheduler scheduler;
private AmqpTransportType transport;
private String fullyQualifiedNamespace;
private String eventHubName;
private String consumerGroup;
private EventHubConnectionProcessor eventHubConnectionProcessor;
private Integer prefetchCount;
private ClientOptions clientOptions;
private SslDomain.VerifyMode verifyMode;
private URL customEndpointAddress;
/**
* Keeps track of the open clients that were created from this builder when there is a shared connection.
*/
private final AtomicInteger openClients = new AtomicInteger();
/**
* Creates a new instance with the default transport {@link AmqpTransportType
* non-shared connection means that a dedicated AMQP connection is created for every Event Hub consumer or producer
* created using the builder.
*/
public EventHubClientBuilder() {
transport = AmqpTransportType.AMQP;
}
/**
* Sets the credential information given a connection string to the Event Hub instance.
*
* <p>
* If the connection string is copied from the Event Hubs namespace, it will likely not contain the name to the
* desired Event Hub, which is needed. In this case, the name can be added manually by adding {@literal
* "EntityPath=EVENT_HUB_NAME"} to the end of the connection string. For example, "EntityPath=telemetry-hub".
* </p>
*
* <p>
* If you have defined a shared access policy directly on the Event Hub itself, then copying the connection string
* from that Event Hub will result in a connection string that contains the name.
* </p>
*
* @param connectionString The connection string to use for connecting to the Event Hub instance. It is expected
* that the Event Hub name and the shared access key properties are contained in this connection string.
*
* @return The updated {@link EventHubClientBuilder} object.
* @throws IllegalArgumentException if {@code connectionString} is null or empty. Or, the {@code
* connectionString} does not contain the "EntityPath" key, which is the name of the Event Hub instance.
* @throws AzureException If the shared access signature token credential could not be created using the
* connection string.
*/
public EventHubClientBuilder connectionString(String connectionString) {
ConnectionStringProperties properties = new ConnectionStringProperties(connectionString);
TokenCredential tokenCredential = getTokenCredential(properties);
return credential(properties.getEndpoint().getHost(), properties.getEntityPath(), tokenCredential);
}
private TokenCredential getTokenCredential(ConnectionStringProperties properties) {
TokenCredential tokenCredential;
if (properties.getSharedAccessSignature() == null) {
tokenCredential = new EventHubSharedKeyCredential(properties.getSharedAccessKeyName(),
properties.getSharedAccessKey(), ClientConstants.TOKEN_VALIDITY);
} else {
tokenCredential = new EventHubSharedKeyCredential(properties.getSharedAccessSignature());
}
return tokenCredential;
}
/**
* Sets the client options.
*
* @param clientOptions The client options.
* @return The updated {@link EventHubClientBuilder} object.
*/
public EventHubClientBuilder clientOptions(ClientOptions clientOptions) {
this.clientOptions = clientOptions;
return this;
}
/**
* Sets the credential information given a connection string to the Event Hubs namespace and name to a specific
* Event Hub instance.
*
* @param connectionString The connection string to use for connecting to the Event Hubs namespace; it is
* expected that the shared access key properties are contained in this connection string, but not the Event Hub
* name.
* @param eventHubName The name of the Event Hub to connect the client to.
*
* @return The updated {@link EventHubClientBuilder} object.
* @throws NullPointerException if {@code connectionString} or {@code eventHubName} is null.
* @throws IllegalArgumentException if {@code connectionString} or {@code eventHubName} is an empty string. Or,
* if the {@code connectionString} contains the Event Hub name.
* @throws AzureException If the shared access signature token credential could not be created using the
* connection string.
*/
public EventHubClientBuilder connectionString(String connectionString, String eventHubName) {
Objects.requireNonNull(connectionString, "'connectionString' cannot be null.");
Objects.requireNonNull(eventHubName, "'eventHubName' cannot be null.");
if (connectionString.isEmpty()) {
throw logger.logExceptionAsError(new IllegalArgumentException(
"'connectionString' cannot be an empty string."));
} else if (eventHubName.isEmpty()) {
throw logger.logExceptionAsError(new IllegalArgumentException("'eventHubName' cannot be an empty string."));
}
final ConnectionStringProperties properties = new ConnectionStringProperties(connectionString);
TokenCredential tokenCredential = getTokenCredential(properties);
if (!CoreUtils.isNullOrEmpty(properties.getEntityPath())
&& !eventHubName.equals(properties.getEntityPath())) {
throw logger.logExceptionAsError(new IllegalArgumentException(String.format(Locale.US,
"'connectionString' contains an Event Hub name [%s] and it does not match the given "
+ "'eventHubName' parameter [%s]. Please use the credentials(String connectionString) overload. "
+ "Or supply a 'connectionString' without 'EntityPath' in it.",
properties.getEntityPath(), eventHubName)));
}
return credential(properties.getEndpoint().getHost(), eventHubName, tokenCredential);
}
/**
* Sets the configuration store that is used during construction of the service client.
*
* If not specified, the default configuration store is used to configure the {@link EventHubAsyncClient}. Use
* {@link Configuration
*
* @param configuration The configuration store used to configure the {@link EventHubAsyncClient}.
*
* @return The updated {@link EventHubClientBuilder} object.
*/
public EventHubClientBuilder configuration(Configuration configuration) {
this.configuration = configuration;
return this;
}
/**
* Sets a custom endpoint address when connecting to the Event Hubs service. This can be useful when your network
* does not allow connecting to the standard Azure Event Hubs endpoint address, but does allow connecting through
* an intermediary. For example: {@literal https:
* <p>
* If no port is specified, the default port for the {@link
* used.
*
* @param customEndpointAddress The custom endpoint address.
* @return The updated {@link EventHubClientBuilder} object.
* @throws IllegalArgumentException if {@code customEndpointAddress} cannot be parsed into a valid {@link URL}.
*/
public EventHubClientBuilder customEndpointAddress(String customEndpointAddress) {
if (customEndpointAddress == null) {
this.customEndpointAddress = null;
return this;
}
try {
this.customEndpointAddress = new URL(customEndpointAddress);
} catch (MalformedURLException e) {
throw logger.logExceptionAsError(
new IllegalArgumentException(customEndpointAddress + " : is not a valid URL.", e));
}
return this;
}
/**
* Toggles the builder to use the same connection for producers or consumers that are built from this instance. By
* default, a new connection is constructed and used created for each Event Hub consumer or producer created.
*
* @return The updated {@link EventHubClientBuilder} object.
*/
public EventHubClientBuilder shareConnection() {
this.isSharedConnection.set(true);
return this;
}
/**
* Sets the credential information for which Event Hub instance to connect to, and how to authorize against it.
*
* @param fullyQualifiedNamespace The fully qualified name for the Event Hubs namespace. This is likely to be
* similar to <strong>{@literal "{your-namespace}.servicebus.windows.net}"</strong>.
* @param eventHubName The name of the Event Hub to connect the client to.
* @param credential The token credential to use for authorization. Access controls may be specified by the
* Event Hubs namespace or the requested Event Hub, depending on Azure configuration.
*
* @return The updated {@link EventHubClientBuilder} object.
* @throws IllegalArgumentException if {@code fullyQualifiedNamespace} or {@code eventHubName} is an empty
* string.
* @throws NullPointerException if {@code fullyQualifiedNamespace}, {@code eventHubName}, {@code credentials} is
* null.
*/
public EventHubClientBuilder credential(String fullyQualifiedNamespace, String eventHubName,
TokenCredential credential) {
this.fullyQualifiedNamespace = Objects.requireNonNull(fullyQualifiedNamespace,
"'fullyQualifiedNamespace' cannot be null.");
this.credentials = Objects.requireNonNull(credential, "'credential' cannot be null.");
this.eventHubName = Objects.requireNonNull(eventHubName, "'eventHubName' cannot be null.");
if (CoreUtils.isNullOrEmpty(fullyQualifiedNamespace)) {
throw logger.logExceptionAsError(new IllegalArgumentException("'host' cannot be an empty string."));
} else if (CoreUtils.isNullOrEmpty(eventHubName)) {
throw logger.logExceptionAsError(new IllegalArgumentException("'eventHubName' cannot be an empty string."));
}
return this;
}
/**
* Sets the proxy configuration to use for {@link EventHubAsyncClient}. When a proxy is configured, {@link
* AmqpTransportType
*
* @param proxyOptions The proxy configuration to use.
*
* @return The updated {@link EventHubClientBuilder} object.
*/
public EventHubClientBuilder proxyOptions(ProxyOptions proxyOptions) {
this.proxyOptions = proxyOptions;
return this;
}
/**
* Sets the transport type by which all the communication with Azure Event Hubs occurs. Default value is {@link
* AmqpTransportType
*
* @param transport The transport type to use.
*
* @return The updated {@link EventHubClientBuilder} object.
*/
public EventHubClientBuilder transportType(AmqpTransportType transport) {
this.transport = transport;
return this;
}
/**
* Sets the retry policy for {@link EventHubAsyncClient}. If not specified, the default retry options are used.
*
* @param retryOptions The retry policy to use.
*
* @return The updated {@link EventHubClientBuilder} object.
*/
public EventHubClientBuilder retry(AmqpRetryOptions retryOptions) {
this.retryOptions = retryOptions;
return this;
}
/**
* Sets the name of the consumer group this consumer is associated with. Events are read in the context of this
* group. The name of the consumer group that is created by default is {@link
* "$Default"}.
*
* @param consumerGroup The name of the consumer group this consumer is associated with. Events are read in the
* context of this group. The name of the consumer group that is created by default is {@link
*
*
* @return The updated {@link EventHubClientBuilder} object.
*/
public EventHubClientBuilder consumerGroup(String consumerGroup) {
this.consumerGroup = consumerGroup;
return this;
}
/**
* Sets the count used by the receiver to control the number of events the Event Hub consumer will actively receive
* and queue locally without regard to whether a receive operation is currently active.
*
* @param prefetchCount The amount of events to queue locally.
*
* @return The updated {@link EventHubClientBuilder} object.
* @throws IllegalArgumentException if {@code prefetchCount} is less than {@link
* greater than {@link
*/
public EventHubClientBuilder prefetchCount(int prefetchCount) {
if (prefetchCount < MINIMUM_PREFETCH_COUNT) {
throw logger.logExceptionAsError(new IllegalArgumentException(String.format(Locale.US,
"PrefetchCount, '%s' has to be above %s", prefetchCount, MINIMUM_PREFETCH_COUNT)));
}
if (prefetchCount > MAXIMUM_PREFETCH_COUNT) {
throw logger.logExceptionAsError(new IllegalArgumentException(String.format(Locale.US,
"PrefetchCount, '%s', has to be below %s", prefetchCount, MAXIMUM_PREFETCH_COUNT)));
}
this.prefetchCount = prefetchCount;
return this;
}
/**
* Package-private method that sets the scheduler for the created Event Hub client.
*
* @param scheduler Scheduler to set.
*
* @return The updated {@link EventHubClientBuilder} object.
*/
EventHubClientBuilder scheduler(Scheduler scheduler) {
this.scheduler = scheduler;
return this;
}
/**
* Package-private method that sets the verify mode for this connection.
*
* @param verifyMode The verification mode.
* @return The updated {@link EventHubClientBuilder} object.
*/
EventHubClientBuilder verifyMode(SslDomain.VerifyMode verifyMode) {
this.verifyMode = verifyMode;
return this;
}
/**
* Creates a new {@link EventHubConsumerAsyncClient} based on the options set on this builder. Every time {@code
* buildAsyncConsumer()} is invoked, a new instance of {@link EventHubConsumerAsyncClient} is created.
*
* @return A new {@link EventHubConsumerAsyncClient} with the configured options.
* @throws IllegalArgumentException If shared connection is not used and the credentials have not been set using
* either {@link
* {@link
* {@link AmqpTransportType
*/
public EventHubConsumerAsyncClient buildAsyncConsumerClient() {
if (CoreUtils.isNullOrEmpty(consumerGroup)) {
throw logger.logExceptionAsError(new IllegalArgumentException("'consumerGroup' cannot be null or an empty "
+ "string. using EventHubClientBuilder.consumerGroup(String)"));
}
return buildAsyncClient().createConsumer(consumerGroup, prefetchCount);
}
/**
* Creates a new {@link EventHubConsumerClient} based on the options set on this builder. Every time {@code
* buildConsumer()} is invoked, a new instance of {@link EventHubConsumerClient} is created.
*
* @return A new {@link EventHubConsumerClient} with the configured options.
* @throws IllegalArgumentException If shared connection is not used and the credentials have not been set using
* either {@link
* {@link
* {@link AmqpTransportType
*/
public EventHubConsumerClient buildConsumerClient() {
return buildClient().createConsumer(consumerGroup, prefetchCount);
}
/**
* Creates a new {@link EventHubProducerAsyncClient} based on options set on this builder. Every time {@code
* buildAsyncProducer()} is invoked, a new instance of {@link EventHubProducerAsyncClient} is created.
*
* @return A new {@link EventHubProducerAsyncClient} instance with all the configured options.
* @throws IllegalArgumentException If shared connection is not used and the credentials have not been set using
* either {@link
* proxy is specified but the transport type is not {@link AmqpTransportType
*/
public EventHubProducerAsyncClient buildAsyncProducerClient() {
return buildAsyncClient().createProducer();
}
/**
* Creates a new {@link EventHubProducerClient} based on options set on this builder. Every time {@code
* buildAsyncProducer()} is invoked, a new instance of {@link EventHubProducerClient} is created.
*
* @return A new {@link EventHubProducerClient} instance with all the configured options.
* @throws IllegalArgumentException If shared connection is not used and the credentials have not been set using
* either {@link
* proxy is specified but the transport type is not {@link AmqpTransportType
*/
public EventHubProducerClient buildProducerClient() {
return buildClient().createProducer();
}
/**
* Creates a new {@link EventHubAsyncClient} based on options set on this builder. Every time {@code
* buildAsyncClient()} is invoked, a new instance of {@link EventHubAsyncClient} is created.
*
* <p>
* The following options are used if ones are not specified in the builder:
*
* <ul>
* <li>If no configuration is specified, the {@link Configuration
* is used to provide any shared configuration values. The configuration values read are the {@link
* Configuration
* ProxyOptions
* <li>If no retry is specified, the default retry options are used.</li>
* <li>If no proxy is specified, the builder checks the {@link Configuration
* configuration} for a configured proxy, then it checks to see if a system proxy is configured.</li>
* <li>If no timeout is specified, a {@link ClientConstants
* <li>If no scheduler is specified, an {@link Schedulers
* </ul>
*
* @return A new {@link EventHubAsyncClient} instance with all the configured options.
* @throws IllegalArgumentException if the credentials have not been set using either {@link
*
* specified but the transport type is not {@link AmqpTransportType
*/
EventHubAsyncClient buildAsyncClient() {
if (retryOptions == null) {
retryOptions = DEFAULT_RETRY;
}
if (scheduler == null) {
scheduler = Schedulers.elastic();
}
if (prefetchCount == null) {
prefetchCount = DEFAULT_PREFETCH_COUNT;
}
final MessageSerializer messageSerializer = new EventHubMessageSerializer();
final EventHubConnectionProcessor processor;
if (isSharedConnection.get()) {
synchronized (connectionLock) {
if (eventHubConnectionProcessor == null) {
eventHubConnectionProcessor = buildConnectionProcessor(messageSerializer);
}
}
processor = eventHubConnectionProcessor;
final int numberOfOpenClients = openClients.incrementAndGet();
logger.info("
} else {
processor = buildConnectionProcessor(messageSerializer);
}
final TracerProvider tracerProvider = new TracerProvider(ServiceLoader.load(Tracer.class));
return new EventHubAsyncClient(processor, tracerProvider, messageSerializer, scheduler,
isSharedConnection.get(), this::onClientClose);
}
/**
* Creates a new {@link EventHubClient} based on options set on this builder. Every time {@code buildClient()} is
* invoked, a new instance of {@link EventHubClient} is created.
*
* <p>
* The following options are used if ones are not specified in the builder:
*
* <ul>
* <li>If no configuration is specified, the {@link Configuration
* is used to provide any shared configuration values. The configuration values read are the {@link
* Configuration
* ProxyOptions
* <li>If no retry is specified, the default retry options are used.</li>
* <li>If no proxy is specified, the builder checks the {@link Configuration
* configuration} for a configured proxy, then it checks to see if a system proxy is configured.</li>
* <li>If no timeout is specified, a {@link ClientConstants
* <li>If no scheduler is specified, an {@link Schedulers
* </ul>
*
* @return A new {@link EventHubClient} instance with all the configured options.
* @throws IllegalArgumentException if the credentials have not been set using either {@link
*
* specified but the transport type is not {@link AmqpTransportType
*/
EventHubClient buildClient() {
if (prefetchCount == null) {
prefetchCount = DEFAULT_PREFETCH_COUNT_FOR_SYNC_CLIENT;
}
final EventHubAsyncClient client = buildAsyncClient();
return new EventHubClient(client, retryOptions);
}
void onClientClose() {
synchronized (connectionLock) {
final int numberOfOpenClients = openClients.decrementAndGet();
logger.info("Closing a dependent client.
if (numberOfOpenClients > 0) {
return;
}
if (numberOfOpenClients < 0) {
logger.warning("There should not be less than 0 clients. actual: {}", numberOfOpenClients);
}
logger.info("No more open clients, closing shared connection.");
if (eventHubConnectionProcessor != null) {
eventHubConnectionProcessor.dispose();
eventHubConnectionProcessor = null;
} else {
logger.warning("Shared EventHubConnectionProcessor was already disposed.");
}
}
}
private EventHubConnectionProcessor buildConnectionProcessor(MessageSerializer messageSerializer) {
final ConnectionOptions connectionOptions = getConnectionOptions();
final TokenManagerProvider tokenManagerProvider = new AzureTokenManagerProvider(
connectionOptions.getAuthorizationType(), connectionOptions.getFullyQualifiedNamespace(),
ClientConstants.AZURE_ACTIVE_DIRECTORY_SCOPE);
final ReactorProvider provider = new ReactorProvider();
final ReactorHandlerProvider handlerProvider = new ReactorHandlerProvider(provider);
final Flux<EventHubAmqpConnection> connectionFlux = Flux.create(sink -> {
sink.onRequest(request -> {
if (request == 0) {
return;
} else if (request > 1) {
sink.error(logger.logExceptionAsWarning(new IllegalArgumentException(
"Requested more than one connection. Only emitting one. Request: " + request)));
return;
}
final String connectionId = StringUtil.getRandomString("MF");
logger.info("connectionId[{}]: Emitting a single connection.", connectionId);
final EventHubAmqpConnection connection = new EventHubReactorAmqpConnection(connectionId,
connectionOptions, eventHubName, provider, handlerProvider, tokenManagerProvider,
messageSerializer);
sink.next(connection);
});
});
return connectionFlux.subscribeWith(new EventHubConnectionProcessor(
connectionOptions.getFullyQualifiedNamespace(), eventHubName, connectionOptions.getRetry()));
}
private ProxyOptions getDefaultProxyConfiguration(Configuration configuration) {
ProxyAuthenticationType authentication = ProxyAuthenticationType.NONE;
if (proxyOptions != null) {
authentication = proxyOptions.getAuthentication();
}
String proxyAddress = configuration.get(Configuration.PROPERTY_HTTP_PROXY);
if (CoreUtils.isNullOrEmpty(proxyAddress)) {
return ProxyOptions.SYSTEM_DEFAULTS;
}
return getProxyOptions(authentication, proxyAddress);
}
private ProxyOptions getProxyOptions(ProxyAuthenticationType authentication, String proxyAddress) {
String host;
int port;
if (HOST_PORT_PATTERN.matcher(proxyAddress.trim()).find()) {
final String[] hostPort = proxyAddress.split(":");
host = hostPort[0];
port = Integer.parseInt(hostPort[1]);
final Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(host, port));
final String username = configuration.get(ProxyOptions.PROXY_USERNAME);
final String password = configuration.get(ProxyOptions.PROXY_PASSWORD);
return new ProxyOptions(authentication, proxy, username, password);
} else {
com.azure.core.http.ProxyOptions coreProxyOptions = com.azure.core.http.ProxyOptions
.fromConfiguration(configuration);
return new ProxyOptions(authentication, new Proxy(coreProxyOptions.getType().toProxyType(),
coreProxyOptions.getAddress()), coreProxyOptions.getUsername(), coreProxyOptions.getPassword());
}
}
} |
Is this needed? I don't think `setHeaders` will make a copy of the headers. So, it's just creating another reference to the same header list. | private ConnectionOptions getConnectionOptions() {
configuration = configuration == null ? Configuration.getGlobalConfiguration().clone() : configuration;
if (credentials == null) {
final String connectionString = configuration.get(AZURE_EVENT_HUBS_CONNECTION_STRING);
if (CoreUtils.isNullOrEmpty(connectionString)) {
throw logger.logExceptionAsError(new IllegalArgumentException("Credentials have not been set. "
+ "They can be set using: connectionString(String), connectionString(String, String), "
+ "credentials(String, String, TokenCredential), or setting the environment variable '"
+ AZURE_EVENT_HUBS_CONNECTION_STRING + "' with a connection string"));
}
connectionString(connectionString);
}
if (proxyOptions == null) {
proxyOptions = getDefaultProxyConfiguration(configuration);
}
if (proxyOptions != null && proxyOptions.isProxyAddressConfigured()
&& transport != AmqpTransportType.AMQP_WEB_SOCKETS) {
throw logger.logExceptionAsError(new IllegalArgumentException(
"Cannot use a proxy when TransportType is not AMQP Web Sockets."));
}
final CbsAuthorizationType authorizationType = credentials instanceof EventHubSharedKeyCredential
? CbsAuthorizationType.SHARED_ACCESS_SIGNATURE
: CbsAuthorizationType.JSON_WEB_TOKEN;
final SslDomain.VerifyMode verificationMode = verifyMode != null
? verifyMode
: SslDomain.VerifyMode.VERIFY_PEER_NAME;
final ClientOptions options = new ClientOptions();
if (clientOptions != null) {
options.setApplicationId(clientOptions.getApplicationId())
.setHeaders(clientOptions.getHeaders());
}
final Map<String, String> properties = CoreUtils.getProperties(EVENTHUBS_PROPERTIES_FILE);
final String product = properties.getOrDefault(NAME_KEY, UNKNOWN);
final String clientVersion = properties.getOrDefault(VERSION_KEY, UNKNOWN);
if (customEndpointAddress == null) {
return new ConnectionOptions(fullyQualifiedNamespace, credentials, authorizationType, transport,
retryOptions, proxyOptions, scheduler, options, verificationMode, product, clientVersion);
} else {
return new ConnectionOptions(fullyQualifiedNamespace, credentials, authorizationType, transport,
retryOptions, proxyOptions, scheduler, options, verificationMode, product, clientVersion,
customEndpointAddress.getHost(), customEndpointAddress.getPort());
}
} | } | private ConnectionOptions getConnectionOptions() {
configuration = configuration == null ? Configuration.getGlobalConfiguration().clone() : configuration;
if (credentials == null) {
final String connectionString = configuration.get(AZURE_EVENT_HUBS_CONNECTION_STRING);
if (CoreUtils.isNullOrEmpty(connectionString)) {
throw logger.logExceptionAsError(new IllegalArgumentException("Credentials have not been set. "
+ "They can be set using: connectionString(String), connectionString(String, String), "
+ "credentials(String, String, TokenCredential), or setting the environment variable '"
+ AZURE_EVENT_HUBS_CONNECTION_STRING + "' with a connection string"));
}
connectionString(connectionString);
}
if (proxyOptions == null) {
proxyOptions = getDefaultProxyConfiguration(configuration);
}
if (proxyOptions != null && proxyOptions.isProxyAddressConfigured()
&& transport != AmqpTransportType.AMQP_WEB_SOCKETS) {
throw logger.logExceptionAsError(new IllegalArgumentException(
"Cannot use a proxy when TransportType is not AMQP Web Sockets."));
}
final CbsAuthorizationType authorizationType = credentials instanceof EventHubSharedKeyCredential
? CbsAuthorizationType.SHARED_ACCESS_SIGNATURE
: CbsAuthorizationType.JSON_WEB_TOKEN;
final SslDomain.VerifyMode verificationMode = verifyMode != null
? verifyMode
: SslDomain.VerifyMode.VERIFY_PEER_NAME;
final ClientOptions options = clientOptions != null ? clientOptions : new ClientOptions();
final Map<String, String> properties = CoreUtils.getProperties(EVENTHUBS_PROPERTIES_FILE);
final String product = properties.getOrDefault(NAME_KEY, UNKNOWN);
final String clientVersion = properties.getOrDefault(VERSION_KEY, UNKNOWN);
if (customEndpointAddress == null) {
return new ConnectionOptions(fullyQualifiedNamespace, credentials, authorizationType, transport,
retryOptions, proxyOptions, scheduler, options, verificationMode, product, clientVersion);
} else {
return new ConnectionOptions(fullyQualifiedNamespace, credentials, authorizationType, transport,
retryOptions, proxyOptions, scheduler, options, verificationMode, product, clientVersion,
customEndpointAddress.getHost(), customEndpointAddress.getPort());
}
} | class EventHubClientBuilder {
static final int DEFAULT_PREFETCH_COUNT = 500;
static final int DEFAULT_PREFETCH_COUNT_FOR_SYNC_CLIENT = 1;
/**
* The name of the default consumer group in the Event Hubs service.
*/
public static final String DEFAULT_CONSUMER_GROUP_NAME = "$Default";
/**
* The minimum value allowed for the prefetch count of the consumer.
*/
private static final int MINIMUM_PREFETCH_COUNT = 1;
/**
* The maximum value allowed for the prefetch count of the consumer.
*/
private static final int MAXIMUM_PREFETCH_COUNT = 8000;
private static final String EVENTHUBS_PROPERTIES_FILE = "azure-messaging-eventhubs.properties";
private static final String NAME_KEY = "name";
private static final String VERSION_KEY = "version";
private static final String UNKNOWN = "UNKNOWN";
private static final String AZURE_EVENT_HUBS_CONNECTION_STRING = "AZURE_EVENT_HUBS_CONNECTION_STRING";
private static final AmqpRetryOptions DEFAULT_RETRY = new AmqpRetryOptions()
.setTryTimeout(ClientConstants.OPERATION_TIMEOUT);
private static final Pattern HOST_PORT_PATTERN = Pattern.compile("^[^:]+:\\d+");
private final ClientLogger logger = new ClientLogger(EventHubClientBuilder.class);
private final Object connectionLock = new Object();
private final AtomicBoolean isSharedConnection = new AtomicBoolean();
private TokenCredential credentials;
private Configuration configuration;
private ProxyOptions proxyOptions;
private AmqpRetryOptions retryOptions;
private Scheduler scheduler;
private AmqpTransportType transport;
private String fullyQualifiedNamespace;
private String eventHubName;
private String consumerGroup;
private EventHubConnectionProcessor eventHubConnectionProcessor;
private Integer prefetchCount;
private ClientOptions clientOptions;
private SslDomain.VerifyMode verifyMode;
private URL customEndpointAddress;
/**
* Keeps track of the open clients that were created from this builder when there is a shared connection.
*/
private final AtomicInteger openClients = new AtomicInteger();
/**
* Creates a new instance with the default transport {@link AmqpTransportType
* non-shared connection means that a dedicated AMQP connection is created for every Event Hub consumer or producer
* created using the builder.
*/
public EventHubClientBuilder() {
transport = AmqpTransportType.AMQP;
}
/**
* Sets the credential information given a connection string to the Event Hub instance.
*
* <p>
* If the connection string is copied from the Event Hubs namespace, it will likely not contain the name to the
* desired Event Hub, which is needed. In this case, the name can be added manually by adding {@literal
* "EntityPath=EVENT_HUB_NAME"} to the end of the connection string. For example, "EntityPath=telemetry-hub".
* </p>
*
* <p>
* If you have defined a shared access policy directly on the Event Hub itself, then copying the connection string
* from that Event Hub will result in a connection string that contains the name.
* </p>
*
* @param connectionString The connection string to use for connecting to the Event Hub instance. It is expected
* that the Event Hub name and the shared access key properties are contained in this connection string.
*
* @return The updated {@link EventHubClientBuilder} object.
* @throws IllegalArgumentException if {@code connectionString} is null or empty. Or, the {@code
* connectionString} does not contain the "EntityPath" key, which is the name of the Event Hub instance.
* @throws AzureException If the shared access signature token credential could not be created using the
* connection string.
*/
public EventHubClientBuilder connectionString(String connectionString) {
ConnectionStringProperties properties = new ConnectionStringProperties(connectionString);
TokenCredential tokenCredential = getTokenCredential(properties);
return credential(properties.getEndpoint().getHost(), properties.getEntityPath(), tokenCredential);
}
private TokenCredential getTokenCredential(ConnectionStringProperties properties) {
TokenCredential tokenCredential;
if (properties.getSharedAccessSignature() == null) {
tokenCredential = new EventHubSharedKeyCredential(properties.getSharedAccessKeyName(),
properties.getSharedAccessKey(), ClientConstants.TOKEN_VALIDITY);
} else {
tokenCredential = new EventHubSharedKeyCredential(properties.getSharedAccessSignature());
}
return tokenCredential;
}
/**
* Sets the client options.
*
* @param clientOptions The client options.
* @return The updated {@link EventHubClientBuilder} object.
*/
public EventHubClientBuilder clientOptions(ClientOptions clientOptions) {
this.clientOptions = clientOptions;
return this;
}
/**
* Sets the credential information given a connection string to the Event Hubs namespace and name to a specific
* Event Hub instance.
*
* @param connectionString The connection string to use for connecting to the Event Hubs namespace; it is
* expected that the shared access key properties are contained in this connection string, but not the Event Hub
* name.
* @param eventHubName The name of the Event Hub to connect the client to.
*
* @return The updated {@link EventHubClientBuilder} object.
* @throws NullPointerException if {@code connectionString} or {@code eventHubName} is null.
* @throws IllegalArgumentException if {@code connectionString} or {@code eventHubName} is an empty string. Or,
* if the {@code connectionString} contains the Event Hub name.
* @throws AzureException If the shared access signature token credential could not be created using the
* connection string.
*/
public EventHubClientBuilder connectionString(String connectionString, String eventHubName) {
Objects.requireNonNull(connectionString, "'connectionString' cannot be null.");
Objects.requireNonNull(eventHubName, "'eventHubName' cannot be null.");
if (connectionString.isEmpty()) {
throw logger.logExceptionAsError(new IllegalArgumentException(
"'connectionString' cannot be an empty string."));
} else if (eventHubName.isEmpty()) {
throw logger.logExceptionAsError(new IllegalArgumentException("'eventHubName' cannot be an empty string."));
}
final ConnectionStringProperties properties = new ConnectionStringProperties(connectionString);
TokenCredential tokenCredential = getTokenCredential(properties);
if (!CoreUtils.isNullOrEmpty(properties.getEntityPath())
&& !eventHubName.equals(properties.getEntityPath())) {
throw logger.logExceptionAsError(new IllegalArgumentException(String.format(Locale.US,
"'connectionString' contains an Event Hub name [%s] and it does not match the given "
+ "'eventHubName' parameter [%s]. Please use the credentials(String connectionString) overload. "
+ "Or supply a 'connectionString' without 'EntityPath' in it.",
properties.getEntityPath(), eventHubName)));
}
return credential(properties.getEndpoint().getHost(), eventHubName, tokenCredential);
}
/**
* Sets the configuration store that is used during construction of the service client.
*
* If not specified, the default configuration store is used to configure the {@link EventHubAsyncClient}. Use
* {@link Configuration
*
* @param configuration The configuration store used to configure the {@link EventHubAsyncClient}.
*
* @return The updated {@link EventHubClientBuilder} object.
*/
public EventHubClientBuilder configuration(Configuration configuration) {
this.configuration = configuration;
return this;
}
/**
* Sets a custom endpoint address when connecting to the Event Hubs service. This can be useful when your network
* does not allow connecting to the standard Azure Event Hubs endpoint address, but does allow connecting through
* an intermediary. For example: {@literal https:
* <p>
* If no port is specified, the default port for the {@link
* used.
*
* @param customEndpointAddress The custom endpoint address.
* @return The updated {@link EventHubClientBuilder} object.
* @throws IllegalArgumentException if {@code customEndpointAddress} cannot be parsed into a valid {@link URL}.
*/
public EventHubClientBuilder customEndpointAddress(String customEndpointAddress) {
if (customEndpointAddress == null) {
this.customEndpointAddress = null;
return this;
}
try {
this.customEndpointAddress = new URL(customEndpointAddress);
} catch (MalformedURLException e) {
throw logger.logExceptionAsError(
new IllegalArgumentException(customEndpointAddress + " : is not a valid URL.", e));
}
return this;
}
/**
* Toggles the builder to use the same connection for producers or consumers that are built from this instance. By
* default, a new connection is constructed and used created for each Event Hub consumer or producer created.
*
* @return The updated {@link EventHubClientBuilder} object.
*/
public EventHubClientBuilder shareConnection() {
this.isSharedConnection.set(true);
return this;
}
/**
* Sets the credential information for which Event Hub instance to connect to, and how to authorize against it.
*
* @param fullyQualifiedNamespace The fully qualified name for the Event Hubs namespace. This is likely to be
* similar to <strong>{@literal "{your-namespace}.servicebus.windows.net}"</strong>.
* @param eventHubName The name of the Event Hub to connect the client to.
* @param credential The token credential to use for authorization. Access controls may be specified by the
* Event Hubs namespace or the requested Event Hub, depending on Azure configuration.
*
* @return The updated {@link EventHubClientBuilder} object.
* @throws IllegalArgumentException if {@code fullyQualifiedNamespace} or {@code eventHubName} is an empty
* string.
* @throws NullPointerException if {@code fullyQualifiedNamespace}, {@code eventHubName}, {@code credentials} is
* null.
*/
public EventHubClientBuilder credential(String fullyQualifiedNamespace, String eventHubName,
TokenCredential credential) {
this.fullyQualifiedNamespace = Objects.requireNonNull(fullyQualifiedNamespace,
"'fullyQualifiedNamespace' cannot be null.");
this.credentials = Objects.requireNonNull(credential, "'credential' cannot be null.");
this.eventHubName = Objects.requireNonNull(eventHubName, "'eventHubName' cannot be null.");
if (CoreUtils.isNullOrEmpty(fullyQualifiedNamespace)) {
throw logger.logExceptionAsError(new IllegalArgumentException("'host' cannot be an empty string."));
} else if (CoreUtils.isNullOrEmpty(eventHubName)) {
throw logger.logExceptionAsError(new IllegalArgumentException("'eventHubName' cannot be an empty string."));
}
return this;
}
/**
* Sets the proxy configuration to use for {@link EventHubAsyncClient}. When a proxy is configured, {@link
* AmqpTransportType
*
* @param proxyOptions The proxy configuration to use.
*
* @return The updated {@link EventHubClientBuilder} object.
*/
public EventHubClientBuilder proxyOptions(ProxyOptions proxyOptions) {
this.proxyOptions = proxyOptions;
return this;
}
/**
* Sets the transport type by which all the communication with Azure Event Hubs occurs. Default value is {@link
* AmqpTransportType
*
* @param transport The transport type to use.
*
* @return The updated {@link EventHubClientBuilder} object.
*/
public EventHubClientBuilder transportType(AmqpTransportType transport) {
this.transport = transport;
return this;
}
/**
* Sets the retry policy for {@link EventHubAsyncClient}. If not specified, the default retry options are used.
*
* @param retryOptions The retry policy to use.
*
* @return The updated {@link EventHubClientBuilder} object.
*/
public EventHubClientBuilder retry(AmqpRetryOptions retryOptions) {
this.retryOptions = retryOptions;
return this;
}
/**
* Sets the name of the consumer group this consumer is associated with. Events are read in the context of this
* group. The name of the consumer group that is created by default is {@link
* "$Default"}.
*
* @param consumerGroup The name of the consumer group this consumer is associated with. Events are read in the
* context of this group. The name of the consumer group that is created by default is {@link
*
*
* @return The updated {@link EventHubClientBuilder} object.
*/
public EventHubClientBuilder consumerGroup(String consumerGroup) {
this.consumerGroup = consumerGroup;
return this;
}
/**
* Sets the count used by the receiver to control the number of events the Event Hub consumer will actively receive
* and queue locally without regard to whether a receive operation is currently active.
*
* @param prefetchCount The amount of events to queue locally.
*
* @return The updated {@link EventHubClientBuilder} object.
* @throws IllegalArgumentException if {@code prefetchCount} is less than {@link
* greater than {@link
*/
public EventHubClientBuilder prefetchCount(int prefetchCount) {
if (prefetchCount < MINIMUM_PREFETCH_COUNT) {
throw logger.logExceptionAsError(new IllegalArgumentException(String.format(Locale.US,
"PrefetchCount, '%s' has to be above %s", prefetchCount, MINIMUM_PREFETCH_COUNT)));
}
if (prefetchCount > MAXIMUM_PREFETCH_COUNT) {
throw logger.logExceptionAsError(new IllegalArgumentException(String.format(Locale.US,
"PrefetchCount, '%s', has to be below %s", prefetchCount, MAXIMUM_PREFETCH_COUNT)));
}
this.prefetchCount = prefetchCount;
return this;
}
/**
* Package-private method that sets the scheduler for the created Event Hub client.
*
* @param scheduler Scheduler to set.
*
* @return The updated {@link EventHubClientBuilder} object.
*/
EventHubClientBuilder scheduler(Scheduler scheduler) {
this.scheduler = scheduler;
return this;
}
/**
* Package-private method that sets the verify mode for this connection.
*
* @param verifyMode The verification mode.
* @return The updated {@link EventHubClientBuilder} object.
*/
EventHubClientBuilder verifyMode(SslDomain.VerifyMode verifyMode) {
this.verifyMode = verifyMode;
return this;
}
/**
* Creates a new {@link EventHubConsumerAsyncClient} based on the options set on this builder. Every time {@code
* buildAsyncConsumer()} is invoked, a new instance of {@link EventHubConsumerAsyncClient} is created.
*
* @return A new {@link EventHubConsumerAsyncClient} with the configured options.
* @throws IllegalArgumentException If shared connection is not used and the credentials have not been set using
* either {@link
* {@link
* {@link AmqpTransportType
*/
public EventHubConsumerAsyncClient buildAsyncConsumerClient() {
if (CoreUtils.isNullOrEmpty(consumerGroup)) {
throw logger.logExceptionAsError(new IllegalArgumentException("'consumerGroup' cannot be null or an empty "
+ "string. using EventHubClientBuilder.consumerGroup(String)"));
}
return buildAsyncClient().createConsumer(consumerGroup, prefetchCount);
}
/**
* Creates a new {@link EventHubConsumerClient} based on the options set on this builder. Every time {@code
* buildConsumer()} is invoked, a new instance of {@link EventHubConsumerClient} is created.
*
* @return A new {@link EventHubConsumerClient} with the configured options.
* @throws IllegalArgumentException If shared connection is not used and the credentials have not been set using
* either {@link
* {@link
* {@link AmqpTransportType
*/
public EventHubConsumerClient buildConsumerClient() {
return buildClient().createConsumer(consumerGroup, prefetchCount);
}
/**
* Creates a new {@link EventHubProducerAsyncClient} based on options set on this builder. Every time {@code
* buildAsyncProducer()} is invoked, a new instance of {@link EventHubProducerAsyncClient} is created.
*
* @return A new {@link EventHubProducerAsyncClient} instance with all the configured options.
* @throws IllegalArgumentException If shared connection is not used and the credentials have not been set using
* either {@link
* proxy is specified but the transport type is not {@link AmqpTransportType
*/
public EventHubProducerAsyncClient buildAsyncProducerClient() {
return buildAsyncClient().createProducer();
}
/**
* Creates a new {@link EventHubProducerClient} based on options set on this builder. Every time {@code
* buildAsyncProducer()} is invoked, a new instance of {@link EventHubProducerClient} is created.
*
* @return A new {@link EventHubProducerClient} instance with all the configured options.
* @throws IllegalArgumentException If shared connection is not used and the credentials have not been set using
* either {@link
* proxy is specified but the transport type is not {@link AmqpTransportType
*/
public EventHubProducerClient buildProducerClient() {
return buildClient().createProducer();
}
/**
* Creates a new {@link EventHubAsyncClient} based on options set on this builder. Every time {@code
* buildAsyncClient()} is invoked, a new instance of {@link EventHubAsyncClient} is created.
*
* <p>
* The following options are used if ones are not specified in the builder:
*
* <ul>
* <li>If no configuration is specified, the {@link Configuration
* is used to provide any shared configuration values. The configuration values read are the {@link
* Configuration
* ProxyOptions
* <li>If no retry is specified, the default retry options are used.</li>
* <li>If no proxy is specified, the builder checks the {@link Configuration
* configuration} for a configured proxy, then it checks to see if a system proxy is configured.</li>
* <li>If no timeout is specified, a {@link ClientConstants
* <li>If no scheduler is specified, an {@link Schedulers
* </ul>
*
* @return A new {@link EventHubAsyncClient} instance with all the configured options.
* @throws IllegalArgumentException if the credentials have not been set using either {@link
*
* specified but the transport type is not {@link AmqpTransportType
*/
EventHubAsyncClient buildAsyncClient() {
if (retryOptions == null) {
retryOptions = DEFAULT_RETRY;
}
if (scheduler == null) {
scheduler = Schedulers.elastic();
}
if (prefetchCount == null) {
prefetchCount = DEFAULT_PREFETCH_COUNT;
}
final MessageSerializer messageSerializer = new EventHubMessageSerializer();
final EventHubConnectionProcessor processor;
if (isSharedConnection.get()) {
synchronized (connectionLock) {
if (eventHubConnectionProcessor == null) {
eventHubConnectionProcessor = buildConnectionProcessor(messageSerializer);
}
}
processor = eventHubConnectionProcessor;
final int numberOfOpenClients = openClients.incrementAndGet();
logger.info("
} else {
processor = buildConnectionProcessor(messageSerializer);
}
final TracerProvider tracerProvider = new TracerProvider(ServiceLoader.load(Tracer.class));
return new EventHubAsyncClient(processor, tracerProvider, messageSerializer, scheduler,
isSharedConnection.get(), this::onClientClose);
}
/**
* Creates a new {@link EventHubClient} based on options set on this builder. Every time {@code buildClient()} is
* invoked, a new instance of {@link EventHubClient} is created.
*
* <p>
* The following options are used if ones are not specified in the builder:
*
* <ul>
* <li>If no configuration is specified, the {@link Configuration
* is used to provide any shared configuration values. The configuration values read are the {@link
* Configuration
* ProxyOptions
* <li>If no retry is specified, the default retry options are used.</li>
* <li>If no proxy is specified, the builder checks the {@link Configuration
* configuration} for a configured proxy, then it checks to see if a system proxy is configured.</li>
* <li>If no timeout is specified, a {@link ClientConstants
* <li>If no scheduler is specified, an {@link Schedulers
* </ul>
*
* @return A new {@link EventHubClient} instance with all the configured options.
* @throws IllegalArgumentException if the credentials have not been set using either {@link
*
* specified but the transport type is not {@link AmqpTransportType
*/
EventHubClient buildClient() {
if (prefetchCount == null) {
prefetchCount = DEFAULT_PREFETCH_COUNT_FOR_SYNC_CLIENT;
}
final EventHubAsyncClient client = buildAsyncClient();
return new EventHubClient(client, retryOptions);
}
void onClientClose() {
synchronized (connectionLock) {
final int numberOfOpenClients = openClients.decrementAndGet();
logger.info("Closing a dependent client.
if (numberOfOpenClients > 0) {
return;
}
if (numberOfOpenClients < 0) {
logger.warning("There should not be less than 0 clients. actual: {}", numberOfOpenClients);
}
logger.info("No more open clients, closing shared connection.");
if (eventHubConnectionProcessor != null) {
eventHubConnectionProcessor.dispose();
eventHubConnectionProcessor = null;
} else {
logger.warning("Shared EventHubConnectionProcessor was already disposed.");
}
}
}
private EventHubConnectionProcessor buildConnectionProcessor(MessageSerializer messageSerializer) {
final ConnectionOptions connectionOptions = getConnectionOptions();
final TokenManagerProvider tokenManagerProvider = new AzureTokenManagerProvider(
connectionOptions.getAuthorizationType(), connectionOptions.getFullyQualifiedNamespace(),
ClientConstants.AZURE_ACTIVE_DIRECTORY_SCOPE);
final ReactorProvider provider = new ReactorProvider();
final ReactorHandlerProvider handlerProvider = new ReactorHandlerProvider(provider);
final Flux<EventHubAmqpConnection> connectionFlux = Flux.create(sink -> {
sink.onRequest(request -> {
if (request == 0) {
return;
} else if (request > 1) {
sink.error(logger.logExceptionAsWarning(new IllegalArgumentException(
"Requested more than one connection. Only emitting one. Request: " + request)));
return;
}
final String connectionId = StringUtil.getRandomString("MF");
logger.info("connectionId[{}]: Emitting a single connection.", connectionId);
final EventHubAmqpConnection connection = new EventHubReactorAmqpConnection(connectionId,
connectionOptions, eventHubName, provider, handlerProvider, tokenManagerProvider,
messageSerializer);
sink.next(connection);
});
});
return connectionFlux.subscribeWith(new EventHubConnectionProcessor(
connectionOptions.getFullyQualifiedNamespace(), eventHubName, connectionOptions.getRetry()));
}
private ProxyOptions getDefaultProxyConfiguration(Configuration configuration) {
ProxyAuthenticationType authentication = ProxyAuthenticationType.NONE;
if (proxyOptions != null) {
authentication = proxyOptions.getAuthentication();
}
String proxyAddress = configuration.get(Configuration.PROPERTY_HTTP_PROXY);
if (CoreUtils.isNullOrEmpty(proxyAddress)) {
return ProxyOptions.SYSTEM_DEFAULTS;
}
return getProxyOptions(authentication, proxyAddress);
}
private ProxyOptions getProxyOptions(ProxyAuthenticationType authentication, String proxyAddress) {
String host;
int port;
if (HOST_PORT_PATTERN.matcher(proxyAddress.trim()).find()) {
final String[] hostPort = proxyAddress.split(":");
host = hostPort[0];
port = Integer.parseInt(hostPort[1]);
final Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(host, port));
final String username = configuration.get(ProxyOptions.PROXY_USERNAME);
final String password = configuration.get(ProxyOptions.PROXY_PASSWORD);
return new ProxyOptions(authentication, proxy, username, password);
} else {
com.azure.core.http.ProxyOptions coreProxyOptions = com.azure.core.http.ProxyOptions
.fromConfiguration(configuration);
return new ProxyOptions(authentication, new Proxy(coreProxyOptions.getType().toProxyType(),
coreProxyOptions.getAddress()), coreProxyOptions.getUsername(), coreProxyOptions.getPassword());
}
}
} | class EventHubClientBuilder {
static final int DEFAULT_PREFETCH_COUNT = 500;
static final int DEFAULT_PREFETCH_COUNT_FOR_SYNC_CLIENT = 1;
/**
* The name of the default consumer group in the Event Hubs service.
*/
public static final String DEFAULT_CONSUMER_GROUP_NAME = "$Default";
/**
* The minimum value allowed for the prefetch count of the consumer.
*/
private static final int MINIMUM_PREFETCH_COUNT = 1;
/**
* The maximum value allowed for the prefetch count of the consumer.
*/
private static final int MAXIMUM_PREFETCH_COUNT = 8000;
private static final String EVENTHUBS_PROPERTIES_FILE = "azure-messaging-eventhubs.properties";
private static final String NAME_KEY = "name";
private static final String VERSION_KEY = "version";
private static final String UNKNOWN = "UNKNOWN";
private static final String AZURE_EVENT_HUBS_CONNECTION_STRING = "AZURE_EVENT_HUBS_CONNECTION_STRING";
private static final AmqpRetryOptions DEFAULT_RETRY = new AmqpRetryOptions()
.setTryTimeout(ClientConstants.OPERATION_TIMEOUT);
private static final Pattern HOST_PORT_PATTERN = Pattern.compile("^[^:]+:\\d+");
private final ClientLogger logger = new ClientLogger(EventHubClientBuilder.class);
private final Object connectionLock = new Object();
private final AtomicBoolean isSharedConnection = new AtomicBoolean();
private TokenCredential credentials;
private Configuration configuration;
private ProxyOptions proxyOptions;
private AmqpRetryOptions retryOptions;
private Scheduler scheduler;
private AmqpTransportType transport;
private String fullyQualifiedNamespace;
private String eventHubName;
private String consumerGroup;
private EventHubConnectionProcessor eventHubConnectionProcessor;
private Integer prefetchCount;
private ClientOptions clientOptions;
private SslDomain.VerifyMode verifyMode;
private URL customEndpointAddress;
/**
* Keeps track of the open clients that were created from this builder when there is a shared connection.
*/
private final AtomicInteger openClients = new AtomicInteger();
/**
* Creates a new instance with the default transport {@link AmqpTransportType
* non-shared connection means that a dedicated AMQP connection is created for every Event Hub consumer or producer
* created using the builder.
*/
public EventHubClientBuilder() {
transport = AmqpTransportType.AMQP;
}
/**
* Sets the credential information given a connection string to the Event Hub instance.
*
* <p>
* If the connection string is copied from the Event Hubs namespace, it will likely not contain the name to the
* desired Event Hub, which is needed. In this case, the name can be added manually by adding {@literal
* "EntityPath=EVENT_HUB_NAME"} to the end of the connection string. For example, "EntityPath=telemetry-hub".
* </p>
*
* <p>
* If you have defined a shared access policy directly on the Event Hub itself, then copying the connection string
* from that Event Hub will result in a connection string that contains the name.
* </p>
*
* @param connectionString The connection string to use for connecting to the Event Hub instance. It is expected
* that the Event Hub name and the shared access key properties are contained in this connection string.
*
* @return The updated {@link EventHubClientBuilder} object.
* @throws IllegalArgumentException if {@code connectionString} is null or empty. Or, the {@code
* connectionString} does not contain the "EntityPath" key, which is the name of the Event Hub instance.
* @throws AzureException If the shared access signature token credential could not be created using the
* connection string.
*/
public EventHubClientBuilder connectionString(String connectionString) {
ConnectionStringProperties properties = new ConnectionStringProperties(connectionString);
TokenCredential tokenCredential = getTokenCredential(properties);
return credential(properties.getEndpoint().getHost(), properties.getEntityPath(), tokenCredential);
}
private TokenCredential getTokenCredential(ConnectionStringProperties properties) {
TokenCredential tokenCredential;
if (properties.getSharedAccessSignature() == null) {
tokenCredential = new EventHubSharedKeyCredential(properties.getSharedAccessKeyName(),
properties.getSharedAccessKey(), ClientConstants.TOKEN_VALIDITY);
} else {
tokenCredential = new EventHubSharedKeyCredential(properties.getSharedAccessSignature());
}
return tokenCredential;
}
/**
* Sets the client options.
*
* @param clientOptions The client options.
* @return The updated {@link EventHubClientBuilder} object.
*/
public EventHubClientBuilder clientOptions(ClientOptions clientOptions) {
this.clientOptions = clientOptions;
return this;
}
/**
* Sets the credential information given a connection string to the Event Hubs namespace and name to a specific
* Event Hub instance.
*
* @param connectionString The connection string to use for connecting to the Event Hubs namespace; it is
* expected that the shared access key properties are contained in this connection string, but not the Event Hub
* name.
* @param eventHubName The name of the Event Hub to connect the client to.
*
* @return The updated {@link EventHubClientBuilder} object.
* @throws NullPointerException if {@code connectionString} or {@code eventHubName} is null.
* @throws IllegalArgumentException if {@code connectionString} or {@code eventHubName} is an empty string. Or,
* if the {@code connectionString} contains the Event Hub name.
* @throws AzureException If the shared access signature token credential could not be created using the
* connection string.
*/
public EventHubClientBuilder connectionString(String connectionString, String eventHubName) {
Objects.requireNonNull(connectionString, "'connectionString' cannot be null.");
Objects.requireNonNull(eventHubName, "'eventHubName' cannot be null.");
if (connectionString.isEmpty()) {
throw logger.logExceptionAsError(new IllegalArgumentException(
"'connectionString' cannot be an empty string."));
} else if (eventHubName.isEmpty()) {
throw logger.logExceptionAsError(new IllegalArgumentException("'eventHubName' cannot be an empty string."));
}
final ConnectionStringProperties properties = new ConnectionStringProperties(connectionString);
TokenCredential tokenCredential = getTokenCredential(properties);
if (!CoreUtils.isNullOrEmpty(properties.getEntityPath())
&& !eventHubName.equals(properties.getEntityPath())) {
throw logger.logExceptionAsError(new IllegalArgumentException(String.format(Locale.US,
"'connectionString' contains an Event Hub name [%s] and it does not match the given "
+ "'eventHubName' parameter [%s]. Please use the credentials(String connectionString) overload. "
+ "Or supply a 'connectionString' without 'EntityPath' in it.",
properties.getEntityPath(), eventHubName)));
}
return credential(properties.getEndpoint().getHost(), eventHubName, tokenCredential);
}
/**
* Sets the configuration store that is used during construction of the service client.
*
* If not specified, the default configuration store is used to configure the {@link EventHubAsyncClient}. Use
* {@link Configuration
*
* @param configuration The configuration store used to configure the {@link EventHubAsyncClient}.
*
* @return The updated {@link EventHubClientBuilder} object.
*/
public EventHubClientBuilder configuration(Configuration configuration) {
this.configuration = configuration;
return this;
}
/**
* Sets a custom endpoint address when connecting to the Event Hubs service. This can be useful when your network
* does not allow connecting to the standard Azure Event Hubs endpoint address, but does allow connecting through
* an intermediary. For example: {@literal https:
* <p>
* If no port is specified, the default port for the {@link
* used.
*
* @param customEndpointAddress The custom endpoint address.
* @return The updated {@link EventHubClientBuilder} object.
* @throws IllegalArgumentException if {@code customEndpointAddress} cannot be parsed into a valid {@link URL}.
*/
public EventHubClientBuilder customEndpointAddress(String customEndpointAddress) {
if (customEndpointAddress == null) {
this.customEndpointAddress = null;
return this;
}
try {
this.customEndpointAddress = new URL(customEndpointAddress);
} catch (MalformedURLException e) {
throw logger.logExceptionAsError(
new IllegalArgumentException(customEndpointAddress + " : is not a valid URL.", e));
}
return this;
}
/**
* Toggles the builder to use the same connection for producers or consumers that are built from this instance. By
* default, a new connection is constructed and used created for each Event Hub consumer or producer created.
*
* @return The updated {@link EventHubClientBuilder} object.
*/
public EventHubClientBuilder shareConnection() {
this.isSharedConnection.set(true);
return this;
}
/**
* Sets the credential information for which Event Hub instance to connect to, and how to authorize against it.
*
* @param fullyQualifiedNamespace The fully qualified name for the Event Hubs namespace. This is likely to be
* similar to <strong>{@literal "{your-namespace}.servicebus.windows.net}"</strong>.
* @param eventHubName The name of the Event Hub to connect the client to.
* @param credential The token credential to use for authorization. Access controls may be specified by the
* Event Hubs namespace or the requested Event Hub, depending on Azure configuration.
*
* @return The updated {@link EventHubClientBuilder} object.
* @throws IllegalArgumentException if {@code fullyQualifiedNamespace} or {@code eventHubName} is an empty
* string.
* @throws NullPointerException if {@code fullyQualifiedNamespace}, {@code eventHubName}, {@code credentials} is
* null.
*/
public EventHubClientBuilder credential(String fullyQualifiedNamespace, String eventHubName,
TokenCredential credential) {
this.fullyQualifiedNamespace = Objects.requireNonNull(fullyQualifiedNamespace,
"'fullyQualifiedNamespace' cannot be null.");
this.credentials = Objects.requireNonNull(credential, "'credential' cannot be null.");
this.eventHubName = Objects.requireNonNull(eventHubName, "'eventHubName' cannot be null.");
if (CoreUtils.isNullOrEmpty(fullyQualifiedNamespace)) {
throw logger.logExceptionAsError(new IllegalArgumentException("'host' cannot be an empty string."));
} else if (CoreUtils.isNullOrEmpty(eventHubName)) {
throw logger.logExceptionAsError(new IllegalArgumentException("'eventHubName' cannot be an empty string."));
}
return this;
}
/**
* Sets the proxy configuration to use for {@link EventHubAsyncClient}. When a proxy is configured, {@link
* AmqpTransportType
*
* @param proxyOptions The proxy configuration to use.
*
* @return The updated {@link EventHubClientBuilder} object.
*/
public EventHubClientBuilder proxyOptions(ProxyOptions proxyOptions) {
this.proxyOptions = proxyOptions;
return this;
}
/**
* Sets the transport type by which all the communication with Azure Event Hubs occurs. Default value is {@link
* AmqpTransportType
*
* @param transport The transport type to use.
*
* @return The updated {@link EventHubClientBuilder} object.
*/
public EventHubClientBuilder transportType(AmqpTransportType transport) {
this.transport = transport;
return this;
}
/**
* Sets the retry policy for {@link EventHubAsyncClient}. If not specified, the default retry options are used.
*
* @param retryOptions The retry policy to use.
*
* @return The updated {@link EventHubClientBuilder} object.
*/
public EventHubClientBuilder retry(AmqpRetryOptions retryOptions) {
this.retryOptions = retryOptions;
return this;
}
/**
* Sets the name of the consumer group this consumer is associated with. Events are read in the context of this
* group. The name of the consumer group that is created by default is {@link
* "$Default"}.
*
* @param consumerGroup The name of the consumer group this consumer is associated with. Events are read in the
* context of this group. The name of the consumer group that is created by default is {@link
*
*
* @return The updated {@link EventHubClientBuilder} object.
*/
public EventHubClientBuilder consumerGroup(String consumerGroup) {
this.consumerGroup = consumerGroup;
return this;
}
/**
* Sets the count used by the receiver to control the number of events the Event Hub consumer will actively receive
* and queue locally without regard to whether a receive operation is currently active.
*
* @param prefetchCount The amount of events to queue locally.
*
* @return The updated {@link EventHubClientBuilder} object.
* @throws IllegalArgumentException if {@code prefetchCount} is less than {@link
* greater than {@link
*/
public EventHubClientBuilder prefetchCount(int prefetchCount) {
if (prefetchCount < MINIMUM_PREFETCH_COUNT) {
throw logger.logExceptionAsError(new IllegalArgumentException(String.format(Locale.US,
"PrefetchCount, '%s' has to be above %s", prefetchCount, MINIMUM_PREFETCH_COUNT)));
}
if (prefetchCount > MAXIMUM_PREFETCH_COUNT) {
throw logger.logExceptionAsError(new IllegalArgumentException(String.format(Locale.US,
"PrefetchCount, '%s', has to be below %s", prefetchCount, MAXIMUM_PREFETCH_COUNT)));
}
this.prefetchCount = prefetchCount;
return this;
}
/**
* Package-private method that sets the scheduler for the created Event Hub client.
*
* @param scheduler Scheduler to set.
*
* @return The updated {@link EventHubClientBuilder} object.
*/
EventHubClientBuilder scheduler(Scheduler scheduler) {
this.scheduler = scheduler;
return this;
}
/**
* Package-private method that sets the verify mode for this connection.
*
* @param verifyMode The verification mode.
* @return The updated {@link EventHubClientBuilder} object.
*/
EventHubClientBuilder verifyMode(SslDomain.VerifyMode verifyMode) {
this.verifyMode = verifyMode;
return this;
}
/**
* Creates a new {@link EventHubConsumerAsyncClient} based on the options set on this builder. Every time {@code
* buildAsyncConsumer()} is invoked, a new instance of {@link EventHubConsumerAsyncClient} is created.
*
* @return A new {@link EventHubConsumerAsyncClient} with the configured options.
* @throws IllegalArgumentException If shared connection is not used and the credentials have not been set using
* either {@link
* {@link
* {@link AmqpTransportType
*/
public EventHubConsumerAsyncClient buildAsyncConsumerClient() {
if (CoreUtils.isNullOrEmpty(consumerGroup)) {
throw logger.logExceptionAsError(new IllegalArgumentException("'consumerGroup' cannot be null or an empty "
+ "string. using EventHubClientBuilder.consumerGroup(String)"));
}
return buildAsyncClient().createConsumer(consumerGroup, prefetchCount);
}
/**
* Creates a new {@link EventHubConsumerClient} based on the options set on this builder. Every time {@code
* buildConsumer()} is invoked, a new instance of {@link EventHubConsumerClient} is created.
*
* @return A new {@link EventHubConsumerClient} with the configured options.
* @throws IllegalArgumentException If shared connection is not used and the credentials have not been set using
* either {@link
* {@link
* {@link AmqpTransportType
*/
public EventHubConsumerClient buildConsumerClient() {
return buildClient().createConsumer(consumerGroup, prefetchCount);
}
/**
* Creates a new {@link EventHubProducerAsyncClient} based on options set on this builder. Every time {@code
* buildAsyncProducer()} is invoked, a new instance of {@link EventHubProducerAsyncClient} is created.
*
* @return A new {@link EventHubProducerAsyncClient} instance with all the configured options.
* @throws IllegalArgumentException If shared connection is not used and the credentials have not been set using
* either {@link
* proxy is specified but the transport type is not {@link AmqpTransportType
*/
public EventHubProducerAsyncClient buildAsyncProducerClient() {
return buildAsyncClient().createProducer();
}
/**
* Creates a new {@link EventHubProducerClient} based on options set on this builder. Every time {@code
* buildAsyncProducer()} is invoked, a new instance of {@link EventHubProducerClient} is created.
*
* @return A new {@link EventHubProducerClient} instance with all the configured options.
* @throws IllegalArgumentException If shared connection is not used and the credentials have not been set using
* either {@link
* proxy is specified but the transport type is not {@link AmqpTransportType
*/
public EventHubProducerClient buildProducerClient() {
return buildClient().createProducer();
}
/**
* Creates a new {@link EventHubAsyncClient} based on options set on this builder. Every time {@code
* buildAsyncClient()} is invoked, a new instance of {@link EventHubAsyncClient} is created.
*
* <p>
* The following options are used if ones are not specified in the builder:
*
* <ul>
* <li>If no configuration is specified, the {@link Configuration
* is used to provide any shared configuration values. The configuration values read are the {@link
* Configuration
* ProxyOptions
* <li>If no retry is specified, the default retry options are used.</li>
* <li>If no proxy is specified, the builder checks the {@link Configuration
* configuration} for a configured proxy, then it checks to see if a system proxy is configured.</li>
* <li>If no timeout is specified, a {@link ClientConstants
* <li>If no scheduler is specified, an {@link Schedulers
* </ul>
*
* @return A new {@link EventHubAsyncClient} instance with all the configured options.
* @throws IllegalArgumentException if the credentials have not been set using either {@link
*
* specified but the transport type is not {@link AmqpTransportType
*/
EventHubAsyncClient buildAsyncClient() {
if (retryOptions == null) {
retryOptions = DEFAULT_RETRY;
}
if (scheduler == null) {
scheduler = Schedulers.elastic();
}
if (prefetchCount == null) {
prefetchCount = DEFAULT_PREFETCH_COUNT;
}
final MessageSerializer messageSerializer = new EventHubMessageSerializer();
final EventHubConnectionProcessor processor;
if (isSharedConnection.get()) {
synchronized (connectionLock) {
if (eventHubConnectionProcessor == null) {
eventHubConnectionProcessor = buildConnectionProcessor(messageSerializer);
}
}
processor = eventHubConnectionProcessor;
final int numberOfOpenClients = openClients.incrementAndGet();
logger.info("
} else {
processor = buildConnectionProcessor(messageSerializer);
}
final TracerProvider tracerProvider = new TracerProvider(ServiceLoader.load(Tracer.class));
return new EventHubAsyncClient(processor, tracerProvider, messageSerializer, scheduler,
isSharedConnection.get(), this::onClientClose);
}
/**
* Creates a new {@link EventHubClient} based on options set on this builder. Every time {@code buildClient()} is
* invoked, a new instance of {@link EventHubClient} is created.
*
* <p>
* The following options are used if ones are not specified in the builder:
*
* <ul>
* <li>If no configuration is specified, the {@link Configuration
* is used to provide any shared configuration values. The configuration values read are the {@link
* Configuration
* ProxyOptions
* <li>If no retry is specified, the default retry options are used.</li>
* <li>If no proxy is specified, the builder checks the {@link Configuration
* configuration} for a configured proxy, then it checks to see if a system proxy is configured.</li>
* <li>If no timeout is specified, a {@link ClientConstants
* <li>If no scheduler is specified, an {@link Schedulers
* </ul>
*
* @return A new {@link EventHubClient} instance with all the configured options.
* @throws IllegalArgumentException if the credentials have not been set using either {@link
*
* specified but the transport type is not {@link AmqpTransportType
*/
EventHubClient buildClient() {
if (prefetchCount == null) {
prefetchCount = DEFAULT_PREFETCH_COUNT_FOR_SYNC_CLIENT;
}
final EventHubAsyncClient client = buildAsyncClient();
return new EventHubClient(client, retryOptions);
}
void onClientClose() {
synchronized (connectionLock) {
final int numberOfOpenClients = openClients.decrementAndGet();
logger.info("Closing a dependent client.
if (numberOfOpenClients > 0) {
return;
}
if (numberOfOpenClients < 0) {
logger.warning("There should not be less than 0 clients. actual: {}", numberOfOpenClients);
}
logger.info("No more open clients, closing shared connection.");
if (eventHubConnectionProcessor != null) {
eventHubConnectionProcessor.dispose();
eventHubConnectionProcessor = null;
} else {
logger.warning("Shared EventHubConnectionProcessor was already disposed.");
}
}
}
private EventHubConnectionProcessor buildConnectionProcessor(MessageSerializer messageSerializer) {
final ConnectionOptions connectionOptions = getConnectionOptions();
final TokenManagerProvider tokenManagerProvider = new AzureTokenManagerProvider(
connectionOptions.getAuthorizationType(), connectionOptions.getFullyQualifiedNamespace(),
ClientConstants.AZURE_ACTIVE_DIRECTORY_SCOPE);
final ReactorProvider provider = new ReactorProvider();
final ReactorHandlerProvider handlerProvider = new ReactorHandlerProvider(provider);
final Flux<EventHubAmqpConnection> connectionFlux = Flux.create(sink -> {
sink.onRequest(request -> {
if (request == 0) {
return;
} else if (request > 1) {
sink.error(logger.logExceptionAsWarning(new IllegalArgumentException(
"Requested more than one connection. Only emitting one. Request: " + request)));
return;
}
final String connectionId = StringUtil.getRandomString("MF");
logger.info("connectionId[{}]: Emitting a single connection.", connectionId);
final EventHubAmqpConnection connection = new EventHubReactorAmqpConnection(connectionId,
connectionOptions, eventHubName, provider, handlerProvider, tokenManagerProvider,
messageSerializer);
sink.next(connection);
});
});
return connectionFlux.subscribeWith(new EventHubConnectionProcessor(
connectionOptions.getFullyQualifiedNamespace(), eventHubName, connectionOptions.getRetry()));
}
private ProxyOptions getDefaultProxyConfiguration(Configuration configuration) {
ProxyAuthenticationType authentication = ProxyAuthenticationType.NONE;
if (proxyOptions != null) {
authentication = proxyOptions.getAuthentication();
}
String proxyAddress = configuration.get(Configuration.PROPERTY_HTTP_PROXY);
if (CoreUtils.isNullOrEmpty(proxyAddress)) {
return ProxyOptions.SYSTEM_DEFAULTS;
}
return getProxyOptions(authentication, proxyAddress);
}
private ProxyOptions getProxyOptions(ProxyAuthenticationType authentication, String proxyAddress) {
String host;
int port;
if (HOST_PORT_PATTERN.matcher(proxyAddress.trim()).find()) {
final String[] hostPort = proxyAddress.split(":");
host = hostPort[0];
port = Integer.parseInt(hostPort[1]);
final Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(host, port));
final String username = configuration.get(ProxyOptions.PROXY_USERNAME);
final String password = configuration.get(ProxyOptions.PROXY_PASSWORD);
return new ProxyOptions(authentication, proxy, username, password);
} else {
com.azure.core.http.ProxyOptions coreProxyOptions = com.azure.core.http.ProxyOptions
.fromConfiguration(configuration);
return new ProxyOptions(authentication, new Proxy(coreProxyOptions.getType().toProxyType(),
coreProxyOptions.getAddress()), coreProxyOptions.getUsername(), coreProxyOptions.getPassword());
}
}
} |
Same here, don't need to clone ClientOptions. | private ConnectionOptions getConnectionOptions() {
configuration = configuration == null ? Configuration.getGlobalConfiguration().clone() : configuration;
if (credentials == null) {
throw logger.logExceptionAsError(new IllegalArgumentException("Credentials have not been set. "
+ "They can be set using: connectionString(String), connectionString(String, String), "
+ "or credentials(String, String, TokenCredential)"
));
}
if (proxyOptions != null && proxyOptions.isProxyAddressConfigured()
&& transport != AmqpTransportType.AMQP_WEB_SOCKETS) {
throw logger.logExceptionAsError(new IllegalArgumentException(
"Cannot use a proxy when TransportType is not AMQP."));
}
if (proxyOptions == null) {
proxyOptions = getDefaultProxyConfiguration(configuration);
}
final CbsAuthorizationType authorizationType = credentials instanceof ServiceBusSharedKeyCredential
? CbsAuthorizationType.SHARED_ACCESS_SIGNATURE
: CbsAuthorizationType.JSON_WEB_TOKEN;
final SslDomain.VerifyMode verificationMode = verifyMode != null
? verifyMode
: SslDomain.VerifyMode.VERIFY_PEER_NAME;
final ClientOptions options = new ClientOptions();
if (clientOptions != null) {
options.setApplicationId(clientOptions.getApplicationId())
.setHeaders(clientOptions.getHeaders());
}
final Map<String, String> properties = CoreUtils.getProperties(SERVICE_BUS_PROPERTIES_FILE);
final String product = properties.getOrDefault(NAME_KEY, UNKNOWN);
final String clientVersion = properties.getOrDefault(VERSION_KEY, UNKNOWN);
return new ConnectionOptions(fullyQualifiedNamespace, credentials, authorizationType, transport, retryOptions,
proxyOptions, scheduler, options, verificationMode, product, clientVersion);
} | } | private ConnectionOptions getConnectionOptions() {
configuration = configuration == null ? Configuration.getGlobalConfiguration().clone() : configuration;
if (credentials == null) {
throw logger.logExceptionAsError(new IllegalArgumentException("Credentials have not been set. "
+ "They can be set using: connectionString(String), connectionString(String, String), "
+ "or credentials(String, String, TokenCredential)"
));
}
if (proxyOptions != null && proxyOptions.isProxyAddressConfigured()
&& transport != AmqpTransportType.AMQP_WEB_SOCKETS) {
throw logger.logExceptionAsError(new IllegalArgumentException(
"Cannot use a proxy when TransportType is not AMQP."));
}
if (proxyOptions == null) {
proxyOptions = getDefaultProxyConfiguration(configuration);
}
final CbsAuthorizationType authorizationType = credentials instanceof ServiceBusSharedKeyCredential
? CbsAuthorizationType.SHARED_ACCESS_SIGNATURE
: CbsAuthorizationType.JSON_WEB_TOKEN;
final SslDomain.VerifyMode verificationMode = verifyMode != null
? verifyMode
: SslDomain.VerifyMode.VERIFY_PEER_NAME;
final ClientOptions options = clientOptions != null ? clientOptions : new ClientOptions();
final Map<String, String> properties = CoreUtils.getProperties(SERVICE_BUS_PROPERTIES_FILE);
final String product = properties.getOrDefault(NAME_KEY, UNKNOWN);
final String clientVersion = properties.getOrDefault(VERSION_KEY, UNKNOWN);
return new ConnectionOptions(fullyQualifiedNamespace, credentials, authorizationType, transport, retryOptions,
proxyOptions, scheduler, options, verificationMode, product, clientVersion);
} | class ServiceBusClientBuilder {
private static final AmqpRetryOptions DEFAULT_RETRY =
new AmqpRetryOptions().setTryTimeout(ServiceBusConstants.OPERATION_TIMEOUT);
private static final String SERVICE_BUS_PROPERTIES_FILE = "azure-messaging-servicebus.properties";
private static final String SUBSCRIPTION_ENTITY_PATH_FORMAT = "%s/subscriptions/%s";
private static final String DEAD_LETTER_QUEUE_NAME_SUFFIX = "/$deadletterqueue";
private static final String TRANSFER_DEAD_LETTER_QUEUE_NAME_SUFFIX = "/$Transfer/$deadletterqueue";
private static final int DEFAULT_PREFETCH_COUNT = 0;
private static final String NAME_KEY = "name";
private static final String VERSION_KEY = "version";
private static final String UNKNOWN = "UNKNOWN";
private static final Pattern HOST_PORT_PATTERN = Pattern.compile("^[^:]+:\\d+");
private static final Duration MAX_LOCK_RENEW_DEFAULT_DURATION = Duration.ofMinutes(5);
private final Object connectionLock = new Object();
private final ClientLogger logger = new ClientLogger(ServiceBusClientBuilder.class);
private final MessageSerializer messageSerializer = new ServiceBusMessageSerializer();
private final TracerProvider tracerProvider = new TracerProvider(ServiceLoader.load(Tracer.class));
private ClientOptions clientOptions;
private Configuration configuration;
private ServiceBusConnectionProcessor sharedConnection;
private String connectionStringEntityName;
private TokenCredential credentials;
private String fullyQualifiedNamespace;
private ProxyOptions proxyOptions;
private AmqpRetryOptions retryOptions;
private Scheduler scheduler;
private AmqpTransportType transport = AmqpTransportType.AMQP;
private SslDomain.VerifyMode verifyMode;
/**
* Keeps track of the open clients that were created from this builder when there is a shared connection.
*/
private final AtomicInteger openClients = new AtomicInteger();
/**
* Creates a new instance with the default transport {@link AmqpTransportType
*/
public ServiceBusClientBuilder() {
}
/**
* Sets the {@link ClientOptions} to be sent from the client built from this builder, enabling customization of
* certain properties, as well as support the addition of custom header information. Refer to the {@link
* ClientOptions} documentation for more information.
*
* @param clientOptions to be set on the client.
*
* @return The updated {@link ServiceBusClientBuilder} object.
*/
public ServiceBusClientBuilder clientOptions(ClientOptions clientOptions) {
this.clientOptions = clientOptions;
return this;
}
/**
* Sets the connection string for a Service Bus namespace or a specific Service Bus resource.
*
* @param connectionString Connection string for a Service Bus namespace or a specific Service Bus resource.
*
* @return The updated {@link ServiceBusClientBuilder} object.
*/
public ServiceBusClientBuilder connectionString(String connectionString) {
final ConnectionStringProperties properties = new ConnectionStringProperties(connectionString);
final TokenCredential tokenCredential;
try {
tokenCredential = getTokenCredential(properties);
} catch (Exception e) {
throw logger.logExceptionAsError(
new AzureException("Could not create the ServiceBusSharedKeyCredential.", e));
}
this.fullyQualifiedNamespace = properties.getEndpoint().getHost();
if (properties.getEntityPath() != null && !properties.getEntityPath().isEmpty()) {
logger.info("Setting 'entityName' [{}] from connectionString.", properties.getEntityPath());
this.connectionStringEntityName = properties.getEntityPath();
}
return credential(properties.getEndpoint().getHost(), tokenCredential);
}
private TokenCredential getTokenCredential(ConnectionStringProperties properties) {
TokenCredential tokenCredential;
if (properties.getSharedAccessSignature() == null) {
tokenCredential = new ServiceBusSharedKeyCredential(properties.getSharedAccessKeyName(),
properties.getSharedAccessKey(), ServiceBusConstants.TOKEN_VALIDITY);
} else {
tokenCredential = new ServiceBusSharedKeyCredential(properties.getSharedAccessSignature());
}
return tokenCredential;
}
/**
* Sets the configuration store that is used during construction of the service client.
*
* If not specified, the default configuration store is used to configure Service Bus clients. Use {@link
* Configuration
*
* @param configuration The configuration store used to configure Service Bus clients.
*
* @return The updated {@link ServiceBusClientBuilder} object.
*/
public ServiceBusClientBuilder configuration(Configuration configuration) {
this.configuration = configuration;
return this;
}
/**
* Sets the credential for the Service Bus resource.
*
* @param fullyQualifiedNamespace for the Service Bus.
* @param credential {@link TokenCredential} to be used for authentication.
*
* @return The updated {@link ServiceBusClientBuilder} object.
*/
public ServiceBusClientBuilder credential(String fullyQualifiedNamespace, TokenCredential credential) {
this.fullyQualifiedNamespace = Objects.requireNonNull(fullyQualifiedNamespace,
"'fullyQualifiedNamespace' cannot be null.");
this.credentials = Objects.requireNonNull(credential, "'credential' cannot be null.");
if (CoreUtils.isNullOrEmpty(fullyQualifiedNamespace)) {
throw logger.logExceptionAsError(
new IllegalArgumentException("'fullyQualifiedNamespace' cannot be an empty string."));
}
return this;
}
/**
* Sets the proxy configuration to use for {@link ServiceBusSenderAsyncClient}. When a proxy is configured, {@link
* AmqpTransportType
*
* @param proxyOptions The proxy configuration to use.
*
* @return The updated {@link ServiceBusClientBuilder} object.
*/
public ServiceBusClientBuilder proxyOptions(ProxyOptions proxyOptions) {
this.proxyOptions = proxyOptions;
return this;
}
/**
* Package-private method that sets the verify mode for this connection.
*
* @param verifyMode The verification mode.
* @return The updated {@link ServiceBusClientBuilder} object.
*/
ServiceBusClientBuilder verifyMode(SslDomain.VerifyMode verifyMode) {
this.verifyMode = verifyMode;
return this;
}
/**
* Sets the retry options for Service Bus clients. If not specified, the default retry options are used.
*
* @param retryOptions The retry options to use.
*
* @return The updated {@link ServiceBusClientBuilder} object.
*/
public ServiceBusClientBuilder retryOptions(AmqpRetryOptions retryOptions) {
this.retryOptions = retryOptions;
return this;
}
/**
* Sets the scheduler to use.
*
* @param scheduler Scheduler to be used.
*
* @return The updated {@link ServiceBusClientBuilder} object.
*/
ServiceBusClientBuilder scheduler(Scheduler scheduler) {
this.scheduler = scheduler;
return this;
}
/**
* Sets the transport type by which all the communication with Azure Service Bus occurs. Default value is {@link
* AmqpTransportType
*
* @param transportType The transport type to use.
*
* @return The updated {@link ServiceBusClientBuilder} object.
*/
public ServiceBusClientBuilder transportType(AmqpTransportType transportType) {
this.transport = transportType;
return this;
}
/**
* A new instance of {@link ServiceBusSenderClientBuilder} used to configure Service Bus message senders.
*
* @return A new instance of {@link ServiceBusSenderClientBuilder}.
*/
public ServiceBusSenderClientBuilder sender() {
return new ServiceBusSenderClientBuilder();
}
/**
* A new instance of {@link ServiceBusReceiverClientBuilder} used to configure Service Bus message receivers.
*
* @return A new instance of {@link ServiceBusReceiverClientBuilder}.
*/
public ServiceBusReceiverClientBuilder receiver() {
return new ServiceBusReceiverClientBuilder();
}
/**
* A new instance of {@link ServiceBusSessionReceiverClientBuilder} used to configure <b>session aware</b> Service
* Bus message receivers.
*
* @return A new instance of {@link ServiceBusSessionReceiverClientBuilder}.
*/
public ServiceBusSessionReceiverClientBuilder sessionReceiver() {
return new ServiceBusSessionReceiverClientBuilder();
}
/**
* A new instance of {@link ServiceBusProcessorClientBuilder} used to configure {@link ServiceBusProcessorClient}
* instance.
*
* @return A new instance of {@link ServiceBusProcessorClientBuilder}.
*/
public ServiceBusProcessorClientBuilder processor() {
return new ServiceBusProcessorClientBuilder();
}
/**
* A new instance of {@link ServiceBusSessionProcessorClientBuilder} used to configure a Service Bus processor
* instance that processes sessions.
* @return A new instance of {@link ServiceBusSessionProcessorClientBuilder}.
*/
public ServiceBusSessionProcessorClientBuilder sessionProcessor() {
return new ServiceBusSessionProcessorClientBuilder();
}
/**
* Called when a child client is closed. Disposes of the shared connection if there are no more clients.
*/
void onClientClose() {
synchronized (connectionLock) {
final int numberOfOpenClients = openClients.decrementAndGet();
logger.info("Closing a dependent client.
if (numberOfOpenClients > 0) {
return;
}
if (numberOfOpenClients < 0) {
logger.warning("There should not be less than 0 clients. actual: {}", numberOfOpenClients);
}
logger.info("No more open clients, closing shared connection [{}].", sharedConnection);
if (sharedConnection != null) {
sharedConnection.dispose();
sharedConnection = null;
} else {
logger.warning("Shared ServiceBusConnectionProcessor was already disposed.");
}
}
}
private ServiceBusConnectionProcessor getOrCreateConnectionProcessor(MessageSerializer serializer) {
if (retryOptions == null) {
retryOptions = DEFAULT_RETRY;
}
if (scheduler == null) {
scheduler = Schedulers.elastic();
}
synchronized (connectionLock) {
if (sharedConnection == null) {
final ConnectionOptions connectionOptions = getConnectionOptions();
final TokenManagerProvider tokenManagerProvider = new AzureTokenManagerProvider(
connectionOptions.getAuthorizationType(), connectionOptions.getFullyQualifiedNamespace(),
ServiceBusConstants.AZURE_ACTIVE_DIRECTORY_SCOPE);
final ReactorProvider provider = new ReactorProvider();
final ReactorHandlerProvider handlerProvider = new ReactorHandlerProvider(provider);
final Flux<ServiceBusAmqpConnection> connectionFlux = Mono.fromCallable(() -> {
final String connectionId = StringUtil.getRandomString("MF");
return (ServiceBusAmqpConnection) new ServiceBusReactorAmqpConnection(connectionId,
connectionOptions, provider, handlerProvider, tokenManagerProvider, serializer);
}).repeat();
sharedConnection = connectionFlux.subscribeWith(new ServiceBusConnectionProcessor(
connectionOptions.getFullyQualifiedNamespace(), connectionOptions.getRetry()));
}
}
final int numberOfOpenClients = openClients.incrementAndGet();
logger.info("
return sharedConnection;
}
private ProxyOptions getDefaultProxyConfiguration(Configuration configuration) {
ProxyAuthenticationType authentication = ProxyAuthenticationType.NONE;
if (proxyOptions != null) {
authentication = proxyOptions.getAuthentication();
}
String proxyAddress = configuration.get(Configuration.PROPERTY_HTTP_PROXY);
if (CoreUtils.isNullOrEmpty(proxyAddress)) {
return ProxyOptions.SYSTEM_DEFAULTS;
}
return getProxyOptions(authentication, proxyAddress);
}
private ProxyOptions getProxyOptions(ProxyAuthenticationType authentication, String proxyAddress) {
String host;
int port;
if (HOST_PORT_PATTERN.matcher(proxyAddress.trim()).find()) {
final String[] hostPort = proxyAddress.split(":");
host = hostPort[0];
port = Integer.parseInt(hostPort[1]);
final Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(host, port));
final String username = configuration.get(ProxyOptions.PROXY_USERNAME);
final String password = configuration.get(ProxyOptions.PROXY_PASSWORD);
return new ProxyOptions(authentication, proxy, username, password);
} else {
com.azure.core.http.ProxyOptions coreProxyOptions = com.azure.core.http.ProxyOptions
.fromConfiguration(configuration);
return new ProxyOptions(authentication, new Proxy(coreProxyOptions.getType().toProxyType(),
coreProxyOptions.getAddress()), coreProxyOptions.getUsername(), coreProxyOptions.getPassword());
}
}
private static boolean isNullOrEmpty(String item) {
return item == null || item.isEmpty();
}
private static MessagingEntityType validateEntityPaths(ClientLogger logger, String connectionStringEntityName,
String topicName, String queueName) {
final boolean hasTopicName = !isNullOrEmpty(topicName);
final boolean hasQueueName = !isNullOrEmpty(queueName);
final boolean hasConnectionStringEntity = !isNullOrEmpty(connectionStringEntityName);
final MessagingEntityType entityType;
if (!hasConnectionStringEntity && !hasQueueName && !hasTopicName) {
throw logger.logExceptionAsError(new IllegalStateException(
"Cannot build client without setting either a queueName or topicName."));
} else if (hasQueueName && hasTopicName) {
throw logger.logExceptionAsError(new IllegalStateException(String.format(
"Cannot build client with both queueName (%s) and topicName (%s) set.", queueName, topicName)));
} else if (hasQueueName) {
if (hasConnectionStringEntity && !queueName.equals(connectionStringEntityName)) {
throw logger.logExceptionAsError(new IllegalStateException(String.format(
"queueName (%s) is different than the connectionString's EntityPath (%s).",
queueName, connectionStringEntityName)));
}
entityType = MessagingEntityType.QUEUE;
} else if (hasTopicName) {
if (hasConnectionStringEntity && !topicName.equals(connectionStringEntityName)) {
throw logger.logExceptionAsError(new IllegalStateException(String.format(
"topicName (%s) is different than the connectionString's EntityPath (%s).",
topicName, connectionStringEntityName)));
}
entityType = MessagingEntityType.SUBSCRIPTION;
} else {
entityType = MessagingEntityType.UNKNOWN;
}
return entityType;
}
private static String getEntityPath(ClientLogger logger, MessagingEntityType entityType, String queueName,
String topicName, String subscriptionName, SubQueue subQueue) {
String entityPath;
switch (entityType) {
case QUEUE:
entityPath = queueName;
break;
case SUBSCRIPTION:
if (isNullOrEmpty(subscriptionName)) {
throw logger.logExceptionAsError(new IllegalStateException(String.format(
"topicName (%s) must have a subscriptionName associated with it.", topicName)));
}
entityPath = String.format(Locale.ROOT, SUBSCRIPTION_ENTITY_PATH_FORMAT, topicName,
subscriptionName);
break;
default:
throw logger.logExceptionAsError(
new IllegalArgumentException("Unknown entity type: " + entityType));
}
if (subQueue == null) {
return entityPath;
}
switch (subQueue) {
case NONE:
break;
case TRANSFER_DEAD_LETTER_QUEUE:
entityPath += TRANSFER_DEAD_LETTER_QUEUE_NAME_SUFFIX;
break;
case DEAD_LETTER_QUEUE:
entityPath += DEAD_LETTER_QUEUE_NAME_SUFFIX;
break;
default:
throw logger.logExceptionAsError(new IllegalArgumentException("Unsupported value of subqueue type: "
+ subQueue));
}
return entityPath;
}
/**
* Builder for creating {@link ServiceBusSenderClient} and {@link ServiceBusSenderAsyncClient} to publish messages
* to Service Bus.
*
* @see ServiceBusSenderAsyncClient
* @see ServiceBusSenderClient
*/
@ServiceClientBuilder(serviceClients = {ServiceBusSenderClient.class, ServiceBusSenderAsyncClient.class})
public final class ServiceBusSenderClientBuilder {
private String queueName;
private String topicName;
private ServiceBusSenderClientBuilder() {
}
/**
* Sets the name of the Service Bus queue to publish messages to.
*
* @param queueName Name of the queue.
*
* @return The modified {@link ServiceBusSenderClientBuilder} object.
*/
public ServiceBusSenderClientBuilder queueName(String queueName) {
this.queueName = queueName;
return this;
}
/**
* Sets the name of the Service Bus topic to publish messages to.
*
* @param topicName Name of the topic.
*
* @return The modified {@link ServiceBusSenderClientBuilder} object.
*/
public ServiceBusSenderClientBuilder topicName(String topicName) {
this.topicName = topicName;
return this;
}
/**
* Creates an <b>asynchronous</b> {@link ServiceBusSenderAsyncClient client} for transmitting {@link
* ServiceBusMessage} to a Service Bus queue or topic.
*
* @return A new {@link ServiceBusSenderAsyncClient} for transmitting to a Service queue or topic.
* @throws IllegalStateException if {@link
* topicName} are not set or, both of these fields are set. It is also thrown if the Service Bus {@link
*
* {@link
* @throws IllegalArgumentException if the entity type is not a queue or a topic.
*/
public ServiceBusSenderAsyncClient buildAsyncClient() {
final ServiceBusConnectionProcessor connectionProcessor = getOrCreateConnectionProcessor(messageSerializer);
final MessagingEntityType entityType = validateEntityPaths(logger, connectionStringEntityName, topicName,
queueName);
final String entityName;
switch (entityType) {
case QUEUE:
entityName = queueName;
break;
case SUBSCRIPTION:
entityName = topicName;
break;
case UNKNOWN:
entityName = connectionStringEntityName;
break;
default:
throw logger.logExceptionAsError(
new IllegalArgumentException("Unknown entity type: " + entityType));
}
return new ServiceBusSenderAsyncClient(entityName, entityType, connectionProcessor, retryOptions,
tracerProvider, messageSerializer, ServiceBusClientBuilder.this::onClientClose, null);
}
/**
* Creates a <b>synchronous</b> {@link ServiceBusSenderClient client} for transmitting {@link ServiceBusMessage}
* to a Service Bus queue or topic.
*
* @return A new {@link ServiceBusSenderAsyncClient} for transmitting to a Service queue or topic.
* @throws IllegalStateException if {@link
* topicName} are not set or, both of these fields are set. It is also thrown if the Service Bus {@link
*
* {@link
* @throws IllegalArgumentException if the entity type is not a queue or a topic.
*/
public ServiceBusSenderClient buildClient() {
return new ServiceBusSenderClient(buildAsyncClient(), MessageUtils.getTotalTimeout(retryOptions));
}
}
/**
* Builder for creating {@link ServiceBusProcessorClient} to consume messages from a session-based Service Bus
* entity. {@link ServiceBusProcessorClient} processes messages and errors via {@link
* and {@link
* next session to process.
*
* <p>
* By default, the processor:
* <ul>
* <li>Automatically settles messages. Disabled via {@link
* <li>Processes 1 session concurrently. Configured via {@link
* <li>Invokes 1 instance of {@link
* {@link
* </ul>
*
* <p><strong>Instantiate a session-enabled processor client</strong></p>
* {@codesnippet com.azure.messaging.servicebus.servicebusprocessorclient
*
* @see ServiceBusProcessorClient
*/
public final class ServiceBusSessionProcessorClientBuilder {
private final ServiceBusProcessorClientOptions processorClientOptions;
private final ServiceBusSessionReceiverClientBuilder sessionReceiverClientBuilder;
private Consumer<ServiceBusReceivedMessageContext> processMessage;
private Consumer<ServiceBusErrorContext> processError;
private ServiceBusSessionProcessorClientBuilder() {
sessionReceiverClientBuilder = new ServiceBusSessionReceiverClientBuilder();
processorClientOptions = new ServiceBusProcessorClientOptions()
.setMaxConcurrentCalls(1)
.setTracerProvider(tracerProvider);
sessionReceiverClientBuilder.maxConcurrentSessions(1);
}
/**
* Enables session processing roll-over by processing at most {@code maxConcurrentSessions}.
*
* @param maxConcurrentSessions Maximum number of concurrent sessions to process at any given time.
*
* @return The modified {@link ServiceBusSessionProcessorClientBuilder} object.
* @throws IllegalArgumentException if {@code maxConcurrentSessions} is less than 1.
*/
public ServiceBusSessionProcessorClientBuilder maxConcurrentSessions(int maxConcurrentSessions) {
if (maxConcurrentSessions < 1) {
throw logger.logExceptionAsError(
new IllegalArgumentException("'maxConcurrentSessions' cannot be less than 1"));
}
sessionReceiverClientBuilder.maxConcurrentSessions(maxConcurrentSessions);
return this;
}
/**
* Sets the prefetch count of the processor. For both {@link ServiceBusReceiveMode
* {@link ServiceBusReceiveMode
*
* Prefetch speeds up the message flow by aiming to have a message readily available for local retrieval when
* and before the application starts the processor.
* Setting a non-zero value will prefetch that number of messages. Setting the value to zero turns prefetch off.
* Using a non-zero prefetch risks of losing messages even though it has better performance.
* @see <a href="https:
*
* @param prefetchCount The prefetch count.
*
* @return The modified {@link ServiceBusProcessorClientBuilder} object.
*/
public ServiceBusSessionProcessorClientBuilder prefetchCount(int prefetchCount) {
sessionReceiverClientBuilder.prefetchCount(prefetchCount);
return this;
}
/**
* Sets the name of the queue to create a processor for.
* @param queueName Name of the queue.
*
* @return The modified {@link ServiceBusSessionProcessorClientBuilder} object.
*/
public ServiceBusSessionProcessorClientBuilder queueName(String queueName) {
sessionReceiverClientBuilder.queueName(queueName);
return this;
}
/**
* Sets the receive mode for the processor.
* @param receiveMode Mode for receiving messages.
*
* @return The modified {@link ServiceBusSessionProcessorClientBuilder} object.
*/
public ServiceBusSessionProcessorClientBuilder receiveMode(ServiceBusReceiveMode receiveMode) {
sessionReceiverClientBuilder.receiveMode(receiveMode);
return this;
}
/**
* Sets the name of the subscription in the topic to listen to. <b>{@link
* </b>
* @param subscriptionName Name of the subscription.
*
* @return The modified {@link ServiceBusSessionProcessorClientBuilder} object.
* @see
*/
public ServiceBusSessionProcessorClientBuilder subscriptionName(String subscriptionName) {
sessionReceiverClientBuilder.subscriptionName(subscriptionName);
return this;
}
/**
* Sets the name of the topic. <b>{@link
* @param topicName Name of the topic.
*
* @return The modified {@link ServiceBusSessionProcessorClientBuilder} object.
* @see
*/
public ServiceBusSessionProcessorClientBuilder topicName(String topicName) {
sessionReceiverClientBuilder.topicName(topicName);
return this;
}
/**
* The message processing callback for the processor that will be executed when a message is received.
* @param processMessage The message processing consumer that will be executed when a message is received.
*
* @return The updated {@link ServiceBusProcessorClientBuilder} object.
*/
public ServiceBusSessionProcessorClientBuilder processMessage(
Consumer<ServiceBusReceivedMessageContext> processMessage) {
this.processMessage = processMessage;
return this;
}
/**
* The error handler for the processor which will be invoked in the event of an error while receiving messages.
* @param processError The error handler which will be executed when an error occurs.
*
* @return The updated {@link ServiceBusProcessorClientBuilder} object
*/
public ServiceBusSessionProcessorClientBuilder processError(
Consumer<ServiceBusErrorContext> processError) {
this.processError = processError;
return this;
}
/**
* Max concurrent messages that this processor should process.
*
* @param maxConcurrentCalls max concurrent messages that this processor should process.
*
* @return The updated {@link ServiceBusSessionProcessorClientBuilder} object.
* @throws IllegalArgumentException if {@code maxConcurrentCalls} is less than 1.
*/
public ServiceBusSessionProcessorClientBuilder maxConcurrentCalls(int maxConcurrentCalls) {
if (maxConcurrentCalls < 1) {
throw logger.logExceptionAsError(
new IllegalArgumentException("'maxConcurrentCalls' cannot be less than 1"));
}
processorClientOptions.setMaxConcurrentCalls(maxConcurrentCalls);
return this;
}
/**
* Disables auto-complete and auto-abandon of received messages. By default, a successfully processed message is
* {@link ServiceBusReceivedMessageContext
* the message is processed, it is {@link ServiceBusReceivedMessageContext
* abandoned}.
*
* @return The modified {@link ServiceBusSessionProcessorClientBuilder} object.
*/
public ServiceBusSessionProcessorClientBuilder disableAutoComplete() {
sessionReceiverClientBuilder.disableAutoComplete();
processorClientOptions.setDisableAutoComplete(true);
return this;
}
/**
* Creates a <b>session-aware</b> Service Bus processor responsible for reading
* {@link ServiceBusReceivedMessage messages} from a specific queue or subscription.
*
* @return An new {@link ServiceBusProcessorClient} that receives messages from a queue or subscription.
* @throws IllegalStateException if {@link
* topicName} are not set or, both of these fields are set. It is also thrown if the Service Bus {@link
*
* {@link
*
* @throws IllegalArgumentException Queue or topic name are not set via {@link
* queueName()} or {@link
* @throws NullPointerException if the {@link
* callbacks are not set.
*/
public ServiceBusProcessorClient buildProcessorClient() {
return new ServiceBusProcessorClient(sessionReceiverClientBuilder,
Objects.requireNonNull(processMessage, "'processMessage' cannot be null"),
Objects.requireNonNull(processError, "'processError' cannot be null"), processorClientOptions);
}
}
/**
* Builder for creating {@link ServiceBusReceiverClient} and {@link ServiceBusReceiverAsyncClient} to consume
* messages from a <b>session aware</b> Service Bus entity.
*
* @see ServiceBusReceiverAsyncClient
* @see ServiceBusReceiverClient
*/
@ServiceClientBuilder(serviceClients = {ServiceBusReceiverClient.class, ServiceBusReceiverAsyncClient.class})
public final class ServiceBusSessionReceiverClientBuilder {
private boolean enableAutoComplete = true;
private Integer maxConcurrentSessions = null;
private int prefetchCount = DEFAULT_PREFETCH_COUNT;
private String queueName;
private ServiceBusReceiveMode receiveMode = ServiceBusReceiveMode.PEEK_LOCK;
private String subscriptionName;
private String topicName;
private Duration maxAutoLockRenewDuration = MAX_LOCK_RENEW_DEFAULT_DURATION;
private ServiceBusSessionReceiverClientBuilder() {
}
/**
* Disables auto-complete and auto-abandon of received messages. By default, a successfully processed message is
* {@link ServiceBusReceiverAsyncClient
* the message is processed, it is {@link ServiceBusReceiverAsyncClient
* abandoned}.
*
* @return The modified {@link ServiceBusSessionReceiverClientBuilder} object.
*/
public ServiceBusSessionReceiverClientBuilder disableAutoComplete() {
this.enableAutoComplete = false;
return this;
}
/**
* Sets the amount of time to continue auto-renewing the session lock. Setting {@link Duration
* {@code null} disables auto-renewal. For {@link ServiceBusReceiveMode
* mode, auto-renewal is disabled.
*
* @param maxAutoLockRenewDuration the amount of time to continue auto-renewing the session lock.
* {@link Duration
*
* @return The updated {@link ServiceBusSessionReceiverClientBuilder} object.
* @throws IllegalArgumentException If {code maxAutoLockRenewDuration} is negative.
*/
public ServiceBusSessionReceiverClientBuilder maxAutoLockRenewDuration(Duration maxAutoLockRenewDuration) {
validateAndThrow(maxAutoLockRenewDuration);
this.maxAutoLockRenewDuration = maxAutoLockRenewDuration;
return this;
}
/**
* Enables session processing roll-over by processing at most {@code maxConcurrentSessions}.
*
* @param maxConcurrentSessions Maximum number of concurrent sessions to process at any given time.
*
* @return The modified {@link ServiceBusSessionReceiverClientBuilder} object.
* @throws IllegalArgumentException if {@code maxConcurrentSessions} is less than 1.
*/
ServiceBusSessionReceiverClientBuilder maxConcurrentSessions(int maxConcurrentSessions) {
if (maxConcurrentSessions < 1) {
throw logger.logExceptionAsError(new IllegalArgumentException(
"maxConcurrentSessions cannot be less than 1."));
}
this.maxConcurrentSessions = maxConcurrentSessions;
return this;
}
/**
* Sets the prefetch count of the receiver. For both {@link ServiceBusReceiveMode
* {@link ServiceBusReceiveMode
*
* Prefetch speeds up the message flow by aiming to have a message readily available for local retrieval when
* and before the application asks for one using {@link ServiceBusReceiverAsyncClient
* Setting a non-zero value will prefetch that number of messages. Setting the value to zero turns prefetch
* off.
*
* @param prefetchCount The prefetch count.
*
* @return The modified {@link ServiceBusSessionReceiverClientBuilder} object.
* @throws IllegalArgumentException If {code prefetchCount} is negative.
*/
public ServiceBusSessionReceiverClientBuilder prefetchCount(int prefetchCount) {
validateAndThrow(prefetchCount);
this.prefetchCount = prefetchCount;
return this;
}
/**
* Sets the name of the queue to create a receiver for.
*
* @param queueName Name of the queue.
*
* @return The modified {@link ServiceBusSessionReceiverClientBuilder} object.
*/
public ServiceBusSessionReceiverClientBuilder queueName(String queueName) {
this.queueName = queueName;
return this;
}
/**
* Sets the receive mode for the receiver.
*
* @param receiveMode Mode for receiving messages.
*
* @return The modified {@link ServiceBusSessionReceiverClientBuilder} object.
*/
public ServiceBusSessionReceiverClientBuilder receiveMode(ServiceBusReceiveMode receiveMode) {
this.receiveMode = receiveMode;
return this;
}
/**
* Sets the name of the subscription in the topic to listen to. <b>{@link
* </b>
*
* @param subscriptionName Name of the subscription.
*
* @return The modified {@link ServiceBusSessionReceiverClientBuilder} object.
* @see
*/
public ServiceBusSessionReceiverClientBuilder subscriptionName(String subscriptionName) {
this.subscriptionName = subscriptionName;
return this;
}
/**
* Sets the name of the topic. <b>{@link
*
* @param topicName Name of the topic.
*
* @return The modified {@link ServiceBusSessionReceiverClientBuilder} object.
* @see
*/
public ServiceBusSessionReceiverClientBuilder topicName(String topicName) {
this.topicName = topicName;
return this;
}
/**
* Creates an <b>asynchronous</b>, <b>session-aware</b> Service Bus receiver responsible for reading {@link
* ServiceBusMessage messages} from a specific queue or subscription.
*
* @return An new {@link ServiceBusReceiverAsyncClient} that receives messages from a queue or subscription.
* @throws IllegalStateException if {@link
* topicName} are not set or, both of these fields are set. It is also thrown if the Service Bus {@link
*
* {@link
*
* @throws IllegalArgumentException Queue or topic name are not set via {@link
* queueName()} or {@link
*/
ServiceBusReceiverAsyncClient buildAsyncClientForProcessor() {
final MessagingEntityType entityType = validateEntityPaths(logger, connectionStringEntityName, topicName,
queueName);
final String entityPath = getEntityPath(logger, entityType, queueName, topicName, subscriptionName,
SubQueue.NONE);
if (enableAutoComplete && receiveMode == ServiceBusReceiveMode.RECEIVE_AND_DELETE) {
logger.warning("'enableAutoComplete' is not needed in for RECEIVE_AND_DELETE mode.");
enableAutoComplete = false;
}
if (receiveMode == ServiceBusReceiveMode.RECEIVE_AND_DELETE) {
maxAutoLockRenewDuration = Duration.ZERO;
}
final ServiceBusConnectionProcessor connectionProcessor = getOrCreateConnectionProcessor(messageSerializer);
final ReceiverOptions receiverOptions = new ReceiverOptions(receiveMode, prefetchCount,
maxAutoLockRenewDuration, enableAutoComplete, null,
maxConcurrentSessions);
final ServiceBusSessionManager sessionManager = new ServiceBusSessionManager(entityPath, entityType,
connectionProcessor, tracerProvider, messageSerializer, receiverOptions);
return new ServiceBusReceiverAsyncClient(connectionProcessor.getFullyQualifiedNamespace(), entityPath,
entityType, receiverOptions, connectionProcessor, ServiceBusConstants.OPERATION_TIMEOUT,
tracerProvider, messageSerializer, ServiceBusClientBuilder.this::onClientClose, sessionManager);
}
/**
* Creates an <b>asynchronous</b>, <b>session-aware</b> Service Bus receiver responsible for reading {@link
* ServiceBusMessage messages} from a specific queue or subscription.
*
* @return An new {@link ServiceBusSessionReceiverAsyncClient} that receives messages from a queue or
* subscription.
* @throws IllegalStateException if {@link
* topicName} are not set or, both of these fields are set. It is also thrown if the Service Bus {@link
*
* {@link
*
* @throws IllegalArgumentException Queue or topic name are not set via {@link
* queueName()} or {@link
*/
public ServiceBusSessionReceiverAsyncClient buildAsyncClient() {
return buildAsyncClient(true);
}
/**
* Creates a <b>synchronous</b>, <b>session-aware</b> Service Bus receiver responsible for reading {@link
* ServiceBusMessage messages} from a specific queue or subscription.
*
* @return An new {@link ServiceBusReceiverClient} that receives messages from a queue or subscription.
* @throws IllegalStateException if {@link
* topicName} are not set or, both of these fields are set. It is also thrown if the Service Bus {@link
*
* {@link
*
* @throws IllegalArgumentException Queue or topic name are not set via {@link
* queueName()} or {@link
*/
public ServiceBusSessionReceiverClient buildClient() {
return new ServiceBusSessionReceiverClient(buildAsyncClient(false),
MessageUtils.getTotalTimeout(retryOptions));
}
private ServiceBusSessionReceiverAsyncClient buildAsyncClient(boolean isAutoCompleteAllowed) {
final MessagingEntityType entityType = validateEntityPaths(logger, connectionStringEntityName, topicName,
queueName);
final String entityPath = getEntityPath(logger, entityType, queueName, topicName, subscriptionName,
SubQueue.NONE);
if (!isAutoCompleteAllowed && enableAutoComplete) {
logger.warning(
"'enableAutoComplete' is not supported in synchronous client except through callback receive.");
enableAutoComplete = false;
} else if (enableAutoComplete && receiveMode == ServiceBusReceiveMode.RECEIVE_AND_DELETE) {
logger.warning("'enableAutoComplete' is not needed in for RECEIVE_AND_DELETE mode.");
enableAutoComplete = false;
}
if (receiveMode == ServiceBusReceiveMode.RECEIVE_AND_DELETE) {
maxAutoLockRenewDuration = Duration.ZERO;
}
final ServiceBusConnectionProcessor connectionProcessor = getOrCreateConnectionProcessor(messageSerializer);
final ReceiverOptions receiverOptions = new ReceiverOptions(receiveMode, prefetchCount,
maxAutoLockRenewDuration, enableAutoComplete, null, maxConcurrentSessions);
return new ServiceBusSessionReceiverAsyncClient(connectionProcessor.getFullyQualifiedNamespace(),
entityPath, entityType, receiverOptions, connectionProcessor, tracerProvider, messageSerializer,
ServiceBusClientBuilder.this::onClientClose);
}
}
/**
* Builder for creating {@link ServiceBusProcessorClient} to consume messages from a Service Bus entity.
* {@link ServiceBusProcessorClient ServiceBusProcessorClients} provides a push-based mechanism that notifies
* the message processing callback when a message is received or the error handle when an error is observed. To
* create an instance, therefore, configuring the two callbacks - {@link
* {@link
* with auto-completion and auto-lock renewal capabilities.
*
* <p><strong>Sample code to instantiate a processor client</strong></p>
* {@codesnippet com.azure.messaging.servicebus.servicebusprocessorclient
*
* @see ServiceBusProcessorClient
*/
public final class ServiceBusProcessorClientBuilder {
private final ServiceBusReceiverClientBuilder serviceBusReceiverClientBuilder;
private final ServiceBusProcessorClientOptions processorClientOptions;
private Consumer<ServiceBusReceivedMessageContext> processMessage;
private Consumer<ServiceBusErrorContext> processError;
private ServiceBusProcessorClientBuilder() {
serviceBusReceiverClientBuilder = new ServiceBusReceiverClientBuilder();
processorClientOptions = new ServiceBusProcessorClientOptions()
.setMaxConcurrentCalls(1)
.setTracerProvider(tracerProvider);
}
/**
* Sets the prefetch count of the processor. For both {@link ServiceBusReceiveMode
* {@link ServiceBusReceiveMode
*
* Prefetch speeds up the message flow by aiming to have a message readily available for local retrieval when
* and before the application starts the processor.
* Setting a non-zero value will prefetch that number of messages. Setting the value to zero turns prefetch off.
*
* @param prefetchCount The prefetch count.
*
* @return The modified {@link ServiceBusProcessorClientBuilder} object.
*/
public ServiceBusProcessorClientBuilder prefetchCount(int prefetchCount) {
serviceBusReceiverClientBuilder.prefetchCount(prefetchCount);
return this;
}
/**
* Sets the name of the queue to create a processor for.
* @param queueName Name of the queue.
*
* @return The modified {@link ServiceBusProcessorClientBuilder} object.
*/
public ServiceBusProcessorClientBuilder queueName(String queueName) {
serviceBusReceiverClientBuilder.queueName(queueName);
return this;
}
/**
* Sets the receive mode for the processor.
* @param receiveMode Mode for receiving messages.
*
* @return The modified {@link ServiceBusProcessorClientBuilder} object.
*/
public ServiceBusProcessorClientBuilder receiveMode(ServiceBusReceiveMode receiveMode) {
serviceBusReceiverClientBuilder.receiveMode(receiveMode);
return this;
}
/**
* Sets the name of the subscription in the topic to listen to. <b>{@link
* </b>
* @param subscriptionName Name of the subscription.
*
* @return The modified {@link ServiceBusProcessorClientBuilder} object.
* @see
*/
public ServiceBusProcessorClientBuilder subscriptionName(String subscriptionName) {
serviceBusReceiverClientBuilder.subscriptionName(subscriptionName);
return this;
}
/**
* Sets the name of the topic. <b>{@link
* @param topicName Name of the topic.
*
* @return The modified {@link ServiceBusProcessorClientBuilder} object.
* @see
*/
public ServiceBusProcessorClientBuilder topicName(String topicName) {
serviceBusReceiverClientBuilder.topicName(topicName);
return this;
}
/**
* The message processing callback for the processor which will be executed when a message is received.
* @param processMessage The message processing consumer that will be executed when a message is received.
*
* @return The updated {@link ServiceBusProcessorClientBuilder} object.
*/
public ServiceBusProcessorClientBuilder processMessage(
Consumer<ServiceBusReceivedMessageContext> processMessage) {
this.processMessage = processMessage;
return this;
}
/**
* The error handler for the processor which will be invoked in the event of an error while receiving messages.
* @param processError The error handler which will be executed when an error occurs.
*
* @return The updated {@link ServiceBusProcessorClientBuilder} object
*/
public ServiceBusProcessorClientBuilder processError(Consumer<ServiceBusErrorContext> processError) {
this.processError = processError;
return this;
}
/**
* Max concurrent messages that this processor should process. By default, this is set to 1.
*
* @param maxConcurrentCalls max concurrent messages that this processor should process.
* @return The updated {@link ServiceBusProcessorClientBuilder} object.
* @throws IllegalArgumentException if the {@code maxConcurrentCalls} is set to a value less than 1.
*/
public ServiceBusProcessorClientBuilder maxConcurrentCalls(int maxConcurrentCalls) {
if (maxConcurrentCalls < 1) {
throw logger.logExceptionAsError(
new IllegalArgumentException("'maxConcurrentCalls' cannot be less than 1"));
}
processorClientOptions.setMaxConcurrentCalls(maxConcurrentCalls);
return this;
}
/**
* Disables auto-complete and auto-abandon of received messages. By default, a successfully processed message is
* {@link ServiceBusReceivedMessageContext
* the message is processed, it is {@link ServiceBusReceivedMessageContext
* abandoned}.
*
* @return The modified {@link ServiceBusProcessorClientBuilder} object.
*/
public ServiceBusProcessorClientBuilder disableAutoComplete() {
serviceBusReceiverClientBuilder.disableAutoComplete();
processorClientOptions.setDisableAutoComplete(true);
return this;
}
/**
* Creates Service Bus message processor responsible for reading {@link ServiceBusReceivedMessage
* messages} from a specific queue or subscription.
*
* @return An new {@link ServiceBusProcessorClient} that processes messages from a queue or subscription.
* @throws IllegalStateException if {@link
* topicName} are not set or, both of these fields are set. It is also thrown if the Service Bus {@link
*
* {@link
*
* @throws IllegalArgumentException Queue or topic name are not set via {@link
* queueName()} or {@link
* @throws NullPointerException if the {@link
* callbacks are not set.
*/
public ServiceBusProcessorClient buildProcessorClient() {
return new ServiceBusProcessorClient(serviceBusReceiverClientBuilder,
Objects.requireNonNull(processMessage, "'processMessage' cannot be null"),
Objects.requireNonNull(processError, "'processError' cannot be null"), processorClientOptions);
}
}
/**
* Builder for creating {@link ServiceBusReceiverClient} and {@link ServiceBusReceiverAsyncClient} to consume
* messages from Service Bus.
*
* @see ServiceBusReceiverAsyncClient
* @see ServiceBusReceiverClient
*/
@ServiceClientBuilder(serviceClients = {ServiceBusReceiverClient.class, ServiceBusReceiverAsyncClient.class})
public final class ServiceBusReceiverClientBuilder {
private boolean enableAutoComplete = true;
private int prefetchCount = DEFAULT_PREFETCH_COUNT;
private String queueName;
private SubQueue subQueue;
private ServiceBusReceiveMode receiveMode = ServiceBusReceiveMode.PEEK_LOCK;
private String subscriptionName;
private String topicName;
private Duration maxAutoLockRenewDuration = MAX_LOCK_RENEW_DEFAULT_DURATION;
private ServiceBusReceiverClientBuilder() {
}
/**
* Disables auto-complete and auto-abandon of received messages. By default, a successfully processed message is
* {@link ServiceBusReceiverAsyncClient
* the message is processed, it is {@link ServiceBusReceiverAsyncClient
* abandoned}.
*
* @return The modified {@link ServiceBusReceiverClientBuilder} object.
*/
public ServiceBusReceiverClientBuilder disableAutoComplete() {
this.enableAutoComplete = false;
return this;
}
/**
* Sets the amount of time to continue auto-renewing the lock. Setting {@link Duration
* disables auto-renewal. For {@link ServiceBusReceiveMode
* auto-renewal is disabled.
*
* @param maxAutoLockRenewDuration the amount of time to continue auto-renewing the lock. {@link Duration
* or {@code null} indicates that auto-renewal is disabled.
*
* @return The updated {@link ServiceBusReceiverClientBuilder} object.
* @throws IllegalArgumentException If {code maxAutoLockRenewDuration} is negative.
*/
public ServiceBusReceiverClientBuilder maxAutoLockRenewDuration(Duration maxAutoLockRenewDuration) {
validateAndThrow(maxAutoLockRenewDuration);
this.maxAutoLockRenewDuration = maxAutoLockRenewDuration;
return this;
}
/**
* Sets the prefetch count of the receiver. For both {@link ServiceBusReceiveMode
* {@link ServiceBusReceiveMode
*
* Prefetch speeds up the message flow by aiming to have a message readily available for local retrieval when
* and before the application asks for one using {@link ServiceBusReceiverAsyncClient
* Setting a non-zero value will prefetch that number of messages. Setting the value to zero turns prefetch
* off.
*
* @param prefetchCount The prefetch count.
*
* @return The modified {@link ServiceBusReceiverClientBuilder} object.
* @throws IllegalArgumentException If {code prefetchCount} is negative.
*/
public ServiceBusReceiverClientBuilder prefetchCount(int prefetchCount) {
validateAndThrow(prefetchCount);
this.prefetchCount = prefetchCount;
return this;
}
/**
* Sets the name of the queue to create a receiver for.
*
* @param queueName Name of the queue.
*
* @return The modified {@link ServiceBusReceiverClientBuilder} object.
*/
public ServiceBusReceiverClientBuilder queueName(String queueName) {
this.queueName = queueName;
return this;
}
/**
* Sets the receive mode for the receiver.
*
* @param receiveMode Mode for receiving messages.
*
* @return The modified {@link ServiceBusReceiverClientBuilder} object.
*/
public ServiceBusReceiverClientBuilder receiveMode(ServiceBusReceiveMode receiveMode) {
this.receiveMode = receiveMode;
return this;
}
/**
* Sets the type of the {@link SubQueue} to connect to.
*
* @param subQueue The type of the sub queue.
*
* @return The modified {@link ServiceBusReceiverClientBuilder} object.
* @see
*/
public ServiceBusReceiverClientBuilder subQueue(SubQueue subQueue) {
this.subQueue = subQueue;
return this;
}
/**
* Sets the name of the subscription in the topic to listen to. <b>{@link
* </b>
*
* @param subscriptionName Name of the subscription.
*
* @return The modified {@link ServiceBusReceiverClientBuilder} object.
* @see
*/
public ServiceBusReceiverClientBuilder subscriptionName(String subscriptionName) {
this.subscriptionName = subscriptionName;
return this;
}
/**
* Sets the name of the topic. <b>{@link
*
* @param topicName Name of the topic.
*
* @return The modified {@link ServiceBusReceiverClientBuilder} object.
* @see
*/
public ServiceBusReceiverClientBuilder topicName(String topicName) {
this.topicName = topicName;
return this;
}
/**
* Creates an <b>asynchronous</b> Service Bus receiver responsible for reading {@link ServiceBusMessage
* messages} from a specific queue or subscription.
*
* @return An new {@link ServiceBusReceiverAsyncClient} that receives messages from a queue or subscription.
* @throws IllegalStateException if {@link
* topicName} are not set or, both of these fields are set. It is also thrown if the Service Bus {@link
*
* {@link
*
* @throws IllegalArgumentException Queue or topic name are not set via {@link
* queueName()} or {@link
*/
public ServiceBusReceiverAsyncClient buildAsyncClient() {
return buildAsyncClient(true);
}
/**
* Creates <b>synchronous</b> Service Bus receiver responsible for reading {@link ServiceBusMessage messages}
* from a specific queue or subscription.
*
* @return An new {@link ServiceBusReceiverClient} that receives messages from a queue or subscription.
* @throws IllegalStateException if {@link
* topicName} are not set or, both of these fields are set. It is also thrown if the Service Bus {@link
*
* {@link
*
* @throws IllegalArgumentException Queue or topic name are not set via {@link
* queueName()} or {@link
*/
public ServiceBusReceiverClient buildClient() {
return new ServiceBusReceiverClient(buildAsyncClient(false),
MessageUtils.getTotalTimeout(retryOptions));
}
ServiceBusReceiverAsyncClient buildAsyncClient(boolean isAutoCompleteAllowed) {
final MessagingEntityType entityType = validateEntityPaths(logger, connectionStringEntityName, topicName,
queueName);
final String entityPath = getEntityPath(logger, entityType, queueName, topicName, subscriptionName,
subQueue);
if (!isAutoCompleteAllowed && enableAutoComplete) {
logger.warning(
"'enableAutoComplete' is not supported in synchronous client except through callback receive.");
enableAutoComplete = false;
} else if (enableAutoComplete && receiveMode == ServiceBusReceiveMode.RECEIVE_AND_DELETE) {
logger.warning("'enableAutoComplete' is not needed in for RECEIVE_AND_DELETE mode.");
enableAutoComplete = false;
}
if (receiveMode == ServiceBusReceiveMode.RECEIVE_AND_DELETE) {
maxAutoLockRenewDuration = Duration.ZERO;
}
final ServiceBusConnectionProcessor connectionProcessor = getOrCreateConnectionProcessor(messageSerializer);
final ReceiverOptions receiverOptions = new ReceiverOptions(receiveMode, prefetchCount,
maxAutoLockRenewDuration, enableAutoComplete);
return new ServiceBusReceiverAsyncClient(connectionProcessor.getFullyQualifiedNamespace(), entityPath,
entityType, receiverOptions, connectionProcessor, ServiceBusConstants.OPERATION_TIMEOUT,
tracerProvider, messageSerializer, ServiceBusClientBuilder.this::onClientClose);
}
}
private void validateAndThrow(int prefetchCount) {
if (prefetchCount < 0) {
throw logger.logExceptionAsError(new IllegalArgumentException(String.format(
"prefetchCount (%s) cannot be less than 0.", prefetchCount)));
}
}
private void validateAndThrow(Duration maxLockRenewalDuration) {
if (maxLockRenewalDuration != null && maxLockRenewalDuration.isNegative()) {
throw logger.logExceptionAsError(new IllegalArgumentException(
"'maxLockRenewalDuration' cannot be negative."));
}
}
} | class ServiceBusClientBuilder {
private static final AmqpRetryOptions DEFAULT_RETRY =
new AmqpRetryOptions().setTryTimeout(ServiceBusConstants.OPERATION_TIMEOUT);
private static final String SERVICE_BUS_PROPERTIES_FILE = "azure-messaging-servicebus.properties";
private static final String SUBSCRIPTION_ENTITY_PATH_FORMAT = "%s/subscriptions/%s";
private static final String DEAD_LETTER_QUEUE_NAME_SUFFIX = "/$deadletterqueue";
private static final String TRANSFER_DEAD_LETTER_QUEUE_NAME_SUFFIX = "/$Transfer/$deadletterqueue";
private static final int DEFAULT_PREFETCH_COUNT = 0;
private static final String NAME_KEY = "name";
private static final String VERSION_KEY = "version";
private static final String UNKNOWN = "UNKNOWN";
private static final Pattern HOST_PORT_PATTERN = Pattern.compile("^[^:]+:\\d+");
private static final Duration MAX_LOCK_RENEW_DEFAULT_DURATION = Duration.ofMinutes(5);
private final Object connectionLock = new Object();
private final ClientLogger logger = new ClientLogger(ServiceBusClientBuilder.class);
private final MessageSerializer messageSerializer = new ServiceBusMessageSerializer();
private final TracerProvider tracerProvider = new TracerProvider(ServiceLoader.load(Tracer.class));
private ClientOptions clientOptions;
private Configuration configuration;
private ServiceBusConnectionProcessor sharedConnection;
private String connectionStringEntityName;
private TokenCredential credentials;
private String fullyQualifiedNamespace;
private ProxyOptions proxyOptions;
private AmqpRetryOptions retryOptions;
private Scheduler scheduler;
private AmqpTransportType transport = AmqpTransportType.AMQP;
private SslDomain.VerifyMode verifyMode;
/**
* Keeps track of the open clients that were created from this builder when there is a shared connection.
*/
private final AtomicInteger openClients = new AtomicInteger();
/**
* Creates a new instance with the default transport {@link AmqpTransportType
*/
public ServiceBusClientBuilder() {
}
/**
* Sets the {@link ClientOptions} to be sent from the client built from this builder, enabling customization of
* certain properties, as well as support the addition of custom header information. Refer to the {@link
* ClientOptions} documentation for more information.
*
* @param clientOptions to be set on the client.
*
* @return The updated {@link ServiceBusClientBuilder} object.
*/
public ServiceBusClientBuilder clientOptions(ClientOptions clientOptions) {
this.clientOptions = clientOptions;
return this;
}
/**
* Sets the connection string for a Service Bus namespace or a specific Service Bus resource.
*
* @param connectionString Connection string for a Service Bus namespace or a specific Service Bus resource.
*
* @return The updated {@link ServiceBusClientBuilder} object.
*/
public ServiceBusClientBuilder connectionString(String connectionString) {
final ConnectionStringProperties properties = new ConnectionStringProperties(connectionString);
final TokenCredential tokenCredential;
try {
tokenCredential = getTokenCredential(properties);
} catch (Exception e) {
throw logger.logExceptionAsError(
new AzureException("Could not create the ServiceBusSharedKeyCredential.", e));
}
this.fullyQualifiedNamespace = properties.getEndpoint().getHost();
if (properties.getEntityPath() != null && !properties.getEntityPath().isEmpty()) {
logger.info("Setting 'entityName' [{}] from connectionString.", properties.getEntityPath());
this.connectionStringEntityName = properties.getEntityPath();
}
return credential(properties.getEndpoint().getHost(), tokenCredential);
}
private TokenCredential getTokenCredential(ConnectionStringProperties properties) {
TokenCredential tokenCredential;
if (properties.getSharedAccessSignature() == null) {
tokenCredential = new ServiceBusSharedKeyCredential(properties.getSharedAccessKeyName(),
properties.getSharedAccessKey(), ServiceBusConstants.TOKEN_VALIDITY);
} else {
tokenCredential = new ServiceBusSharedKeyCredential(properties.getSharedAccessSignature());
}
return tokenCredential;
}
/**
* Sets the configuration store that is used during construction of the service client.
*
* If not specified, the default configuration store is used to configure Service Bus clients. Use {@link
* Configuration
*
* @param configuration The configuration store used to configure Service Bus clients.
*
* @return The updated {@link ServiceBusClientBuilder} object.
*/
public ServiceBusClientBuilder configuration(Configuration configuration) {
this.configuration = configuration;
return this;
}
/**
* Sets the credential for the Service Bus resource.
*
* @param fullyQualifiedNamespace for the Service Bus.
* @param credential {@link TokenCredential} to be used for authentication.
*
* @return The updated {@link ServiceBusClientBuilder} object.
*/
public ServiceBusClientBuilder credential(String fullyQualifiedNamespace, TokenCredential credential) {
this.fullyQualifiedNamespace = Objects.requireNonNull(fullyQualifiedNamespace,
"'fullyQualifiedNamespace' cannot be null.");
this.credentials = Objects.requireNonNull(credential, "'credential' cannot be null.");
if (CoreUtils.isNullOrEmpty(fullyQualifiedNamespace)) {
throw logger.logExceptionAsError(
new IllegalArgumentException("'fullyQualifiedNamespace' cannot be an empty string."));
}
return this;
}
/**
* Sets the proxy configuration to use for {@link ServiceBusSenderAsyncClient}. When a proxy is configured, {@link
* AmqpTransportType
*
* @param proxyOptions The proxy configuration to use.
*
* @return The updated {@link ServiceBusClientBuilder} object.
*/
public ServiceBusClientBuilder proxyOptions(ProxyOptions proxyOptions) {
this.proxyOptions = proxyOptions;
return this;
}
/**
* Package-private method that sets the verify mode for this connection.
*
* @param verifyMode The verification mode.
* @return The updated {@link ServiceBusClientBuilder} object.
*/
ServiceBusClientBuilder verifyMode(SslDomain.VerifyMode verifyMode) {
this.verifyMode = verifyMode;
return this;
}
/**
* Sets the retry options for Service Bus clients. If not specified, the default retry options are used.
*
* @param retryOptions The retry options to use.
*
* @return The updated {@link ServiceBusClientBuilder} object.
*/
public ServiceBusClientBuilder retryOptions(AmqpRetryOptions retryOptions) {
this.retryOptions = retryOptions;
return this;
}
/**
* Sets the scheduler to use.
*
* @param scheduler Scheduler to be used.
*
* @return The updated {@link ServiceBusClientBuilder} object.
*/
ServiceBusClientBuilder scheduler(Scheduler scheduler) {
this.scheduler = scheduler;
return this;
}
/**
* Sets the transport type by which all the communication with Azure Service Bus occurs. Default value is {@link
* AmqpTransportType
*
* @param transportType The transport type to use.
*
* @return The updated {@link ServiceBusClientBuilder} object.
*/
public ServiceBusClientBuilder transportType(AmqpTransportType transportType) {
this.transport = transportType;
return this;
}
/**
* A new instance of {@link ServiceBusSenderClientBuilder} used to configure Service Bus message senders.
*
* @return A new instance of {@link ServiceBusSenderClientBuilder}.
*/
public ServiceBusSenderClientBuilder sender() {
return new ServiceBusSenderClientBuilder();
}
/**
* A new instance of {@link ServiceBusReceiverClientBuilder} used to configure Service Bus message receivers.
*
* @return A new instance of {@link ServiceBusReceiverClientBuilder}.
*/
public ServiceBusReceiverClientBuilder receiver() {
return new ServiceBusReceiverClientBuilder();
}
/**
* A new instance of {@link ServiceBusSessionReceiverClientBuilder} used to configure <b>session aware</b> Service
* Bus message receivers.
*
* @return A new instance of {@link ServiceBusSessionReceiverClientBuilder}.
*/
public ServiceBusSessionReceiverClientBuilder sessionReceiver() {
return new ServiceBusSessionReceiverClientBuilder();
}
/**
* A new instance of {@link ServiceBusProcessorClientBuilder} used to configure {@link ServiceBusProcessorClient}
* instance.
*
* @return A new instance of {@link ServiceBusProcessorClientBuilder}.
*/
public ServiceBusProcessorClientBuilder processor() {
return new ServiceBusProcessorClientBuilder();
}
/**
* A new instance of {@link ServiceBusSessionProcessorClientBuilder} used to configure a Service Bus processor
* instance that processes sessions.
* @return A new instance of {@link ServiceBusSessionProcessorClientBuilder}.
*/
public ServiceBusSessionProcessorClientBuilder sessionProcessor() {
return new ServiceBusSessionProcessorClientBuilder();
}
/**
* Called when a child client is closed. Disposes of the shared connection if there are no more clients.
*/
void onClientClose() {
synchronized (connectionLock) {
final int numberOfOpenClients = openClients.decrementAndGet();
logger.info("Closing a dependent client.
if (numberOfOpenClients > 0) {
return;
}
if (numberOfOpenClients < 0) {
logger.warning("There should not be less than 0 clients. actual: {}", numberOfOpenClients);
}
logger.info("No more open clients, closing shared connection [{}].", sharedConnection);
if (sharedConnection != null) {
sharedConnection.dispose();
sharedConnection = null;
} else {
logger.warning("Shared ServiceBusConnectionProcessor was already disposed.");
}
}
}
private ServiceBusConnectionProcessor getOrCreateConnectionProcessor(MessageSerializer serializer) {
if (retryOptions == null) {
retryOptions = DEFAULT_RETRY;
}
if (scheduler == null) {
scheduler = Schedulers.elastic();
}
synchronized (connectionLock) {
if (sharedConnection == null) {
final ConnectionOptions connectionOptions = getConnectionOptions();
final TokenManagerProvider tokenManagerProvider = new AzureTokenManagerProvider(
connectionOptions.getAuthorizationType(), connectionOptions.getFullyQualifiedNamespace(),
ServiceBusConstants.AZURE_ACTIVE_DIRECTORY_SCOPE);
final ReactorProvider provider = new ReactorProvider();
final ReactorHandlerProvider handlerProvider = new ReactorHandlerProvider(provider);
final Flux<ServiceBusAmqpConnection> connectionFlux = Mono.fromCallable(() -> {
final String connectionId = StringUtil.getRandomString("MF");
return (ServiceBusAmqpConnection) new ServiceBusReactorAmqpConnection(connectionId,
connectionOptions, provider, handlerProvider, tokenManagerProvider, serializer);
}).repeat();
sharedConnection = connectionFlux.subscribeWith(new ServiceBusConnectionProcessor(
connectionOptions.getFullyQualifiedNamespace(), connectionOptions.getRetry()));
}
}
final int numberOfOpenClients = openClients.incrementAndGet();
logger.info("
return sharedConnection;
}
private ProxyOptions getDefaultProxyConfiguration(Configuration configuration) {
ProxyAuthenticationType authentication = ProxyAuthenticationType.NONE;
if (proxyOptions != null) {
authentication = proxyOptions.getAuthentication();
}
String proxyAddress = configuration.get(Configuration.PROPERTY_HTTP_PROXY);
if (CoreUtils.isNullOrEmpty(proxyAddress)) {
return ProxyOptions.SYSTEM_DEFAULTS;
}
return getProxyOptions(authentication, proxyAddress);
}
private ProxyOptions getProxyOptions(ProxyAuthenticationType authentication, String proxyAddress) {
String host;
int port;
if (HOST_PORT_PATTERN.matcher(proxyAddress.trim()).find()) {
final String[] hostPort = proxyAddress.split(":");
host = hostPort[0];
port = Integer.parseInt(hostPort[1]);
final Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(host, port));
final String username = configuration.get(ProxyOptions.PROXY_USERNAME);
final String password = configuration.get(ProxyOptions.PROXY_PASSWORD);
return new ProxyOptions(authentication, proxy, username, password);
} else {
com.azure.core.http.ProxyOptions coreProxyOptions = com.azure.core.http.ProxyOptions
.fromConfiguration(configuration);
return new ProxyOptions(authentication, new Proxy(coreProxyOptions.getType().toProxyType(),
coreProxyOptions.getAddress()), coreProxyOptions.getUsername(), coreProxyOptions.getPassword());
}
}
private static boolean isNullOrEmpty(String item) {
return item == null || item.isEmpty();
}
private static MessagingEntityType validateEntityPaths(ClientLogger logger, String connectionStringEntityName,
String topicName, String queueName) {
final boolean hasTopicName = !isNullOrEmpty(topicName);
final boolean hasQueueName = !isNullOrEmpty(queueName);
final boolean hasConnectionStringEntity = !isNullOrEmpty(connectionStringEntityName);
final MessagingEntityType entityType;
if (!hasConnectionStringEntity && !hasQueueName && !hasTopicName) {
throw logger.logExceptionAsError(new IllegalStateException(
"Cannot build client without setting either a queueName or topicName."));
} else if (hasQueueName && hasTopicName) {
throw logger.logExceptionAsError(new IllegalStateException(String.format(
"Cannot build client with both queueName (%s) and topicName (%s) set.", queueName, topicName)));
} else if (hasQueueName) {
if (hasConnectionStringEntity && !queueName.equals(connectionStringEntityName)) {
throw logger.logExceptionAsError(new IllegalStateException(String.format(
"queueName (%s) is different than the connectionString's EntityPath (%s).",
queueName, connectionStringEntityName)));
}
entityType = MessagingEntityType.QUEUE;
} else if (hasTopicName) {
if (hasConnectionStringEntity && !topicName.equals(connectionStringEntityName)) {
throw logger.logExceptionAsError(new IllegalStateException(String.format(
"topicName (%s) is different than the connectionString's EntityPath (%s).",
topicName, connectionStringEntityName)));
}
entityType = MessagingEntityType.SUBSCRIPTION;
} else {
entityType = MessagingEntityType.UNKNOWN;
}
return entityType;
}
private static String getEntityPath(ClientLogger logger, MessagingEntityType entityType, String queueName,
String topicName, String subscriptionName, SubQueue subQueue) {
String entityPath;
switch (entityType) {
case QUEUE:
entityPath = queueName;
break;
case SUBSCRIPTION:
if (isNullOrEmpty(subscriptionName)) {
throw logger.logExceptionAsError(new IllegalStateException(String.format(
"topicName (%s) must have a subscriptionName associated with it.", topicName)));
}
entityPath = String.format(Locale.ROOT, SUBSCRIPTION_ENTITY_PATH_FORMAT, topicName,
subscriptionName);
break;
default:
throw logger.logExceptionAsError(
new IllegalArgumentException("Unknown entity type: " + entityType));
}
if (subQueue == null) {
return entityPath;
}
switch (subQueue) {
case NONE:
break;
case TRANSFER_DEAD_LETTER_QUEUE:
entityPath += TRANSFER_DEAD_LETTER_QUEUE_NAME_SUFFIX;
break;
case DEAD_LETTER_QUEUE:
entityPath += DEAD_LETTER_QUEUE_NAME_SUFFIX;
break;
default:
throw logger.logExceptionAsError(new IllegalArgumentException("Unsupported value of subqueue type: "
+ subQueue));
}
return entityPath;
}
/**
* Builder for creating {@link ServiceBusSenderClient} and {@link ServiceBusSenderAsyncClient} to publish messages
* to Service Bus.
*
* @see ServiceBusSenderAsyncClient
* @see ServiceBusSenderClient
*/
@ServiceClientBuilder(serviceClients = {ServiceBusSenderClient.class, ServiceBusSenderAsyncClient.class})
public final class ServiceBusSenderClientBuilder {
private String queueName;
private String topicName;
private ServiceBusSenderClientBuilder() {
}
/**
* Sets the name of the Service Bus queue to publish messages to.
*
* @param queueName Name of the queue.
*
* @return The modified {@link ServiceBusSenderClientBuilder} object.
*/
public ServiceBusSenderClientBuilder queueName(String queueName) {
this.queueName = queueName;
return this;
}
/**
* Sets the name of the Service Bus topic to publish messages to.
*
* @param topicName Name of the topic.
*
* @return The modified {@link ServiceBusSenderClientBuilder} object.
*/
public ServiceBusSenderClientBuilder topicName(String topicName) {
this.topicName = topicName;
return this;
}
/**
* Creates an <b>asynchronous</b> {@link ServiceBusSenderAsyncClient client} for transmitting {@link
* ServiceBusMessage} to a Service Bus queue or topic.
*
* @return A new {@link ServiceBusSenderAsyncClient} for transmitting to a Service queue or topic.
* @throws IllegalStateException if {@link
* topicName} are not set or, both of these fields are set. It is also thrown if the Service Bus {@link
*
* {@link
* @throws IllegalArgumentException if the entity type is not a queue or a topic.
*/
public ServiceBusSenderAsyncClient buildAsyncClient() {
final ServiceBusConnectionProcessor connectionProcessor = getOrCreateConnectionProcessor(messageSerializer);
final MessagingEntityType entityType = validateEntityPaths(logger, connectionStringEntityName, topicName,
queueName);
final String entityName;
switch (entityType) {
case QUEUE:
entityName = queueName;
break;
case SUBSCRIPTION:
entityName = topicName;
break;
case UNKNOWN:
entityName = connectionStringEntityName;
break;
default:
throw logger.logExceptionAsError(
new IllegalArgumentException("Unknown entity type: " + entityType));
}
return new ServiceBusSenderAsyncClient(entityName, entityType, connectionProcessor, retryOptions,
tracerProvider, messageSerializer, ServiceBusClientBuilder.this::onClientClose, null);
}
/**
* Creates a <b>synchronous</b> {@link ServiceBusSenderClient client} for transmitting {@link ServiceBusMessage}
* to a Service Bus queue or topic.
*
* @return A new {@link ServiceBusSenderAsyncClient} for transmitting to a Service queue or topic.
* @throws IllegalStateException if {@link
* topicName} are not set or, both of these fields are set. It is also thrown if the Service Bus {@link
*
* {@link
* @throws IllegalArgumentException if the entity type is not a queue or a topic.
*/
public ServiceBusSenderClient buildClient() {
return new ServiceBusSenderClient(buildAsyncClient(), MessageUtils.getTotalTimeout(retryOptions));
}
}
/**
* Builder for creating {@link ServiceBusProcessorClient} to consume messages from a session-based Service Bus
* entity. {@link ServiceBusProcessorClient} processes messages and errors via {@link
* and {@link
* next session to process.
*
* <p>
* By default, the processor:
* <ul>
* <li>Automatically settles messages. Disabled via {@link
* <li>Processes 1 session concurrently. Configured via {@link
* <li>Invokes 1 instance of {@link
* {@link
* </ul>
*
* <p><strong>Instantiate a session-enabled processor client</strong></p>
* {@codesnippet com.azure.messaging.servicebus.servicebusprocessorclient
*
* @see ServiceBusProcessorClient
*/
public final class ServiceBusSessionProcessorClientBuilder {
private final ServiceBusProcessorClientOptions processorClientOptions;
private final ServiceBusSessionReceiverClientBuilder sessionReceiverClientBuilder;
private Consumer<ServiceBusReceivedMessageContext> processMessage;
private Consumer<ServiceBusErrorContext> processError;
private ServiceBusSessionProcessorClientBuilder() {
sessionReceiverClientBuilder = new ServiceBusSessionReceiverClientBuilder();
processorClientOptions = new ServiceBusProcessorClientOptions()
.setMaxConcurrentCalls(1)
.setTracerProvider(tracerProvider);
sessionReceiverClientBuilder.maxConcurrentSessions(1);
}
/**
* Enables session processing roll-over by processing at most {@code maxConcurrentSessions}.
*
* @param maxConcurrentSessions Maximum number of concurrent sessions to process at any given time.
*
* @return The modified {@link ServiceBusSessionProcessorClientBuilder} object.
* @throws IllegalArgumentException if {@code maxConcurrentSessions} is less than 1.
*/
public ServiceBusSessionProcessorClientBuilder maxConcurrentSessions(int maxConcurrentSessions) {
if (maxConcurrentSessions < 1) {
throw logger.logExceptionAsError(
new IllegalArgumentException("'maxConcurrentSessions' cannot be less than 1"));
}
sessionReceiverClientBuilder.maxConcurrentSessions(maxConcurrentSessions);
return this;
}
/**
* Sets the prefetch count of the processor. For both {@link ServiceBusReceiveMode
* {@link ServiceBusReceiveMode
*
* Prefetch speeds up the message flow by aiming to have a message readily available for local retrieval when
* and before the application starts the processor.
* Setting a non-zero value will prefetch that number of messages. Setting the value to zero turns prefetch off.
* Using a non-zero prefetch risks of losing messages even though it has better performance.
* @see <a href="https:
*
* @param prefetchCount The prefetch count.
*
* @return The modified {@link ServiceBusProcessorClientBuilder} object.
*/
public ServiceBusSessionProcessorClientBuilder prefetchCount(int prefetchCount) {
sessionReceiverClientBuilder.prefetchCount(prefetchCount);
return this;
}
/**
* Sets the name of the queue to create a processor for.
* @param queueName Name of the queue.
*
* @return The modified {@link ServiceBusSessionProcessorClientBuilder} object.
*/
public ServiceBusSessionProcessorClientBuilder queueName(String queueName) {
sessionReceiverClientBuilder.queueName(queueName);
return this;
}
/**
* Sets the receive mode for the processor.
* @param receiveMode Mode for receiving messages.
*
* @return The modified {@link ServiceBusSessionProcessorClientBuilder} object.
*/
public ServiceBusSessionProcessorClientBuilder receiveMode(ServiceBusReceiveMode receiveMode) {
sessionReceiverClientBuilder.receiveMode(receiveMode);
return this;
}
/**
* Sets the name of the subscription in the topic to listen to. <b>{@link
* </b>
* @param subscriptionName Name of the subscription.
*
* @return The modified {@link ServiceBusSessionProcessorClientBuilder} object.
* @see
*/
public ServiceBusSessionProcessorClientBuilder subscriptionName(String subscriptionName) {
sessionReceiverClientBuilder.subscriptionName(subscriptionName);
return this;
}
/**
* Sets the name of the topic. <b>{@link
* @param topicName Name of the topic.
*
* @return The modified {@link ServiceBusSessionProcessorClientBuilder} object.
* @see
*/
public ServiceBusSessionProcessorClientBuilder topicName(String topicName) {
sessionReceiverClientBuilder.topicName(topicName);
return this;
}
/**
* The message processing callback for the processor that will be executed when a message is received.
* @param processMessage The message processing consumer that will be executed when a message is received.
*
* @return The updated {@link ServiceBusProcessorClientBuilder} object.
*/
public ServiceBusSessionProcessorClientBuilder processMessage(
Consumer<ServiceBusReceivedMessageContext> processMessage) {
this.processMessage = processMessage;
return this;
}
/**
* The error handler for the processor which will be invoked in the event of an error while receiving messages.
* @param processError The error handler which will be executed when an error occurs.
*
* @return The updated {@link ServiceBusProcessorClientBuilder} object
*/
public ServiceBusSessionProcessorClientBuilder processError(
Consumer<ServiceBusErrorContext> processError) {
this.processError = processError;
return this;
}
/**
* Max concurrent messages that this processor should process.
*
* @param maxConcurrentCalls max concurrent messages that this processor should process.
*
* @return The updated {@link ServiceBusSessionProcessorClientBuilder} object.
* @throws IllegalArgumentException if {@code maxConcurrentCalls} is less than 1.
*/
public ServiceBusSessionProcessorClientBuilder maxConcurrentCalls(int maxConcurrentCalls) {
if (maxConcurrentCalls < 1) {
throw logger.logExceptionAsError(
new IllegalArgumentException("'maxConcurrentCalls' cannot be less than 1"));
}
processorClientOptions.setMaxConcurrentCalls(maxConcurrentCalls);
return this;
}
/**
* Disables auto-complete and auto-abandon of received messages. By default, a successfully processed message is
* {@link ServiceBusReceivedMessageContext
* the message is processed, it is {@link ServiceBusReceivedMessageContext
* abandoned}.
*
* @return The modified {@link ServiceBusSessionProcessorClientBuilder} object.
*/
public ServiceBusSessionProcessorClientBuilder disableAutoComplete() {
sessionReceiverClientBuilder.disableAutoComplete();
processorClientOptions.setDisableAutoComplete(true);
return this;
}
/**
* Creates a <b>session-aware</b> Service Bus processor responsible for reading
* {@link ServiceBusReceivedMessage messages} from a specific queue or subscription.
*
* @return An new {@link ServiceBusProcessorClient} that receives messages from a queue or subscription.
* @throws IllegalStateException if {@link
* topicName} are not set or, both of these fields are set. It is also thrown if the Service Bus {@link
*
* {@link
*
* @throws IllegalArgumentException Queue or topic name are not set via {@link
* queueName()} or {@link
* @throws NullPointerException if the {@link
* callbacks are not set.
*/
public ServiceBusProcessorClient buildProcessorClient() {
return new ServiceBusProcessorClient(sessionReceiverClientBuilder,
Objects.requireNonNull(processMessage, "'processMessage' cannot be null"),
Objects.requireNonNull(processError, "'processError' cannot be null"), processorClientOptions);
}
}
/**
* Builder for creating {@link ServiceBusReceiverClient} and {@link ServiceBusReceiverAsyncClient} to consume
* messages from a <b>session aware</b> Service Bus entity.
*
* @see ServiceBusReceiverAsyncClient
* @see ServiceBusReceiverClient
*/
@ServiceClientBuilder(serviceClients = {ServiceBusReceiverClient.class, ServiceBusReceiverAsyncClient.class})
public final class ServiceBusSessionReceiverClientBuilder {
private boolean enableAutoComplete = true;
private Integer maxConcurrentSessions = null;
private int prefetchCount = DEFAULT_PREFETCH_COUNT;
private String queueName;
private ServiceBusReceiveMode receiveMode = ServiceBusReceiveMode.PEEK_LOCK;
private String subscriptionName;
private String topicName;
private Duration maxAutoLockRenewDuration = MAX_LOCK_RENEW_DEFAULT_DURATION;
private ServiceBusSessionReceiverClientBuilder() {
}
/**
* Disables auto-complete and auto-abandon of received messages. By default, a successfully processed message is
* {@link ServiceBusReceiverAsyncClient
* the message is processed, it is {@link ServiceBusReceiverAsyncClient
* abandoned}.
*
* @return The modified {@link ServiceBusSessionReceiverClientBuilder} object.
*/
public ServiceBusSessionReceiverClientBuilder disableAutoComplete() {
this.enableAutoComplete = false;
return this;
}
/**
* Sets the amount of time to continue auto-renewing the session lock. Setting {@link Duration
* {@code null} disables auto-renewal. For {@link ServiceBusReceiveMode
* mode, auto-renewal is disabled.
*
* @param maxAutoLockRenewDuration the amount of time to continue auto-renewing the session lock.
* {@link Duration
*
* @return The updated {@link ServiceBusSessionReceiverClientBuilder} object.
* @throws IllegalArgumentException If {code maxAutoLockRenewDuration} is negative.
*/
public ServiceBusSessionReceiverClientBuilder maxAutoLockRenewDuration(Duration maxAutoLockRenewDuration) {
validateAndThrow(maxAutoLockRenewDuration);
this.maxAutoLockRenewDuration = maxAutoLockRenewDuration;
return this;
}
/**
* Enables session processing roll-over by processing at most {@code maxConcurrentSessions}.
*
* @param maxConcurrentSessions Maximum number of concurrent sessions to process at any given time.
*
* @return The modified {@link ServiceBusSessionReceiverClientBuilder} object.
* @throws IllegalArgumentException if {@code maxConcurrentSessions} is less than 1.
*/
ServiceBusSessionReceiverClientBuilder maxConcurrentSessions(int maxConcurrentSessions) {
if (maxConcurrentSessions < 1) {
throw logger.logExceptionAsError(new IllegalArgumentException(
"maxConcurrentSessions cannot be less than 1."));
}
this.maxConcurrentSessions = maxConcurrentSessions;
return this;
}
/**
* Sets the prefetch count of the receiver. For both {@link ServiceBusReceiveMode
* {@link ServiceBusReceiveMode
*
* Prefetch speeds up the message flow by aiming to have a message readily available for local retrieval when
* and before the application asks for one using {@link ServiceBusReceiverAsyncClient
* Setting a non-zero value will prefetch that number of messages. Setting the value to zero turns prefetch
* off.
*
* @param prefetchCount The prefetch count.
*
* @return The modified {@link ServiceBusSessionReceiverClientBuilder} object.
* @throws IllegalArgumentException If {code prefetchCount} is negative.
*/
public ServiceBusSessionReceiverClientBuilder prefetchCount(int prefetchCount) {
validateAndThrow(prefetchCount);
this.prefetchCount = prefetchCount;
return this;
}
/**
* Sets the name of the queue to create a receiver for.
*
* @param queueName Name of the queue.
*
* @return The modified {@link ServiceBusSessionReceiverClientBuilder} object.
*/
public ServiceBusSessionReceiverClientBuilder queueName(String queueName) {
this.queueName = queueName;
return this;
}
/**
* Sets the receive mode for the receiver.
*
* @param receiveMode Mode for receiving messages.
*
* @return The modified {@link ServiceBusSessionReceiverClientBuilder} object.
*/
public ServiceBusSessionReceiverClientBuilder receiveMode(ServiceBusReceiveMode receiveMode) {
this.receiveMode = receiveMode;
return this;
}
/**
* Sets the name of the subscription in the topic to listen to. <b>{@link
* </b>
*
* @param subscriptionName Name of the subscription.
*
* @return The modified {@link ServiceBusSessionReceiverClientBuilder} object.
* @see
*/
public ServiceBusSessionReceiverClientBuilder subscriptionName(String subscriptionName) {
this.subscriptionName = subscriptionName;
return this;
}
/**
* Sets the name of the topic. <b>{@link
*
* @param topicName Name of the topic.
*
* @return The modified {@link ServiceBusSessionReceiverClientBuilder} object.
* @see
*/
public ServiceBusSessionReceiverClientBuilder topicName(String topicName) {
this.topicName = topicName;
return this;
}
/**
* Creates an <b>asynchronous</b>, <b>session-aware</b> Service Bus receiver responsible for reading {@link
* ServiceBusMessage messages} from a specific queue or subscription.
*
* @return An new {@link ServiceBusReceiverAsyncClient} that receives messages from a queue or subscription.
* @throws IllegalStateException if {@link
* topicName} are not set or, both of these fields are set. It is also thrown if the Service Bus {@link
*
* {@link
*
* @throws IllegalArgumentException Queue or topic name are not set via {@link
* queueName()} or {@link
*/
ServiceBusReceiverAsyncClient buildAsyncClientForProcessor() {
final MessagingEntityType entityType = validateEntityPaths(logger, connectionStringEntityName, topicName,
queueName);
final String entityPath = getEntityPath(logger, entityType, queueName, topicName, subscriptionName,
SubQueue.NONE);
if (enableAutoComplete && receiveMode == ServiceBusReceiveMode.RECEIVE_AND_DELETE) {
logger.warning("'enableAutoComplete' is not needed in for RECEIVE_AND_DELETE mode.");
enableAutoComplete = false;
}
if (receiveMode == ServiceBusReceiveMode.RECEIVE_AND_DELETE) {
maxAutoLockRenewDuration = Duration.ZERO;
}
final ServiceBusConnectionProcessor connectionProcessor = getOrCreateConnectionProcessor(messageSerializer);
final ReceiverOptions receiverOptions = new ReceiverOptions(receiveMode, prefetchCount,
maxAutoLockRenewDuration, enableAutoComplete, null,
maxConcurrentSessions);
final ServiceBusSessionManager sessionManager = new ServiceBusSessionManager(entityPath, entityType,
connectionProcessor, tracerProvider, messageSerializer, receiverOptions);
return new ServiceBusReceiverAsyncClient(connectionProcessor.getFullyQualifiedNamespace(), entityPath,
entityType, receiverOptions, connectionProcessor, ServiceBusConstants.OPERATION_TIMEOUT,
tracerProvider, messageSerializer, ServiceBusClientBuilder.this::onClientClose, sessionManager);
}
/**
* Creates an <b>asynchronous</b>, <b>session-aware</b> Service Bus receiver responsible for reading {@link
* ServiceBusMessage messages} from a specific queue or subscription.
*
* @return An new {@link ServiceBusSessionReceiverAsyncClient} that receives messages from a queue or
* subscription.
* @throws IllegalStateException if {@link
* topicName} are not set or, both of these fields are set. It is also thrown if the Service Bus {@link
*
* {@link
*
* @throws IllegalArgumentException Queue or topic name are not set via {@link
* queueName()} or {@link
*/
public ServiceBusSessionReceiverAsyncClient buildAsyncClient() {
return buildAsyncClient(true);
}
/**
* Creates a <b>synchronous</b>, <b>session-aware</b> Service Bus receiver responsible for reading {@link
* ServiceBusMessage messages} from a specific queue or subscription.
*
* @return An new {@link ServiceBusReceiverClient} that receives messages from a queue or subscription.
* @throws IllegalStateException if {@link
* topicName} are not set or, both of these fields are set. It is also thrown if the Service Bus {@link
*
* {@link
*
* @throws IllegalArgumentException Queue or topic name are not set via {@link
* queueName()} or {@link
*/
public ServiceBusSessionReceiverClient buildClient() {
return new ServiceBusSessionReceiverClient(buildAsyncClient(false),
MessageUtils.getTotalTimeout(retryOptions));
}
private ServiceBusSessionReceiverAsyncClient buildAsyncClient(boolean isAutoCompleteAllowed) {
final MessagingEntityType entityType = validateEntityPaths(logger, connectionStringEntityName, topicName,
queueName);
final String entityPath = getEntityPath(logger, entityType, queueName, topicName, subscriptionName,
SubQueue.NONE);
if (!isAutoCompleteAllowed && enableAutoComplete) {
logger.warning(
"'enableAutoComplete' is not supported in synchronous client except through callback receive.");
enableAutoComplete = false;
} else if (enableAutoComplete && receiveMode == ServiceBusReceiveMode.RECEIVE_AND_DELETE) {
logger.warning("'enableAutoComplete' is not needed in for RECEIVE_AND_DELETE mode.");
enableAutoComplete = false;
}
if (receiveMode == ServiceBusReceiveMode.RECEIVE_AND_DELETE) {
maxAutoLockRenewDuration = Duration.ZERO;
}
final ServiceBusConnectionProcessor connectionProcessor = getOrCreateConnectionProcessor(messageSerializer);
final ReceiverOptions receiverOptions = new ReceiverOptions(receiveMode, prefetchCount,
maxAutoLockRenewDuration, enableAutoComplete, null, maxConcurrentSessions);
return new ServiceBusSessionReceiverAsyncClient(connectionProcessor.getFullyQualifiedNamespace(),
entityPath, entityType, receiverOptions, connectionProcessor, tracerProvider, messageSerializer,
ServiceBusClientBuilder.this::onClientClose);
}
}
/**
* Builder for creating {@link ServiceBusProcessorClient} to consume messages from a Service Bus entity.
* {@link ServiceBusProcessorClient ServiceBusProcessorClients} provides a push-based mechanism that notifies
* the message processing callback when a message is received or the error handle when an error is observed. To
* create an instance, therefore, configuring the two callbacks - {@link
* {@link
* with auto-completion and auto-lock renewal capabilities.
*
* <p><strong>Sample code to instantiate a processor client</strong></p>
* {@codesnippet com.azure.messaging.servicebus.servicebusprocessorclient
*
* @see ServiceBusProcessorClient
*/
public final class ServiceBusProcessorClientBuilder {
private final ServiceBusReceiverClientBuilder serviceBusReceiverClientBuilder;
private final ServiceBusProcessorClientOptions processorClientOptions;
private Consumer<ServiceBusReceivedMessageContext> processMessage;
private Consumer<ServiceBusErrorContext> processError;
private ServiceBusProcessorClientBuilder() {
serviceBusReceiverClientBuilder = new ServiceBusReceiverClientBuilder();
processorClientOptions = new ServiceBusProcessorClientOptions()
.setMaxConcurrentCalls(1)
.setTracerProvider(tracerProvider);
}
/**
* Sets the prefetch count of the processor. For both {@link ServiceBusReceiveMode
* {@link ServiceBusReceiveMode
*
* Prefetch speeds up the message flow by aiming to have a message readily available for local retrieval when
* and before the application starts the processor.
* Setting a non-zero value will prefetch that number of messages. Setting the value to zero turns prefetch off.
*
* @param prefetchCount The prefetch count.
*
* @return The modified {@link ServiceBusProcessorClientBuilder} object.
*/
public ServiceBusProcessorClientBuilder prefetchCount(int prefetchCount) {
serviceBusReceiverClientBuilder.prefetchCount(prefetchCount);
return this;
}
/**
* Sets the name of the queue to create a processor for.
* @param queueName Name of the queue.
*
* @return The modified {@link ServiceBusProcessorClientBuilder} object.
*/
public ServiceBusProcessorClientBuilder queueName(String queueName) {
serviceBusReceiverClientBuilder.queueName(queueName);
return this;
}
/**
* Sets the receive mode for the processor.
* @param receiveMode Mode for receiving messages.
*
* @return The modified {@link ServiceBusProcessorClientBuilder} object.
*/
public ServiceBusProcessorClientBuilder receiveMode(ServiceBusReceiveMode receiveMode) {
serviceBusReceiverClientBuilder.receiveMode(receiveMode);
return this;
}
/**
* Sets the name of the subscription in the topic to listen to. <b>{@link
* </b>
* @param subscriptionName Name of the subscription.
*
* @return The modified {@link ServiceBusProcessorClientBuilder} object.
* @see
*/
public ServiceBusProcessorClientBuilder subscriptionName(String subscriptionName) {
serviceBusReceiverClientBuilder.subscriptionName(subscriptionName);
return this;
}
/**
* Sets the name of the topic. <b>{@link
* @param topicName Name of the topic.
*
* @return The modified {@link ServiceBusProcessorClientBuilder} object.
* @see
*/
public ServiceBusProcessorClientBuilder topicName(String topicName) {
serviceBusReceiverClientBuilder.topicName(topicName);
return this;
}
/**
* The message processing callback for the processor which will be executed when a message is received.
* @param processMessage The message processing consumer that will be executed when a message is received.
*
* @return The updated {@link ServiceBusProcessorClientBuilder} object.
*/
public ServiceBusProcessorClientBuilder processMessage(
Consumer<ServiceBusReceivedMessageContext> processMessage) {
this.processMessage = processMessage;
return this;
}
/**
* The error handler for the processor which will be invoked in the event of an error while receiving messages.
* @param processError The error handler which will be executed when an error occurs.
*
* @return The updated {@link ServiceBusProcessorClientBuilder} object
*/
public ServiceBusProcessorClientBuilder processError(Consumer<ServiceBusErrorContext> processError) {
this.processError = processError;
return this;
}
/**
* Max concurrent messages that this processor should process. By default, this is set to 1.
*
* @param maxConcurrentCalls max concurrent messages that this processor should process.
* @return The updated {@link ServiceBusProcessorClientBuilder} object.
* @throws IllegalArgumentException if the {@code maxConcurrentCalls} is set to a value less than 1.
*/
public ServiceBusProcessorClientBuilder maxConcurrentCalls(int maxConcurrentCalls) {
if (maxConcurrentCalls < 1) {
throw logger.logExceptionAsError(
new IllegalArgumentException("'maxConcurrentCalls' cannot be less than 1"));
}
processorClientOptions.setMaxConcurrentCalls(maxConcurrentCalls);
return this;
}
/**
* Disables auto-complete and auto-abandon of received messages. By default, a successfully processed message is
* {@link ServiceBusReceivedMessageContext
* the message is processed, it is {@link ServiceBusReceivedMessageContext
* abandoned}.
*
* @return The modified {@link ServiceBusProcessorClientBuilder} object.
*/
public ServiceBusProcessorClientBuilder disableAutoComplete() {
serviceBusReceiverClientBuilder.disableAutoComplete();
processorClientOptions.setDisableAutoComplete(true);
return this;
}
/**
* Creates Service Bus message processor responsible for reading {@link ServiceBusReceivedMessage
* messages} from a specific queue or subscription.
*
* @return An new {@link ServiceBusProcessorClient} that processes messages from a queue or subscription.
* @throws IllegalStateException if {@link
* topicName} are not set or, both of these fields are set. It is also thrown if the Service Bus {@link
*
* {@link
*
* @throws IllegalArgumentException Queue or topic name are not set via {@link
* queueName()} or {@link
* @throws NullPointerException if the {@link
* callbacks are not set.
*/
public ServiceBusProcessorClient buildProcessorClient() {
return new ServiceBusProcessorClient(serviceBusReceiverClientBuilder,
Objects.requireNonNull(processMessage, "'processMessage' cannot be null"),
Objects.requireNonNull(processError, "'processError' cannot be null"), processorClientOptions);
}
}
/**
* Builder for creating {@link ServiceBusReceiverClient} and {@link ServiceBusReceiverAsyncClient} to consume
* messages from Service Bus.
*
* @see ServiceBusReceiverAsyncClient
* @see ServiceBusReceiverClient
*/
@ServiceClientBuilder(serviceClients = {ServiceBusReceiverClient.class, ServiceBusReceiverAsyncClient.class})
public final class ServiceBusReceiverClientBuilder {
private boolean enableAutoComplete = true;
private int prefetchCount = DEFAULT_PREFETCH_COUNT;
private String queueName;
private SubQueue subQueue;
private ServiceBusReceiveMode receiveMode = ServiceBusReceiveMode.PEEK_LOCK;
private String subscriptionName;
private String topicName;
private Duration maxAutoLockRenewDuration = MAX_LOCK_RENEW_DEFAULT_DURATION;
private ServiceBusReceiverClientBuilder() {
}
/**
* Disables auto-complete and auto-abandon of received messages. By default, a successfully processed message is
* {@link ServiceBusReceiverAsyncClient
* the message is processed, it is {@link ServiceBusReceiverAsyncClient
* abandoned}.
*
* @return The modified {@link ServiceBusReceiverClientBuilder} object.
*/
public ServiceBusReceiverClientBuilder disableAutoComplete() {
this.enableAutoComplete = false;
return this;
}
/**
* Sets the amount of time to continue auto-renewing the lock. Setting {@link Duration
* disables auto-renewal. For {@link ServiceBusReceiveMode
* auto-renewal is disabled.
*
* @param maxAutoLockRenewDuration the amount of time to continue auto-renewing the lock. {@link Duration
* or {@code null} indicates that auto-renewal is disabled.
*
* @return The updated {@link ServiceBusReceiverClientBuilder} object.
* @throws IllegalArgumentException If {code maxAutoLockRenewDuration} is negative.
*/
public ServiceBusReceiverClientBuilder maxAutoLockRenewDuration(Duration maxAutoLockRenewDuration) {
validateAndThrow(maxAutoLockRenewDuration);
this.maxAutoLockRenewDuration = maxAutoLockRenewDuration;
return this;
}
/**
* Sets the prefetch count of the receiver. For both {@link ServiceBusReceiveMode
* {@link ServiceBusReceiveMode
*
* Prefetch speeds up the message flow by aiming to have a message readily available for local retrieval when
* and before the application asks for one using {@link ServiceBusReceiverAsyncClient
* Setting a non-zero value will prefetch that number of messages. Setting the value to zero turns prefetch
* off.
*
* @param prefetchCount The prefetch count.
*
* @return The modified {@link ServiceBusReceiverClientBuilder} object.
* @throws IllegalArgumentException If {code prefetchCount} is negative.
*/
public ServiceBusReceiverClientBuilder prefetchCount(int prefetchCount) {
validateAndThrow(prefetchCount);
this.prefetchCount = prefetchCount;
return this;
}
/**
* Sets the name of the queue to create a receiver for.
*
* @param queueName Name of the queue.
*
* @return The modified {@link ServiceBusReceiverClientBuilder} object.
*/
public ServiceBusReceiverClientBuilder queueName(String queueName) {
this.queueName = queueName;
return this;
}
/**
* Sets the receive mode for the receiver.
*
* @param receiveMode Mode for receiving messages.
*
* @return The modified {@link ServiceBusReceiverClientBuilder} object.
*/
public ServiceBusReceiverClientBuilder receiveMode(ServiceBusReceiveMode receiveMode) {
this.receiveMode = receiveMode;
return this;
}
/**
* Sets the type of the {@link SubQueue} to connect to.
*
* @param subQueue The type of the sub queue.
*
* @return The modified {@link ServiceBusReceiverClientBuilder} object.
* @see
*/
public ServiceBusReceiverClientBuilder subQueue(SubQueue subQueue) {
this.subQueue = subQueue;
return this;
}
/**
* Sets the name of the subscription in the topic to listen to. <b>{@link
* </b>
*
* @param subscriptionName Name of the subscription.
*
* @return The modified {@link ServiceBusReceiverClientBuilder} object.
* @see
*/
public ServiceBusReceiverClientBuilder subscriptionName(String subscriptionName) {
this.subscriptionName = subscriptionName;
return this;
}
/**
* Sets the name of the topic. <b>{@link
*
* @param topicName Name of the topic.
*
* @return The modified {@link ServiceBusReceiverClientBuilder} object.
* @see
*/
public ServiceBusReceiverClientBuilder topicName(String topicName) {
this.topicName = topicName;
return this;
}
/**
* Creates an <b>asynchronous</b> Service Bus receiver responsible for reading {@link ServiceBusMessage
* messages} from a specific queue or subscription.
*
* @return An new {@link ServiceBusReceiverAsyncClient} that receives messages from a queue or subscription.
* @throws IllegalStateException if {@link
* topicName} are not set or, both of these fields are set. It is also thrown if the Service Bus {@link
*
* {@link
*
* @throws IllegalArgumentException Queue or topic name are not set via {@link
* queueName()} or {@link
*/
public ServiceBusReceiverAsyncClient buildAsyncClient() {
return buildAsyncClient(true);
}
/**
* Creates <b>synchronous</b> Service Bus receiver responsible for reading {@link ServiceBusMessage messages}
* from a specific queue or subscription.
*
* @return An new {@link ServiceBusReceiverClient} that receives messages from a queue or subscription.
* @throws IllegalStateException if {@link
* topicName} are not set or, both of these fields are set. It is also thrown if the Service Bus {@link
*
* {@link
*
* @throws IllegalArgumentException Queue or topic name are not set via {@link
* queueName()} or {@link
*/
public ServiceBusReceiverClient buildClient() {
return new ServiceBusReceiverClient(buildAsyncClient(false),
MessageUtils.getTotalTimeout(retryOptions));
}
ServiceBusReceiverAsyncClient buildAsyncClient(boolean isAutoCompleteAllowed) {
final MessagingEntityType entityType = validateEntityPaths(logger, connectionStringEntityName, topicName,
queueName);
final String entityPath = getEntityPath(logger, entityType, queueName, topicName, subscriptionName,
subQueue);
if (!isAutoCompleteAllowed && enableAutoComplete) {
logger.warning(
"'enableAutoComplete' is not supported in synchronous client except through callback receive.");
enableAutoComplete = false;
} else if (enableAutoComplete && receiveMode == ServiceBusReceiveMode.RECEIVE_AND_DELETE) {
logger.warning("'enableAutoComplete' is not needed in for RECEIVE_AND_DELETE mode.");
enableAutoComplete = false;
}
if (receiveMode == ServiceBusReceiveMode.RECEIVE_AND_DELETE) {
maxAutoLockRenewDuration = Duration.ZERO;
}
final ServiceBusConnectionProcessor connectionProcessor = getOrCreateConnectionProcessor(messageSerializer);
final ReceiverOptions receiverOptions = new ReceiverOptions(receiveMode, prefetchCount,
maxAutoLockRenewDuration, enableAutoComplete);
return new ServiceBusReceiverAsyncClient(connectionProcessor.getFullyQualifiedNamespace(), entityPath,
entityType, receiverOptions, connectionProcessor, ServiceBusConstants.OPERATION_TIMEOUT,
tracerProvider, messageSerializer, ServiceBusClientBuilder.this::onClientClose);
}
}
private void validateAndThrow(int prefetchCount) {
if (prefetchCount < 0) {
throw logger.logExceptionAsError(new IllegalArgumentException(String.format(
"prefetchCount (%s) cannot be less than 0.", prefetchCount)));
}
}
private void validateAndThrow(Duration maxLockRenewalDuration) {
if (maxLockRenewalDuration != null && maxLockRenewalDuration.isNegative()) {
throw logger.logExceptionAsError(new IllegalArgumentException(
"'maxLockRenewalDuration' cannot be negative."));
}
}
} |
It tests if the `TimeoutPolicy" could be working in the client. | public void timeoutPolicy() {
final String key = "newKey";
final String value = "newValue";
connectionString = interceptorManager.isPlaybackMode()
? "Endpoint=http:
: Configuration.getGlobalConfiguration().get(AZURE_APPCONFIG_CONNECTION_STRING);
final ConfigurationClient client = new ConfigurationClientBuilder()
.connectionString(connectionString)
.addPolicy(new TimeoutPolicy(Duration.ofMillis(1))).buildClient();
assertThrows(RuntimeException.class, () -> client.setConfigurationSetting(key, null, value));
} | public void timeoutPolicy() {
final String key = "newKey";
final String value = "newValue";
connectionString = interceptorManager.isPlaybackMode()
? "Endpoint=http:
: Configuration.getGlobalConfiguration().get(AZURE_APPCONFIG_CONNECTION_STRING);
final ConfigurationClient client = new ConfigurationClientBuilder()
.connectionString(connectionString)
.addPolicy(new TimeoutPolicy(Duration.ofMillis(1))).buildClient();
assertThrows(RuntimeException.class, () -> client.setConfigurationSetting(key, null, value));
} | class ConfigurationClientBuilderTest extends TestBase {
private static final String AZURE_APPCONFIG_CONNECTION_STRING = "AZURE_APPCONFIG_CONNECTION_STRING";
private static final String DEFAULT_DOMAIN_NAME = ".azconfig.io";
private static final String NAMESPACE_NAME = "dummyNamespaceName";
private static final String ENDPOINT = getURI(ClientConstants.ENDPOINT_FORMAT, NAMESPACE_NAME, DEFAULT_DOMAIN_NAME).toString();
static String connectionString;
@Test
public void missingEndpoint() {
assertThrows(NullPointerException.class, () -> {
final ConfigurationClientBuilder builder = new ConfigurationClientBuilder();
builder.buildAsyncClient();
});
}
@Test
public void malformedURLExceptionForEndpoint() {
assertThrows(IllegalArgumentException.class, () -> {
final ConfigurationClientBuilder builder = new ConfigurationClientBuilder();
builder.endpoint("htp:
});
}
@Test
public void nullConnectionString() {
assertThrows(NullPointerException.class, () -> {
final ConfigurationClientBuilder builder = new ConfigurationClientBuilder();
builder.connectionString(null).buildAsyncClient();
});
}
@Test
public void emptyConnectionString() {
assertThrows(IllegalArgumentException.class, () -> {
final ConfigurationClientBuilder builder = new ConfigurationClientBuilder();
builder.connectionString("").buildAsyncClient();
});
}
@Test
public void missingSecretKey() {
assertThrows(IllegalArgumentException.class, () -> {
final ConfigurationClientBuilder builder = new ConfigurationClientBuilder();
builder.connectionString("endpoint=" + ENDPOINT + ";Id=aaa;Secret=").buildAsyncClient();
});
}
@Test
public void missingId() {
assertThrows(IllegalArgumentException.class, () -> {
final ConfigurationClientBuilder builder = new ConfigurationClientBuilder();
builder.connectionString("endpoint=" + ENDPOINT + ";Id=;Secret=aaa").buildAsyncClient();
});
}
@Test
public void invalidConnectionStringSegmentCount() {
assertThrows(IllegalArgumentException.class, () -> {
final ConfigurationClientBuilder builder = new ConfigurationClientBuilder();
builder.connectionString("endpoint=" + ENDPOINT + ";Id=aaa").buildAsyncClient();
});
}
@Test
public void nullAADCredential() {
assertThrows(NullPointerException.class, () -> {
final ConfigurationClientBuilder builder = new ConfigurationClientBuilder();
builder.endpoint(ENDPOINT).credential(null).buildAsyncClient();
});
}
@Test
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.data.appconfiguration.TestHelper
public void nullServiceVersion(HttpClient httpClient) {
final String key = "newKey";
final String value = "newValue";
connectionString = interceptorManager.isPlaybackMode()
? "Endpoint=http:
: Configuration.getGlobalConfiguration().get(AZURE_APPCONFIG_CONNECTION_STRING);
Objects.requireNonNull(connectionString, "`AZURE_APPCONFIG_CONNECTION_STRING` expected to be set.");
final ConfigurationClientBuilder clientBuilder = new ConfigurationClientBuilder()
.connectionString(connectionString)
.retryPolicy(new RetryPolicy())
.httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS))
.serviceVersion(null)
.httpClient(httpClient == null ? interceptorManager.getPlaybackClient() : httpClient);
if (!interceptorManager.isPlaybackMode()) {
clientBuilder.addPolicy(interceptorManager.getRecordPolicy());
}
ConfigurationSetting addedSetting = clientBuilder.buildClient().setConfigurationSetting(key, null, value);
Assertions.assertEquals(addedSetting.getKey(), key);
Assertions.assertEquals(addedSetting.getValue(), value);
}
@Test
public void defaultPipeline() {
final String key = "newKey";
final String value = "newValue";
connectionString = interceptorManager.isPlaybackMode()
? "Endpoint=http:
: Configuration.getGlobalConfiguration().get(AZURE_APPCONFIG_CONNECTION_STRING);
Objects.requireNonNull(connectionString, "`AZURE_APPCONFIG_CONNECTION_STRING` expected to be set.");
final ConfigurationClientBuilder clientBuilder = new ConfigurationClientBuilder()
.connectionString(connectionString)
.retryPolicy(new RetryPolicy())
.configuration(Configuration.getGlobalConfiguration())
.httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS))
.pipeline(new HttpPipelineBuilder().build());
if (!interceptorManager.isPlaybackMode()) {
clientBuilder.addPolicy(interceptorManager.getRecordPolicy());
assertThrows(HttpResponseException.class,
() -> clientBuilder.buildClient().setConfigurationSetting(key, null, value));
}
HttpClient defaultHttpClient = interceptorManager.isPlaybackMode() ? interceptorManager.getPlaybackClient()
: new NettyAsyncHttpClientBuilder().wiretap(true).build();
clientBuilder.pipeline(null).httpClient(defaultHttpClient);
ConfigurationSetting addedSetting = clientBuilder.buildClient().setConfigurationSetting(key, null, value);
Assertions.assertEquals(addedSetting.getKey(), key);
Assertions.assertEquals(addedSetting.getValue(), value);
}
private static URI getURI(String endpointFormat, String namespace, String domainName) {
try {
return new URI(String.format(Locale.US, endpointFormat, namespace, domainName));
} catch (URISyntaxException exception) {
throw new IllegalArgumentException(String.format(Locale.US,
"Invalid namespace name: %s", namespace), exception);
}
}
} | class ConfigurationClientBuilderTest extends TestBase {
private static final String AZURE_APPCONFIG_CONNECTION_STRING = "AZURE_APPCONFIG_CONNECTION_STRING";
private static final String DEFAULT_DOMAIN_NAME = ".azconfig.io";
private static final String NAMESPACE_NAME = "dummyNamespaceName";
private static final String ENDPOINT = getURI(ClientConstants.ENDPOINT_FORMAT, NAMESPACE_NAME, DEFAULT_DOMAIN_NAME).toString();
static String connectionString;
@Test
public void missingEndpoint() {
assertThrows(NullPointerException.class, () -> {
final ConfigurationClientBuilder builder = new ConfigurationClientBuilder();
builder.buildAsyncClient();
});
}
@Test
public void malformedURLExceptionForEndpoint() {
assertThrows(IllegalArgumentException.class, () -> {
final ConfigurationClientBuilder builder = new ConfigurationClientBuilder();
builder.endpoint("htp:
});
}
@Test
public void nullConnectionString() {
assertThrows(NullPointerException.class, () -> {
final ConfigurationClientBuilder builder = new ConfigurationClientBuilder();
builder.connectionString(null).buildAsyncClient();
});
}
@Test
public void emptyConnectionString() {
assertThrows(IllegalArgumentException.class, () -> {
final ConfigurationClientBuilder builder = new ConfigurationClientBuilder();
builder.connectionString("").buildAsyncClient();
});
}
@Test
public void missingSecretKey() {
assertThrows(IllegalArgumentException.class, () -> {
final ConfigurationClientBuilder builder = new ConfigurationClientBuilder();
builder.connectionString("endpoint=" + ENDPOINT + ";Id=aaa;Secret=").buildAsyncClient();
});
}
@Test
public void missingId() {
assertThrows(IllegalArgumentException.class, () -> {
final ConfigurationClientBuilder builder = new ConfigurationClientBuilder();
builder.connectionString("endpoint=" + ENDPOINT + ";Id=;Secret=aaa").buildAsyncClient();
});
}
@Test
public void invalidConnectionStringSegmentCount() {
assertThrows(IllegalArgumentException.class, () -> {
final ConfigurationClientBuilder builder = new ConfigurationClientBuilder();
builder.connectionString("endpoint=" + ENDPOINT + ";Id=aaa").buildAsyncClient();
});
}
@Test
public void nullAADCredential() {
assertThrows(NullPointerException.class, () -> {
final ConfigurationClientBuilder builder = new ConfigurationClientBuilder();
builder.endpoint(ENDPOINT).credential(null).buildAsyncClient();
});
}
@Test
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.data.appconfiguration.TestHelper
public void nullServiceVersion(HttpClient httpClient) {
final String key = "newKey";
final String value = "newValue";
connectionString = interceptorManager.isPlaybackMode()
? "Endpoint=http:
: Configuration.getGlobalConfiguration().get(AZURE_APPCONFIG_CONNECTION_STRING);
Objects.requireNonNull(connectionString, "`AZURE_APPCONFIG_CONNECTION_STRING` expected to be set.");
final ConfigurationClientBuilder clientBuilder = new ConfigurationClientBuilder()
.connectionString(connectionString)
.retryPolicy(new RetryPolicy())
.httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS))
.serviceVersion(null)
.httpClient(httpClient == null ? interceptorManager.getPlaybackClient() : httpClient);
if (!interceptorManager.isPlaybackMode()) {
clientBuilder.addPolicy(interceptorManager.getRecordPolicy());
}
ConfigurationSetting addedSetting = clientBuilder.buildClient().setConfigurationSetting(key, null, value);
Assertions.assertEquals(addedSetting.getKey(), key);
Assertions.assertEquals(addedSetting.getValue(), value);
}
@Test
public void defaultPipeline() {
final String key = "newKey";
final String value = "newValue";
connectionString = interceptorManager.isPlaybackMode()
? "Endpoint=http:
: Configuration.getGlobalConfiguration().get(AZURE_APPCONFIG_CONNECTION_STRING);
Objects.requireNonNull(connectionString, "`AZURE_APPCONFIG_CONNECTION_STRING` expected to be set.");
final ConfigurationClientBuilder clientBuilder = new ConfigurationClientBuilder()
.connectionString(connectionString)
.retryPolicy(new RetryPolicy())
.configuration(Configuration.getGlobalConfiguration())
.httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS))
.pipeline(new HttpPipelineBuilder().build());
if (!interceptorManager.isPlaybackMode()) {
clientBuilder.addPolicy(interceptorManager.getRecordPolicy());
assertThrows(HttpResponseException.class,
() -> clientBuilder.buildClient().setConfigurationSetting(key, null, value));
}
HttpClient defaultHttpClient = interceptorManager.isPlaybackMode() ? interceptorManager.getPlaybackClient()
: new NettyAsyncHttpClientBuilder().wiretap(true).build();
clientBuilder.pipeline(null).httpClient(defaultHttpClient);
ConfigurationSetting addedSetting = clientBuilder.buildClient().setConfigurationSetting(key, null, value);
Assertions.assertEquals(addedSetting.getKey(), key);
Assertions.assertEquals(addedSetting.getValue(), value);
}
private static URI getURI(String endpointFormat, String namespace, String domainName) {
try {
return new URI(String.format(Locale.US, endpointFormat, namespace, domainName));
} catch (URISyntaxException exception) {
throw new IllegalArgumentException(String.format(Locale.US,
"Invalid namespace name: %s", namespace), exception);
}
}
} | |
Could this be removed for a test in `azure-core`? | public void timeoutPolicy() {
final String key = "newKey";
final String value = "newValue";
connectionString = interceptorManager.isPlaybackMode()
? "Endpoint=http:
: Configuration.getGlobalConfiguration().get(AZURE_APPCONFIG_CONNECTION_STRING);
final ConfigurationClient client = new ConfigurationClientBuilder()
.connectionString(connectionString)
.addPolicy(new TimeoutPolicy(Duration.ofMillis(1))).buildClient();
assertThrows(RuntimeException.class, () -> client.setConfigurationSetting(key, null, value));
} | public void timeoutPolicy() {
final String key = "newKey";
final String value = "newValue";
connectionString = interceptorManager.isPlaybackMode()
? "Endpoint=http:
: Configuration.getGlobalConfiguration().get(AZURE_APPCONFIG_CONNECTION_STRING);
final ConfigurationClient client = new ConfigurationClientBuilder()
.connectionString(connectionString)
.addPolicy(new TimeoutPolicy(Duration.ofMillis(1))).buildClient();
assertThrows(RuntimeException.class, () -> client.setConfigurationSetting(key, null, value));
} | class ConfigurationClientBuilderTest extends TestBase {
private static final String AZURE_APPCONFIG_CONNECTION_STRING = "AZURE_APPCONFIG_CONNECTION_STRING";
private static final String DEFAULT_DOMAIN_NAME = ".azconfig.io";
private static final String NAMESPACE_NAME = "dummyNamespaceName";
private static final String ENDPOINT = getURI(ClientConstants.ENDPOINT_FORMAT, NAMESPACE_NAME, DEFAULT_DOMAIN_NAME).toString();
static String connectionString;
@Test
public void missingEndpoint() {
assertThrows(NullPointerException.class, () -> {
final ConfigurationClientBuilder builder = new ConfigurationClientBuilder();
builder.buildAsyncClient();
});
}
@Test
public void malformedURLExceptionForEndpoint() {
assertThrows(IllegalArgumentException.class, () -> {
final ConfigurationClientBuilder builder = new ConfigurationClientBuilder();
builder.endpoint("htp:
});
}
@Test
public void nullConnectionString() {
assertThrows(NullPointerException.class, () -> {
final ConfigurationClientBuilder builder = new ConfigurationClientBuilder();
builder.connectionString(null).buildAsyncClient();
});
}
@Test
public void emptyConnectionString() {
assertThrows(IllegalArgumentException.class, () -> {
final ConfigurationClientBuilder builder = new ConfigurationClientBuilder();
builder.connectionString("").buildAsyncClient();
});
}
@Test
public void missingSecretKey() {
assertThrows(IllegalArgumentException.class, () -> {
final ConfigurationClientBuilder builder = new ConfigurationClientBuilder();
builder.connectionString("endpoint=" + ENDPOINT + ";Id=aaa;Secret=").buildAsyncClient();
});
}
@Test
public void missingId() {
assertThrows(IllegalArgumentException.class, () -> {
final ConfigurationClientBuilder builder = new ConfigurationClientBuilder();
builder.connectionString("endpoint=" + ENDPOINT + ";Id=;Secret=aaa").buildAsyncClient();
});
}
@Test
public void invalidConnectionStringSegmentCount() {
assertThrows(IllegalArgumentException.class, () -> {
final ConfigurationClientBuilder builder = new ConfigurationClientBuilder();
builder.connectionString("endpoint=" + ENDPOINT + ";Id=aaa").buildAsyncClient();
});
}
@Test
public void nullAADCredential() {
assertThrows(NullPointerException.class, () -> {
final ConfigurationClientBuilder builder = new ConfigurationClientBuilder();
builder.endpoint(ENDPOINT).credential(null).buildAsyncClient();
});
}
@Test
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.data.appconfiguration.TestHelper
public void nullServiceVersion(HttpClient httpClient) {
final String key = "newKey";
final String value = "newValue";
connectionString = interceptorManager.isPlaybackMode()
? "Endpoint=http:
: Configuration.getGlobalConfiguration().get(AZURE_APPCONFIG_CONNECTION_STRING);
Objects.requireNonNull(connectionString, "`AZURE_APPCONFIG_CONNECTION_STRING` expected to be set.");
final ConfigurationClientBuilder clientBuilder = new ConfigurationClientBuilder()
.connectionString(connectionString)
.retryPolicy(new RetryPolicy())
.httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS))
.serviceVersion(null)
.httpClient(httpClient == null ? interceptorManager.getPlaybackClient() : httpClient);
if (!interceptorManager.isPlaybackMode()) {
clientBuilder.addPolicy(interceptorManager.getRecordPolicy());
}
ConfigurationSetting addedSetting = clientBuilder.buildClient().setConfigurationSetting(key, null, value);
Assertions.assertEquals(addedSetting.getKey(), key);
Assertions.assertEquals(addedSetting.getValue(), value);
}
@Test
public void defaultPipeline() {
final String key = "newKey";
final String value = "newValue";
connectionString = interceptorManager.isPlaybackMode()
? "Endpoint=http:
: Configuration.getGlobalConfiguration().get(AZURE_APPCONFIG_CONNECTION_STRING);
Objects.requireNonNull(connectionString, "`AZURE_APPCONFIG_CONNECTION_STRING` expected to be set.");
final ConfigurationClientBuilder clientBuilder = new ConfigurationClientBuilder()
.connectionString(connectionString)
.retryPolicy(new RetryPolicy())
.configuration(Configuration.getGlobalConfiguration())
.httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS))
.pipeline(new HttpPipelineBuilder().build());
if (!interceptorManager.isPlaybackMode()) {
clientBuilder.addPolicy(interceptorManager.getRecordPolicy());
assertThrows(HttpResponseException.class,
() -> clientBuilder.buildClient().setConfigurationSetting(key, null, value));
}
HttpClient defaultHttpClient = interceptorManager.isPlaybackMode() ? interceptorManager.getPlaybackClient()
: new NettyAsyncHttpClientBuilder().wiretap(true).build();
clientBuilder.pipeline(null).httpClient(defaultHttpClient);
ConfigurationSetting addedSetting = clientBuilder.buildClient().setConfigurationSetting(key, null, value);
Assertions.assertEquals(addedSetting.getKey(), key);
Assertions.assertEquals(addedSetting.getValue(), value);
}
private static URI getURI(String endpointFormat, String namespace, String domainName) {
try {
return new URI(String.format(Locale.US, endpointFormat, namespace, domainName));
} catch (URISyntaxException exception) {
throw new IllegalArgumentException(String.format(Locale.US,
"Invalid namespace name: %s", namespace), exception);
}
}
} | class ConfigurationClientBuilderTest extends TestBase {
private static final String AZURE_APPCONFIG_CONNECTION_STRING = "AZURE_APPCONFIG_CONNECTION_STRING";
private static final String DEFAULT_DOMAIN_NAME = ".azconfig.io";
private static final String NAMESPACE_NAME = "dummyNamespaceName";
private static final String ENDPOINT = getURI(ClientConstants.ENDPOINT_FORMAT, NAMESPACE_NAME, DEFAULT_DOMAIN_NAME).toString();
static String connectionString;
@Test
public void missingEndpoint() {
assertThrows(NullPointerException.class, () -> {
final ConfigurationClientBuilder builder = new ConfigurationClientBuilder();
builder.buildAsyncClient();
});
}
@Test
public void malformedURLExceptionForEndpoint() {
assertThrows(IllegalArgumentException.class, () -> {
final ConfigurationClientBuilder builder = new ConfigurationClientBuilder();
builder.endpoint("htp:
});
}
@Test
public void nullConnectionString() {
assertThrows(NullPointerException.class, () -> {
final ConfigurationClientBuilder builder = new ConfigurationClientBuilder();
builder.connectionString(null).buildAsyncClient();
});
}
@Test
public void emptyConnectionString() {
assertThrows(IllegalArgumentException.class, () -> {
final ConfigurationClientBuilder builder = new ConfigurationClientBuilder();
builder.connectionString("").buildAsyncClient();
});
}
@Test
public void missingSecretKey() {
assertThrows(IllegalArgumentException.class, () -> {
final ConfigurationClientBuilder builder = new ConfigurationClientBuilder();
builder.connectionString("endpoint=" + ENDPOINT + ";Id=aaa;Secret=").buildAsyncClient();
});
}
@Test
public void missingId() {
assertThrows(IllegalArgumentException.class, () -> {
final ConfigurationClientBuilder builder = new ConfigurationClientBuilder();
builder.connectionString("endpoint=" + ENDPOINT + ";Id=;Secret=aaa").buildAsyncClient();
});
}
@Test
public void invalidConnectionStringSegmentCount() {
assertThrows(IllegalArgumentException.class, () -> {
final ConfigurationClientBuilder builder = new ConfigurationClientBuilder();
builder.connectionString("endpoint=" + ENDPOINT + ";Id=aaa").buildAsyncClient();
});
}
@Test
public void nullAADCredential() {
assertThrows(NullPointerException.class, () -> {
final ConfigurationClientBuilder builder = new ConfigurationClientBuilder();
builder.endpoint(ENDPOINT).credential(null).buildAsyncClient();
});
}
@Test
@ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS)
@MethodSource("com.azure.data.appconfiguration.TestHelper
public void nullServiceVersion(HttpClient httpClient) {
final String key = "newKey";
final String value = "newValue";
connectionString = interceptorManager.isPlaybackMode()
? "Endpoint=http:
: Configuration.getGlobalConfiguration().get(AZURE_APPCONFIG_CONNECTION_STRING);
Objects.requireNonNull(connectionString, "`AZURE_APPCONFIG_CONNECTION_STRING` expected to be set.");
final ConfigurationClientBuilder clientBuilder = new ConfigurationClientBuilder()
.connectionString(connectionString)
.retryPolicy(new RetryPolicy())
.httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS))
.serviceVersion(null)
.httpClient(httpClient == null ? interceptorManager.getPlaybackClient() : httpClient);
if (!interceptorManager.isPlaybackMode()) {
clientBuilder.addPolicy(interceptorManager.getRecordPolicy());
}
ConfigurationSetting addedSetting = clientBuilder.buildClient().setConfigurationSetting(key, null, value);
Assertions.assertEquals(addedSetting.getKey(), key);
Assertions.assertEquals(addedSetting.getValue(), value);
}
@Test
public void defaultPipeline() {
final String key = "newKey";
final String value = "newValue";
connectionString = interceptorManager.isPlaybackMode()
? "Endpoint=http:
: Configuration.getGlobalConfiguration().get(AZURE_APPCONFIG_CONNECTION_STRING);
Objects.requireNonNull(connectionString, "`AZURE_APPCONFIG_CONNECTION_STRING` expected to be set.");
final ConfigurationClientBuilder clientBuilder = new ConfigurationClientBuilder()
.connectionString(connectionString)
.retryPolicy(new RetryPolicy())
.configuration(Configuration.getGlobalConfiguration())
.httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS))
.pipeline(new HttpPipelineBuilder().build());
if (!interceptorManager.isPlaybackMode()) {
clientBuilder.addPolicy(interceptorManager.getRecordPolicy());
assertThrows(HttpResponseException.class,
() -> clientBuilder.buildClient().setConfigurationSetting(key, null, value));
}
HttpClient defaultHttpClient = interceptorManager.isPlaybackMode() ? interceptorManager.getPlaybackClient()
: new NettyAsyncHttpClientBuilder().wiretap(true).build();
clientBuilder.pipeline(null).httpClient(defaultHttpClient);
ConfigurationSetting addedSetting = clientBuilder.buildClient().setConfigurationSetting(key, null, value);
Assertions.assertEquals(addedSetting.getKey(), key);
Assertions.assertEquals(addedSetting.getValue(), value);
}
private static URI getURI(String endpointFormat, String namespace, String domainName) {
try {
return new URI(String.format(Locale.US, endpointFormat, namespace, domainName));
} catch (URISyntaxException exception) {
throw new IllegalArgumentException(String.format(Locale.US,
"Invalid namespace name: %s", namespace), exception);
}
}
} | |
user still able to customize this one, right? | public StorageAccountImpl define(String name) {
return wrapModel(name)
.withSku(StorageAccountSkuType.STANDARD_RAGRS)
.withGeneralPurposeAccountKindV2()
.withOnlyHttpsTraffic()
.withMinimumTlsVersion(MinimumTlsVersion.TLS1_2);
} | .withMinimumTlsVersion(MinimumTlsVersion.TLS1_2); | public StorageAccountImpl define(String name) {
return wrapModel(name)
.withSku(StorageAccountSkuType.STANDARD_RAGRS)
.withGeneralPurposeAccountKindV2()
.withOnlyHttpsTraffic()
.withMinimumTlsVersion(MinimumTlsVersion.TLS1_2);
} | class StorageAccountsImpl
extends TopLevelModifiableResourcesImpl<
StorageAccount, StorageAccountImpl, StorageAccountInner, StorageAccountsClient, StorageManager>
implements StorageAccounts {
public StorageAccountsImpl(final StorageManager storageManager) {
super(storageManager.serviceClient().getStorageAccounts(), storageManager);
}
@Override
public CheckNameAvailabilityResult checkNameAvailability(String name) {
return this.checkNameAvailabilityAsync(name).block();
}
@Override
public Mono<CheckNameAvailabilityResult> checkNameAvailabilityAsync(String name) {
return this
.inner()
.checkNameAvailabilityAsync(name)
.map(CheckNameAvailabilityResult::new);
}
@Override
@Override
protected StorageAccountImpl wrapModel(String name) {
return new StorageAccountImpl(name, new StorageAccountInner(), this.manager());
}
@Override
protected StorageAccountImpl wrapModel(StorageAccountInner storageAccountInner) {
if (storageAccountInner == null) {
return null;
}
return new StorageAccountImpl(storageAccountInner.name(), storageAccountInner, this.manager());
}
@Override
public String createSasToken(String resourceGroupName, String accountName, ServiceSasParameters parameters) {
return createSasTokenAsync(resourceGroupName, accountName, parameters).block();
}
@Override
public Mono<String> createSasTokenAsync(
String resourceGroupName, String accountName, ServiceSasParameters parameters) {
return this
.inner()
.listServiceSasAsync(resourceGroupName, accountName, parameters)
.map(ListServiceSasResponseInner::serviceSasToken);
}
@Override
public void failover(String resourceGroupName, String accountName) {
failoverAsync(resourceGroupName, accountName).block();
}
@Override
public Mono<Void> failoverAsync(String resourceGroupName, String accountName) {
return this.inner().failoverAsync(resourceGroupName, accountName);
}
} | class StorageAccountsImpl
extends TopLevelModifiableResourcesImpl<
StorageAccount, StorageAccountImpl, StorageAccountInner, StorageAccountsClient, StorageManager>
implements StorageAccounts {
public StorageAccountsImpl(final StorageManager storageManager) {
super(storageManager.serviceClient().getStorageAccounts(), storageManager);
}
@Override
public CheckNameAvailabilityResult checkNameAvailability(String name) {
return this.checkNameAvailabilityAsync(name).block();
}
@Override
public Mono<CheckNameAvailabilityResult> checkNameAvailabilityAsync(String name) {
return this
.inner()
.checkNameAvailabilityAsync(name)
.map(CheckNameAvailabilityResult::new);
}
@Override
@Override
protected StorageAccountImpl wrapModel(String name) {
return new StorageAccountImpl(name, new StorageAccountInner(), this.manager());
}
@Override
protected StorageAccountImpl wrapModel(StorageAccountInner storageAccountInner) {
if (storageAccountInner == null) {
return null;
}
return new StorageAccountImpl(storageAccountInner.name(), storageAccountInner, this.manager());
}
@Override
public String createSasToken(String resourceGroupName, String accountName, ServiceSasParameters parameters) {
return createSasTokenAsync(resourceGroupName, accountName, parameters).block();
}
@Override
public Mono<String> createSasTokenAsync(
String resourceGroupName, String accountName, ServiceSasParameters parameters) {
return this
.inner()
.listServiceSasAsync(resourceGroupName, accountName, parameters)
.map(ListServiceSasResponseInner::serviceSasToken);
}
@Override
public void failover(String resourceGroupName, String accountName) {
failoverAsync(resourceGroupName, accountName).block();
}
@Override
public Mono<Void> failoverAsync(String resourceGroupName, String accountName) {
return this.inner().failoverAsync(resourceGroupName, accountName);
}
} |
Yes, customer can configure differently as in test code https://github.com/Azure/azure-sdk-for-java/pull/19649/files#diff-edf813069045825a9ed68c4408e389ba75eae39461b4a2ff37b8a5df20469e05R246-R250 The default here in SDK matches Portal default. | public StorageAccountImpl define(String name) {
return wrapModel(name)
.withSku(StorageAccountSkuType.STANDARD_RAGRS)
.withGeneralPurposeAccountKindV2()
.withOnlyHttpsTraffic()
.withMinimumTlsVersion(MinimumTlsVersion.TLS1_2);
} | .withMinimumTlsVersion(MinimumTlsVersion.TLS1_2); | public StorageAccountImpl define(String name) {
return wrapModel(name)
.withSku(StorageAccountSkuType.STANDARD_RAGRS)
.withGeneralPurposeAccountKindV2()
.withOnlyHttpsTraffic()
.withMinimumTlsVersion(MinimumTlsVersion.TLS1_2);
} | class StorageAccountsImpl
extends TopLevelModifiableResourcesImpl<
StorageAccount, StorageAccountImpl, StorageAccountInner, StorageAccountsClient, StorageManager>
implements StorageAccounts {
public StorageAccountsImpl(final StorageManager storageManager) {
super(storageManager.serviceClient().getStorageAccounts(), storageManager);
}
@Override
public CheckNameAvailabilityResult checkNameAvailability(String name) {
return this.checkNameAvailabilityAsync(name).block();
}
@Override
public Mono<CheckNameAvailabilityResult> checkNameAvailabilityAsync(String name) {
return this
.inner()
.checkNameAvailabilityAsync(name)
.map(CheckNameAvailabilityResult::new);
}
@Override
@Override
protected StorageAccountImpl wrapModel(String name) {
return new StorageAccountImpl(name, new StorageAccountInner(), this.manager());
}
@Override
protected StorageAccountImpl wrapModel(StorageAccountInner storageAccountInner) {
if (storageAccountInner == null) {
return null;
}
return new StorageAccountImpl(storageAccountInner.name(), storageAccountInner, this.manager());
}
@Override
public String createSasToken(String resourceGroupName, String accountName, ServiceSasParameters parameters) {
return createSasTokenAsync(resourceGroupName, accountName, parameters).block();
}
@Override
public Mono<String> createSasTokenAsync(
String resourceGroupName, String accountName, ServiceSasParameters parameters) {
return this
.inner()
.listServiceSasAsync(resourceGroupName, accountName, parameters)
.map(ListServiceSasResponseInner::serviceSasToken);
}
@Override
public void failover(String resourceGroupName, String accountName) {
failoverAsync(resourceGroupName, accountName).block();
}
@Override
public Mono<Void> failoverAsync(String resourceGroupName, String accountName) {
return this.inner().failoverAsync(resourceGroupName, accountName);
}
} | class StorageAccountsImpl
extends TopLevelModifiableResourcesImpl<
StorageAccount, StorageAccountImpl, StorageAccountInner, StorageAccountsClient, StorageManager>
implements StorageAccounts {
public StorageAccountsImpl(final StorageManager storageManager) {
super(storageManager.serviceClient().getStorageAccounts(), storageManager);
}
@Override
public CheckNameAvailabilityResult checkNameAvailability(String name) {
return this.checkNameAvailabilityAsync(name).block();
}
@Override
public Mono<CheckNameAvailabilityResult> checkNameAvailabilityAsync(String name) {
return this
.inner()
.checkNameAvailabilityAsync(name)
.map(CheckNameAvailabilityResult::new);
}
@Override
@Override
protected StorageAccountImpl wrapModel(String name) {
return new StorageAccountImpl(name, new StorageAccountInner(), this.manager());
}
@Override
protected StorageAccountImpl wrapModel(StorageAccountInner storageAccountInner) {
if (storageAccountInner == null) {
return null;
}
return new StorageAccountImpl(storageAccountInner.name(), storageAccountInner, this.manager());
}
@Override
public String createSasToken(String resourceGroupName, String accountName, ServiceSasParameters parameters) {
return createSasTokenAsync(resourceGroupName, accountName, parameters).block();
}
@Override
public Mono<String> createSasTokenAsync(
String resourceGroupName, String accountName, ServiceSasParameters parameters) {
return this
.inner()
.listServiceSasAsync(resourceGroupName, accountName, parameters)
.map(ListServiceSasResponseInner::serviceSasToken);
}
@Override
public void failover(String resourceGroupName, String accountName) {
failoverAsync(resourceGroupName, accountName).block();
}
@Override
public Mono<Void> failoverAsync(String resourceGroupName, String accountName) {
return this.inner().failoverAsync(resourceGroupName, accountName);
}
} |
Is this same to `primaryDatabaseTemplate.findById(...)`? | public void run(String... var1) throws Exception {
final List<CosmosUser> cosmosUsers = this.userRepository.findByEmailOrName(this.cosmosUser.getEmail(),
this.cosmosUser.getName()).collectList().block();
cosmosUsers.stream().forEach(this::insertValueToMYSQL);
CosmosUser secondaryCosmosUserGet = secondaryDatabaseTemplate.findById(CosmosUser.class.getSimpleName(), cosmosUser.getId(), CosmosUser.class);
System.out.println(secondaryCosmosUserGet);
mysqlUserRepository.findAll().forEach(System.out::println);
} | this.cosmosUser.getName()).collectList().block(); | public void run(String... var1) throws Exception {
CosmosUser cosmosUserGet = primaryDatabaseTemplate.findById(cosmosUser.getId(), cosmosUser.getClass()).block();
MysqlUser mysqlUser = new MysqlUser(cosmosUserGet.getId(), cosmosUserGet.getEmail(), cosmosUserGet.getName(), cosmosUserGet.getAddress());
mysqlUserRepository.save(mysqlUser);
mysqlUserRepository.findAll().forEach(System.out::println);
CosmosUser secondaryCosmosUserGet = secondaryDatabaseTemplate.findById(CosmosUser.class.getSimpleName(), cosmosUser.getId(), CosmosUser.class);
System.out.println(secondaryCosmosUserGet);
} | class MultiDatabaseApplication implements CommandLineRunner {
@Autowired
private UserRepository userRepository;
@Autowired
private MysqlUserRepository mysqlUserRepository;
@Autowired
@Qualifier("secondaryDatabaseTemplate")
private CosmosTemplate secondaryDatabaseTemplate;
@Autowired
@Qualifier("primaryDatabaseTemplate")
private ReactiveCosmosTemplate primaryDatabaseTemplate;
private final CosmosUser cosmosUser = new CosmosUser("1024", "1024@geek.com", "1k", "Mars");
private MysqlUser userForMYSQL;
private static CosmosEntityInformation<CosmosUser, String> userInfo = new CosmosEntityInformation<>(CosmosUser.class);
public static void main(String[] args) {
SpringApplication.run(MultiDatabaseApplication.class, args);
}
public void insertValueToMYSQL(CosmosUser cosmosUser){
userForMYSQL = new MysqlUser(cosmosUser.getId(), cosmosUser.getEmail(), cosmosUser.getName(), cosmosUser.getAddress());
mysqlUserRepository.save(userForMYSQL);
}
@PostConstruct
public void setup() {
primaryDatabaseTemplate.createContainerIfNotExists(userInfo).block();
primaryDatabaseTemplate.insert(CosmosUser.class.getSimpleName(), cosmosUser,
new PartitionKey(cosmosUser.getName())).block();
secondaryDatabaseTemplate.createContainerIfNotExists(userInfo);
secondaryDatabaseTemplate.insert(CosmosUser.class.getSimpleName(), cosmosUser, new PartitionKey(cosmosUser.getName()));
}
@PreDestroy
public void cleanup() {
primaryDatabaseTemplate.deleteAll(CosmosUser.class.getSimpleName(),
CosmosUser.class).block();
secondaryDatabaseTemplate.deleteAll(CosmosUser.class.getSimpleName() , CosmosUser.class);
mysqlUserRepository.deleteAll();
}
} | class MultiDatabaseApplication implements CommandLineRunner {
@Autowired
private CosmosUserRepository cosmosUserRepository;
@Autowired
private MysqlUserRepository mysqlUserRepository;
@Autowired
@Qualifier("secondaryDatabaseTemplate")
private CosmosTemplate secondaryDatabaseTemplate;
@Autowired
@Qualifier("primaryDatabaseTemplate")
private ReactiveCosmosTemplate primaryDatabaseTemplate;
private final CosmosUser cosmosUser = new CosmosUser("1024", "1024@geek.com", "1k", "Mars");
private static CosmosEntityInformation<CosmosUser, String> userInfo = new CosmosEntityInformation<>(CosmosUser.class);
public static void main(String[] args) {
SpringApplication.run(MultiDatabaseApplication.class, args);
}
@PostConstruct
public void setup() {
primaryDatabaseTemplate.createContainerIfNotExists(userInfo).block();
primaryDatabaseTemplate.insert(CosmosUser.class.getSimpleName(), cosmosUser, new PartitionKey(cosmosUser.getName())).block();
secondaryDatabaseTemplate.createContainerIfNotExists(userInfo);
secondaryDatabaseTemplate.insert(CosmosUser.class.getSimpleName(), cosmosUser, new PartitionKey(cosmosUser.getName()));
}
@PreDestroy
public void cleanup() {
primaryDatabaseTemplate.deleteAll(CosmosUser.class.getSimpleName(), CosmosUser.class).block();
secondaryDatabaseTemplate.deleteAll(CosmosUser.class.getSimpleName() , CosmosUser.class);
mysqlUserRepository.deleteAll();
}
} |
Do not break line if the line's width not exceed 120. | public void run(String... var1) throws Exception {
User database1UserGet = database1Template.findById(User.class.getSimpleName(),
user.getId(), User.class).block();
System.out.println(database1UserGet);
User database2UserGet = database2Template.findById(User.class.getSimpleName(), user.getId(), User.class).block();
System.out.println(database2UserGet);
} | user.getId(), User.class).block(); | public void run(String... var1) throws Exception {
User1 database1UserGet = database1Template.findById(User1.class.getSimpleName(), user1.getId(), User1.class).block();
System.out.println(database1UserGet);
User2 database2UserGet = database2Template.findById(User2.class.getSimpleName(), user2.getId(), User2.class).block();
System.out.println(database2UserGet);
} | class MultiDatabaseApplication implements CommandLineRunner {
@Autowired
private UserRepository userRepository;
@Autowired
@Qualifier("database1Template")
private ReactiveCosmosTemplate database1Template;
@Autowired
@Qualifier("database2Template")
private ReactiveCosmosTemplate database2Template;
private final User user = new User("1024", "1024@geek.com", "1k", "Mars");
private static CosmosEntityInformation<User, String> userInfo = new CosmosEntityInformation<>(User.class);
public static void main(String[] args) {
SpringApplication.run(MultiDatabaseApplication.class, args);
}
@PostConstruct
public void setup() {
database1Template.createContainerIfNotExists(userInfo).block();
database1Template.insert(User.class.getSimpleName(), user,
new PartitionKey(user.getName())).block();
database2Template.createContainerIfNotExists(userInfo).block();
database2Template.insert(User.class.getSimpleName(), user,
new PartitionKey(user.getName())).block();
}
@PreDestroy
public void cleanup() {
database1Template.deleteAll(User.class.getSimpleName(),
User.class).block();
database2Template.deleteAll(User.class.getSimpleName(),
User.class).block();
}
} | class MultiDatabaseApplication implements CommandLineRunner {
@Autowired
private User1Repository user1Repository;
@Autowired
@Qualifier("database1Template")
private ReactiveCosmosTemplate database1Template;
@Autowired
@Qualifier("database2Template")
private ReactiveCosmosTemplate database2Template;
private final User1 user1 = new User1("1024", "1024@geek.com", "1k", "Mars");
private static CosmosEntityInformation<User1, String> user1Info = new CosmosEntityInformation<>(User1.class);
private final User2 user2 = new User2("2048", "2048@geek.com", "2k", "Mars");
private static CosmosEntityInformation<User2, String> user2Info = new CosmosEntityInformation<>(User2.class);
public static void main(String[] args) {
SpringApplication.run(MultiDatabaseApplication.class, args);
}
@PostConstruct
public void setup() {
database1Template.createContainerIfNotExists(user1Info).block();
database1Template.insert(User1.class.getSimpleName(), user1, new PartitionKey(user1.getName())).block();
database2Template.createContainerIfNotExists(user2Info).block();
database2Template.insert(User2.class.getSimpleName(), user2, new PartitionKey(user2.getName())).block();
}
@PreDestroy
public void cleanup() {
database1Template.deleteAll(User1.class.getSimpleName(), User1.class).block();
database2Template.deleteAll(User2.class.getSimpleName(), User2.class).block();
}
} |
Same here. | public void setup() {
database1Template.createContainerIfNotExists(userInfo).block();
database1Template.insert(User.class.getSimpleName(), user,
new PartitionKey(user.getName())).block();
database2Template.createContainerIfNotExists(userInfo).block();
database2Template.insert(User.class.getSimpleName(), user,
new PartitionKey(user.getName())).block();
} | new PartitionKey(user.getName())).block(); | public void setup() {
database1Template.createContainerIfNotExists(user1Info).block();
database1Template.insert(User1.class.getSimpleName(), user1, new PartitionKey(user1.getName())).block();
database2Template.createContainerIfNotExists(user2Info).block();
database2Template.insert(User2.class.getSimpleName(), user2, new PartitionKey(user2.getName())).block();
} | class MultiDatabaseApplication implements CommandLineRunner {
@Autowired
private UserRepository userRepository;
@Autowired
@Qualifier("database1Template")
private ReactiveCosmosTemplate database1Template;
@Autowired
@Qualifier("database2Template")
private ReactiveCosmosTemplate database2Template;
private final User user = new User("1024", "1024@geek.com", "1k", "Mars");
private static CosmosEntityInformation<User, String> userInfo = new CosmosEntityInformation<>(User.class);
public static void main(String[] args) {
SpringApplication.run(MultiDatabaseApplication.class, args);
}
public void run(String... var1) throws Exception {
User database1UserGet = database1Template.findById(User.class.getSimpleName(),
user.getId(), User.class).block();
System.out.println(database1UserGet);
User database2UserGet = database2Template.findById(User.class.getSimpleName(), user.getId(), User.class).block();
System.out.println(database2UserGet);
}
@PostConstruct
@PreDestroy
public void cleanup() {
database1Template.deleteAll(User.class.getSimpleName(),
User.class).block();
database2Template.deleteAll(User.class.getSimpleName(),
User.class).block();
}
} | class MultiDatabaseApplication implements CommandLineRunner {
@Autowired
private User1Repository user1Repository;
@Autowired
@Qualifier("database1Template")
private ReactiveCosmosTemplate database1Template;
@Autowired
@Qualifier("database2Template")
private ReactiveCosmosTemplate database2Template;
private final User1 user1 = new User1("1024", "1024@geek.com", "1k", "Mars");
private static CosmosEntityInformation<User1, String> user1Info = new CosmosEntityInformation<>(User1.class);
private final User2 user2 = new User2("2048", "2048@geek.com", "2k", "Mars");
private static CosmosEntityInformation<User2, String> user2Info = new CosmosEntityInformation<>(User2.class);
public static void main(String[] args) {
SpringApplication.run(MultiDatabaseApplication.class, args);
}
public void run(String... var1) throws Exception {
User1 database1UserGet = database1Template.findById(User1.class.getSimpleName(), user1.getId(), User1.class).block();
System.out.println(database1UserGet);
User2 database2UserGet = database2Template.findById(User2.class.getSimpleName(), user2.getId(), User2.class).block();
System.out.println(database2UserGet);
}
@PostConstruct
@PreDestroy
public void cleanup() {
database1Template.deleteAll(User1.class.getSimpleName(), User1.class).block();
database2Template.deleteAll(User2.class.getSimpleName(), User2.class).block();
}
} |
Here. | public void setup() {
database1Template.createContainerIfNotExists(userInfo).block();
database1Template.insert(User.class.getSimpleName(), user,
new PartitionKey(user.getName())).block();
database2Template.createContainerIfNotExists(userInfo).block();
database2Template.insert(User.class.getSimpleName(), user,
new PartitionKey(user.getName())).block();
} | new PartitionKey(user.getName())).block(); | public void setup() {
database1Template.createContainerIfNotExists(user1Info).block();
database1Template.insert(User1.class.getSimpleName(), user1, new PartitionKey(user1.getName())).block();
database2Template.createContainerIfNotExists(user2Info).block();
database2Template.insert(User2.class.getSimpleName(), user2, new PartitionKey(user2.getName())).block();
} | class MultiDatabaseApplication implements CommandLineRunner {
@Autowired
private UserRepository userRepository;
@Autowired
@Qualifier("database1Template")
private ReactiveCosmosTemplate database1Template;
@Autowired
@Qualifier("database2Template")
private ReactiveCosmosTemplate database2Template;
private final User user = new User("1024", "1024@geek.com", "1k", "Mars");
private static CosmosEntityInformation<User, String> userInfo = new CosmosEntityInformation<>(User.class);
public static void main(String[] args) {
SpringApplication.run(MultiDatabaseApplication.class, args);
}
public void run(String... var1) throws Exception {
User database1UserGet = database1Template.findById(User.class.getSimpleName(),
user.getId(), User.class).block();
System.out.println(database1UserGet);
User database2UserGet = database2Template.findById(User.class.getSimpleName(), user.getId(), User.class).block();
System.out.println(database2UserGet);
}
@PostConstruct
@PreDestroy
public void cleanup() {
database1Template.deleteAll(User.class.getSimpleName(),
User.class).block();
database2Template.deleteAll(User.class.getSimpleName(),
User.class).block();
}
} | class MultiDatabaseApplication implements CommandLineRunner {
@Autowired
private User1Repository user1Repository;
@Autowired
@Qualifier("database1Template")
private ReactiveCosmosTemplate database1Template;
@Autowired
@Qualifier("database2Template")
private ReactiveCosmosTemplate database2Template;
private final User1 user1 = new User1("1024", "1024@geek.com", "1k", "Mars");
private static CosmosEntityInformation<User1, String> user1Info = new CosmosEntityInformation<>(User1.class);
private final User2 user2 = new User2("2048", "2048@geek.com", "2k", "Mars");
private static CosmosEntityInformation<User2, String> user2Info = new CosmosEntityInformation<>(User2.class);
public static void main(String[] args) {
SpringApplication.run(MultiDatabaseApplication.class, args);
}
public void run(String... var1) throws Exception {
User1 database1UserGet = database1Template.findById(User1.class.getSimpleName(), user1.getId(), User1.class).block();
System.out.println(database1UserGet);
User2 database2UserGet = database2Template.findById(User2.class.getSimpleName(), user2.getId(), User2.class).block();
System.out.println(database2UserGet);
}
@PostConstruct
@PreDestroy
public void cleanup() {
database1Template.deleteAll(User1.class.getSimpleName(), User1.class).block();
database2Template.deleteAll(User2.class.getSimpleName(), User2.class).block();
}
} |
Here. And all other places. | public void cleanup() {
database1Template.deleteAll(User.class.getSimpleName(),
User.class).block();
database2Template.deleteAll(User.class.getSimpleName(),
User.class).block();
} | User.class).block(); | public void cleanup() {
database1Template.deleteAll(User1.class.getSimpleName(), User1.class).block();
database2Template.deleteAll(User2.class.getSimpleName(), User2.class).block();
} | class MultiDatabaseApplication implements CommandLineRunner {
@Autowired
private UserRepository userRepository;
@Autowired
@Qualifier("database1Template")
private ReactiveCosmosTemplate database1Template;
@Autowired
@Qualifier("database2Template")
private ReactiveCosmosTemplate database2Template;
private final User user = new User("1024", "1024@geek.com", "1k", "Mars");
private static CosmosEntityInformation<User, String> userInfo = new CosmosEntityInformation<>(User.class);
public static void main(String[] args) {
SpringApplication.run(MultiDatabaseApplication.class, args);
}
public void run(String... var1) throws Exception {
User database1UserGet = database1Template.findById(User.class.getSimpleName(),
user.getId(), User.class).block();
System.out.println(database1UserGet);
User database2UserGet = database2Template.findById(User.class.getSimpleName(), user.getId(), User.class).block();
System.out.println(database2UserGet);
}
@PostConstruct
public void setup() {
database1Template.createContainerIfNotExists(userInfo).block();
database1Template.insert(User.class.getSimpleName(), user,
new PartitionKey(user.getName())).block();
database2Template.createContainerIfNotExists(userInfo).block();
database2Template.insert(User.class.getSimpleName(), user,
new PartitionKey(user.getName())).block();
}
@PreDestroy
} | class MultiDatabaseApplication implements CommandLineRunner {
@Autowired
private User1Repository user1Repository;
@Autowired
@Qualifier("database1Template")
private ReactiveCosmosTemplate database1Template;
@Autowired
@Qualifier("database2Template")
private ReactiveCosmosTemplate database2Template;
private final User1 user1 = new User1("1024", "1024@geek.com", "1k", "Mars");
private static CosmosEntityInformation<User1, String> user1Info = new CosmosEntityInformation<>(User1.class);
private final User2 user2 = new User2("2048", "2048@geek.com", "2k", "Mars");
private static CosmosEntityInformation<User2, String> user2Info = new CosmosEntityInformation<>(User2.class);
public static void main(String[] args) {
SpringApplication.run(MultiDatabaseApplication.class, args);
}
public void run(String... var1) throws Exception {
User1 database1UserGet = database1Template.findById(User1.class.getSimpleName(), user1.getId(), User1.class).block();
System.out.println(database1UserGet);
User2 database2UserGet = database2Template.findById(User2.class.getSimpleName(), user2.getId(), User2.class).block();
System.out.println(database2UserGet);
}
@PostConstruct
public void setup() {
database1Template.createContainerIfNotExists(user1Info).block();
database1Template.insert(User1.class.getSimpleName(), user1, new PartitionKey(user1.getName())).block();
database2Template.createContainerIfNotExists(user2Info).block();
database2Template.insert(User2.class.getSimpleName(), user2, new PartitionKey(user2.getName())).block();
}
@PreDestroy
} |
nope, this function is defined in `UserRepository` which will be analysis by cosmos, the same function is `this.userRepository.findById(cosmosUser.getId()).block()` | public void run(String... var1) throws Exception {
final List<CosmosUser> cosmosUsers = this.userRepository.findByEmailOrName(this.cosmosUser.getEmail(),
this.cosmosUser.getName()).collectList().block();
cosmosUsers.stream().forEach(this::insertValueToMYSQL);
CosmosUser secondaryCosmosUserGet = secondaryDatabaseTemplate.findById(CosmosUser.class.getSimpleName(), cosmosUser.getId(), CosmosUser.class);
System.out.println(secondaryCosmosUserGet);
mysqlUserRepository.findAll().forEach(System.out::println);
} | this.cosmosUser.getName()).collectList().block(); | public void run(String... var1) throws Exception {
CosmosUser cosmosUserGet = primaryDatabaseTemplate.findById(cosmosUser.getId(), cosmosUser.getClass()).block();
MysqlUser mysqlUser = new MysqlUser(cosmosUserGet.getId(), cosmosUserGet.getEmail(), cosmosUserGet.getName(), cosmosUserGet.getAddress());
mysqlUserRepository.save(mysqlUser);
mysqlUserRepository.findAll().forEach(System.out::println);
CosmosUser secondaryCosmosUserGet = secondaryDatabaseTemplate.findById(CosmosUser.class.getSimpleName(), cosmosUser.getId(), CosmosUser.class);
System.out.println(secondaryCosmosUserGet);
} | class MultiDatabaseApplication implements CommandLineRunner {
@Autowired
private UserRepository userRepository;
@Autowired
private MysqlUserRepository mysqlUserRepository;
@Autowired
@Qualifier("secondaryDatabaseTemplate")
private CosmosTemplate secondaryDatabaseTemplate;
@Autowired
@Qualifier("primaryDatabaseTemplate")
private ReactiveCosmosTemplate primaryDatabaseTemplate;
private final CosmosUser cosmosUser = new CosmosUser("1024", "1024@geek.com", "1k", "Mars");
private MysqlUser userForMYSQL;
private static CosmosEntityInformation<CosmosUser, String> userInfo = new CosmosEntityInformation<>(CosmosUser.class);
public static void main(String[] args) {
SpringApplication.run(MultiDatabaseApplication.class, args);
}
public void insertValueToMYSQL(CosmosUser cosmosUser){
userForMYSQL = new MysqlUser(cosmosUser.getId(), cosmosUser.getEmail(), cosmosUser.getName(), cosmosUser.getAddress());
mysqlUserRepository.save(userForMYSQL);
}
@PostConstruct
public void setup() {
primaryDatabaseTemplate.createContainerIfNotExists(userInfo).block();
primaryDatabaseTemplate.insert(CosmosUser.class.getSimpleName(), cosmosUser,
new PartitionKey(cosmosUser.getName())).block();
secondaryDatabaseTemplate.createContainerIfNotExists(userInfo);
secondaryDatabaseTemplate.insert(CosmosUser.class.getSimpleName(), cosmosUser, new PartitionKey(cosmosUser.getName()));
}
@PreDestroy
public void cleanup() {
primaryDatabaseTemplate.deleteAll(CosmosUser.class.getSimpleName(),
CosmosUser.class).block();
secondaryDatabaseTemplate.deleteAll(CosmosUser.class.getSimpleName() , CosmosUser.class);
mysqlUserRepository.deleteAll();
}
} | class MultiDatabaseApplication implements CommandLineRunner {
@Autowired
private CosmosUserRepository cosmosUserRepository;
@Autowired
private MysqlUserRepository mysqlUserRepository;
@Autowired
@Qualifier("secondaryDatabaseTemplate")
private CosmosTemplate secondaryDatabaseTemplate;
@Autowired
@Qualifier("primaryDatabaseTemplate")
private ReactiveCosmosTemplate primaryDatabaseTemplate;
private final CosmosUser cosmosUser = new CosmosUser("1024", "1024@geek.com", "1k", "Mars");
private static CosmosEntityInformation<CosmosUser, String> userInfo = new CosmosEntityInformation<>(CosmosUser.class);
public static void main(String[] args) {
SpringApplication.run(MultiDatabaseApplication.class, args);
}
@PostConstruct
public void setup() {
primaryDatabaseTemplate.createContainerIfNotExists(userInfo).block();
primaryDatabaseTemplate.insert(CosmosUser.class.getSimpleName(), cosmosUser, new PartitionKey(cosmosUser.getName())).block();
secondaryDatabaseTemplate.createContainerIfNotExists(userInfo);
secondaryDatabaseTemplate.insert(CosmosUser.class.getSimpleName(), cosmosUser, new PartitionKey(cosmosUser.getName()));
}
@PreDestroy
public void cleanup() {
primaryDatabaseTemplate.deleteAll(CosmosUser.class.getSimpleName(), CosmosUser.class).block();
secondaryDatabaseTemplate.deleteAll(CosmosUser.class.getSimpleName() , CosmosUser.class);
mysqlUserRepository.deleteAll();
}
} |
It's better to use `User2` here. And create `user2`, just link `user1`. | public void run(String... var1) throws Exception {
User1 database1UserGet = database1Template.findById(User1.class.getSimpleName(), user.getId(), User1.class).block();
System.out.println(database1UserGet);
User1 database2UserGet = database2Template.findById(User1.class.getSimpleName(), user.getId(), User1.class).block();
System.out.println(database2UserGet);
} | User1 database2UserGet = database2Template.findById(User1.class.getSimpleName(), user.getId(), User1.class).block(); | public void run(String... var1) throws Exception {
User1 database1UserGet = database1Template.findById(User1.class.getSimpleName(), user1.getId(), User1.class).block();
System.out.println(database1UserGet);
User2 database2UserGet = database2Template.findById(User2.class.getSimpleName(), user2.getId(), User2.class).block();
System.out.println(database2UserGet);
} | class MultiDatabaseApplication implements CommandLineRunner {
@Autowired
private UserRepository1 userRepository1;
@Autowired
@Qualifier("database1Template")
private ReactiveCosmosTemplate database1Template;
@Autowired
@Qualifier("database2Template")
private ReactiveCosmosTemplate database2Template;
private final User1 user = new User1("1024", "1024@geek.com", "1k", "Mars");
private static CosmosEntityInformation<User1, String> userInfo = new CosmosEntityInformation<>(User1.class);
public static void main(String[] args) {
SpringApplication.run(MultiDatabaseApplication.class, args);
}
@PostConstruct
public void setup() {
database1Template.createContainerIfNotExists(userInfo).block();
database1Template.insert(User1.class.getSimpleName(), user, new PartitionKey(user.getName())).block();
database2Template.createContainerIfNotExists(userInfo).block();
database2Template.insert(User1.class.getSimpleName(), user, new PartitionKey(user.getName())).block();
}
@PreDestroy
public void cleanup() {
database1Template.deleteAll(User1.class.getSimpleName(), User1.class).block();
database2Template.deleteAll(User1.class.getSimpleName(), User1.class).block();
}
} | class MultiDatabaseApplication implements CommandLineRunner {
@Autowired
private User1Repository user1Repository;
@Autowired
@Qualifier("database1Template")
private ReactiveCosmosTemplate database1Template;
@Autowired
@Qualifier("database2Template")
private ReactiveCosmosTemplate database2Template;
private final User1 user1 = new User1("1024", "1024@geek.com", "1k", "Mars");
private static CosmosEntityInformation<User1, String> user1Info = new CosmosEntityInformation<>(User1.class);
private final User2 user2 = new User2("2048", "2048@geek.com", "2k", "Mars");
private static CosmosEntityInformation<User2, String> user2Info = new CosmosEntityInformation<>(User2.class);
public static void main(String[] args) {
SpringApplication.run(MultiDatabaseApplication.class, args);
}
@PostConstruct
public void setup() {
database1Template.createContainerIfNotExists(user1Info).block();
database1Template.insert(User1.class.getSimpleName(), user1, new PartitionKey(user1.getName())).block();
database2Template.createContainerIfNotExists(user2Info).block();
database2Template.insert(User2.class.getSimpleName(), user2, new PartitionKey(user2.getName())).block();
}
@PreDestroy
public void cleanup() {
database1Template.deleteAll(User1.class.getSimpleName(), User1.class).block();
database2Template.deleteAll(User2.class.getSimpleName(), User2.class).block();
}
} |
Same here. | public void setup() {
database1Template.createContainerIfNotExists(userInfo).block();
database1Template.insert(User1.class.getSimpleName(), user, new PartitionKey(user.getName())).block();
database2Template.createContainerIfNotExists(userInfo).block();
database2Template.insert(User1.class.getSimpleName(), user, new PartitionKey(user.getName())).block();
} | database2Template.insert(User1.class.getSimpleName(), user, new PartitionKey(user.getName())).block(); | public void setup() {
database1Template.createContainerIfNotExists(user1Info).block();
database1Template.insert(User1.class.getSimpleName(), user1, new PartitionKey(user1.getName())).block();
database2Template.createContainerIfNotExists(user2Info).block();
database2Template.insert(User2.class.getSimpleName(), user2, new PartitionKey(user2.getName())).block();
} | class MultiDatabaseApplication implements CommandLineRunner {
@Autowired
private UserRepository1 userRepository1;
@Autowired
@Qualifier("database1Template")
private ReactiveCosmosTemplate database1Template;
@Autowired
@Qualifier("database2Template")
private ReactiveCosmosTemplate database2Template;
private final User1 user = new User1("1024", "1024@geek.com", "1k", "Mars");
private static CosmosEntityInformation<User1, String> userInfo = new CosmosEntityInformation<>(User1.class);
public static void main(String[] args) {
SpringApplication.run(MultiDatabaseApplication.class, args);
}
public void run(String... var1) throws Exception {
User1 database1UserGet = database1Template.findById(User1.class.getSimpleName(), user.getId(), User1.class).block();
System.out.println(database1UserGet);
User1 database2UserGet = database2Template.findById(User1.class.getSimpleName(), user.getId(), User1.class).block();
System.out.println(database2UserGet);
}
@PostConstruct
@PreDestroy
public void cleanup() {
database1Template.deleteAll(User1.class.getSimpleName(), User1.class).block();
database2Template.deleteAll(User1.class.getSimpleName(), User1.class).block();
}
} | class MultiDatabaseApplication implements CommandLineRunner {
@Autowired
private User1Repository user1Repository;
@Autowired
@Qualifier("database1Template")
private ReactiveCosmosTemplate database1Template;
@Autowired
@Qualifier("database2Template")
private ReactiveCosmosTemplate database2Template;
private final User1 user1 = new User1("1024", "1024@geek.com", "1k", "Mars");
private static CosmosEntityInformation<User1, String> user1Info = new CosmosEntityInformation<>(User1.class);
private final User2 user2 = new User2("2048", "2048@geek.com", "2k", "Mars");
private static CosmosEntityInformation<User2, String> user2Info = new CosmosEntityInformation<>(User2.class);
public static void main(String[] args) {
SpringApplication.run(MultiDatabaseApplication.class, args);
}
public void run(String... var1) throws Exception {
User1 database1UserGet = database1Template.findById(User1.class.getSimpleName(), user1.getId(), User1.class).block();
System.out.println(database1UserGet);
User2 database2UserGet = database2Template.findById(User2.class.getSimpleName(), user2.getId(), User2.class).block();
System.out.println(database2UserGet);
}
@PostConstruct
@PreDestroy
public void cleanup() {
database1Template.deleteAll(User1.class.getSimpleName(), User1.class).block();
database2Template.deleteAll(User2.class.getSimpleName(), User2.class).block();
}
} |
Same here. | public void cleanup() {
database1Template.deleteAll(User1.class.getSimpleName(), User1.class).block();
database2Template.deleteAll(User1.class.getSimpleName(), User1.class).block();
} | database2Template.deleteAll(User1.class.getSimpleName(), User1.class).block(); | public void cleanup() {
database1Template.deleteAll(User1.class.getSimpleName(), User1.class).block();
database2Template.deleteAll(User2.class.getSimpleName(), User2.class).block();
} | class MultiDatabaseApplication implements CommandLineRunner {
@Autowired
private UserRepository1 userRepository1;
@Autowired
@Qualifier("database1Template")
private ReactiveCosmosTemplate database1Template;
@Autowired
@Qualifier("database2Template")
private ReactiveCosmosTemplate database2Template;
private final User1 user = new User1("1024", "1024@geek.com", "1k", "Mars");
private static CosmosEntityInformation<User1, String> userInfo = new CosmosEntityInformation<>(User1.class);
public static void main(String[] args) {
SpringApplication.run(MultiDatabaseApplication.class, args);
}
public void run(String... var1) throws Exception {
User1 database1UserGet = database1Template.findById(User1.class.getSimpleName(), user.getId(), User1.class).block();
System.out.println(database1UserGet);
User1 database2UserGet = database2Template.findById(User1.class.getSimpleName(), user.getId(), User1.class).block();
System.out.println(database2UserGet);
}
@PostConstruct
public void setup() {
database1Template.createContainerIfNotExists(userInfo).block();
database1Template.insert(User1.class.getSimpleName(), user, new PartitionKey(user.getName())).block();
database2Template.createContainerIfNotExists(userInfo).block();
database2Template.insert(User1.class.getSimpleName(), user, new PartitionKey(user.getName())).block();
}
@PreDestroy
} | class MultiDatabaseApplication implements CommandLineRunner {
@Autowired
private User1Repository user1Repository;
@Autowired
@Qualifier("database1Template")
private ReactiveCosmosTemplate database1Template;
@Autowired
@Qualifier("database2Template")
private ReactiveCosmosTemplate database2Template;
private final User1 user1 = new User1("1024", "1024@geek.com", "1k", "Mars");
private static CosmosEntityInformation<User1, String> user1Info = new CosmosEntityInformation<>(User1.class);
private final User2 user2 = new User2("2048", "2048@geek.com", "2k", "Mars");
private static CosmosEntityInformation<User2, String> user2Info = new CosmosEntityInformation<>(User2.class);
public static void main(String[] args) {
SpringApplication.run(MultiDatabaseApplication.class, args);
}
public void run(String... var1) throws Exception {
User1 database1UserGet = database1Template.findById(User1.class.getSimpleName(), user1.getId(), User1.class).block();
System.out.println(database1UserGet);
User2 database2UserGet = database2Template.findById(User2.class.getSimpleName(), user2.getId(), User2.class).block();
System.out.println(database2UserGet);
}
@PostConstruct
public void setup() {
database1Template.createContainerIfNotExists(user1Info).block();
database1Template.insert(User1.class.getSimpleName(), user1, new PartitionKey(user1.getName())).block();
database2Template.createContainerIfNotExists(user2Info).block();
database2Template.insert(User2.class.getSimpleName(), user2, new PartitionKey(user2.getName())).block();
}
@PreDestroy
} |
Here I think will be nice to show the developer to how to check to whom the messge was sent like System.out.println(" Message sent to : " result.getTo()); | public void sendMessageToGroupWithOptions() {
SmsClient smsClient = createSmsClientUsingAzureKeyCredential();
SmsSendOptions options = new SmsSendOptions();
options.setDeliveryReportEnabled(true);
options.setTag("Tag");
Iterable<SmsSendResult> sendResults = smsClient.sendWithResponse(
"<from-phone-number>",
Arrays.asList("<to-phone-number1>", "<to-phone-number2>"),
"Hi",
options /* Optional */,
Context.NONE).getValue();
for (SmsSendResult result : sendResults) {
System.out.println("Message Id: " + result.getMessageId());
System.out.println("Send Result Successful:" + result.isSuccessful());
}
} | System.out.println("Send Result Successful:" + result.isSuccessful()); | public void sendMessageToGroupWithOptions() {
SmsClient smsClient = createSmsClientUsingAzureKeyCredential();
SmsSendOptions options = new SmsSendOptions();
options.setDeliveryReportEnabled(true);
options.setTag("Tag");
Iterable<SmsSendResult> sendResults = smsClient.sendWithResponse(
"<from-phone-number>",
Arrays.asList("<to-phone-number1>", "<to-phone-number2>"),
"Hi",
options /* Optional */,
Context.NONE).getValue();
for (SmsSendResult result : sendResults) {
System.out.println("Message Id: " + result.getMessageId());
System.out.println("Recipient Number: " + result.getTo());
System.out.println("Send Result Successful:" + result.isSuccessful());
}
} | class ReadmeSamples {
public SmsClient createSmsClientUsingAzureKeyCredential() {
String endpoint = "https:
AzureKeyCredential azureKeyCredential = new AzureKeyCredential("<access-key>");
HttpClient httpClient = new NettyAsyncHttpClientBuilder().build();
SmsClient smsClient = new SmsClientBuilder()
.endpoint(endpoint)
.credential(azureKeyCredential)
.httpClient(httpClient)
.buildClient();
return smsClient;
}
public SmsClient createSmsClientWithConnectionString() {
String connectionString = "https:
HttpClient httpClient = new NettyAsyncHttpClientBuilder().build();
SmsClient smsClient = new SmsClientBuilder()
.connectionString(connectionString)
.httpClient(httpClient)
.buildClient();
return smsClient;
}
public SmsClient createSmsClientWithAAD() {
String endpoint = "https:
HttpClient httpClient = new NettyAsyncHttpClientBuilder().build();
SmsClient smsClient = new SmsClientBuilder()
.endpoint(endpoint)
.credential(new DefaultAzureCredentialBuilder().build())
.httpClient(httpClient)
.buildClient();
return smsClient;
}
public void sendMessageToOneRecipient() {
SmsClient smsClient = createSmsClientUsingAzureKeyCredential();
SmsSendResult sendResult = smsClient.send(
"<from-phone-number>",
"<to-phone-number>",
"Hi");
System.out.println("Message Id: " + sendResult.getMessageId());
System.out.println("Send Result Successful:" + sendResult.isSuccessful());
}
/**
* Sample code for troubleshooting
*/
public void sendSMSTroubleshooting() {
SmsClient smsClient = createSmsClientUsingAzureKeyCredential();
try {
SmsSendResult sendResult = smsClient.send(
"<from-phone-number>",
"<to-phone-number>",
"Hi"
);
} catch (RuntimeException ex) {
System.out.println(ex.getMessage());
}
}
} | class ReadmeSamples {
public SmsClient createSmsClientUsingAzureKeyCredential() {
String endpoint = "https:
AzureKeyCredential azureKeyCredential = new AzureKeyCredential("<access-key>");
HttpClient httpClient = new NettyAsyncHttpClientBuilder().build();
SmsClient smsClient = new SmsClientBuilder()
.endpoint(endpoint)
.credential(azureKeyCredential)
.httpClient(httpClient)
.buildClient();
return smsClient;
}
public SmsClient createSmsClientWithConnectionString() {
String connectionString = "https:
HttpClient httpClient = new NettyAsyncHttpClientBuilder().build();
SmsClient smsClient = new SmsClientBuilder()
.connectionString(connectionString)
.httpClient(httpClient)
.buildClient();
return smsClient;
}
public SmsClient createSmsClientWithAAD() {
String endpoint = "https:
HttpClient httpClient = new NettyAsyncHttpClientBuilder().build();
SmsClient smsClient = new SmsClientBuilder()
.endpoint(endpoint)
.credential(new DefaultAzureCredentialBuilder().build())
.httpClient(httpClient)
.buildClient();
return smsClient;
}
public void sendMessageToOneRecipient() {
SmsClient smsClient = createSmsClientUsingAzureKeyCredential();
SmsSendResult sendResult = smsClient.send(
"<from-phone-number>",
"<to-phone-number>",
"Hi");
System.out.println("Message Id: " + sendResult.getMessageId());
System.out.println("Recipient Number: " + sendResult.getTo());
System.out.println("Send Result Successful:" + sendResult.isSuccessful());
}
/**
* Sample code for troubleshooting
*/
public void sendSMSTroubleshooting() {
SmsClient smsClient = createSmsClientUsingAzureKeyCredential();
try {
SmsSendResult sendResult = smsClient.send(
"<from-phone-number>",
"<to-phone-number>",
"Hi"
);
} catch (RuntimeException ex) {
System.out.println(ex.getMessage());
}
}
} |
What is this line for? | void setAndGetSessionState(MessagingEntityType entityType) {
setSender(entityType, TestUtils.USE_CASE_DEFAULT, true);
final byte[] sessionState = "Finished".getBytes(UTF_8);
final String messageId = UUID.randomUUID().toString();
final ServiceBusMessage messageToSend = getMessage(messageId, true);
sendMessage(messageToSend).block(Duration.ofSeconds(10));
setReceiver(entityType, TestUtils.USE_CASE_DEFAULT, true);
StepVerifier.create(receiver.receiveMessages()
.flatMap(message -> {
logger.info("SessionId: {}. LockToken: {}. LockedUntil: {}. Message received.",
message.getSessionId(), message.getLockToken(), message.getLockedUntil());
assertMessageEquals(message, messageId, isSessionEnabled);
messagesPending.decrementAndGet();
return receiver.abandon(message)
.then(receiver.setSessionState(sessionState))
.then(receiver.getSessionState());
}
).take(1))
.assertNext(state -> {
logger.info("State received: {}", new String(state, UTF_8));
assertArrayEquals(sessionState, state);
})
.verifyComplete();
} | .then(receiver.getSessionState()); | void setAndGetSessionState(MessagingEntityType entityType) {
setSender(entityType, TestUtils.USE_CASE_DEFAULT, true);
final byte[] sessionState = "Finished".getBytes(UTF_8);
final String messageId = UUID.randomUUID().toString();
final ServiceBusMessage messageToSend = getMessage(messageId, true);
sendMessage(messageToSend).block(Duration.ofSeconds(10));
setReceiver(entityType, TestUtils.USE_CASE_DEFAULT, true);
StepVerifier.create(receiver.receiveMessages()
.flatMap(message -> {
logger.info("SessionId: {}. LockToken: {}. LockedUntil: {}. Message received.",
message.getSessionId(), message.getLockToken(), message.getLockedUntil());
assertMessageEquals(message, messageId, isSessionEnabled);
messagesPending.decrementAndGet();
return receiver.abandon(message)
.then(receiver.setSessionState(sessionState))
.then(receiver.getSessionState());
}
).take(1))
.assertNext(state -> {
logger.info("State received: {}", new String(state, UTF_8));
assertArrayEquals(sessionState, state);
})
.verifyComplete();
} | class ServiceBusReceiverAsyncClientIntegrationTest extends IntegrationTestBase {
private final ClientLogger logger = new ClientLogger(ServiceBusReceiverAsyncClientIntegrationTest.class);
private final AtomicInteger messagesPending = new AtomicInteger();
private final boolean isSessionEnabled = false;
private ServiceBusReceiverAsyncClient receiver;
private ServiceBusSenderAsyncClient sender;
private ServiceBusSessionReceiverAsyncClient sessionReceiver;
ServiceBusReceiverAsyncClientIntegrationTest() {
super(new ClientLogger(ServiceBusReceiverAsyncClientIntegrationTest.class));
}
@Override
protected void beforeTest() {
sessionId = UUID.randomUUID().toString();
}
@Override
protected void afterTest() {
sharedBuilder = null;
try {
dispose(receiver, sender, sessionReceiver);
} catch (Exception e) {
logger.warning("Error occurred when draining queue.", e);
}
}
/**
* Verifies that we can create multiple transaction using sender and receiver.
*/
@Test
void createMultipleTransactionTest() {
setSenderAndReceiver(MessagingEntityType.QUEUE, 0, isSessionEnabled);
StepVerifier.create(receiver.createTransaction())
.assertNext(Assertions::assertNotNull)
.verifyComplete();
StepVerifier.create(receiver.createTransaction())
.assertNext(Assertions::assertNotNull)
.verifyComplete();
}
/**
* Verifies that we can create transaction and complete.
*/
@MethodSource("com.azure.messaging.servicebus.IntegrationTestBase
@ParameterizedTest
void createTransactionAndRollbackMessagesTest(MessagingEntityType entityType) {
setSender(entityType, TestUtils.USE_CASE_DEFAULT, isSessionEnabled);
final String messageId = UUID.randomUUID().toString();
final ServiceBusMessage message = getMessage(messageId, isSessionEnabled);
sendMessage(message).block(OPERATION_TIMEOUT);
setReceiver(entityType, TestUtils.USE_CASE_DEFAULT, isSessionEnabled);
AtomicReference<ServiceBusTransactionContext> transaction = new AtomicReference<>();
StepVerifier.create(receiver.createTransaction())
.assertNext(txn -> {
transaction.set(txn);
assertNotNull(transaction);
})
.verifyComplete();
StepVerifier.create(receiver.receiveMessages()
.flatMap(receivedMessage -> receiver.complete(receivedMessage).thenReturn(receivedMessage)).take(1))
.assertNext(receivedMessage -> {
assertMessageEquals(receivedMessage, messageId, isSessionEnabled);
messagesPending.decrementAndGet();
}).verifyComplete();
StepVerifier.create(receiver.rollbackTransaction(transaction.get()))
.verifyComplete();
}
/**
* Verifies that we can do following using shared connection and on non session entity. 1. create transaction 2.
* receive and settle with transactionContext. 3. commit Rollback this transaction.
*/
@ParameterizedTest
@EnumSource(DispositionStatus.class)
void transactionSendReceiveAndCommit(DispositionStatus dispositionStatus) {
final MessagingEntityType entityType = MessagingEntityType.QUEUE;
setSenderAndReceiver(entityType, TestUtils.USE_CASE_PEEK_TRANSACTION_SENDRECEIVE_AND_COMPLETE, isSessionEnabled);
final String messageId1 = UUID.randomUUID().toString();
final ServiceBusMessage message1 = getMessage(messageId1, isSessionEnabled);
final String deadLetterReason = "test reason";
sendMessage(message1).block(TIMEOUT);
AtomicReference<ServiceBusTransactionContext> transaction = new AtomicReference<>();
StepVerifier.create(receiver.createTransaction())
.assertNext(txn -> {
transaction.set(txn);
assertNotNull(transaction);
})
.verifyComplete();
assertNotNull(transaction.get());
final ServiceBusReceivedMessage receivedMessage = receiver.receiveMessages().next().block(TIMEOUT);
assertNotNull(receivedMessage);
final Mono<Void> operation;
switch (dispositionStatus) {
case COMPLETED:
operation = receiver.complete(receivedMessage, new CompleteOptions().setTransactionContext(transaction.get()));
messagesPending.decrementAndGet();
break;
case ABANDONED:
operation = receiver.abandon(receivedMessage, new AbandonOptions().setTransactionContext(transaction.get()));
break;
case SUSPENDED:
DeadLetterOptions deadLetterOptions = new DeadLetterOptions().setTransactionContext(transaction.get())
.setDeadLetterReason(deadLetterReason);
operation = receiver.deadLetter(receivedMessage, deadLetterOptions);
messagesPending.decrementAndGet();
break;
case DEFERRED:
operation = receiver.defer(receivedMessage, new DeferOptions().setTransactionContext(transaction.get()));
break;
default:
throw logger.logExceptionAsError(new IllegalArgumentException(
"Disposition status not recognized for this test case: " + dispositionStatus));
}
StepVerifier.create(operation)
.verifyComplete();
StepVerifier.create(receiver.commitTransaction(transaction.get()))
.verifyComplete();
}
/**
* Verifies that we can do following on different clients i.e. sender and receiver. 1. create transaction using
* sender 2. receive and complete with transactionContext. 3. Commit this transaction using sender.
*/
@MethodSource("com.azure.messaging.servicebus.IntegrationTestBase
@ParameterizedTest
@Disabled
void transactionReceiveCompleteCommitMixClient(MessagingEntityType entityType) {
final boolean shareConnection = true;
final boolean useCredentials = false;
final int entityIndex = 0;
this.sender = getSenderBuilder(useCredentials, entityType, entityIndex, isSessionEnabled, shareConnection)
.buildAsyncClient();
this.receiver = getReceiverBuilder(useCredentials, entityType, entityIndex, shareConnection)
.buildAsyncClient();
final String messageId = UUID.randomUUID().toString();
final ServiceBusMessage message = getMessage(messageId, isSessionEnabled);
sendMessage(message).block(TIMEOUT);
AtomicReference<ServiceBusTransactionContext> transaction = new AtomicReference<>();
StepVerifier.create(sender.createTransaction())
.assertNext(txn -> {
transaction.set(txn);
assertNotNull(transaction);
})
.verifyComplete();
assertNotNull(transaction.get());
final ServiceBusReceivedMessage receivedMessage = receiver.receiveMessages().next().block(TIMEOUT);
assertNotNull(receivedMessage);
StepVerifier.create(receiver.complete(receivedMessage, new CompleteOptions().setTransactionContext(transaction.get())))
.verifyComplete();
StepVerifier.create(sender.commitTransaction(transaction.get()))
.verifyComplete();
}
/**
* Verifies that we can send and receive two messages.
*/
@MethodSource("com.azure.messaging.servicebus.IntegrationTestBase
@ParameterizedTest
void receiveTwoMessagesAutoComplete(MessagingEntityType entityType, boolean isSessionEnabled) {
final int entityIndex = 0;
final boolean shareConnection = false;
final boolean useCredentials = false;
final Duration shortWait = Duration.ofSeconds(3);
this.sender = getSenderBuilder(useCredentials, entityType, entityIndex, isSessionEnabled, shareConnection)
.buildAsyncClient();
final String messageId = UUID.randomUUID().toString();
final ServiceBusMessage message = getMessage(messageId, isSessionEnabled);
Mono.when(sendMessage(message), sendMessage(message)).block(TIMEOUT);
if (isSessionEnabled) {
assertNotNull(sessionId, "'sessionId' should have been set.");
this.sessionReceiver = getSessionReceiverBuilder(useCredentials, entityType, entityIndex, shareConnection)
.buildAsyncClient();
this.receiver = sessionReceiver.acceptSession(sessionId).block();
} else {
this.receiver = getReceiverBuilder(useCredentials, entityType, entityIndex, shareConnection)
.buildAsyncClient();
}
StepVerifier.create(receiver.receiveMessages())
.assertNext(receivedMessage -> {
assertMessageEquals(receivedMessage, messageId, isSessionEnabled);
})
.assertNext(receivedMessage -> {
assertMessageEquals(receivedMessage, messageId, isSessionEnabled);
})
.thenAwait(shortWait)
.thenCancel()
.verify();
}
/**
* Verifies that we can send and receive a message.
*/
@MethodSource("com.azure.messaging.servicebus.IntegrationTestBase
@ParameterizedTest
void receiveMessageAutoComplete(MessagingEntityType entityType, boolean isSessionEnabled) {
final int entityIndex = 0;
final boolean shareConnection = false;
final boolean useCredentials = false;
final Duration shortWait = Duration.ofSeconds(3);
this.sender = getSenderBuilder(useCredentials, entityType, entityIndex, isSessionEnabled, shareConnection)
.buildAsyncClient();
final String messageId = UUID.randomUUID().toString();
final ServiceBusMessage message = getMessage(messageId, isSessionEnabled);
sendMessage(message).block(TIMEOUT);
if (isSessionEnabled) {
assertNotNull(sessionId, "'sessionId' should have been set.");
this.sessionReceiver = getSessionReceiverBuilder(useCredentials, entityType, entityIndex, shareConnection)
.buildAsyncClient();
this.receiver = this.sessionReceiver.acceptSession(sessionId).block();
} else {
this.receiver = getReceiverBuilder(useCredentials, entityType, entityIndex, shareConnection)
.buildAsyncClient();
}
StepVerifier.create(receiver.receiveMessages())
.assertNext(receivedMessage -> {
assertMessageEquals(receivedMessage, messageId, isSessionEnabled);
})
.thenAwait(shortWait)
.thenCancel()
.verify();
StepVerifier.create(receiver.receiveMessages())
.thenAwait(shortWait)
.thenCancel()
.verify();
}
/**
* Verifies that we can send and peek a message.
*/
@MethodSource("com.azure.messaging.servicebus.IntegrationTestBase
@ParameterizedTest
void peekMessage(MessagingEntityType entityType, boolean isSessionEnabled) {
setSender(entityType, TestUtils.USE_CASE_DEFAULT, isSessionEnabled);
final String messageId = UUID.randomUUID().toString();
final ServiceBusMessage message = getMessage(messageId, isSessionEnabled);
sendMessage(message).block(TIMEOUT);
setReceiver(entityType, TestUtils.USE_CASE_DEFAULT, isSessionEnabled);
StepVerifier.create(receiver.peekMessage())
.assertNext(receivedMessage -> assertMessageEquals(receivedMessage, messageId, isSessionEnabled))
.verifyComplete();
StepVerifier.create(receiver.receiveMessages().flatMap(receivedMessage -> receiver.complete(receivedMessage).thenReturn(receivedMessage)).take(1))
.assertNext(receivedMessage -> assertMessageEquals(receivedMessage, messageId, isSessionEnabled))
.verifyComplete();
}
/**
* Verifies that an empty entity does not error when peeking.
*/
@MethodSource("com.azure.messaging.servicebus.IntegrationTestBase
@ParameterizedTest
void peekMessageEmptyEntity(MessagingEntityType entityType, boolean isSessionEnabled) {
setReceiver(entityType, TestUtils.USE_CASE_EMPTY_ENTITY, isSessionEnabled);
final int fromSequenceNumber = 1;
StepVerifier.create(receiver.peekMessage(fromSequenceNumber))
.verifyComplete();
}
/**
* Verifies that we can schedule and receive a message.
*/
@MethodSource("com.azure.messaging.servicebus.IntegrationTestBase
@ParameterizedTest
void sendScheduledMessageAndReceive(MessagingEntityType entityType, boolean isSessionEnabled) {
setSender(entityType, TestUtils.USE_CASE_DEFAULT, isSessionEnabled);
final Duration shortDelay = Duration.ofSeconds(4);
final String messageId = UUID.randomUUID().toString();
final ServiceBusMessage message = getMessage(messageId, isSessionEnabled);
final OffsetDateTime scheduledEnqueueTime = OffsetDateTime.now().plusSeconds(2);
sender.scheduleMessage(message, scheduledEnqueueTime).block(TIMEOUT);
setReceiver(entityType, TestUtils.USE_CASE_DEFAULT, isSessionEnabled);
StepVerifier.create(Mono.delay(shortDelay).then(receiver.receiveMessages()
.flatMap(receivedMessage -> receiver.complete(receivedMessage).thenReturn(receivedMessage)).next()))
.assertNext(receivedMessage -> {
assertMessageEquals(receivedMessage, messageId, isSessionEnabled);
messagesPending.decrementAndGet();
}).verifyComplete();
}
/**
* Verifies that we can cancel a scheduled message.
*/
@MethodSource("com.azure.messaging.servicebus.IntegrationTestBase
@ParameterizedTest
void cancelScheduledMessage(MessagingEntityType entityType, boolean isSessionEnabled) {
setSender(entityType, TestUtils.USE_CASE_DEFAULT, isSessionEnabled);
final String messageId = UUID.randomUUID().toString();
final ServiceBusMessage message = getMessage(messageId, isSessionEnabled);
final OffsetDateTime scheduledEnqueueTime = OffsetDateTime.now().plusSeconds(10);
final Duration delayDuration = Duration.ofSeconds(3);
final Long sequenceNumber = sender.scheduleMessage(message, scheduledEnqueueTime).block(TIMEOUT);
logger.verbose("Scheduled the message, sequence number {}.", sequenceNumber);
assertNotNull(sequenceNumber);
Mono.delay(delayDuration)
.then(sender.cancelScheduledMessage(sequenceNumber))
.block(TIMEOUT);
messagesPending.decrementAndGet();
logger.verbose("Cancelled the scheduled message, sequence number {}.", sequenceNumber);
setReceiver(entityType, TestUtils.USE_CASE_DEFAULT, isSessionEnabled);
StepVerifier.create(receiver.receiveMessages().take(1))
.thenAwait(Duration.ofSeconds(5))
.thenCancel()
.verify();
}
/**
* Verifies that we can send and peek a message.
*/
@MethodSource("com.azure.messaging.servicebus.IntegrationTestBase
@ParameterizedTest
void peekFromSequenceNumberMessage(MessagingEntityType entityType, boolean isSessionEnabled) {
final int entityIndex = 3;
setSender(entityType, entityIndex, isSessionEnabled);
final String messageId = UUID.randomUUID().toString();
final ServiceBusMessage message = getMessage(messageId, isSessionEnabled);
sendMessage(message).block(TIMEOUT);
setReceiver(entityType, entityIndex, isSessionEnabled);
final ServiceBusReceivedMessage peekMessage = receiver.peekMessage().block(TIMEOUT);
assertNotNull(peekMessage);
final long sequenceNumber = peekMessage.getSequenceNumber();
try {
StepVerifier.create(receiver.peekMessage(sequenceNumber))
.assertNext(m -> {
assertEquals(sequenceNumber, m.getSequenceNumber());
assertMessageEquals(m, messageId, isSessionEnabled);
})
.verifyComplete();
} finally {
StepVerifier.create(receiver.receiveMessages()
.flatMap(receivedMessage -> receiver.complete(receivedMessage).thenReturn(receivedMessage)).take(1))
.expectNextCount(1)
.verifyComplete();
messagesPending.decrementAndGet();
}
}
/**
* Verifies that we can send and peek a batch of messages and the sequence number is tracked correctly.
*/
@MethodSource("com.azure.messaging.servicebus.IntegrationTestBase
@ParameterizedTest
void peekMessages(MessagingEntityType entityType, boolean isSessionEnabled) {
setSender(entityType, TestUtils.USE_CASE_PEEK_BATCH_MESSAGES, isSessionEnabled);
final BiConsumer<ServiceBusReceivedMessage, Integer> checkCorrectMessage = (message, index) -> {
final Map<String, Object> properties = message.getApplicationProperties();
final Object value = properties.get(MESSAGE_POSITION_ID);
assertTrue(value instanceof Integer, "Did not contain correct position number: " + value);
final int position = (int) value;
assertEquals(index, position);
};
final String messageId = UUID.randomUUID().toString();
final List<ServiceBusMessage> messages = TestUtils.getServiceBusMessages(10, messageId, CONTENTS_BYTES);
if (isSessionEnabled) {
messages.forEach(m -> m.setSessionId(sessionId));
}
sender.sendMessages(messages)
.doOnSuccess(aVoid -> {
int number = messagesPending.addAndGet(messages.size());
logger.info("Number of messages sent: {}", number);
})
.block(TIMEOUT);
setReceiver(entityType, TestUtils.USE_CASE_PEEK_BATCH_MESSAGES, isSessionEnabled);
try {
StepVerifier.create(receiver.peekMessages(3))
.assertNext(message -> checkCorrectMessage.accept(message, 0))
.assertNext(message -> checkCorrectMessage.accept(message, 1))
.assertNext(message -> checkCorrectMessage.accept(message, 2))
.verifyComplete();
StepVerifier.create(receiver.peekMessages(4))
.assertNext(message -> checkCorrectMessage.accept(message, 3))
.assertNext(message -> checkCorrectMessage.accept(message, 4))
.assertNext(message -> checkCorrectMessage.accept(message, 5))
.assertNext(message -> checkCorrectMessage.accept(message, 6))
.verifyComplete();
StepVerifier.create(receiver.peekMessage())
.assertNext(message -> checkCorrectMessage.accept(message, 7))
.verifyComplete();
} finally {
AtomicInteger completed = new AtomicInteger();
StepVerifier.create(receiver.receiveMessages().take(messages.size()))
.thenConsumeWhile(receivedMessage -> {
completed.incrementAndGet();
receiver.complete(receivedMessage).block(OPERATION_TIMEOUT);
return completed.get() <= messages.size();
})
.thenCancel()
.verify();
messagesPending.addAndGet(-messages.size());
}
}
/**
* Verifies that we can send and peek a batch of messages.
*/
@MethodSource("com.azure.messaging.servicebus.IntegrationTestBase
@ParameterizedTest
void peekMessagesFromSequence(MessagingEntityType entityType) {
setSenderAndReceiver(entityType, TestUtils.USE_CASE_PEEK_MESSAGE_FROM_SEQUENCE, false);
final String messageId = UUID.randomUUID().toString();
final ServiceBusMessage message = getMessage(messageId, false);
final int maxMessages = 2;
final int fromSequenceNumber = 1;
Mono.when(sendMessage(message), sendMessage(message)).block(TIMEOUT);
StepVerifier.create(receiver.peekMessages(maxMessages, fromSequenceNumber))
.expectNextCount(maxMessages)
.verifyComplete();
StepVerifier.create(receiver.receiveMessages().take(maxMessages))
.assertNext(receivedMessage -> {
receiver.complete(receivedMessage).block(Duration.ofSeconds(15));
})
.assertNext(receivedMessage -> {
receiver.complete(receivedMessage).block(Duration.ofSeconds(15));
})
.expectComplete()
.verify(TIMEOUT);
}
/**
* Verifies that an empty entity does not error when peeking.
*/
@MethodSource("com.azure.messaging.servicebus.IntegrationTestBase
@ParameterizedTest
void peekMessagesFromSequenceEmptyEntity(MessagingEntityType entityType, boolean isSessionEnabled) {
setReceiver(entityType, TestUtils.USE_CASE_EMPTY_ENTITY, isSessionEnabled);
final int maxMessages = 10;
final int fromSequenceNumber = 1;
StepVerifier.create(receiver.peekMessages(maxMessages, fromSequenceNumber))
.verifyComplete();
}
/**
* Verifies that we can dead-letter a message.
*/
@MethodSource("com.azure.messaging.servicebus.IntegrationTestBase
@ParameterizedTest
void deadLetterMessage(MessagingEntityType entityType, boolean isSessionEnabled) {
final int entityIndex = 0;
setSender(entityType, entityIndex, isSessionEnabled);
final String messageId = UUID.randomUUID().toString();
final ServiceBusMessage message = getMessage(messageId, isSessionEnabled);
sendMessage(message).block(TIMEOUT);
setReceiver(entityType, entityIndex, isSessionEnabled);
StepVerifier.create(receiver.receiveMessages()
.flatMap(receivedMessage -> receiver.deadLetter(receivedMessage).thenReturn(receivedMessage)).take(1))
.assertNext(receivedMessage -> {
assertMessageEquals(receivedMessage, messageId, isSessionEnabled);
messagesPending.decrementAndGet();
})
.thenCancel()
.verify();
}
@MethodSource("com.azure.messaging.servicebus.IntegrationTestBase
@ParameterizedTest
void receiveAndComplete(MessagingEntityType entityType, boolean isSessionEnabled) {
setSender(entityType, TestUtils.USE_CASE_DEFAULT, isSessionEnabled);
final String messageId = UUID.randomUUID().toString();
final ServiceBusMessage message = getMessage(messageId, isSessionEnabled);
sendMessage(message).block(TIMEOUT);
setReceiver(entityType, TestUtils.USE_CASE_DEFAULT, isSessionEnabled);
StepVerifier.create(receiver.receiveMessages()
.flatMap(receivedMessage -> receiver.complete(receivedMessage).thenReturn(receivedMessage)).take(1))
.assertNext(receivedMessage -> {
assertMessageEquals(receivedMessage, messageId, isSessionEnabled);
messagesPending.decrementAndGet();
}).verifyComplete();
messagesPending.decrementAndGet();
}
/**
* Verifies that we can renew message lock on a non-session receiver.
*/
@MethodSource("com.azure.messaging.servicebus.IntegrationTestBase
@ParameterizedTest
void receiveAndRenewLock(MessagingEntityType entityType) {
setSender(entityType, TestUtils.USE_CASE_DEFAULT, false);
final String messageId = UUID.randomUUID().toString();
final ServiceBusMessage message = getMessage(messageId, false);
sendMessage(message).block(TIMEOUT);
setReceiver(entityType, TestUtils.USE_CASE_DEFAULT, false);
final ServiceBusReceivedMessage receivedMessage = receiver.receiveMessages().next().block(TIMEOUT);
assertNotNull(receivedMessage);
assertNotNull(receivedMessage.getLockedUntil());
final OffsetDateTime initialLock = receivedMessage.getLockedUntil();
logger.info("Received message. Seq: {}. lockedUntil: {}", receivedMessage.getSequenceNumber(), initialLock);
try {
StepVerifier.create(Mono.delay(Duration.ofSeconds(7))
.then(Mono.defer(() -> receiver.renewMessageLock(receivedMessage))))
.assertNext(lockedUntil -> {
assertTrue(lockedUntil.isAfter(initialLock),
String.format("Updated lock is not after the initial Lock. updated: [%s]. initial:[%s]",
lockedUntil, initialLock));
})
.verifyComplete();
} finally {
logger.info("Completing message. Seq: {}.", receivedMessage.getSequenceNumber());
receiver.complete(receivedMessage)
.doOnSuccess(aVoid -> messagesPending.decrementAndGet())
.block(TIMEOUT);
}
}
/**
* Verifies that the lock can be automatically renewed.
*/
@MethodSource("com.azure.messaging.servicebus.IntegrationTestBase
@ParameterizedTest
void autoRenewLockOnReceiveMessage(MessagingEntityType entityType, boolean isSessionEnabled) {
final AtomicInteger lockRenewCount = new AtomicInteger();
setSender(entityType, TestUtils.USE_CASE_DEFAULT, isSessionEnabled);
final String messageId = UUID.randomUUID().toString();
final ServiceBusMessage message = getMessage(messageId, isSessionEnabled);
sendMessage(message).block(TIMEOUT);
setReceiver(entityType, TestUtils.USE_CASE_DEFAULT, isSessionEnabled);
StepVerifier.create(receiver.receiveMessages().flatMap(received -> {
logger.info("{}: lockToken[{}]. lockedUntil[{}]. now[{}]", received.getSequenceNumber(),
received.getLockToken(), received.getLockedUntil(), OffsetDateTime.now());
while (lockRenewCount.get() < 4) {
lockRenewCount.incrementAndGet();
logger.info("Iteration {}: Curren time {}.", lockRenewCount.get(), OffsetDateTime.now());
try {
TimeUnit.SECONDS.sleep(5);
} catch (InterruptedException error) {
logger.error("Error occurred while sleeping: " + error);
}
}
return receiver.complete(received).thenReturn(received);
}))
.assertNext(received -> {
assertTrue(lockRenewCount.get() > 0);
messagesPending.decrementAndGet();
})
.thenCancel()
.verify();
}
@MethodSource("com.azure.messaging.servicebus.IntegrationTestBase
@ParameterizedTest
void receiveAndAbandon(MessagingEntityType entityType, boolean isSessionEnabled) {
setSender(entityType, TestUtils.USE_CASE_DEFAULT, isSessionEnabled);
final String messageId = UUID.randomUUID().toString();
final ServiceBusMessage message = getMessage(messageId, isSessionEnabled);
sendMessage(message).block(TIMEOUT);
setReceiver(entityType, TestUtils.USE_CASE_DEFAULT, isSessionEnabled);
StepVerifier.create(receiver.receiveMessages()
.flatMap(receivedMessage -> receiver.abandon(receivedMessage).thenReturn(receivedMessage)).take(1))
.assertNext(receivedMessage -> assertMessageEquals(receivedMessage, messageId, isSessionEnabled))
.expectComplete();
}
@MethodSource("com.azure.messaging.servicebus.IntegrationTestBase
@ParameterizedTest
void receiveAndDefer(MessagingEntityType entityType, boolean isSessionEnabled) {
setSender(entityType, TestUtils.USE_CASE_PEEK_RECEIVE_AND_DEFER, isSessionEnabled);
final String messageId = UUID.randomUUID().toString();
final ServiceBusMessage message = getMessage(messageId, isSessionEnabled);
sendMessage(message).block(TIMEOUT);
setReceiver(entityType, TestUtils.USE_CASE_PEEK_RECEIVE_AND_DEFER, isSessionEnabled);
AtomicReference<ServiceBusReceivedMessage> received = new AtomicReference<>();
StepVerifier.create(receiver.receiveMessages()
.flatMap(receivedMessage -> receiver.defer(receivedMessage).thenReturn(receivedMessage)).take(1))
.assertNext(m -> {
received.set(m);
assertMessageEquals(m, messageId, isSessionEnabled);
messagesPending.decrementAndGet();
}).verifyComplete();
/*receiver.receiveDeferredMessage(received.get().getSequenceNumber())
.flatMap(m -> receiver.complete(m))
.block(TIMEOUT);
messagesPending.decrementAndGet();
*/
}
/**
* Test we can receive a deferred message via sequence number and then perform abandon, suspend, or complete on it.
*/
@MethodSource("com.azure.messaging.servicebus.IntegrationTestBase
@ParameterizedTest
void receiveDeferredMessageBySequenceNumber(MessagingEntityType entityType, DispositionStatus dispositionStatus) {
setSenderAndReceiver(entityType, TestUtils.USE_CASE_DEFERRED_MESSAGE_BY_SEQUENCE_NUMBER, false);
final String messageId = UUID.randomUUID().toString();
final ServiceBusMessage message = getMessage(messageId, false);
sendMessage(message).block(TIMEOUT);
final ServiceBusReceivedMessage receivedMessage = receiver.receiveMessages().next().block(TIMEOUT);
assertNotNull(receivedMessage);
receiver.defer(receivedMessage).block(TIMEOUT);
final ServiceBusReceivedMessage receivedDeferredMessage = receiver
.receiveDeferredMessage(receivedMessage.getSequenceNumber())
.block(TIMEOUT);
assertNotNull(receivedDeferredMessage);
assertEquals(receivedMessage.getSequenceNumber(), receivedDeferredMessage.getSequenceNumber());
final Mono<Void> operation;
switch (dispositionStatus) {
case ABANDONED:
operation = receiver.abandon(receivedDeferredMessage);
break;
case SUSPENDED:
operation = receiver.deadLetter(receivedDeferredMessage);
break;
case COMPLETED:
operation = receiver.complete(receivedDeferredMessage);
break;
default:
throw logger.logExceptionAsError(new IllegalArgumentException(
"Disposition status not recognized for this test case: " + dispositionStatus));
}
StepVerifier.create(operation)
.expectComplete()
.verify();
if (dispositionStatus != DispositionStatus.COMPLETED) {
messagesPending.decrementAndGet();
}
}
@MethodSource("com.azure.messaging.servicebus.IntegrationTestBase
@ParameterizedTest
void sendReceiveMessageWithVariousPropertyTypes(MessagingEntityType entityType) {
final boolean isSessionEnabled = true;
setSender(entityType, TestUtils.USE_CASE_SEND_RECEIVE_WITH_PROPERTIES, isSessionEnabled);
final String messageId = UUID.randomUUID().toString();
final ServiceBusMessage messageToSend = getMessage(messageId, isSessionEnabled);
Map<String, Object> sentProperties = messageToSend.getApplicationProperties();
sentProperties.put("NullProperty", null);
sentProperties.put("BooleanProperty", true);
sentProperties.put("ByteProperty", (byte) 1);
sentProperties.put("ShortProperty", (short) 2);
sentProperties.put("IntProperty", 3);
sentProperties.put("LongProperty", 4L);
sentProperties.put("FloatProperty", 5.5f);
sentProperties.put("DoubleProperty", 6.6f);
sentProperties.put("CharProperty", 'z');
sentProperties.put("UUIDProperty", UUID.fromString("38400000-8cf0-11bd-b23e-10b96e4ef00d"));
sentProperties.put("StringProperty", "string");
sendMessage(messageToSend).block(TIMEOUT);
setReceiver(entityType, TestUtils.USE_CASE_SEND_RECEIVE_WITH_PROPERTIES, isSessionEnabled);
StepVerifier.create(receiver.receiveMessages().flatMap(receivedMessage -> receiver.complete(receivedMessage).thenReturn(receivedMessage)).take(1))
.assertNext(receivedMessage -> {
messagesPending.decrementAndGet();
assertMessageEquals(receivedMessage, messageId, isSessionEnabled);
final Map<String, Object> received = receivedMessage.getApplicationProperties();
assertEquals(sentProperties.size(), received.size());
for (Map.Entry<String, Object> sentEntry : sentProperties.entrySet()) {
if (sentEntry.getValue() != null && sentEntry.getValue().getClass().isArray()) {
assertArrayEquals((Object[]) sentEntry.getValue(), (Object[]) received.get(sentEntry.getKey()));
} else {
final Object expected = sentEntry.getValue();
final Object actual = received.get(sentEntry.getKey());
assertEquals(expected, actual, String.format(
"Key '%s' does not match. Expected: '%s'. Actual: '%s'", sentEntry.getKey(), expected,
actual));
}
}
})
.thenCancel()
.verify();
}
@MethodSource("com.azure.messaging.servicebus.IntegrationTestBase
@ParameterizedTest
/**
* Verifies that we can receive a message from dead letter queue.
*/
@MethodSource("com.azure.messaging.servicebus.IntegrationTestBase
@ParameterizedTest
void receiveFromDeadLetter(MessagingEntityType entityType) {
final Duration shortWait = Duration.ofSeconds(2);
final boolean isSessionEnabled = false;
final int entityIndex = 0;
setSender(entityType, entityIndex, isSessionEnabled);
final String messageId = UUID.randomUUID().toString();
final ServiceBusMessage message = getMessage(messageId, isSessionEnabled);
final List<ServiceBusReceivedMessage> receivedMessages = new ArrayList<>();
sendMessage(message).block(TIMEOUT);
setReceiver(entityType, entityIndex, isSessionEnabled);
StepVerifier.create(receiver.receiveMessages().flatMap(receivedMessage -> receiver.deadLetter(receivedMessage).thenReturn(receivedMessage)).take(1))
.assertNext(receivedMessage -> {
assertMessageEquals(receivedMessage, messageId, isSessionEnabled);
messagesPending.decrementAndGet();
}).verifyComplete();
final ServiceBusReceiverAsyncClient deadLetterReceiver;
switch (entityType) {
case QUEUE:
final String queueName = getQueueName(entityIndex);
assertNotNull(queueName, "'queueName' cannot be null.");
deadLetterReceiver = getBuilder(false).receiver()
.queueName(queueName)
.subQueue(SubQueue.DEAD_LETTER_QUEUE)
.buildAsyncClient();
break;
case SUBSCRIPTION:
final String topicName = getTopicName(entityIndex);
final String subscriptionName = getSubscriptionBaseName();
assertNotNull(topicName, "'topicName' cannot be null.");
assertNotNull(subscriptionName, "'subscriptionName' cannot be null.");
deadLetterReceiver = getBuilder(false).receiver()
.topicName(topicName)
.subscriptionName(subscriptionName)
.subQueue(SubQueue.DEAD_LETTER_QUEUE)
.buildAsyncClient();
break;
default:
throw logger.logExceptionAsError(new IllegalArgumentException("Unknown entity type: " + entityType));
}
try {
StepVerifier.create(deadLetterReceiver.receiveMessages())
.assertNext(serviceBusReceivedMessage -> {
receivedMessages.add(serviceBusReceivedMessage);
assertMessageEquals(serviceBusReceivedMessage, messageId, isSessionEnabled);
})
.thenAwait(shortWait)
.thenCancel()
.verify();
} finally {
deadLetterReceiver.close();
}
}
@MethodSource("com.azure.messaging.servicebus.IntegrationTestBase
@ParameterizedTest
void renewMessageLock(MessagingEntityType entityType) {
final boolean isSessionEnabled = false;
setSenderAndReceiver(entityType, TestUtils.USE_CASE_DEFAULT, isSessionEnabled);
final Duration maximumDuration = Duration.ofSeconds(35);
final Duration sleepDuration = maximumDuration.plusMillis(500);
final String messageId = UUID.randomUUID().toString();
final ServiceBusMessage message = getMessage(messageId, isSessionEnabled);
final ServiceBusReceivedMessage receivedMessage = sendMessage(message)
.then(receiver.receiveMessages().next())
.block(TIMEOUT);
assertNotNull(receivedMessage);
final OffsetDateTime lockedUntil = receivedMessage.getLockedUntil();
assertNotNull(lockedUntil);
StepVerifier.create(receiver.renewMessageLock(receivedMessage, maximumDuration))
.thenAwait(sleepDuration)
.then(() -> {
logger.info("Completing message.");
int numberCompleted = completeMessages(receiver, Collections.singletonList(receivedMessage));
messagesPending.addAndGet(-numberCompleted);
})
.expectComplete()
.verify(Duration.ofMinutes(3));
}
/**
* Verifies that we can receive a message which have different section set (i.e header, footer, annotations,
* application properties etc).
*/
@MethodSource("com.azure.messaging.servicebus.IntegrationTestBase
@ParameterizedTest
void receiveAndValidateProperties(MessagingEntityType entityType) {
final boolean isSessionEnabled = false;
final int totalMessages = 1;
final String subject = "subject";
final Map<String, Object> footer = new HashMap<>();
footer.put("footer-key-1", "footer-value-1");
footer.put("footer-key-2", "footer-value-2");
final Map<String, Object> applicationProperties = new HashMap<>();
applicationProperties.put("ap-key-1", "ap-value-1");
applicationProperties.put("ap-key-2", "ap-value-2");
final Map<String, Object> deliveryAnnotation = new HashMap<>();
deliveryAnnotation.put("delivery-annotations-key-1", "delivery-annotations-value-1");
deliveryAnnotation.put("delivery-annotations-key-2", "delivery-annotations-value-2");
final String messageId = UUID.randomUUID().toString();
final AmqpAnnotatedMessage expectedAmqpProperties = new AmqpAnnotatedMessage(
AmqpMessageBody.fromData(CONTENTS_BYTES));
expectedAmqpProperties.getProperties().setSubject(subject);
expectedAmqpProperties.getProperties().setReplyToGroupId("r-gid");
expectedAmqpProperties.getProperties().setReplyTo(new AmqpAddress("reply-to"));
expectedAmqpProperties.getProperties().setContentType("content-type");
expectedAmqpProperties.getProperties().setCorrelationId(new AmqpMessageId("correlation-id"));
expectedAmqpProperties.getProperties().setTo(new AmqpAddress("to"));
expectedAmqpProperties.getProperties().setAbsoluteExpiryTime(OffsetDateTime.now().plusSeconds(60));
expectedAmqpProperties.getProperties().setUserId("user-id-1".getBytes());
expectedAmqpProperties.getProperties().setContentEncoding("string");
expectedAmqpProperties.getProperties().setGroupSequence(2L);
expectedAmqpProperties.getProperties().setCreationTime(OffsetDateTime.now().plusSeconds(30));
expectedAmqpProperties.getHeader().setPriority((short) 2);
expectedAmqpProperties.getHeader().setFirstAcquirer(true);
expectedAmqpProperties.getHeader().setDurable(true);
expectedAmqpProperties.getFooter().putAll(footer);
expectedAmqpProperties.getDeliveryAnnotations().putAll(deliveryAnnotation);
expectedAmqpProperties.getApplicationProperties().putAll(applicationProperties);
final ServiceBusMessage message = TestUtils.getServiceBusMessage(CONTENTS_BYTES, messageId);
final AmqpAnnotatedMessage amqpAnnotatedMessage = message.getRawAmqpMessage();
amqpAnnotatedMessage.getMessageAnnotations().putAll(expectedAmqpProperties.getMessageAnnotations());
amqpAnnotatedMessage.getApplicationProperties().putAll(expectedAmqpProperties.getApplicationProperties());
amqpAnnotatedMessage.getDeliveryAnnotations().putAll(expectedAmqpProperties.getDeliveryAnnotations());
amqpAnnotatedMessage.getFooter().putAll(expectedAmqpProperties.getFooter());
final AmqpMessageHeader header = amqpAnnotatedMessage.getHeader();
header.setFirstAcquirer(expectedAmqpProperties.getHeader().isFirstAcquirer());
header.setTimeToLive(expectedAmqpProperties.getHeader().getTimeToLive());
header.setDurable(expectedAmqpProperties.getHeader().isDurable());
header.setDeliveryCount(expectedAmqpProperties.getHeader().getDeliveryCount());
header.setPriority(expectedAmqpProperties.getHeader().getPriority());
final AmqpMessageProperties amqpMessageProperties = amqpAnnotatedMessage.getProperties();
amqpMessageProperties.setReplyTo((expectedAmqpProperties.getProperties().getReplyTo()));
amqpMessageProperties.setContentEncoding((expectedAmqpProperties.getProperties().getContentEncoding()));
amqpMessageProperties.setAbsoluteExpiryTime((expectedAmqpProperties.getProperties().getAbsoluteExpiryTime()));
amqpMessageProperties.setSubject((expectedAmqpProperties.getProperties().getSubject()));
amqpMessageProperties.setContentType(expectedAmqpProperties.getProperties().getContentType());
amqpMessageProperties.setCorrelationId(expectedAmqpProperties.getProperties().getCorrelationId());
amqpMessageProperties.setTo(expectedAmqpProperties.getProperties().getTo());
amqpMessageProperties.setGroupSequence(expectedAmqpProperties.getProperties().getGroupSequence());
amqpMessageProperties.setUserId(expectedAmqpProperties.getProperties().getUserId());
amqpMessageProperties.setAbsoluteExpiryTime(expectedAmqpProperties.getProperties().getAbsoluteExpiryTime());
amqpMessageProperties.setCreationTime(expectedAmqpProperties.getProperties().getCreationTime());
amqpMessageProperties.setReplyToGroupId(expectedAmqpProperties.getProperties().getReplyToGroupId());
setSender(entityType, TestUtils.USE_CASE_VALIDATE_AMQP_PROPERTIES, isSessionEnabled);
sendMessage(message).block(TIMEOUT);
setReceiver(entityType, TestUtils.USE_CASE_VALIDATE_AMQP_PROPERTIES, isSessionEnabled);
StepVerifier.create(receiver.receiveMessages()/*.take(totalMessages)*/)
.assertNext(received -> {
assertNotNull(received.getLockToken());
AmqpAnnotatedMessage actual = received.getRawAmqpMessage();
try {
assertArrayEquals(CONTENTS_BYTES, message.getBody().toBytes());
assertEquals(expectedAmqpProperties.getHeader().getPriority(), actual.getHeader().getPriority());
assertEquals(expectedAmqpProperties.getHeader().isFirstAcquirer(), actual.getHeader().isFirstAcquirer());
assertEquals(expectedAmqpProperties.getHeader().isDurable(), actual.getHeader().isDurable());
assertEquals(expectedAmqpProperties.getProperties().getSubject(), actual.getProperties().getSubject());
assertEquals(expectedAmqpProperties.getProperties().getReplyToGroupId(), actual.getProperties().getReplyToGroupId());
assertEquals(expectedAmqpProperties.getProperties().getReplyTo(), actual.getProperties().getReplyTo());
assertEquals(expectedAmqpProperties.getProperties().getContentType(), actual.getProperties().getContentType());
assertEquals(expectedAmqpProperties.getProperties().getCorrelationId(), actual.getProperties().getCorrelationId());
assertEquals(expectedAmqpProperties.getProperties().getTo(), actual.getProperties().getTo());
assertEquals(expectedAmqpProperties.getProperties().getAbsoluteExpiryTime().toEpochSecond(), actual.getProperties().getAbsoluteExpiryTime().toEpochSecond());
assertEquals(expectedAmqpProperties.getProperties().getSubject(), actual.getProperties().getSubject());
assertEquals(expectedAmqpProperties.getProperties().getContentEncoding(), actual.getProperties().getContentEncoding());
assertEquals(expectedAmqpProperties.getProperties().getGroupSequence(), actual.getProperties().getGroupSequence());
assertEquals(expectedAmqpProperties.getProperties().getCreationTime().toEpochSecond(), actual.getProperties().getCreationTime().toEpochSecond());
assertArrayEquals(expectedAmqpProperties.getProperties().getUserId(), actual.getProperties().getUserId());
assertMapValues(expectedAmqpProperties.getDeliveryAnnotations(), actual.getDeliveryAnnotations());
assertMapValues(expectedAmqpProperties.getMessageAnnotations(), actual.getMessageAnnotations());
assertMapValues(expectedAmqpProperties.getApplicationProperties(), actual.getApplicationProperties());
assertMapValues(expectedAmqpProperties.getFooter(), actual.getFooter());
} finally {
logger.info("Completing message.");
receiver.complete(received).block(Duration.ofSeconds(15));
messagesPending.decrementAndGet();
}
})
.thenCancel()
.verify(Duration.ofMinutes(2));
}
/**
* Verifies we can autocomplete for a queue.
*
* @param entityType Entity Type.
*/
@MethodSource("com.azure.messaging.servicebus.IntegrationTestBase
@ParameterizedTest
void autoComplete(MessagingEntityType entityType) {
final Duration shortWait = Duration.ofSeconds(2);
final int index = TestUtils.USE_CASE_AUTO_COMPLETE;
setSender(entityType, index, false);
final int numberOfEvents = 3;
final String messageId = UUID.randomUUID().toString();
final List<ServiceBusMessage> messages = getServiceBusMessages(numberOfEvents, messageId);
setReceiver(entityType, index, false);
final ServiceBusReceivedMessage lastMessage = receiver.peekMessage().block(TIMEOUT);
Mono.when(messages.stream().map(this::sendMessage)
.collect(Collectors.toList()))
.block(TIMEOUT);
final ServiceBusReceiverAsyncClient autoCompleteReceiver =
getReceiverBuilder(false, entityType, index, false)
.buildAsyncClient();
try {
StepVerifier.create(autoCompleteReceiver.receiveMessages())
.assertNext(receivedMessage -> {
if (lastMessage != null) {
assertEquals(lastMessage.getMessageId(), receivedMessage.getMessageId());
} else {
assertEquals(messageId, receivedMessage.getMessageId());
}
})
.assertNext(context -> {
if (lastMessage == null) {
assertEquals(messageId, context.getMessageId());
}
})
.assertNext(context -> {
if (lastMessage == null) {
assertEquals(messageId, context.getMessageId());
}
})
.thenAwait(shortWait)
.thenCancel()
.verify(TIMEOUT);
} finally {
autoCompleteReceiver.close();
}
final ServiceBusReceivedMessage newLastMessage = receiver.peekMessage().block(TIMEOUT);
if (lastMessage == null) {
assertNull(newLastMessage,
String.format("Actual messageId[%s]", newLastMessage != null ? newLastMessage.getMessageId() : "n/a"));
} else {
assertNotNull(newLastMessage);
assertEquals(lastMessage.getSequenceNumber(), newLastMessage.getSequenceNumber());
}
}
/**
* Asserts the length and values with in the map.
*/
private void assertMapValues(Map<String, Object> expectedMap, Map<String, Object> actualMap) {
assertTrue(actualMap.size() >= expectedMap.size());
for (String key : expectedMap.keySet()) {
assertEquals(expectedMap.get(key), actualMap.get(key), "Value is not equal for Key " + key);
}
}
/**
* Sets the sender and receiver. If session is enabled, then a single-named session receiver is created.
*/
private void setSenderAndReceiver(MessagingEntityType entityType, int entityIndex, boolean isSessionEnabled) {
setSender(entityType, entityIndex, isSessionEnabled);
setReceiver(entityType, entityIndex, isSessionEnabled);
}
private void setReceiver(MessagingEntityType entityType, int entityIndex, boolean isSessionEnabled) {
final boolean shareConnection = false;
final boolean useCredentials = false;
if (isSessionEnabled) {
assertNotNull(sessionId, "'sessionId' should have been set.");
sessionReceiver = getSessionReceiverBuilder(useCredentials, entityType, entityIndex, shareConnection)
.disableAutoComplete()
.buildAsyncClient();
this.receiver = sessionReceiver.acceptSession(sessionId).block();
} else {
this.receiver = getReceiverBuilder(useCredentials, entityType, entityIndex, shareConnection)
.disableAutoComplete()
.buildAsyncClient();
}
}
private void setSender(MessagingEntityType entityType, int entityIndex, boolean isSessionEnabled) {
final boolean shareConnection = false;
final boolean useCredentials = false;
this.sender = getSenderBuilder(useCredentials, entityType, entityIndex, isSessionEnabled, shareConnection)
.buildAsyncClient();
}
private Mono<Void> sendMessage(ServiceBusMessage message) {
return sender.sendMessage(message).doOnSuccess(aVoid -> {
int number = messagesPending.incrementAndGet();
logger.info("Message Id {}. Number sent: {}", message.getMessageId(), number);
});
}
private int completeMessages(ServiceBusReceiverAsyncClient client, List<ServiceBusReceivedMessage> messages) {
Mono.when(messages.stream().map(e -> client.complete(e))
.collect(Collectors.toList()))
.block(TIMEOUT);
return messages.size();
}
} | class ServiceBusReceiverAsyncClientIntegrationTest extends IntegrationTestBase {
private final ClientLogger logger = new ClientLogger(ServiceBusReceiverAsyncClientIntegrationTest.class);
private final AtomicInteger messagesPending = new AtomicInteger();
private final boolean isSessionEnabled = false;
private ServiceBusReceiverAsyncClient receiver;
private ServiceBusSenderAsyncClient sender;
private ServiceBusSessionReceiverAsyncClient sessionReceiver;
ServiceBusReceiverAsyncClientIntegrationTest() {
super(new ClientLogger(ServiceBusReceiverAsyncClientIntegrationTest.class));
}
@Override
protected void beforeTest() {
sessionId = UUID.randomUUID().toString();
}
@Override
protected void afterTest() {
sharedBuilder = null;
try {
dispose(receiver, sender, sessionReceiver);
} catch (Exception e) {
logger.warning("Error occurred when draining queue.", e);
}
}
/**
* Verifies that we can create multiple transaction using sender and receiver.
*/
@Test
void createMultipleTransactionTest() {
setSenderAndReceiver(MessagingEntityType.QUEUE, 0, isSessionEnabled);
StepVerifier.create(receiver.createTransaction())
.assertNext(Assertions::assertNotNull)
.verifyComplete();
StepVerifier.create(receiver.createTransaction())
.assertNext(Assertions::assertNotNull)
.verifyComplete();
}
/**
* Verifies that we can create transaction and complete.
*/
@MethodSource("com.azure.messaging.servicebus.IntegrationTestBase
@ParameterizedTest
void createTransactionAndRollbackMessagesTest(MessagingEntityType entityType) {
setSender(entityType, TestUtils.USE_CASE_DEFAULT, isSessionEnabled);
final String messageId = UUID.randomUUID().toString();
final ServiceBusMessage message = getMessage(messageId, isSessionEnabled);
sendMessage(message).block(OPERATION_TIMEOUT);
setReceiver(entityType, TestUtils.USE_CASE_DEFAULT, isSessionEnabled);
AtomicReference<ServiceBusTransactionContext> transaction = new AtomicReference<>();
StepVerifier.create(receiver.createTransaction())
.assertNext(txn -> {
transaction.set(txn);
assertNotNull(transaction);
})
.verifyComplete();
StepVerifier.create(receiver.receiveMessages()
.flatMap(receivedMessage -> receiver.complete(receivedMessage).thenReturn(receivedMessage)).take(1))
.assertNext(receivedMessage -> {
assertMessageEquals(receivedMessage, messageId, isSessionEnabled);
messagesPending.decrementAndGet();
}).verifyComplete();
StepVerifier.create(receiver.rollbackTransaction(transaction.get()))
.verifyComplete();
}
/**
* Verifies that we can do following using shared connection and on non session entity. 1. create transaction 2.
* receive and settle with transactionContext. 3. commit Rollback this transaction.
*/
@ParameterizedTest
@EnumSource(DispositionStatus.class)
void transactionSendReceiveAndCommit(DispositionStatus dispositionStatus) {
final MessagingEntityType entityType = MessagingEntityType.QUEUE;
setSenderAndReceiver(entityType, TestUtils.USE_CASE_PEEK_TRANSACTION_SENDRECEIVE_AND_COMPLETE, isSessionEnabled);
final String messageId1 = UUID.randomUUID().toString();
final ServiceBusMessage message1 = getMessage(messageId1, isSessionEnabled);
final String deadLetterReason = "test reason";
sendMessage(message1).block(TIMEOUT);
AtomicReference<ServiceBusTransactionContext> transaction = new AtomicReference<>();
StepVerifier.create(receiver.createTransaction())
.assertNext(txn -> {
transaction.set(txn);
assertNotNull(transaction);
})
.verifyComplete();
assertNotNull(transaction.get());
final ServiceBusReceivedMessage receivedMessage = receiver.receiveMessages().next().block(TIMEOUT);
assertNotNull(receivedMessage);
final Mono<Void> operation;
switch (dispositionStatus) {
case COMPLETED:
operation = receiver.complete(receivedMessage, new CompleteOptions().setTransactionContext(transaction.get()));
messagesPending.decrementAndGet();
break;
case ABANDONED:
operation = receiver.abandon(receivedMessage, new AbandonOptions().setTransactionContext(transaction.get()));
break;
case SUSPENDED:
DeadLetterOptions deadLetterOptions = new DeadLetterOptions().setTransactionContext(transaction.get())
.setDeadLetterReason(deadLetterReason);
operation = receiver.deadLetter(receivedMessage, deadLetterOptions);
messagesPending.decrementAndGet();
break;
case DEFERRED:
operation = receiver.defer(receivedMessage, new DeferOptions().setTransactionContext(transaction.get()));
break;
default:
throw logger.logExceptionAsError(new IllegalArgumentException(
"Disposition status not recognized for this test case: " + dispositionStatus));
}
StepVerifier.create(operation)
.verifyComplete();
StepVerifier.create(receiver.commitTransaction(transaction.get()))
.verifyComplete();
}
/**
* Verifies that we can do following on different clients i.e. sender and receiver. 1. create transaction using
* sender 2. receive and complete with transactionContext. 3. Commit this transaction using sender.
*/
@MethodSource("com.azure.messaging.servicebus.IntegrationTestBase
@ParameterizedTest
@Disabled
void transactionReceiveCompleteCommitMixClient(MessagingEntityType entityType) {
final boolean shareConnection = true;
final boolean useCredentials = false;
final int entityIndex = 0;
this.sender = getSenderBuilder(useCredentials, entityType, entityIndex, isSessionEnabled, shareConnection)
.buildAsyncClient();
this.receiver = getReceiverBuilder(useCredentials, entityType, entityIndex, shareConnection)
.buildAsyncClient();
final String messageId = UUID.randomUUID().toString();
final ServiceBusMessage message = getMessage(messageId, isSessionEnabled);
sendMessage(message).block(TIMEOUT);
AtomicReference<ServiceBusTransactionContext> transaction = new AtomicReference<>();
StepVerifier.create(sender.createTransaction())
.assertNext(txn -> {
transaction.set(txn);
assertNotNull(transaction);
})
.verifyComplete();
assertNotNull(transaction.get());
final ServiceBusReceivedMessage receivedMessage = receiver.receiveMessages().next().block(TIMEOUT);
assertNotNull(receivedMessage);
StepVerifier.create(receiver.complete(receivedMessage, new CompleteOptions().setTransactionContext(transaction.get())))
.verifyComplete();
StepVerifier.create(sender.commitTransaction(transaction.get()))
.verifyComplete();
}
/**
* Verifies that we can send and receive two messages.
*/
@MethodSource("com.azure.messaging.servicebus.IntegrationTestBase
@ParameterizedTest
void receiveTwoMessagesAutoComplete(MessagingEntityType entityType, boolean isSessionEnabled) {
final int entityIndex = 0;
final boolean shareConnection = false;
final boolean useCredentials = false;
final Duration shortWait = Duration.ofSeconds(3);
this.sender = getSenderBuilder(useCredentials, entityType, entityIndex, isSessionEnabled, shareConnection)
.buildAsyncClient();
final String messageId = UUID.randomUUID().toString();
final ServiceBusMessage message = getMessage(messageId, isSessionEnabled);
Mono.when(sendMessage(message), sendMessage(message)).block(TIMEOUT);
if (isSessionEnabled) {
assertNotNull(sessionId, "'sessionId' should have been set.");
this.sessionReceiver = getSessionReceiverBuilder(useCredentials, entityType, entityIndex, shareConnection)
.buildAsyncClient();
this.receiver = sessionReceiver.acceptSession(sessionId).block();
} else {
this.receiver = getReceiverBuilder(useCredentials, entityType, entityIndex, shareConnection)
.buildAsyncClient();
}
StepVerifier.create(receiver.receiveMessages())
.assertNext(receivedMessage -> {
assertMessageEquals(receivedMessage, messageId, isSessionEnabled);
})
.assertNext(receivedMessage -> {
assertMessageEquals(receivedMessage, messageId, isSessionEnabled);
})
.thenAwait(shortWait)
.thenCancel()
.verify();
}
/**
* Verifies that we can send and receive a message.
*/
@MethodSource("com.azure.messaging.servicebus.IntegrationTestBase
@ParameterizedTest
void receiveMessageAutoComplete(MessagingEntityType entityType, boolean isSessionEnabled) {
final int entityIndex = 0;
final boolean shareConnection = false;
final boolean useCredentials = false;
final Duration shortWait = Duration.ofSeconds(3);
this.sender = getSenderBuilder(useCredentials, entityType, entityIndex, isSessionEnabled, shareConnection)
.buildAsyncClient();
final String messageId = UUID.randomUUID().toString();
final ServiceBusMessage message = getMessage(messageId, isSessionEnabled);
sendMessage(message).block(TIMEOUT);
if (isSessionEnabled) {
assertNotNull(sessionId, "'sessionId' should have been set.");
this.sessionReceiver = getSessionReceiverBuilder(useCredentials, entityType, entityIndex, shareConnection)
.buildAsyncClient();
this.receiver = this.sessionReceiver.acceptSession(sessionId).block();
} else {
this.receiver = getReceiverBuilder(useCredentials, entityType, entityIndex, shareConnection)
.buildAsyncClient();
}
StepVerifier.create(receiver.receiveMessages())
.assertNext(receivedMessage -> {
assertMessageEquals(receivedMessage, messageId, isSessionEnabled);
})
.thenAwait(shortWait)
.thenCancel()
.verify();
StepVerifier.create(receiver.receiveMessages())
.thenAwait(shortWait)
.thenCancel()
.verify();
}
/**
* Verifies that we can send and peek a message.
*/
@MethodSource("com.azure.messaging.servicebus.IntegrationTestBase
@ParameterizedTest
void peekMessage(MessagingEntityType entityType, boolean isSessionEnabled) {
setSender(entityType, TestUtils.USE_CASE_DEFAULT, isSessionEnabled);
final String messageId = UUID.randomUUID().toString();
final ServiceBusMessage message = getMessage(messageId, isSessionEnabled);
sendMessage(message).block(TIMEOUT);
setReceiver(entityType, TestUtils.USE_CASE_DEFAULT, isSessionEnabled);
StepVerifier.create(receiver.peekMessage())
.assertNext(receivedMessage -> assertMessageEquals(receivedMessage, messageId, isSessionEnabled))
.verifyComplete();
StepVerifier.create(receiver.receiveMessages().flatMap(receivedMessage -> receiver.complete(receivedMessage).thenReturn(receivedMessage)).take(1))
.assertNext(receivedMessage -> assertMessageEquals(receivedMessage, messageId, isSessionEnabled))
.verifyComplete();
}
/**
* Verifies that an empty entity does not error when peeking.
*/
@MethodSource("com.azure.messaging.servicebus.IntegrationTestBase
@ParameterizedTest
void peekMessageEmptyEntity(MessagingEntityType entityType, boolean isSessionEnabled) {
setReceiver(entityType, TestUtils.USE_CASE_EMPTY_ENTITY, isSessionEnabled);
final int fromSequenceNumber = 1;
StepVerifier.create(receiver.peekMessage(fromSequenceNumber))
.verifyComplete();
}
/**
* Verifies that we can schedule and receive a message.
*/
@MethodSource("com.azure.messaging.servicebus.IntegrationTestBase
@ParameterizedTest
void sendScheduledMessageAndReceive(MessagingEntityType entityType, boolean isSessionEnabled) {
setSender(entityType, TestUtils.USE_CASE_DEFAULT, isSessionEnabled);
final Duration shortDelay = Duration.ofSeconds(4);
final String messageId = UUID.randomUUID().toString();
final ServiceBusMessage message = getMessage(messageId, isSessionEnabled);
final OffsetDateTime scheduledEnqueueTime = OffsetDateTime.now().plusSeconds(2);
sender.scheduleMessage(message, scheduledEnqueueTime).block(TIMEOUT);
setReceiver(entityType, TestUtils.USE_CASE_DEFAULT, isSessionEnabled);
StepVerifier.create(Mono.delay(shortDelay).then(receiver.receiveMessages()
.flatMap(receivedMessage -> receiver.complete(receivedMessage).thenReturn(receivedMessage)).next()))
.assertNext(receivedMessage -> {
assertMessageEquals(receivedMessage, messageId, isSessionEnabled);
messagesPending.decrementAndGet();
}).verifyComplete();
}
/**
* Verifies that we can cancel a scheduled message.
*/
@MethodSource("com.azure.messaging.servicebus.IntegrationTestBase
@ParameterizedTest
void cancelScheduledMessage(MessagingEntityType entityType, boolean isSessionEnabled) {
setSender(entityType, TestUtils.USE_CASE_DEFAULT, isSessionEnabled);
final String messageId = UUID.randomUUID().toString();
final ServiceBusMessage message = getMessage(messageId, isSessionEnabled);
final OffsetDateTime scheduledEnqueueTime = OffsetDateTime.now().plusSeconds(10);
final Duration delayDuration = Duration.ofSeconds(3);
final Long sequenceNumber = sender.scheduleMessage(message, scheduledEnqueueTime).block(TIMEOUT);
logger.verbose("Scheduled the message, sequence number {}.", sequenceNumber);
assertNotNull(sequenceNumber);
Mono.delay(delayDuration)
.then(sender.cancelScheduledMessage(sequenceNumber))
.block(TIMEOUT);
messagesPending.decrementAndGet();
logger.verbose("Cancelled the scheduled message, sequence number {}.", sequenceNumber);
setReceiver(entityType, TestUtils.USE_CASE_DEFAULT, isSessionEnabled);
StepVerifier.create(receiver.receiveMessages().take(1))
.thenAwait(Duration.ofSeconds(5))
.thenCancel()
.verify();
}
/**
* Verifies that we can send and peek a message.
*/
@MethodSource("com.azure.messaging.servicebus.IntegrationTestBase
@ParameterizedTest
void peekFromSequenceNumberMessage(MessagingEntityType entityType, boolean isSessionEnabled) {
final int entityIndex = 3;
setSender(entityType, entityIndex, isSessionEnabled);
final String messageId = UUID.randomUUID().toString();
final ServiceBusMessage message = getMessage(messageId, isSessionEnabled);
sendMessage(message).block(TIMEOUT);
setReceiver(entityType, entityIndex, isSessionEnabled);
final ServiceBusReceivedMessage peekMessage = receiver.peekMessage().block(TIMEOUT);
assertNotNull(peekMessage);
final long sequenceNumber = peekMessage.getSequenceNumber();
try {
StepVerifier.create(receiver.peekMessage(sequenceNumber))
.assertNext(m -> {
assertEquals(sequenceNumber, m.getSequenceNumber());
assertMessageEquals(m, messageId, isSessionEnabled);
})
.verifyComplete();
} finally {
StepVerifier.create(receiver.receiveMessages()
.flatMap(receivedMessage -> receiver.complete(receivedMessage).thenReturn(receivedMessage)).take(1))
.expectNextCount(1)
.verifyComplete();
messagesPending.decrementAndGet();
}
}
/**
* Verifies that we can send and peek a batch of messages and the sequence number is tracked correctly.
*/
@MethodSource("com.azure.messaging.servicebus.IntegrationTestBase
@ParameterizedTest
void peekMessages(MessagingEntityType entityType, boolean isSessionEnabled) {
setSender(entityType, TestUtils.USE_CASE_PEEK_BATCH_MESSAGES, isSessionEnabled);
final BiConsumer<ServiceBusReceivedMessage, Integer> checkCorrectMessage = (message, index) -> {
final Map<String, Object> properties = message.getApplicationProperties();
final Object value = properties.get(MESSAGE_POSITION_ID);
assertTrue(value instanceof Integer, "Did not contain correct position number: " + value);
final int position = (int) value;
assertEquals(index, position);
};
final String messageId = UUID.randomUUID().toString();
final List<ServiceBusMessage> messages = TestUtils.getServiceBusMessages(10, messageId, CONTENTS_BYTES);
if (isSessionEnabled) {
messages.forEach(m -> m.setSessionId(sessionId));
}
sender.sendMessages(messages)
.doOnSuccess(aVoid -> {
int number = messagesPending.addAndGet(messages.size());
logger.info("Number of messages sent: {}", number);
})
.block(TIMEOUT);
setReceiver(entityType, TestUtils.USE_CASE_PEEK_BATCH_MESSAGES, isSessionEnabled);
try {
StepVerifier.create(receiver.peekMessages(3))
.assertNext(message -> checkCorrectMessage.accept(message, 0))
.assertNext(message -> checkCorrectMessage.accept(message, 1))
.assertNext(message -> checkCorrectMessage.accept(message, 2))
.verifyComplete();
StepVerifier.create(receiver.peekMessages(4))
.assertNext(message -> checkCorrectMessage.accept(message, 3))
.assertNext(message -> checkCorrectMessage.accept(message, 4))
.assertNext(message -> checkCorrectMessage.accept(message, 5))
.assertNext(message -> checkCorrectMessage.accept(message, 6))
.verifyComplete();
StepVerifier.create(receiver.peekMessage())
.assertNext(message -> checkCorrectMessage.accept(message, 7))
.verifyComplete();
} finally {
AtomicInteger completed = new AtomicInteger();
StepVerifier.create(receiver.receiveMessages().take(messages.size()))
.thenConsumeWhile(receivedMessage -> {
completed.incrementAndGet();
receiver.complete(receivedMessage).block(OPERATION_TIMEOUT);
return completed.get() <= messages.size();
})
.thenCancel()
.verify();
messagesPending.addAndGet(-messages.size());
}
}
/**
* Verifies that we can send and peek a batch of messages.
*/
@MethodSource("com.azure.messaging.servicebus.IntegrationTestBase
@ParameterizedTest
void peekMessagesFromSequence(MessagingEntityType entityType) {
setSenderAndReceiver(entityType, TestUtils.USE_CASE_PEEK_MESSAGE_FROM_SEQUENCE, false);
final String messageId = UUID.randomUUID().toString();
final ServiceBusMessage message = getMessage(messageId, false);
final int maxMessages = 2;
final int fromSequenceNumber = 1;
Mono.when(sendMessage(message), sendMessage(message)).block(TIMEOUT);
StepVerifier.create(receiver.peekMessages(maxMessages, fromSequenceNumber))
.expectNextCount(maxMessages)
.verifyComplete();
StepVerifier.create(receiver.receiveMessages().take(maxMessages))
.assertNext(receivedMessage -> {
receiver.complete(receivedMessage).block(Duration.ofSeconds(15));
})
.assertNext(receivedMessage -> {
receiver.complete(receivedMessage).block(Duration.ofSeconds(15));
})
.expectComplete()
.verify(TIMEOUT);
}
/**
* Verifies that an empty entity does not error when peeking.
*/
@MethodSource("com.azure.messaging.servicebus.IntegrationTestBase
@ParameterizedTest
void peekMessagesFromSequenceEmptyEntity(MessagingEntityType entityType, boolean isSessionEnabled) {
setReceiver(entityType, TestUtils.USE_CASE_EMPTY_ENTITY, isSessionEnabled);
final int maxMessages = 10;
final int fromSequenceNumber = 1;
StepVerifier.create(receiver.peekMessages(maxMessages, fromSequenceNumber))
.verifyComplete();
}
/**
* Verifies that we can dead-letter a message.
*/
@MethodSource("com.azure.messaging.servicebus.IntegrationTestBase
@ParameterizedTest
void deadLetterMessage(MessagingEntityType entityType, boolean isSessionEnabled) {
final int entityIndex = 0;
setSender(entityType, entityIndex, isSessionEnabled);
final String messageId = UUID.randomUUID().toString();
final ServiceBusMessage message = getMessage(messageId, isSessionEnabled);
sendMessage(message).block(TIMEOUT);
setReceiver(entityType, entityIndex, isSessionEnabled);
StepVerifier.create(receiver.receiveMessages()
.flatMap(receivedMessage -> receiver.deadLetter(receivedMessage).thenReturn(receivedMessage)).take(1))
.assertNext(receivedMessage -> {
assertMessageEquals(receivedMessage, messageId, isSessionEnabled);
messagesPending.decrementAndGet();
})
.thenCancel()
.verify();
}
@MethodSource("com.azure.messaging.servicebus.IntegrationTestBase
@ParameterizedTest
void receiveAndComplete(MessagingEntityType entityType, boolean isSessionEnabled) {
setSender(entityType, TestUtils.USE_CASE_DEFAULT, isSessionEnabled);
final String messageId = UUID.randomUUID().toString();
final ServiceBusMessage message = getMessage(messageId, isSessionEnabled);
sendMessage(message).block(TIMEOUT);
setReceiver(entityType, TestUtils.USE_CASE_DEFAULT, isSessionEnabled);
StepVerifier.create(receiver.receiveMessages()
.flatMap(receivedMessage -> receiver.complete(receivedMessage).thenReturn(receivedMessage)).take(1))
.assertNext(receivedMessage -> {
assertMessageEquals(receivedMessage, messageId, isSessionEnabled);
messagesPending.decrementAndGet();
}).verifyComplete();
messagesPending.decrementAndGet();
}
/**
* Verifies that we can renew message lock on a non-session receiver.
*/
@MethodSource("com.azure.messaging.servicebus.IntegrationTestBase
@ParameterizedTest
void receiveAndRenewLock(MessagingEntityType entityType) {
setSender(entityType, TestUtils.USE_CASE_DEFAULT, false);
final String messageId = UUID.randomUUID().toString();
final ServiceBusMessage message = getMessage(messageId, false);
sendMessage(message).block(TIMEOUT);
setReceiver(entityType, TestUtils.USE_CASE_DEFAULT, false);
final ServiceBusReceivedMessage receivedMessage = receiver.receiveMessages().next().block(TIMEOUT);
assertNotNull(receivedMessage);
assertNotNull(receivedMessage.getLockedUntil());
final OffsetDateTime initialLock = receivedMessage.getLockedUntil();
logger.info("Received message. Seq: {}. lockedUntil: {}", receivedMessage.getSequenceNumber(), initialLock);
try {
StepVerifier.create(Mono.delay(Duration.ofSeconds(7))
.then(Mono.defer(() -> receiver.renewMessageLock(receivedMessage))))
.assertNext(lockedUntil -> {
assertTrue(lockedUntil.isAfter(initialLock),
String.format("Updated lock is not after the initial Lock. updated: [%s]. initial:[%s]",
lockedUntil, initialLock));
})
.verifyComplete();
} finally {
logger.info("Completing message. Seq: {}.", receivedMessage.getSequenceNumber());
receiver.complete(receivedMessage)
.doOnSuccess(aVoid -> messagesPending.decrementAndGet())
.block(TIMEOUT);
}
}
/**
* Verifies that the lock can be automatically renewed.
*/
@MethodSource("com.azure.messaging.servicebus.IntegrationTestBase
@ParameterizedTest
void autoRenewLockOnReceiveMessage(MessagingEntityType entityType, boolean isSessionEnabled) {
final AtomicInteger lockRenewCount = new AtomicInteger();
setSender(entityType, TestUtils.USE_CASE_DEFAULT, isSessionEnabled);
final String messageId = UUID.randomUUID().toString();
final ServiceBusMessage message = getMessage(messageId, isSessionEnabled);
sendMessage(message).block(TIMEOUT);
setReceiver(entityType, TestUtils.USE_CASE_DEFAULT, isSessionEnabled);
StepVerifier.create(receiver.receiveMessages().flatMap(received -> {
logger.info("{}: lockToken[{}]. lockedUntil[{}]. now[{}]", received.getSequenceNumber(),
received.getLockToken(), received.getLockedUntil(), OffsetDateTime.now());
while (lockRenewCount.get() < 4) {
lockRenewCount.incrementAndGet();
logger.info("Iteration {}: Curren time {}.", lockRenewCount.get(), OffsetDateTime.now());
try {
TimeUnit.SECONDS.sleep(5);
} catch (InterruptedException error) {
logger.error("Error occurred while sleeping: " + error);
}
}
return receiver.complete(received).thenReturn(received);
}))
.assertNext(received -> {
assertTrue(lockRenewCount.get() > 0);
messagesPending.decrementAndGet();
})
.thenCancel()
.verify();
}
@MethodSource("com.azure.messaging.servicebus.IntegrationTestBase
@ParameterizedTest
void receiveAndAbandon(MessagingEntityType entityType, boolean isSessionEnabled) {
setSender(entityType, TestUtils.USE_CASE_DEFAULT, isSessionEnabled);
final String messageId = UUID.randomUUID().toString();
final ServiceBusMessage message = getMessage(messageId, isSessionEnabled);
sendMessage(message).block(TIMEOUT);
setReceiver(entityType, TestUtils.USE_CASE_DEFAULT, isSessionEnabled);
StepVerifier.create(receiver.receiveMessages()
.flatMap(receivedMessage -> receiver.abandon(receivedMessage).thenReturn(receivedMessage)).take(1))
.assertNext(receivedMessage -> assertMessageEquals(receivedMessage, messageId, isSessionEnabled))
.expectComplete();
}
@MethodSource("com.azure.messaging.servicebus.IntegrationTestBase
@ParameterizedTest
void receiveAndDefer(MessagingEntityType entityType, boolean isSessionEnabled) {
setSender(entityType, TestUtils.USE_CASE_PEEK_RECEIVE_AND_DEFER, isSessionEnabled);
final String messageId = UUID.randomUUID().toString();
final ServiceBusMessage message = getMessage(messageId, isSessionEnabled);
sendMessage(message).block(TIMEOUT);
setReceiver(entityType, TestUtils.USE_CASE_PEEK_RECEIVE_AND_DEFER, isSessionEnabled);
AtomicReference<ServiceBusReceivedMessage> received = new AtomicReference<>();
StepVerifier.create(receiver.receiveMessages()
.flatMap(receivedMessage -> receiver.defer(receivedMessage).thenReturn(receivedMessage)).take(1))
.assertNext(m -> {
received.set(m);
assertMessageEquals(m, messageId, isSessionEnabled);
messagesPending.decrementAndGet();
}).verifyComplete();
/*receiver.receiveDeferredMessage(received.get().getSequenceNumber())
.flatMap(m -> receiver.complete(m))
.block(TIMEOUT);
messagesPending.decrementAndGet();
*/
}
/**
* Test we can receive a deferred message via sequence number and then perform abandon, suspend, or complete on it.
*/
@MethodSource("com.azure.messaging.servicebus.IntegrationTestBase
@ParameterizedTest
void receiveDeferredMessageBySequenceNumber(MessagingEntityType entityType, DispositionStatus dispositionStatus) {
setSenderAndReceiver(entityType, TestUtils.USE_CASE_DEFERRED_MESSAGE_BY_SEQUENCE_NUMBER, false);
final String messageId = UUID.randomUUID().toString();
final ServiceBusMessage message = getMessage(messageId, false);
sendMessage(message).block(TIMEOUT);
final ServiceBusReceivedMessage receivedMessage = receiver.receiveMessages().next().block(TIMEOUT);
assertNotNull(receivedMessage);
receiver.defer(receivedMessage).block(TIMEOUT);
final ServiceBusReceivedMessage receivedDeferredMessage = receiver
.receiveDeferredMessage(receivedMessage.getSequenceNumber())
.block(TIMEOUT);
assertNotNull(receivedDeferredMessage);
assertEquals(receivedMessage.getSequenceNumber(), receivedDeferredMessage.getSequenceNumber());
final Mono<Void> operation;
switch (dispositionStatus) {
case ABANDONED:
operation = receiver.abandon(receivedDeferredMessage);
break;
case SUSPENDED:
operation = receiver.deadLetter(receivedDeferredMessage);
break;
case COMPLETED:
operation = receiver.complete(receivedDeferredMessage);
break;
default:
throw logger.logExceptionAsError(new IllegalArgumentException(
"Disposition status not recognized for this test case: " + dispositionStatus));
}
StepVerifier.create(operation)
.expectComplete()
.verify();
if (dispositionStatus != DispositionStatus.COMPLETED) {
messagesPending.decrementAndGet();
}
}
@MethodSource("com.azure.messaging.servicebus.IntegrationTestBase
@ParameterizedTest
void sendReceiveMessageWithVariousPropertyTypes(MessagingEntityType entityType) {
final boolean isSessionEnabled = true;
setSender(entityType, TestUtils.USE_CASE_SEND_RECEIVE_WITH_PROPERTIES, isSessionEnabled);
final String messageId = UUID.randomUUID().toString();
final ServiceBusMessage messageToSend = getMessage(messageId, isSessionEnabled);
Map<String, Object> sentProperties = messageToSend.getApplicationProperties();
sentProperties.put("NullProperty", null);
sentProperties.put("BooleanProperty", true);
sentProperties.put("ByteProperty", (byte) 1);
sentProperties.put("ShortProperty", (short) 2);
sentProperties.put("IntProperty", 3);
sentProperties.put("LongProperty", 4L);
sentProperties.put("FloatProperty", 5.5f);
sentProperties.put("DoubleProperty", 6.6f);
sentProperties.put("CharProperty", 'z');
sentProperties.put("UUIDProperty", UUID.fromString("38400000-8cf0-11bd-b23e-10b96e4ef00d"));
sentProperties.put("StringProperty", "string");
sendMessage(messageToSend).block(TIMEOUT);
setReceiver(entityType, TestUtils.USE_CASE_SEND_RECEIVE_WITH_PROPERTIES, isSessionEnabled);
StepVerifier.create(receiver.receiveMessages().flatMap(receivedMessage -> receiver.complete(receivedMessage).thenReturn(receivedMessage)).take(1))
.assertNext(receivedMessage -> {
messagesPending.decrementAndGet();
assertMessageEquals(receivedMessage, messageId, isSessionEnabled);
final Map<String, Object> received = receivedMessage.getApplicationProperties();
assertEquals(sentProperties.size(), received.size());
for (Map.Entry<String, Object> sentEntry : sentProperties.entrySet()) {
if (sentEntry.getValue() != null && sentEntry.getValue().getClass().isArray()) {
assertArrayEquals((Object[]) sentEntry.getValue(), (Object[]) received.get(sentEntry.getKey()));
} else {
final Object expected = sentEntry.getValue();
final Object actual = received.get(sentEntry.getKey());
assertEquals(expected, actual, String.format(
"Key '%s' does not match. Expected: '%s'. Actual: '%s'", sentEntry.getKey(), expected,
actual));
}
}
})
.thenCancel()
.verify();
}
@MethodSource("com.azure.messaging.servicebus.IntegrationTestBase
@ParameterizedTest
/**
* Verifies that we can receive a message from dead letter queue.
*/
@MethodSource("com.azure.messaging.servicebus.IntegrationTestBase
@ParameterizedTest
void receiveFromDeadLetter(MessagingEntityType entityType) {
final Duration shortWait = Duration.ofSeconds(2);
final boolean isSessionEnabled = false;
final int entityIndex = 0;
setSender(entityType, entityIndex, isSessionEnabled);
final String messageId = UUID.randomUUID().toString();
final ServiceBusMessage message = getMessage(messageId, isSessionEnabled);
final List<ServiceBusReceivedMessage> receivedMessages = new ArrayList<>();
sendMessage(message).block(TIMEOUT);
setReceiver(entityType, entityIndex, isSessionEnabled);
StepVerifier.create(receiver.receiveMessages().flatMap(receivedMessage -> receiver.deadLetter(receivedMessage).thenReturn(receivedMessage)).take(1))
.assertNext(receivedMessage -> {
assertMessageEquals(receivedMessage, messageId, isSessionEnabled);
messagesPending.decrementAndGet();
}).verifyComplete();
final ServiceBusReceiverAsyncClient deadLetterReceiver;
switch (entityType) {
case QUEUE:
final String queueName = getQueueName(entityIndex);
assertNotNull(queueName, "'queueName' cannot be null.");
deadLetterReceiver = getBuilder(false).receiver()
.queueName(queueName)
.subQueue(SubQueue.DEAD_LETTER_QUEUE)
.buildAsyncClient();
break;
case SUBSCRIPTION:
final String topicName = getTopicName(entityIndex);
final String subscriptionName = getSubscriptionBaseName();
assertNotNull(topicName, "'topicName' cannot be null.");
assertNotNull(subscriptionName, "'subscriptionName' cannot be null.");
deadLetterReceiver = getBuilder(false).receiver()
.topicName(topicName)
.subscriptionName(subscriptionName)
.subQueue(SubQueue.DEAD_LETTER_QUEUE)
.buildAsyncClient();
break;
default:
throw logger.logExceptionAsError(new IllegalArgumentException("Unknown entity type: " + entityType));
}
try {
StepVerifier.create(deadLetterReceiver.receiveMessages())
.assertNext(serviceBusReceivedMessage -> {
receivedMessages.add(serviceBusReceivedMessage);
assertMessageEquals(serviceBusReceivedMessage, messageId, isSessionEnabled);
})
.thenAwait(shortWait)
.thenCancel()
.verify();
} finally {
deadLetterReceiver.close();
}
}
@MethodSource("com.azure.messaging.servicebus.IntegrationTestBase
@ParameterizedTest
void renewMessageLock(MessagingEntityType entityType) {
final boolean isSessionEnabled = false;
setSenderAndReceiver(entityType, TestUtils.USE_CASE_DEFAULT, isSessionEnabled);
final Duration maximumDuration = Duration.ofSeconds(35);
final Duration sleepDuration = maximumDuration.plusMillis(500);
final String messageId = UUID.randomUUID().toString();
final ServiceBusMessage message = getMessage(messageId, isSessionEnabled);
final ServiceBusReceivedMessage receivedMessage = sendMessage(message)
.then(receiver.receiveMessages().next())
.block(TIMEOUT);
assertNotNull(receivedMessage);
final OffsetDateTime lockedUntil = receivedMessage.getLockedUntil();
assertNotNull(lockedUntil);
StepVerifier.create(receiver.renewMessageLock(receivedMessage, maximumDuration))
.thenAwait(sleepDuration)
.then(() -> {
logger.info("Completing message.");
int numberCompleted = completeMessages(receiver, Collections.singletonList(receivedMessage));
messagesPending.addAndGet(-numberCompleted);
})
.expectComplete()
.verify(Duration.ofMinutes(3));
}
/**
* Verifies that we can receive a message which have different section set (i.e header, footer, annotations,
* application properties etc).
*/
@MethodSource("com.azure.messaging.servicebus.IntegrationTestBase
@ParameterizedTest
void receiveAndValidateProperties(MessagingEntityType entityType) {
final boolean isSessionEnabled = false;
final int totalMessages = 1;
final String subject = "subject";
final Map<String, Object> footer = new HashMap<>();
footer.put("footer-key-1", "footer-value-1");
footer.put("footer-key-2", "footer-value-2");
final Map<String, Object> applicationProperties = new HashMap<>();
applicationProperties.put("ap-key-1", "ap-value-1");
applicationProperties.put("ap-key-2", "ap-value-2");
final Map<String, Object> deliveryAnnotation = new HashMap<>();
deliveryAnnotation.put("delivery-annotations-key-1", "delivery-annotations-value-1");
deliveryAnnotation.put("delivery-annotations-key-2", "delivery-annotations-value-2");
final String messageId = UUID.randomUUID().toString();
final AmqpAnnotatedMessage expectedAmqpProperties = new AmqpAnnotatedMessage(
AmqpMessageBody.fromData(CONTENTS_BYTES));
expectedAmqpProperties.getProperties().setSubject(subject);
expectedAmqpProperties.getProperties().setReplyToGroupId("r-gid");
expectedAmqpProperties.getProperties().setReplyTo(new AmqpAddress("reply-to"));
expectedAmqpProperties.getProperties().setContentType("content-type");
expectedAmqpProperties.getProperties().setCorrelationId(new AmqpMessageId("correlation-id"));
expectedAmqpProperties.getProperties().setTo(new AmqpAddress("to"));
expectedAmqpProperties.getProperties().setAbsoluteExpiryTime(OffsetDateTime.now().plusSeconds(60));
expectedAmqpProperties.getProperties().setUserId("user-id-1".getBytes());
expectedAmqpProperties.getProperties().setContentEncoding("string");
expectedAmqpProperties.getProperties().setGroupSequence(2L);
expectedAmqpProperties.getProperties().setCreationTime(OffsetDateTime.now().plusSeconds(30));
expectedAmqpProperties.getHeader().setPriority((short) 2);
expectedAmqpProperties.getHeader().setFirstAcquirer(true);
expectedAmqpProperties.getHeader().setDurable(true);
expectedAmqpProperties.getFooter().putAll(footer);
expectedAmqpProperties.getDeliveryAnnotations().putAll(deliveryAnnotation);
expectedAmqpProperties.getApplicationProperties().putAll(applicationProperties);
final ServiceBusMessage message = TestUtils.getServiceBusMessage(CONTENTS_BYTES, messageId);
final AmqpAnnotatedMessage amqpAnnotatedMessage = message.getRawAmqpMessage();
amqpAnnotatedMessage.getMessageAnnotations().putAll(expectedAmqpProperties.getMessageAnnotations());
amqpAnnotatedMessage.getApplicationProperties().putAll(expectedAmqpProperties.getApplicationProperties());
amqpAnnotatedMessage.getDeliveryAnnotations().putAll(expectedAmqpProperties.getDeliveryAnnotations());
amqpAnnotatedMessage.getFooter().putAll(expectedAmqpProperties.getFooter());
final AmqpMessageHeader header = amqpAnnotatedMessage.getHeader();
header.setFirstAcquirer(expectedAmqpProperties.getHeader().isFirstAcquirer());
header.setTimeToLive(expectedAmqpProperties.getHeader().getTimeToLive());
header.setDurable(expectedAmqpProperties.getHeader().isDurable());
header.setDeliveryCount(expectedAmqpProperties.getHeader().getDeliveryCount());
header.setPriority(expectedAmqpProperties.getHeader().getPriority());
final AmqpMessageProperties amqpMessageProperties = amqpAnnotatedMessage.getProperties();
amqpMessageProperties.setReplyTo((expectedAmqpProperties.getProperties().getReplyTo()));
amqpMessageProperties.setContentEncoding((expectedAmqpProperties.getProperties().getContentEncoding()));
amqpMessageProperties.setAbsoluteExpiryTime((expectedAmqpProperties.getProperties().getAbsoluteExpiryTime()));
amqpMessageProperties.setSubject((expectedAmqpProperties.getProperties().getSubject()));
amqpMessageProperties.setContentType(expectedAmqpProperties.getProperties().getContentType());
amqpMessageProperties.setCorrelationId(expectedAmqpProperties.getProperties().getCorrelationId());
amqpMessageProperties.setTo(expectedAmqpProperties.getProperties().getTo());
amqpMessageProperties.setGroupSequence(expectedAmqpProperties.getProperties().getGroupSequence());
amqpMessageProperties.setUserId(expectedAmqpProperties.getProperties().getUserId());
amqpMessageProperties.setAbsoluteExpiryTime(expectedAmqpProperties.getProperties().getAbsoluteExpiryTime());
amqpMessageProperties.setCreationTime(expectedAmqpProperties.getProperties().getCreationTime());
amqpMessageProperties.setReplyToGroupId(expectedAmqpProperties.getProperties().getReplyToGroupId());
setSender(entityType, TestUtils.USE_CASE_VALIDATE_AMQP_PROPERTIES, isSessionEnabled);
sendMessage(message).block(TIMEOUT);
setReceiver(entityType, TestUtils.USE_CASE_VALIDATE_AMQP_PROPERTIES, isSessionEnabled);
StepVerifier.create(receiver.receiveMessages()/*.take(totalMessages)*/)
.assertNext(received -> {
assertNotNull(received.getLockToken());
AmqpAnnotatedMessage actual = received.getRawAmqpMessage();
try {
assertArrayEquals(CONTENTS_BYTES, message.getBody().toBytes());
assertEquals(expectedAmqpProperties.getHeader().getPriority(), actual.getHeader().getPriority());
assertEquals(expectedAmqpProperties.getHeader().isFirstAcquirer(), actual.getHeader().isFirstAcquirer());
assertEquals(expectedAmqpProperties.getHeader().isDurable(), actual.getHeader().isDurable());
assertEquals(expectedAmqpProperties.getProperties().getSubject(), actual.getProperties().getSubject());
assertEquals(expectedAmqpProperties.getProperties().getReplyToGroupId(), actual.getProperties().getReplyToGroupId());
assertEquals(expectedAmqpProperties.getProperties().getReplyTo(), actual.getProperties().getReplyTo());
assertEquals(expectedAmqpProperties.getProperties().getContentType(), actual.getProperties().getContentType());
assertEquals(expectedAmqpProperties.getProperties().getCorrelationId(), actual.getProperties().getCorrelationId());
assertEquals(expectedAmqpProperties.getProperties().getTo(), actual.getProperties().getTo());
assertEquals(expectedAmqpProperties.getProperties().getAbsoluteExpiryTime().toEpochSecond(), actual.getProperties().getAbsoluteExpiryTime().toEpochSecond());
assertEquals(expectedAmqpProperties.getProperties().getSubject(), actual.getProperties().getSubject());
assertEquals(expectedAmqpProperties.getProperties().getContentEncoding(), actual.getProperties().getContentEncoding());
assertEquals(expectedAmqpProperties.getProperties().getGroupSequence(), actual.getProperties().getGroupSequence());
assertEquals(expectedAmqpProperties.getProperties().getCreationTime().toEpochSecond(), actual.getProperties().getCreationTime().toEpochSecond());
assertArrayEquals(expectedAmqpProperties.getProperties().getUserId(), actual.getProperties().getUserId());
assertMapValues(expectedAmqpProperties.getDeliveryAnnotations(), actual.getDeliveryAnnotations());
assertMapValues(expectedAmqpProperties.getMessageAnnotations(), actual.getMessageAnnotations());
assertMapValues(expectedAmqpProperties.getApplicationProperties(), actual.getApplicationProperties());
assertMapValues(expectedAmqpProperties.getFooter(), actual.getFooter());
} finally {
logger.info("Completing message.");
receiver.complete(received).block(Duration.ofSeconds(15));
messagesPending.decrementAndGet();
}
})
.thenCancel()
.verify(Duration.ofMinutes(2));
}
/**
* Verifies we can autocomplete for a queue.
*
* @param entityType Entity Type.
*/
@MethodSource("com.azure.messaging.servicebus.IntegrationTestBase
@ParameterizedTest
void autoComplete(MessagingEntityType entityType) {
final Duration shortWait = Duration.ofSeconds(2);
final int index = TestUtils.USE_CASE_AUTO_COMPLETE;
setSender(entityType, index, false);
final int numberOfEvents = 3;
final String messageId = UUID.randomUUID().toString();
final List<ServiceBusMessage> messages = getServiceBusMessages(numberOfEvents, messageId);
setReceiver(entityType, index, false);
final ServiceBusReceivedMessage lastMessage = receiver.peekMessage().block(TIMEOUT);
Mono.when(messages.stream().map(this::sendMessage)
.collect(Collectors.toList()))
.block(TIMEOUT);
final ServiceBusReceiverAsyncClient autoCompleteReceiver =
getReceiverBuilder(false, entityType, index, false)
.buildAsyncClient();
try {
StepVerifier.create(autoCompleteReceiver.receiveMessages())
.assertNext(receivedMessage -> {
if (lastMessage != null) {
assertEquals(lastMessage.getMessageId(), receivedMessage.getMessageId());
} else {
assertEquals(messageId, receivedMessage.getMessageId());
}
})
.assertNext(context -> {
if (lastMessage == null) {
assertEquals(messageId, context.getMessageId());
}
})
.assertNext(context -> {
if (lastMessage == null) {
assertEquals(messageId, context.getMessageId());
}
})
.thenAwait(shortWait)
.thenCancel()
.verify(TIMEOUT);
} finally {
autoCompleteReceiver.close();
}
final ServiceBusReceivedMessage newLastMessage = receiver.peekMessage().block(TIMEOUT);
if (lastMessage == null) {
assertNull(newLastMessage,
String.format("Actual messageId[%s]", newLastMessage != null ? newLastMessage.getMessageId() : "n/a"));
} else {
assertNotNull(newLastMessage);
assertEquals(lastMessage.getSequenceNumber(), newLastMessage.getSequenceNumber());
}
}
/**
* Asserts the length and values with in the map.
*/
private void assertMapValues(Map<String, Object> expectedMap, Map<String, Object> actualMap) {
assertTrue(actualMap.size() >= expectedMap.size());
for (String key : expectedMap.keySet()) {
assertEquals(expectedMap.get(key), actualMap.get(key), "Value is not equal for Key " + key);
}
}
/**
* Sets the sender and receiver. If session is enabled, then a single-named session receiver is created.
*/
private void setSenderAndReceiver(MessagingEntityType entityType, int entityIndex, boolean isSessionEnabled) {
setSender(entityType, entityIndex, isSessionEnabled);
setReceiver(entityType, entityIndex, isSessionEnabled);
}
private void setReceiver(MessagingEntityType entityType, int entityIndex, boolean isSessionEnabled) {
final boolean shareConnection = false;
final boolean useCredentials = false;
if (isSessionEnabled) {
assertNotNull(sessionId, "'sessionId' should have been set.");
sessionReceiver = getSessionReceiverBuilder(useCredentials, entityType, entityIndex, shareConnection)
.disableAutoComplete()
.buildAsyncClient();
this.receiver = sessionReceiver.acceptSession(sessionId).block();
} else {
this.receiver = getReceiverBuilder(useCredentials, entityType, entityIndex, shareConnection)
.disableAutoComplete()
.buildAsyncClient();
}
}
private void setSender(MessagingEntityType entityType, int entityIndex, boolean isSessionEnabled) {
final boolean shareConnection = false;
final boolean useCredentials = false;
this.sender = getSenderBuilder(useCredentials, entityType, entityIndex, isSessionEnabled, shareConnection)
.buildAsyncClient();
}
private Mono<Void> sendMessage(ServiceBusMessage message) {
return sender.sendMessage(message).doOnSuccess(aVoid -> {
int number = messagesPending.incrementAndGet();
logger.info("Message Id {}. Number sent: {}", message.getMessageId(), number);
});
}
private int completeMessages(ServiceBusReceiverAsyncClient client, List<ServiceBusReceivedMessage> messages) {
Mono.when(messages.stream().map(e -> client.complete(e))
.collect(Collectors.toList()))
.block(TIMEOUT);
return messages.size();
}
} |
This one will retrieve updated `session state` , so we can assert at line 917. | void setAndGetSessionState(MessagingEntityType entityType) {
setSender(entityType, TestUtils.USE_CASE_DEFAULT, true);
final byte[] sessionState = "Finished".getBytes(UTF_8);
final String messageId = UUID.randomUUID().toString();
final ServiceBusMessage messageToSend = getMessage(messageId, true);
sendMessage(messageToSend).block(Duration.ofSeconds(10));
setReceiver(entityType, TestUtils.USE_CASE_DEFAULT, true);
StepVerifier.create(receiver.receiveMessages()
.flatMap(message -> {
logger.info("SessionId: {}. LockToken: {}. LockedUntil: {}. Message received.",
message.getSessionId(), message.getLockToken(), message.getLockedUntil());
assertMessageEquals(message, messageId, isSessionEnabled);
messagesPending.decrementAndGet();
return receiver.abandon(message)
.then(receiver.setSessionState(sessionState))
.then(receiver.getSessionState());
}
).take(1))
.assertNext(state -> {
logger.info("State received: {}", new String(state, UTF_8));
assertArrayEquals(sessionState, state);
})
.verifyComplete();
} | .then(receiver.getSessionState()); | void setAndGetSessionState(MessagingEntityType entityType) {
setSender(entityType, TestUtils.USE_CASE_DEFAULT, true);
final byte[] sessionState = "Finished".getBytes(UTF_8);
final String messageId = UUID.randomUUID().toString();
final ServiceBusMessage messageToSend = getMessage(messageId, true);
sendMessage(messageToSend).block(Duration.ofSeconds(10));
setReceiver(entityType, TestUtils.USE_CASE_DEFAULT, true);
StepVerifier.create(receiver.receiveMessages()
.flatMap(message -> {
logger.info("SessionId: {}. LockToken: {}. LockedUntil: {}. Message received.",
message.getSessionId(), message.getLockToken(), message.getLockedUntil());
assertMessageEquals(message, messageId, isSessionEnabled);
messagesPending.decrementAndGet();
return receiver.abandon(message)
.then(receiver.setSessionState(sessionState))
.then(receiver.getSessionState());
}
).take(1))
.assertNext(state -> {
logger.info("State received: {}", new String(state, UTF_8));
assertArrayEquals(sessionState, state);
})
.verifyComplete();
} | class ServiceBusReceiverAsyncClientIntegrationTest extends IntegrationTestBase {
private final ClientLogger logger = new ClientLogger(ServiceBusReceiverAsyncClientIntegrationTest.class);
private final AtomicInteger messagesPending = new AtomicInteger();
private final boolean isSessionEnabled = false;
private ServiceBusReceiverAsyncClient receiver;
private ServiceBusSenderAsyncClient sender;
private ServiceBusSessionReceiverAsyncClient sessionReceiver;
ServiceBusReceiverAsyncClientIntegrationTest() {
super(new ClientLogger(ServiceBusReceiverAsyncClientIntegrationTest.class));
}
@Override
protected void beforeTest() {
sessionId = UUID.randomUUID().toString();
}
@Override
protected void afterTest() {
sharedBuilder = null;
try {
dispose(receiver, sender, sessionReceiver);
} catch (Exception e) {
logger.warning("Error occurred when draining queue.", e);
}
}
/**
* Verifies that we can create multiple transaction using sender and receiver.
*/
@Test
void createMultipleTransactionTest() {
setSenderAndReceiver(MessagingEntityType.QUEUE, 0, isSessionEnabled);
StepVerifier.create(receiver.createTransaction())
.assertNext(Assertions::assertNotNull)
.verifyComplete();
StepVerifier.create(receiver.createTransaction())
.assertNext(Assertions::assertNotNull)
.verifyComplete();
}
/**
* Verifies that we can create transaction and complete.
*/
@MethodSource("com.azure.messaging.servicebus.IntegrationTestBase
@ParameterizedTest
void createTransactionAndRollbackMessagesTest(MessagingEntityType entityType) {
setSender(entityType, TestUtils.USE_CASE_DEFAULT, isSessionEnabled);
final String messageId = UUID.randomUUID().toString();
final ServiceBusMessage message = getMessage(messageId, isSessionEnabled);
sendMessage(message).block(OPERATION_TIMEOUT);
setReceiver(entityType, TestUtils.USE_CASE_DEFAULT, isSessionEnabled);
AtomicReference<ServiceBusTransactionContext> transaction = new AtomicReference<>();
StepVerifier.create(receiver.createTransaction())
.assertNext(txn -> {
transaction.set(txn);
assertNotNull(transaction);
})
.verifyComplete();
StepVerifier.create(receiver.receiveMessages()
.flatMap(receivedMessage -> receiver.complete(receivedMessage).thenReturn(receivedMessage)).take(1))
.assertNext(receivedMessage -> {
assertMessageEquals(receivedMessage, messageId, isSessionEnabled);
messagesPending.decrementAndGet();
}).verifyComplete();
StepVerifier.create(receiver.rollbackTransaction(transaction.get()))
.verifyComplete();
}
/**
* Verifies that we can do following using shared connection and on non session entity. 1. create transaction 2.
* receive and settle with transactionContext. 3. commit Rollback this transaction.
*/
@ParameterizedTest
@EnumSource(DispositionStatus.class)
void transactionSendReceiveAndCommit(DispositionStatus dispositionStatus) {
final MessagingEntityType entityType = MessagingEntityType.QUEUE;
setSenderAndReceiver(entityType, TestUtils.USE_CASE_PEEK_TRANSACTION_SENDRECEIVE_AND_COMPLETE, isSessionEnabled);
final String messageId1 = UUID.randomUUID().toString();
final ServiceBusMessage message1 = getMessage(messageId1, isSessionEnabled);
final String deadLetterReason = "test reason";
sendMessage(message1).block(TIMEOUT);
AtomicReference<ServiceBusTransactionContext> transaction = new AtomicReference<>();
StepVerifier.create(receiver.createTransaction())
.assertNext(txn -> {
transaction.set(txn);
assertNotNull(transaction);
})
.verifyComplete();
assertNotNull(transaction.get());
final ServiceBusReceivedMessage receivedMessage = receiver.receiveMessages().next().block(TIMEOUT);
assertNotNull(receivedMessage);
final Mono<Void> operation;
switch (dispositionStatus) {
case COMPLETED:
operation = receiver.complete(receivedMessage, new CompleteOptions().setTransactionContext(transaction.get()));
messagesPending.decrementAndGet();
break;
case ABANDONED:
operation = receiver.abandon(receivedMessage, new AbandonOptions().setTransactionContext(transaction.get()));
break;
case SUSPENDED:
DeadLetterOptions deadLetterOptions = new DeadLetterOptions().setTransactionContext(transaction.get())
.setDeadLetterReason(deadLetterReason);
operation = receiver.deadLetter(receivedMessage, deadLetterOptions);
messagesPending.decrementAndGet();
break;
case DEFERRED:
operation = receiver.defer(receivedMessage, new DeferOptions().setTransactionContext(transaction.get()));
break;
default:
throw logger.logExceptionAsError(new IllegalArgumentException(
"Disposition status not recognized for this test case: " + dispositionStatus));
}
StepVerifier.create(operation)
.verifyComplete();
StepVerifier.create(receiver.commitTransaction(transaction.get()))
.verifyComplete();
}
/**
* Verifies that we can do following on different clients i.e. sender and receiver. 1. create transaction using
* sender 2. receive and complete with transactionContext. 3. Commit this transaction using sender.
*/
@MethodSource("com.azure.messaging.servicebus.IntegrationTestBase
@ParameterizedTest
@Disabled
void transactionReceiveCompleteCommitMixClient(MessagingEntityType entityType) {
final boolean shareConnection = true;
final boolean useCredentials = false;
final int entityIndex = 0;
this.sender = getSenderBuilder(useCredentials, entityType, entityIndex, isSessionEnabled, shareConnection)
.buildAsyncClient();
this.receiver = getReceiverBuilder(useCredentials, entityType, entityIndex, shareConnection)
.buildAsyncClient();
final String messageId = UUID.randomUUID().toString();
final ServiceBusMessage message = getMessage(messageId, isSessionEnabled);
sendMessage(message).block(TIMEOUT);
AtomicReference<ServiceBusTransactionContext> transaction = new AtomicReference<>();
StepVerifier.create(sender.createTransaction())
.assertNext(txn -> {
transaction.set(txn);
assertNotNull(transaction);
})
.verifyComplete();
assertNotNull(transaction.get());
final ServiceBusReceivedMessage receivedMessage = receiver.receiveMessages().next().block(TIMEOUT);
assertNotNull(receivedMessage);
StepVerifier.create(receiver.complete(receivedMessage, new CompleteOptions().setTransactionContext(transaction.get())))
.verifyComplete();
StepVerifier.create(sender.commitTransaction(transaction.get()))
.verifyComplete();
}
/**
* Verifies that we can send and receive two messages.
*/
@MethodSource("com.azure.messaging.servicebus.IntegrationTestBase
@ParameterizedTest
void receiveTwoMessagesAutoComplete(MessagingEntityType entityType, boolean isSessionEnabled) {
final int entityIndex = 0;
final boolean shareConnection = false;
final boolean useCredentials = false;
final Duration shortWait = Duration.ofSeconds(3);
this.sender = getSenderBuilder(useCredentials, entityType, entityIndex, isSessionEnabled, shareConnection)
.buildAsyncClient();
final String messageId = UUID.randomUUID().toString();
final ServiceBusMessage message = getMessage(messageId, isSessionEnabled);
Mono.when(sendMessage(message), sendMessage(message)).block(TIMEOUT);
if (isSessionEnabled) {
assertNotNull(sessionId, "'sessionId' should have been set.");
this.sessionReceiver = getSessionReceiverBuilder(useCredentials, entityType, entityIndex, shareConnection)
.buildAsyncClient();
this.receiver = sessionReceiver.acceptSession(sessionId).block();
} else {
this.receiver = getReceiverBuilder(useCredentials, entityType, entityIndex, shareConnection)
.buildAsyncClient();
}
StepVerifier.create(receiver.receiveMessages())
.assertNext(receivedMessage -> {
assertMessageEquals(receivedMessage, messageId, isSessionEnabled);
})
.assertNext(receivedMessage -> {
assertMessageEquals(receivedMessage, messageId, isSessionEnabled);
})
.thenAwait(shortWait)
.thenCancel()
.verify();
}
/**
* Verifies that we can send and receive a message.
*/
@MethodSource("com.azure.messaging.servicebus.IntegrationTestBase
@ParameterizedTest
void receiveMessageAutoComplete(MessagingEntityType entityType, boolean isSessionEnabled) {
final int entityIndex = 0;
final boolean shareConnection = false;
final boolean useCredentials = false;
final Duration shortWait = Duration.ofSeconds(3);
this.sender = getSenderBuilder(useCredentials, entityType, entityIndex, isSessionEnabled, shareConnection)
.buildAsyncClient();
final String messageId = UUID.randomUUID().toString();
final ServiceBusMessage message = getMessage(messageId, isSessionEnabled);
sendMessage(message).block(TIMEOUT);
if (isSessionEnabled) {
assertNotNull(sessionId, "'sessionId' should have been set.");
this.sessionReceiver = getSessionReceiverBuilder(useCredentials, entityType, entityIndex, shareConnection)
.buildAsyncClient();
this.receiver = this.sessionReceiver.acceptSession(sessionId).block();
} else {
this.receiver = getReceiverBuilder(useCredentials, entityType, entityIndex, shareConnection)
.buildAsyncClient();
}
StepVerifier.create(receiver.receiveMessages())
.assertNext(receivedMessage -> {
assertMessageEquals(receivedMessage, messageId, isSessionEnabled);
})
.thenAwait(shortWait)
.thenCancel()
.verify();
StepVerifier.create(receiver.receiveMessages())
.thenAwait(shortWait)
.thenCancel()
.verify();
}
/**
* Verifies that we can send and peek a message.
*/
@MethodSource("com.azure.messaging.servicebus.IntegrationTestBase
@ParameterizedTest
void peekMessage(MessagingEntityType entityType, boolean isSessionEnabled) {
setSender(entityType, TestUtils.USE_CASE_DEFAULT, isSessionEnabled);
final String messageId = UUID.randomUUID().toString();
final ServiceBusMessage message = getMessage(messageId, isSessionEnabled);
sendMessage(message).block(TIMEOUT);
setReceiver(entityType, TestUtils.USE_CASE_DEFAULT, isSessionEnabled);
StepVerifier.create(receiver.peekMessage())
.assertNext(receivedMessage -> assertMessageEquals(receivedMessage, messageId, isSessionEnabled))
.verifyComplete();
StepVerifier.create(receiver.receiveMessages().flatMap(receivedMessage -> receiver.complete(receivedMessage).thenReturn(receivedMessage)).take(1))
.assertNext(receivedMessage -> assertMessageEquals(receivedMessage, messageId, isSessionEnabled))
.verifyComplete();
}
/**
* Verifies that an empty entity does not error when peeking.
*/
@MethodSource("com.azure.messaging.servicebus.IntegrationTestBase
@ParameterizedTest
void peekMessageEmptyEntity(MessagingEntityType entityType, boolean isSessionEnabled) {
setReceiver(entityType, TestUtils.USE_CASE_EMPTY_ENTITY, isSessionEnabled);
final int fromSequenceNumber = 1;
StepVerifier.create(receiver.peekMessage(fromSequenceNumber))
.verifyComplete();
}
/**
* Verifies that we can schedule and receive a message.
*/
@MethodSource("com.azure.messaging.servicebus.IntegrationTestBase
@ParameterizedTest
void sendScheduledMessageAndReceive(MessagingEntityType entityType, boolean isSessionEnabled) {
setSender(entityType, TestUtils.USE_CASE_DEFAULT, isSessionEnabled);
final Duration shortDelay = Duration.ofSeconds(4);
final String messageId = UUID.randomUUID().toString();
final ServiceBusMessage message = getMessage(messageId, isSessionEnabled);
final OffsetDateTime scheduledEnqueueTime = OffsetDateTime.now().plusSeconds(2);
sender.scheduleMessage(message, scheduledEnqueueTime).block(TIMEOUT);
setReceiver(entityType, TestUtils.USE_CASE_DEFAULT, isSessionEnabled);
StepVerifier.create(Mono.delay(shortDelay).then(receiver.receiveMessages()
.flatMap(receivedMessage -> receiver.complete(receivedMessage).thenReturn(receivedMessage)).next()))
.assertNext(receivedMessage -> {
assertMessageEquals(receivedMessage, messageId, isSessionEnabled);
messagesPending.decrementAndGet();
}).verifyComplete();
}
/**
* Verifies that we can cancel a scheduled message.
*/
@MethodSource("com.azure.messaging.servicebus.IntegrationTestBase
@ParameterizedTest
void cancelScheduledMessage(MessagingEntityType entityType, boolean isSessionEnabled) {
setSender(entityType, TestUtils.USE_CASE_DEFAULT, isSessionEnabled);
final String messageId = UUID.randomUUID().toString();
final ServiceBusMessage message = getMessage(messageId, isSessionEnabled);
final OffsetDateTime scheduledEnqueueTime = OffsetDateTime.now().plusSeconds(10);
final Duration delayDuration = Duration.ofSeconds(3);
final Long sequenceNumber = sender.scheduleMessage(message, scheduledEnqueueTime).block(TIMEOUT);
logger.verbose("Scheduled the message, sequence number {}.", sequenceNumber);
assertNotNull(sequenceNumber);
Mono.delay(delayDuration)
.then(sender.cancelScheduledMessage(sequenceNumber))
.block(TIMEOUT);
messagesPending.decrementAndGet();
logger.verbose("Cancelled the scheduled message, sequence number {}.", sequenceNumber);
setReceiver(entityType, TestUtils.USE_CASE_DEFAULT, isSessionEnabled);
StepVerifier.create(receiver.receiveMessages().take(1))
.thenAwait(Duration.ofSeconds(5))
.thenCancel()
.verify();
}
/**
* Verifies that we can send and peek a message.
*/
@MethodSource("com.azure.messaging.servicebus.IntegrationTestBase
@ParameterizedTest
void peekFromSequenceNumberMessage(MessagingEntityType entityType, boolean isSessionEnabled) {
final int entityIndex = 3;
setSender(entityType, entityIndex, isSessionEnabled);
final String messageId = UUID.randomUUID().toString();
final ServiceBusMessage message = getMessage(messageId, isSessionEnabled);
sendMessage(message).block(TIMEOUT);
setReceiver(entityType, entityIndex, isSessionEnabled);
final ServiceBusReceivedMessage peekMessage = receiver.peekMessage().block(TIMEOUT);
assertNotNull(peekMessage);
final long sequenceNumber = peekMessage.getSequenceNumber();
try {
StepVerifier.create(receiver.peekMessage(sequenceNumber))
.assertNext(m -> {
assertEquals(sequenceNumber, m.getSequenceNumber());
assertMessageEquals(m, messageId, isSessionEnabled);
})
.verifyComplete();
} finally {
StepVerifier.create(receiver.receiveMessages()
.flatMap(receivedMessage -> receiver.complete(receivedMessage).thenReturn(receivedMessage)).take(1))
.expectNextCount(1)
.verifyComplete();
messagesPending.decrementAndGet();
}
}
/**
* Verifies that we can send and peek a batch of messages and the sequence number is tracked correctly.
*/
@MethodSource("com.azure.messaging.servicebus.IntegrationTestBase
@ParameterizedTest
void peekMessages(MessagingEntityType entityType, boolean isSessionEnabled) {
setSender(entityType, TestUtils.USE_CASE_PEEK_BATCH_MESSAGES, isSessionEnabled);
final BiConsumer<ServiceBusReceivedMessage, Integer> checkCorrectMessage = (message, index) -> {
final Map<String, Object> properties = message.getApplicationProperties();
final Object value = properties.get(MESSAGE_POSITION_ID);
assertTrue(value instanceof Integer, "Did not contain correct position number: " + value);
final int position = (int) value;
assertEquals(index, position);
};
final String messageId = UUID.randomUUID().toString();
final List<ServiceBusMessage> messages = TestUtils.getServiceBusMessages(10, messageId, CONTENTS_BYTES);
if (isSessionEnabled) {
messages.forEach(m -> m.setSessionId(sessionId));
}
sender.sendMessages(messages)
.doOnSuccess(aVoid -> {
int number = messagesPending.addAndGet(messages.size());
logger.info("Number of messages sent: {}", number);
})
.block(TIMEOUT);
setReceiver(entityType, TestUtils.USE_CASE_PEEK_BATCH_MESSAGES, isSessionEnabled);
try {
StepVerifier.create(receiver.peekMessages(3))
.assertNext(message -> checkCorrectMessage.accept(message, 0))
.assertNext(message -> checkCorrectMessage.accept(message, 1))
.assertNext(message -> checkCorrectMessage.accept(message, 2))
.verifyComplete();
StepVerifier.create(receiver.peekMessages(4))
.assertNext(message -> checkCorrectMessage.accept(message, 3))
.assertNext(message -> checkCorrectMessage.accept(message, 4))
.assertNext(message -> checkCorrectMessage.accept(message, 5))
.assertNext(message -> checkCorrectMessage.accept(message, 6))
.verifyComplete();
StepVerifier.create(receiver.peekMessage())
.assertNext(message -> checkCorrectMessage.accept(message, 7))
.verifyComplete();
} finally {
AtomicInteger completed = new AtomicInteger();
StepVerifier.create(receiver.receiveMessages().take(messages.size()))
.thenConsumeWhile(receivedMessage -> {
completed.incrementAndGet();
receiver.complete(receivedMessage).block(OPERATION_TIMEOUT);
return completed.get() <= messages.size();
})
.thenCancel()
.verify();
messagesPending.addAndGet(-messages.size());
}
}
/**
* Verifies that we can send and peek a batch of messages.
*/
@MethodSource("com.azure.messaging.servicebus.IntegrationTestBase
@ParameterizedTest
void peekMessagesFromSequence(MessagingEntityType entityType) {
setSenderAndReceiver(entityType, TestUtils.USE_CASE_PEEK_MESSAGE_FROM_SEQUENCE, false);
final String messageId = UUID.randomUUID().toString();
final ServiceBusMessage message = getMessage(messageId, false);
final int maxMessages = 2;
final int fromSequenceNumber = 1;
Mono.when(sendMessage(message), sendMessage(message)).block(TIMEOUT);
StepVerifier.create(receiver.peekMessages(maxMessages, fromSequenceNumber))
.expectNextCount(maxMessages)
.verifyComplete();
StepVerifier.create(receiver.receiveMessages().take(maxMessages))
.assertNext(receivedMessage -> {
receiver.complete(receivedMessage).block(Duration.ofSeconds(15));
})
.assertNext(receivedMessage -> {
receiver.complete(receivedMessage).block(Duration.ofSeconds(15));
})
.expectComplete()
.verify(TIMEOUT);
}
/**
* Verifies that an empty entity does not error when peeking.
*/
@MethodSource("com.azure.messaging.servicebus.IntegrationTestBase
@ParameterizedTest
void peekMessagesFromSequenceEmptyEntity(MessagingEntityType entityType, boolean isSessionEnabled) {
setReceiver(entityType, TestUtils.USE_CASE_EMPTY_ENTITY, isSessionEnabled);
final int maxMessages = 10;
final int fromSequenceNumber = 1;
StepVerifier.create(receiver.peekMessages(maxMessages, fromSequenceNumber))
.verifyComplete();
}
/**
* Verifies that we can dead-letter a message.
*/
@MethodSource("com.azure.messaging.servicebus.IntegrationTestBase
@ParameterizedTest
void deadLetterMessage(MessagingEntityType entityType, boolean isSessionEnabled) {
final int entityIndex = 0;
setSender(entityType, entityIndex, isSessionEnabled);
final String messageId = UUID.randomUUID().toString();
final ServiceBusMessage message = getMessage(messageId, isSessionEnabled);
sendMessage(message).block(TIMEOUT);
setReceiver(entityType, entityIndex, isSessionEnabled);
StepVerifier.create(receiver.receiveMessages()
.flatMap(receivedMessage -> receiver.deadLetter(receivedMessage).thenReturn(receivedMessage)).take(1))
.assertNext(receivedMessage -> {
assertMessageEquals(receivedMessage, messageId, isSessionEnabled);
messagesPending.decrementAndGet();
})
.thenCancel()
.verify();
}
@MethodSource("com.azure.messaging.servicebus.IntegrationTestBase
@ParameterizedTest
void receiveAndComplete(MessagingEntityType entityType, boolean isSessionEnabled) {
setSender(entityType, TestUtils.USE_CASE_DEFAULT, isSessionEnabled);
final String messageId = UUID.randomUUID().toString();
final ServiceBusMessage message = getMessage(messageId, isSessionEnabled);
sendMessage(message).block(TIMEOUT);
setReceiver(entityType, TestUtils.USE_CASE_DEFAULT, isSessionEnabled);
StepVerifier.create(receiver.receiveMessages()
.flatMap(receivedMessage -> receiver.complete(receivedMessage).thenReturn(receivedMessage)).take(1))
.assertNext(receivedMessage -> {
assertMessageEquals(receivedMessage, messageId, isSessionEnabled);
messagesPending.decrementAndGet();
}).verifyComplete();
messagesPending.decrementAndGet();
}
/**
* Verifies that we can renew message lock on a non-session receiver.
*/
@MethodSource("com.azure.messaging.servicebus.IntegrationTestBase
@ParameterizedTest
void receiveAndRenewLock(MessagingEntityType entityType) {
setSender(entityType, TestUtils.USE_CASE_DEFAULT, false);
final String messageId = UUID.randomUUID().toString();
final ServiceBusMessage message = getMessage(messageId, false);
sendMessage(message).block(TIMEOUT);
setReceiver(entityType, TestUtils.USE_CASE_DEFAULT, false);
final ServiceBusReceivedMessage receivedMessage = receiver.receiveMessages().next().block(TIMEOUT);
assertNotNull(receivedMessage);
assertNotNull(receivedMessage.getLockedUntil());
final OffsetDateTime initialLock = receivedMessage.getLockedUntil();
logger.info("Received message. Seq: {}. lockedUntil: {}", receivedMessage.getSequenceNumber(), initialLock);
try {
StepVerifier.create(Mono.delay(Duration.ofSeconds(7))
.then(Mono.defer(() -> receiver.renewMessageLock(receivedMessage))))
.assertNext(lockedUntil -> {
assertTrue(lockedUntil.isAfter(initialLock),
String.format("Updated lock is not after the initial Lock. updated: [%s]. initial:[%s]",
lockedUntil, initialLock));
})
.verifyComplete();
} finally {
logger.info("Completing message. Seq: {}.", receivedMessage.getSequenceNumber());
receiver.complete(receivedMessage)
.doOnSuccess(aVoid -> messagesPending.decrementAndGet())
.block(TIMEOUT);
}
}
/**
* Verifies that the lock can be automatically renewed.
*/
@MethodSource("com.azure.messaging.servicebus.IntegrationTestBase
@ParameterizedTest
void autoRenewLockOnReceiveMessage(MessagingEntityType entityType, boolean isSessionEnabled) {
final AtomicInteger lockRenewCount = new AtomicInteger();
setSender(entityType, TestUtils.USE_CASE_DEFAULT, isSessionEnabled);
final String messageId = UUID.randomUUID().toString();
final ServiceBusMessage message = getMessage(messageId, isSessionEnabled);
sendMessage(message).block(TIMEOUT);
setReceiver(entityType, TestUtils.USE_CASE_DEFAULT, isSessionEnabled);
StepVerifier.create(receiver.receiveMessages().flatMap(received -> {
logger.info("{}: lockToken[{}]. lockedUntil[{}]. now[{}]", received.getSequenceNumber(),
received.getLockToken(), received.getLockedUntil(), OffsetDateTime.now());
while (lockRenewCount.get() < 4) {
lockRenewCount.incrementAndGet();
logger.info("Iteration {}: Curren time {}.", lockRenewCount.get(), OffsetDateTime.now());
try {
TimeUnit.SECONDS.sleep(5);
} catch (InterruptedException error) {
logger.error("Error occurred while sleeping: " + error);
}
}
return receiver.complete(received).thenReturn(received);
}))
.assertNext(received -> {
assertTrue(lockRenewCount.get() > 0);
messagesPending.decrementAndGet();
})
.thenCancel()
.verify();
}
@MethodSource("com.azure.messaging.servicebus.IntegrationTestBase
@ParameterizedTest
void receiveAndAbandon(MessagingEntityType entityType, boolean isSessionEnabled) {
setSender(entityType, TestUtils.USE_CASE_DEFAULT, isSessionEnabled);
final String messageId = UUID.randomUUID().toString();
final ServiceBusMessage message = getMessage(messageId, isSessionEnabled);
sendMessage(message).block(TIMEOUT);
setReceiver(entityType, TestUtils.USE_CASE_DEFAULT, isSessionEnabled);
StepVerifier.create(receiver.receiveMessages()
.flatMap(receivedMessage -> receiver.abandon(receivedMessage).thenReturn(receivedMessage)).take(1))
.assertNext(receivedMessage -> assertMessageEquals(receivedMessage, messageId, isSessionEnabled))
.expectComplete();
}
@MethodSource("com.azure.messaging.servicebus.IntegrationTestBase
@ParameterizedTest
void receiveAndDefer(MessagingEntityType entityType, boolean isSessionEnabled) {
setSender(entityType, TestUtils.USE_CASE_PEEK_RECEIVE_AND_DEFER, isSessionEnabled);
final String messageId = UUID.randomUUID().toString();
final ServiceBusMessage message = getMessage(messageId, isSessionEnabled);
sendMessage(message).block(TIMEOUT);
setReceiver(entityType, TestUtils.USE_CASE_PEEK_RECEIVE_AND_DEFER, isSessionEnabled);
AtomicReference<ServiceBusReceivedMessage> received = new AtomicReference<>();
StepVerifier.create(receiver.receiveMessages()
.flatMap(receivedMessage -> receiver.defer(receivedMessage).thenReturn(receivedMessage)).take(1))
.assertNext(m -> {
received.set(m);
assertMessageEquals(m, messageId, isSessionEnabled);
messagesPending.decrementAndGet();
}).verifyComplete();
/*receiver.receiveDeferredMessage(received.get().getSequenceNumber())
.flatMap(m -> receiver.complete(m))
.block(TIMEOUT);
messagesPending.decrementAndGet();
*/
}
/**
* Test we can receive a deferred message via sequence number and then perform abandon, suspend, or complete on it.
*/
@MethodSource("com.azure.messaging.servicebus.IntegrationTestBase
@ParameterizedTest
void receiveDeferredMessageBySequenceNumber(MessagingEntityType entityType, DispositionStatus dispositionStatus) {
setSenderAndReceiver(entityType, TestUtils.USE_CASE_DEFERRED_MESSAGE_BY_SEQUENCE_NUMBER, false);
final String messageId = UUID.randomUUID().toString();
final ServiceBusMessage message = getMessage(messageId, false);
sendMessage(message).block(TIMEOUT);
final ServiceBusReceivedMessage receivedMessage = receiver.receiveMessages().next().block(TIMEOUT);
assertNotNull(receivedMessage);
receiver.defer(receivedMessage).block(TIMEOUT);
final ServiceBusReceivedMessage receivedDeferredMessage = receiver
.receiveDeferredMessage(receivedMessage.getSequenceNumber())
.block(TIMEOUT);
assertNotNull(receivedDeferredMessage);
assertEquals(receivedMessage.getSequenceNumber(), receivedDeferredMessage.getSequenceNumber());
final Mono<Void> operation;
switch (dispositionStatus) {
case ABANDONED:
operation = receiver.abandon(receivedDeferredMessage);
break;
case SUSPENDED:
operation = receiver.deadLetter(receivedDeferredMessage);
break;
case COMPLETED:
operation = receiver.complete(receivedDeferredMessage);
break;
default:
throw logger.logExceptionAsError(new IllegalArgumentException(
"Disposition status not recognized for this test case: " + dispositionStatus));
}
StepVerifier.create(operation)
.expectComplete()
.verify();
if (dispositionStatus != DispositionStatus.COMPLETED) {
messagesPending.decrementAndGet();
}
}
@MethodSource("com.azure.messaging.servicebus.IntegrationTestBase
@ParameterizedTest
void sendReceiveMessageWithVariousPropertyTypes(MessagingEntityType entityType) {
final boolean isSessionEnabled = true;
setSender(entityType, TestUtils.USE_CASE_SEND_RECEIVE_WITH_PROPERTIES, isSessionEnabled);
final String messageId = UUID.randomUUID().toString();
final ServiceBusMessage messageToSend = getMessage(messageId, isSessionEnabled);
Map<String, Object> sentProperties = messageToSend.getApplicationProperties();
sentProperties.put("NullProperty", null);
sentProperties.put("BooleanProperty", true);
sentProperties.put("ByteProperty", (byte) 1);
sentProperties.put("ShortProperty", (short) 2);
sentProperties.put("IntProperty", 3);
sentProperties.put("LongProperty", 4L);
sentProperties.put("FloatProperty", 5.5f);
sentProperties.put("DoubleProperty", 6.6f);
sentProperties.put("CharProperty", 'z');
sentProperties.put("UUIDProperty", UUID.fromString("38400000-8cf0-11bd-b23e-10b96e4ef00d"));
sentProperties.put("StringProperty", "string");
sendMessage(messageToSend).block(TIMEOUT);
setReceiver(entityType, TestUtils.USE_CASE_SEND_RECEIVE_WITH_PROPERTIES, isSessionEnabled);
StepVerifier.create(receiver.receiveMessages().flatMap(receivedMessage -> receiver.complete(receivedMessage).thenReturn(receivedMessage)).take(1))
.assertNext(receivedMessage -> {
messagesPending.decrementAndGet();
assertMessageEquals(receivedMessage, messageId, isSessionEnabled);
final Map<String, Object> received = receivedMessage.getApplicationProperties();
assertEquals(sentProperties.size(), received.size());
for (Map.Entry<String, Object> sentEntry : sentProperties.entrySet()) {
if (sentEntry.getValue() != null && sentEntry.getValue().getClass().isArray()) {
assertArrayEquals((Object[]) sentEntry.getValue(), (Object[]) received.get(sentEntry.getKey()));
} else {
final Object expected = sentEntry.getValue();
final Object actual = received.get(sentEntry.getKey());
assertEquals(expected, actual, String.format(
"Key '%s' does not match. Expected: '%s'. Actual: '%s'", sentEntry.getKey(), expected,
actual));
}
}
})
.thenCancel()
.verify();
}
@MethodSource("com.azure.messaging.servicebus.IntegrationTestBase
@ParameterizedTest
/**
* Verifies that we can receive a message from dead letter queue.
*/
@MethodSource("com.azure.messaging.servicebus.IntegrationTestBase
@ParameterizedTest
void receiveFromDeadLetter(MessagingEntityType entityType) {
final Duration shortWait = Duration.ofSeconds(2);
final boolean isSessionEnabled = false;
final int entityIndex = 0;
setSender(entityType, entityIndex, isSessionEnabled);
final String messageId = UUID.randomUUID().toString();
final ServiceBusMessage message = getMessage(messageId, isSessionEnabled);
final List<ServiceBusReceivedMessage> receivedMessages = new ArrayList<>();
sendMessage(message).block(TIMEOUT);
setReceiver(entityType, entityIndex, isSessionEnabled);
StepVerifier.create(receiver.receiveMessages().flatMap(receivedMessage -> receiver.deadLetter(receivedMessage).thenReturn(receivedMessage)).take(1))
.assertNext(receivedMessage -> {
assertMessageEquals(receivedMessage, messageId, isSessionEnabled);
messagesPending.decrementAndGet();
}).verifyComplete();
final ServiceBusReceiverAsyncClient deadLetterReceiver;
switch (entityType) {
case QUEUE:
final String queueName = getQueueName(entityIndex);
assertNotNull(queueName, "'queueName' cannot be null.");
deadLetterReceiver = getBuilder(false).receiver()
.queueName(queueName)
.subQueue(SubQueue.DEAD_LETTER_QUEUE)
.buildAsyncClient();
break;
case SUBSCRIPTION:
final String topicName = getTopicName(entityIndex);
final String subscriptionName = getSubscriptionBaseName();
assertNotNull(topicName, "'topicName' cannot be null.");
assertNotNull(subscriptionName, "'subscriptionName' cannot be null.");
deadLetterReceiver = getBuilder(false).receiver()
.topicName(topicName)
.subscriptionName(subscriptionName)
.subQueue(SubQueue.DEAD_LETTER_QUEUE)
.buildAsyncClient();
break;
default:
throw logger.logExceptionAsError(new IllegalArgumentException("Unknown entity type: " + entityType));
}
try {
StepVerifier.create(deadLetterReceiver.receiveMessages())
.assertNext(serviceBusReceivedMessage -> {
receivedMessages.add(serviceBusReceivedMessage);
assertMessageEquals(serviceBusReceivedMessage, messageId, isSessionEnabled);
})
.thenAwait(shortWait)
.thenCancel()
.verify();
} finally {
deadLetterReceiver.close();
}
}
@MethodSource("com.azure.messaging.servicebus.IntegrationTestBase
@ParameterizedTest
void renewMessageLock(MessagingEntityType entityType) {
final boolean isSessionEnabled = false;
setSenderAndReceiver(entityType, TestUtils.USE_CASE_DEFAULT, isSessionEnabled);
final Duration maximumDuration = Duration.ofSeconds(35);
final Duration sleepDuration = maximumDuration.plusMillis(500);
final String messageId = UUID.randomUUID().toString();
final ServiceBusMessage message = getMessage(messageId, isSessionEnabled);
final ServiceBusReceivedMessage receivedMessage = sendMessage(message)
.then(receiver.receiveMessages().next())
.block(TIMEOUT);
assertNotNull(receivedMessage);
final OffsetDateTime lockedUntil = receivedMessage.getLockedUntil();
assertNotNull(lockedUntil);
StepVerifier.create(receiver.renewMessageLock(receivedMessage, maximumDuration))
.thenAwait(sleepDuration)
.then(() -> {
logger.info("Completing message.");
int numberCompleted = completeMessages(receiver, Collections.singletonList(receivedMessage));
messagesPending.addAndGet(-numberCompleted);
})
.expectComplete()
.verify(Duration.ofMinutes(3));
}
/**
* Verifies that we can receive a message which have different section set (i.e header, footer, annotations,
* application properties etc).
*/
@MethodSource("com.azure.messaging.servicebus.IntegrationTestBase
@ParameterizedTest
void receiveAndValidateProperties(MessagingEntityType entityType) {
final boolean isSessionEnabled = false;
final int totalMessages = 1;
final String subject = "subject";
final Map<String, Object> footer = new HashMap<>();
footer.put("footer-key-1", "footer-value-1");
footer.put("footer-key-2", "footer-value-2");
final Map<String, Object> applicationProperties = new HashMap<>();
applicationProperties.put("ap-key-1", "ap-value-1");
applicationProperties.put("ap-key-2", "ap-value-2");
final Map<String, Object> deliveryAnnotation = new HashMap<>();
deliveryAnnotation.put("delivery-annotations-key-1", "delivery-annotations-value-1");
deliveryAnnotation.put("delivery-annotations-key-2", "delivery-annotations-value-2");
final String messageId = UUID.randomUUID().toString();
final AmqpAnnotatedMessage expectedAmqpProperties = new AmqpAnnotatedMessage(
AmqpMessageBody.fromData(CONTENTS_BYTES));
expectedAmqpProperties.getProperties().setSubject(subject);
expectedAmqpProperties.getProperties().setReplyToGroupId("r-gid");
expectedAmqpProperties.getProperties().setReplyTo(new AmqpAddress("reply-to"));
expectedAmqpProperties.getProperties().setContentType("content-type");
expectedAmqpProperties.getProperties().setCorrelationId(new AmqpMessageId("correlation-id"));
expectedAmqpProperties.getProperties().setTo(new AmqpAddress("to"));
expectedAmqpProperties.getProperties().setAbsoluteExpiryTime(OffsetDateTime.now().plusSeconds(60));
expectedAmqpProperties.getProperties().setUserId("user-id-1".getBytes());
expectedAmqpProperties.getProperties().setContentEncoding("string");
expectedAmqpProperties.getProperties().setGroupSequence(2L);
expectedAmqpProperties.getProperties().setCreationTime(OffsetDateTime.now().plusSeconds(30));
expectedAmqpProperties.getHeader().setPriority((short) 2);
expectedAmqpProperties.getHeader().setFirstAcquirer(true);
expectedAmqpProperties.getHeader().setDurable(true);
expectedAmqpProperties.getFooter().putAll(footer);
expectedAmqpProperties.getDeliveryAnnotations().putAll(deliveryAnnotation);
expectedAmqpProperties.getApplicationProperties().putAll(applicationProperties);
final ServiceBusMessage message = TestUtils.getServiceBusMessage(CONTENTS_BYTES, messageId);
final AmqpAnnotatedMessage amqpAnnotatedMessage = message.getRawAmqpMessage();
amqpAnnotatedMessage.getMessageAnnotations().putAll(expectedAmqpProperties.getMessageAnnotations());
amqpAnnotatedMessage.getApplicationProperties().putAll(expectedAmqpProperties.getApplicationProperties());
amqpAnnotatedMessage.getDeliveryAnnotations().putAll(expectedAmqpProperties.getDeliveryAnnotations());
amqpAnnotatedMessage.getFooter().putAll(expectedAmqpProperties.getFooter());
final AmqpMessageHeader header = amqpAnnotatedMessage.getHeader();
header.setFirstAcquirer(expectedAmqpProperties.getHeader().isFirstAcquirer());
header.setTimeToLive(expectedAmqpProperties.getHeader().getTimeToLive());
header.setDurable(expectedAmqpProperties.getHeader().isDurable());
header.setDeliveryCount(expectedAmqpProperties.getHeader().getDeliveryCount());
header.setPriority(expectedAmqpProperties.getHeader().getPriority());
final AmqpMessageProperties amqpMessageProperties = amqpAnnotatedMessage.getProperties();
amqpMessageProperties.setReplyTo((expectedAmqpProperties.getProperties().getReplyTo()));
amqpMessageProperties.setContentEncoding((expectedAmqpProperties.getProperties().getContentEncoding()));
amqpMessageProperties.setAbsoluteExpiryTime((expectedAmqpProperties.getProperties().getAbsoluteExpiryTime()));
amqpMessageProperties.setSubject((expectedAmqpProperties.getProperties().getSubject()));
amqpMessageProperties.setContentType(expectedAmqpProperties.getProperties().getContentType());
amqpMessageProperties.setCorrelationId(expectedAmqpProperties.getProperties().getCorrelationId());
amqpMessageProperties.setTo(expectedAmqpProperties.getProperties().getTo());
amqpMessageProperties.setGroupSequence(expectedAmqpProperties.getProperties().getGroupSequence());
amqpMessageProperties.setUserId(expectedAmqpProperties.getProperties().getUserId());
amqpMessageProperties.setAbsoluteExpiryTime(expectedAmqpProperties.getProperties().getAbsoluteExpiryTime());
amqpMessageProperties.setCreationTime(expectedAmqpProperties.getProperties().getCreationTime());
amqpMessageProperties.setReplyToGroupId(expectedAmqpProperties.getProperties().getReplyToGroupId());
setSender(entityType, TestUtils.USE_CASE_VALIDATE_AMQP_PROPERTIES, isSessionEnabled);
sendMessage(message).block(TIMEOUT);
setReceiver(entityType, TestUtils.USE_CASE_VALIDATE_AMQP_PROPERTIES, isSessionEnabled);
StepVerifier.create(receiver.receiveMessages()/*.take(totalMessages)*/)
.assertNext(received -> {
assertNotNull(received.getLockToken());
AmqpAnnotatedMessage actual = received.getRawAmqpMessage();
try {
assertArrayEquals(CONTENTS_BYTES, message.getBody().toBytes());
assertEquals(expectedAmqpProperties.getHeader().getPriority(), actual.getHeader().getPriority());
assertEquals(expectedAmqpProperties.getHeader().isFirstAcquirer(), actual.getHeader().isFirstAcquirer());
assertEquals(expectedAmqpProperties.getHeader().isDurable(), actual.getHeader().isDurable());
assertEquals(expectedAmqpProperties.getProperties().getSubject(), actual.getProperties().getSubject());
assertEquals(expectedAmqpProperties.getProperties().getReplyToGroupId(), actual.getProperties().getReplyToGroupId());
assertEquals(expectedAmqpProperties.getProperties().getReplyTo(), actual.getProperties().getReplyTo());
assertEquals(expectedAmqpProperties.getProperties().getContentType(), actual.getProperties().getContentType());
assertEquals(expectedAmqpProperties.getProperties().getCorrelationId(), actual.getProperties().getCorrelationId());
assertEquals(expectedAmqpProperties.getProperties().getTo(), actual.getProperties().getTo());
assertEquals(expectedAmqpProperties.getProperties().getAbsoluteExpiryTime().toEpochSecond(), actual.getProperties().getAbsoluteExpiryTime().toEpochSecond());
assertEquals(expectedAmqpProperties.getProperties().getSubject(), actual.getProperties().getSubject());
assertEquals(expectedAmqpProperties.getProperties().getContentEncoding(), actual.getProperties().getContentEncoding());
assertEquals(expectedAmqpProperties.getProperties().getGroupSequence(), actual.getProperties().getGroupSequence());
assertEquals(expectedAmqpProperties.getProperties().getCreationTime().toEpochSecond(), actual.getProperties().getCreationTime().toEpochSecond());
assertArrayEquals(expectedAmqpProperties.getProperties().getUserId(), actual.getProperties().getUserId());
assertMapValues(expectedAmqpProperties.getDeliveryAnnotations(), actual.getDeliveryAnnotations());
assertMapValues(expectedAmqpProperties.getMessageAnnotations(), actual.getMessageAnnotations());
assertMapValues(expectedAmqpProperties.getApplicationProperties(), actual.getApplicationProperties());
assertMapValues(expectedAmqpProperties.getFooter(), actual.getFooter());
} finally {
logger.info("Completing message.");
receiver.complete(received).block(Duration.ofSeconds(15));
messagesPending.decrementAndGet();
}
})
.thenCancel()
.verify(Duration.ofMinutes(2));
}
/**
* Verifies we can autocomplete for a queue.
*
* @param entityType Entity Type.
*/
@MethodSource("com.azure.messaging.servicebus.IntegrationTestBase
@ParameterizedTest
void autoComplete(MessagingEntityType entityType) {
final Duration shortWait = Duration.ofSeconds(2);
final int index = TestUtils.USE_CASE_AUTO_COMPLETE;
setSender(entityType, index, false);
final int numberOfEvents = 3;
final String messageId = UUID.randomUUID().toString();
final List<ServiceBusMessage> messages = getServiceBusMessages(numberOfEvents, messageId);
setReceiver(entityType, index, false);
final ServiceBusReceivedMessage lastMessage = receiver.peekMessage().block(TIMEOUT);
Mono.when(messages.stream().map(this::sendMessage)
.collect(Collectors.toList()))
.block(TIMEOUT);
final ServiceBusReceiverAsyncClient autoCompleteReceiver =
getReceiverBuilder(false, entityType, index, false)
.buildAsyncClient();
try {
StepVerifier.create(autoCompleteReceiver.receiveMessages())
.assertNext(receivedMessage -> {
if (lastMessage != null) {
assertEquals(lastMessage.getMessageId(), receivedMessage.getMessageId());
} else {
assertEquals(messageId, receivedMessage.getMessageId());
}
})
.assertNext(context -> {
if (lastMessage == null) {
assertEquals(messageId, context.getMessageId());
}
})
.assertNext(context -> {
if (lastMessage == null) {
assertEquals(messageId, context.getMessageId());
}
})
.thenAwait(shortWait)
.thenCancel()
.verify(TIMEOUT);
} finally {
autoCompleteReceiver.close();
}
final ServiceBusReceivedMessage newLastMessage = receiver.peekMessage().block(TIMEOUT);
if (lastMessage == null) {
assertNull(newLastMessage,
String.format("Actual messageId[%s]", newLastMessage != null ? newLastMessage.getMessageId() : "n/a"));
} else {
assertNotNull(newLastMessage);
assertEquals(lastMessage.getSequenceNumber(), newLastMessage.getSequenceNumber());
}
}
/**
* Asserts the length and values with in the map.
*/
private void assertMapValues(Map<String, Object> expectedMap, Map<String, Object> actualMap) {
assertTrue(actualMap.size() >= expectedMap.size());
for (String key : expectedMap.keySet()) {
assertEquals(expectedMap.get(key), actualMap.get(key), "Value is not equal for Key " + key);
}
}
/**
* Sets the sender and receiver. If session is enabled, then a single-named session receiver is created.
*/
private void setSenderAndReceiver(MessagingEntityType entityType, int entityIndex, boolean isSessionEnabled) {
setSender(entityType, entityIndex, isSessionEnabled);
setReceiver(entityType, entityIndex, isSessionEnabled);
}
private void setReceiver(MessagingEntityType entityType, int entityIndex, boolean isSessionEnabled) {
final boolean shareConnection = false;
final boolean useCredentials = false;
if (isSessionEnabled) {
assertNotNull(sessionId, "'sessionId' should have been set.");
sessionReceiver = getSessionReceiverBuilder(useCredentials, entityType, entityIndex, shareConnection)
.disableAutoComplete()
.buildAsyncClient();
this.receiver = sessionReceiver.acceptSession(sessionId).block();
} else {
this.receiver = getReceiverBuilder(useCredentials, entityType, entityIndex, shareConnection)
.disableAutoComplete()
.buildAsyncClient();
}
}
private void setSender(MessagingEntityType entityType, int entityIndex, boolean isSessionEnabled) {
final boolean shareConnection = false;
final boolean useCredentials = false;
this.sender = getSenderBuilder(useCredentials, entityType, entityIndex, isSessionEnabled, shareConnection)
.buildAsyncClient();
}
private Mono<Void> sendMessage(ServiceBusMessage message) {
return sender.sendMessage(message).doOnSuccess(aVoid -> {
int number = messagesPending.incrementAndGet();
logger.info("Message Id {}. Number sent: {}", message.getMessageId(), number);
});
}
private int completeMessages(ServiceBusReceiverAsyncClient client, List<ServiceBusReceivedMessage> messages) {
Mono.when(messages.stream().map(e -> client.complete(e))
.collect(Collectors.toList()))
.block(TIMEOUT);
return messages.size();
}
} | class ServiceBusReceiverAsyncClientIntegrationTest extends IntegrationTestBase {
private final ClientLogger logger = new ClientLogger(ServiceBusReceiverAsyncClientIntegrationTest.class);
private final AtomicInteger messagesPending = new AtomicInteger();
private final boolean isSessionEnabled = false;
private ServiceBusReceiverAsyncClient receiver;
private ServiceBusSenderAsyncClient sender;
private ServiceBusSessionReceiverAsyncClient sessionReceiver;
ServiceBusReceiverAsyncClientIntegrationTest() {
super(new ClientLogger(ServiceBusReceiverAsyncClientIntegrationTest.class));
}
@Override
protected void beforeTest() {
sessionId = UUID.randomUUID().toString();
}
@Override
protected void afterTest() {
sharedBuilder = null;
try {
dispose(receiver, sender, sessionReceiver);
} catch (Exception e) {
logger.warning("Error occurred when draining queue.", e);
}
}
/**
* Verifies that we can create multiple transaction using sender and receiver.
*/
@Test
void createMultipleTransactionTest() {
setSenderAndReceiver(MessagingEntityType.QUEUE, 0, isSessionEnabled);
StepVerifier.create(receiver.createTransaction())
.assertNext(Assertions::assertNotNull)
.verifyComplete();
StepVerifier.create(receiver.createTransaction())
.assertNext(Assertions::assertNotNull)
.verifyComplete();
}
/**
* Verifies that we can create transaction and complete.
*/
@MethodSource("com.azure.messaging.servicebus.IntegrationTestBase
@ParameterizedTest
void createTransactionAndRollbackMessagesTest(MessagingEntityType entityType) {
setSender(entityType, TestUtils.USE_CASE_DEFAULT, isSessionEnabled);
final String messageId = UUID.randomUUID().toString();
final ServiceBusMessage message = getMessage(messageId, isSessionEnabled);
sendMessage(message).block(OPERATION_TIMEOUT);
setReceiver(entityType, TestUtils.USE_CASE_DEFAULT, isSessionEnabled);
AtomicReference<ServiceBusTransactionContext> transaction = new AtomicReference<>();
StepVerifier.create(receiver.createTransaction())
.assertNext(txn -> {
transaction.set(txn);
assertNotNull(transaction);
})
.verifyComplete();
StepVerifier.create(receiver.receiveMessages()
.flatMap(receivedMessage -> receiver.complete(receivedMessage).thenReturn(receivedMessage)).take(1))
.assertNext(receivedMessage -> {
assertMessageEquals(receivedMessage, messageId, isSessionEnabled);
messagesPending.decrementAndGet();
}).verifyComplete();
StepVerifier.create(receiver.rollbackTransaction(transaction.get()))
.verifyComplete();
}
/**
* Verifies that we can do following using shared connection and on non session entity. 1. create transaction 2.
* receive and settle with transactionContext. 3. commit Rollback this transaction.
*/
@ParameterizedTest
@EnumSource(DispositionStatus.class)
void transactionSendReceiveAndCommit(DispositionStatus dispositionStatus) {
final MessagingEntityType entityType = MessagingEntityType.QUEUE;
setSenderAndReceiver(entityType, TestUtils.USE_CASE_PEEK_TRANSACTION_SENDRECEIVE_AND_COMPLETE, isSessionEnabled);
final String messageId1 = UUID.randomUUID().toString();
final ServiceBusMessage message1 = getMessage(messageId1, isSessionEnabled);
final String deadLetterReason = "test reason";
sendMessage(message1).block(TIMEOUT);
AtomicReference<ServiceBusTransactionContext> transaction = new AtomicReference<>();
StepVerifier.create(receiver.createTransaction())
.assertNext(txn -> {
transaction.set(txn);
assertNotNull(transaction);
})
.verifyComplete();
assertNotNull(transaction.get());
final ServiceBusReceivedMessage receivedMessage = receiver.receiveMessages().next().block(TIMEOUT);
assertNotNull(receivedMessage);
final Mono<Void> operation;
switch (dispositionStatus) {
case COMPLETED:
operation = receiver.complete(receivedMessage, new CompleteOptions().setTransactionContext(transaction.get()));
messagesPending.decrementAndGet();
break;
case ABANDONED:
operation = receiver.abandon(receivedMessage, new AbandonOptions().setTransactionContext(transaction.get()));
break;
case SUSPENDED:
DeadLetterOptions deadLetterOptions = new DeadLetterOptions().setTransactionContext(transaction.get())
.setDeadLetterReason(deadLetterReason);
operation = receiver.deadLetter(receivedMessage, deadLetterOptions);
messagesPending.decrementAndGet();
break;
case DEFERRED:
operation = receiver.defer(receivedMessage, new DeferOptions().setTransactionContext(transaction.get()));
break;
default:
throw logger.logExceptionAsError(new IllegalArgumentException(
"Disposition status not recognized for this test case: " + dispositionStatus));
}
StepVerifier.create(operation)
.verifyComplete();
StepVerifier.create(receiver.commitTransaction(transaction.get()))
.verifyComplete();
}
/**
* Verifies that we can do following on different clients i.e. sender and receiver. 1. create transaction using
* sender 2. receive and complete with transactionContext. 3. Commit this transaction using sender.
*/
@MethodSource("com.azure.messaging.servicebus.IntegrationTestBase
@ParameterizedTest
@Disabled
void transactionReceiveCompleteCommitMixClient(MessagingEntityType entityType) {
final boolean shareConnection = true;
final boolean useCredentials = false;
final int entityIndex = 0;
this.sender = getSenderBuilder(useCredentials, entityType, entityIndex, isSessionEnabled, shareConnection)
.buildAsyncClient();
this.receiver = getReceiverBuilder(useCredentials, entityType, entityIndex, shareConnection)
.buildAsyncClient();
final String messageId = UUID.randomUUID().toString();
final ServiceBusMessage message = getMessage(messageId, isSessionEnabled);
sendMessage(message).block(TIMEOUT);
AtomicReference<ServiceBusTransactionContext> transaction = new AtomicReference<>();
StepVerifier.create(sender.createTransaction())
.assertNext(txn -> {
transaction.set(txn);
assertNotNull(transaction);
})
.verifyComplete();
assertNotNull(transaction.get());
final ServiceBusReceivedMessage receivedMessage = receiver.receiveMessages().next().block(TIMEOUT);
assertNotNull(receivedMessage);
StepVerifier.create(receiver.complete(receivedMessage, new CompleteOptions().setTransactionContext(transaction.get())))
.verifyComplete();
StepVerifier.create(sender.commitTransaction(transaction.get()))
.verifyComplete();
}
/**
* Verifies that we can send and receive two messages.
*/
@MethodSource("com.azure.messaging.servicebus.IntegrationTestBase
@ParameterizedTest
void receiveTwoMessagesAutoComplete(MessagingEntityType entityType, boolean isSessionEnabled) {
final int entityIndex = 0;
final boolean shareConnection = false;
final boolean useCredentials = false;
final Duration shortWait = Duration.ofSeconds(3);
this.sender = getSenderBuilder(useCredentials, entityType, entityIndex, isSessionEnabled, shareConnection)
.buildAsyncClient();
final String messageId = UUID.randomUUID().toString();
final ServiceBusMessage message = getMessage(messageId, isSessionEnabled);
Mono.when(sendMessage(message), sendMessage(message)).block(TIMEOUT);
if (isSessionEnabled) {
assertNotNull(sessionId, "'sessionId' should have been set.");
this.sessionReceiver = getSessionReceiverBuilder(useCredentials, entityType, entityIndex, shareConnection)
.buildAsyncClient();
this.receiver = sessionReceiver.acceptSession(sessionId).block();
} else {
this.receiver = getReceiverBuilder(useCredentials, entityType, entityIndex, shareConnection)
.buildAsyncClient();
}
StepVerifier.create(receiver.receiveMessages())
.assertNext(receivedMessage -> {
assertMessageEquals(receivedMessage, messageId, isSessionEnabled);
})
.assertNext(receivedMessage -> {
assertMessageEquals(receivedMessage, messageId, isSessionEnabled);
})
.thenAwait(shortWait)
.thenCancel()
.verify();
}
/**
* Verifies that we can send and receive a message.
*/
@MethodSource("com.azure.messaging.servicebus.IntegrationTestBase
@ParameterizedTest
void receiveMessageAutoComplete(MessagingEntityType entityType, boolean isSessionEnabled) {
final int entityIndex = 0;
final boolean shareConnection = false;
final boolean useCredentials = false;
final Duration shortWait = Duration.ofSeconds(3);
this.sender = getSenderBuilder(useCredentials, entityType, entityIndex, isSessionEnabled, shareConnection)
.buildAsyncClient();
final String messageId = UUID.randomUUID().toString();
final ServiceBusMessage message = getMessage(messageId, isSessionEnabled);
sendMessage(message).block(TIMEOUT);
if (isSessionEnabled) {
assertNotNull(sessionId, "'sessionId' should have been set.");
this.sessionReceiver = getSessionReceiverBuilder(useCredentials, entityType, entityIndex, shareConnection)
.buildAsyncClient();
this.receiver = this.sessionReceiver.acceptSession(sessionId).block();
} else {
this.receiver = getReceiverBuilder(useCredentials, entityType, entityIndex, shareConnection)
.buildAsyncClient();
}
StepVerifier.create(receiver.receiveMessages())
.assertNext(receivedMessage -> {
assertMessageEquals(receivedMessage, messageId, isSessionEnabled);
})
.thenAwait(shortWait)
.thenCancel()
.verify();
StepVerifier.create(receiver.receiveMessages())
.thenAwait(shortWait)
.thenCancel()
.verify();
}
/**
* Verifies that we can send and peek a message.
*/
@MethodSource("com.azure.messaging.servicebus.IntegrationTestBase
@ParameterizedTest
void peekMessage(MessagingEntityType entityType, boolean isSessionEnabled) {
setSender(entityType, TestUtils.USE_CASE_DEFAULT, isSessionEnabled);
final String messageId = UUID.randomUUID().toString();
final ServiceBusMessage message = getMessage(messageId, isSessionEnabled);
sendMessage(message).block(TIMEOUT);
setReceiver(entityType, TestUtils.USE_CASE_DEFAULT, isSessionEnabled);
StepVerifier.create(receiver.peekMessage())
.assertNext(receivedMessage -> assertMessageEquals(receivedMessage, messageId, isSessionEnabled))
.verifyComplete();
StepVerifier.create(receiver.receiveMessages().flatMap(receivedMessage -> receiver.complete(receivedMessage).thenReturn(receivedMessage)).take(1))
.assertNext(receivedMessage -> assertMessageEquals(receivedMessage, messageId, isSessionEnabled))
.verifyComplete();
}
/**
* Verifies that an empty entity does not error when peeking.
*/
@MethodSource("com.azure.messaging.servicebus.IntegrationTestBase
@ParameterizedTest
void peekMessageEmptyEntity(MessagingEntityType entityType, boolean isSessionEnabled) {
setReceiver(entityType, TestUtils.USE_CASE_EMPTY_ENTITY, isSessionEnabled);
final int fromSequenceNumber = 1;
StepVerifier.create(receiver.peekMessage(fromSequenceNumber))
.verifyComplete();
}
/**
* Verifies that we can schedule and receive a message.
*/
@MethodSource("com.azure.messaging.servicebus.IntegrationTestBase
@ParameterizedTest
void sendScheduledMessageAndReceive(MessagingEntityType entityType, boolean isSessionEnabled) {
setSender(entityType, TestUtils.USE_CASE_DEFAULT, isSessionEnabled);
final Duration shortDelay = Duration.ofSeconds(4);
final String messageId = UUID.randomUUID().toString();
final ServiceBusMessage message = getMessage(messageId, isSessionEnabled);
final OffsetDateTime scheduledEnqueueTime = OffsetDateTime.now().plusSeconds(2);
sender.scheduleMessage(message, scheduledEnqueueTime).block(TIMEOUT);
setReceiver(entityType, TestUtils.USE_CASE_DEFAULT, isSessionEnabled);
StepVerifier.create(Mono.delay(shortDelay).then(receiver.receiveMessages()
.flatMap(receivedMessage -> receiver.complete(receivedMessage).thenReturn(receivedMessage)).next()))
.assertNext(receivedMessage -> {
assertMessageEquals(receivedMessage, messageId, isSessionEnabled);
messagesPending.decrementAndGet();
}).verifyComplete();
}
/**
* Verifies that we can cancel a scheduled message.
*/
@MethodSource("com.azure.messaging.servicebus.IntegrationTestBase
@ParameterizedTest
void cancelScheduledMessage(MessagingEntityType entityType, boolean isSessionEnabled) {
setSender(entityType, TestUtils.USE_CASE_DEFAULT, isSessionEnabled);
final String messageId = UUID.randomUUID().toString();
final ServiceBusMessage message = getMessage(messageId, isSessionEnabled);
final OffsetDateTime scheduledEnqueueTime = OffsetDateTime.now().plusSeconds(10);
final Duration delayDuration = Duration.ofSeconds(3);
final Long sequenceNumber = sender.scheduleMessage(message, scheduledEnqueueTime).block(TIMEOUT);
logger.verbose("Scheduled the message, sequence number {}.", sequenceNumber);
assertNotNull(sequenceNumber);
Mono.delay(delayDuration)
.then(sender.cancelScheduledMessage(sequenceNumber))
.block(TIMEOUT);
messagesPending.decrementAndGet();
logger.verbose("Cancelled the scheduled message, sequence number {}.", sequenceNumber);
setReceiver(entityType, TestUtils.USE_CASE_DEFAULT, isSessionEnabled);
StepVerifier.create(receiver.receiveMessages().take(1))
.thenAwait(Duration.ofSeconds(5))
.thenCancel()
.verify();
}
/**
* Verifies that we can send and peek a message.
*/
@MethodSource("com.azure.messaging.servicebus.IntegrationTestBase
@ParameterizedTest
void peekFromSequenceNumberMessage(MessagingEntityType entityType, boolean isSessionEnabled) {
final int entityIndex = 3;
setSender(entityType, entityIndex, isSessionEnabled);
final String messageId = UUID.randomUUID().toString();
final ServiceBusMessage message = getMessage(messageId, isSessionEnabled);
sendMessage(message).block(TIMEOUT);
setReceiver(entityType, entityIndex, isSessionEnabled);
final ServiceBusReceivedMessage peekMessage = receiver.peekMessage().block(TIMEOUT);
assertNotNull(peekMessage);
final long sequenceNumber = peekMessage.getSequenceNumber();
try {
StepVerifier.create(receiver.peekMessage(sequenceNumber))
.assertNext(m -> {
assertEquals(sequenceNumber, m.getSequenceNumber());
assertMessageEquals(m, messageId, isSessionEnabled);
})
.verifyComplete();
} finally {
StepVerifier.create(receiver.receiveMessages()
.flatMap(receivedMessage -> receiver.complete(receivedMessage).thenReturn(receivedMessage)).take(1))
.expectNextCount(1)
.verifyComplete();
messagesPending.decrementAndGet();
}
}
/**
* Verifies that we can send and peek a batch of messages and the sequence number is tracked correctly.
*/
@MethodSource("com.azure.messaging.servicebus.IntegrationTestBase
@ParameterizedTest
void peekMessages(MessagingEntityType entityType, boolean isSessionEnabled) {
setSender(entityType, TestUtils.USE_CASE_PEEK_BATCH_MESSAGES, isSessionEnabled);
final BiConsumer<ServiceBusReceivedMessage, Integer> checkCorrectMessage = (message, index) -> {
final Map<String, Object> properties = message.getApplicationProperties();
final Object value = properties.get(MESSAGE_POSITION_ID);
assertTrue(value instanceof Integer, "Did not contain correct position number: " + value);
final int position = (int) value;
assertEquals(index, position);
};
final String messageId = UUID.randomUUID().toString();
final List<ServiceBusMessage> messages = TestUtils.getServiceBusMessages(10, messageId, CONTENTS_BYTES);
if (isSessionEnabled) {
messages.forEach(m -> m.setSessionId(sessionId));
}
sender.sendMessages(messages)
.doOnSuccess(aVoid -> {
int number = messagesPending.addAndGet(messages.size());
logger.info("Number of messages sent: {}", number);
})
.block(TIMEOUT);
setReceiver(entityType, TestUtils.USE_CASE_PEEK_BATCH_MESSAGES, isSessionEnabled);
try {
StepVerifier.create(receiver.peekMessages(3))
.assertNext(message -> checkCorrectMessage.accept(message, 0))
.assertNext(message -> checkCorrectMessage.accept(message, 1))
.assertNext(message -> checkCorrectMessage.accept(message, 2))
.verifyComplete();
StepVerifier.create(receiver.peekMessages(4))
.assertNext(message -> checkCorrectMessage.accept(message, 3))
.assertNext(message -> checkCorrectMessage.accept(message, 4))
.assertNext(message -> checkCorrectMessage.accept(message, 5))
.assertNext(message -> checkCorrectMessage.accept(message, 6))
.verifyComplete();
StepVerifier.create(receiver.peekMessage())
.assertNext(message -> checkCorrectMessage.accept(message, 7))
.verifyComplete();
} finally {
AtomicInteger completed = new AtomicInteger();
StepVerifier.create(receiver.receiveMessages().take(messages.size()))
.thenConsumeWhile(receivedMessage -> {
completed.incrementAndGet();
receiver.complete(receivedMessage).block(OPERATION_TIMEOUT);
return completed.get() <= messages.size();
})
.thenCancel()
.verify();
messagesPending.addAndGet(-messages.size());
}
}
/**
* Verifies that we can send and peek a batch of messages.
*/
@MethodSource("com.azure.messaging.servicebus.IntegrationTestBase
@ParameterizedTest
void peekMessagesFromSequence(MessagingEntityType entityType) {
setSenderAndReceiver(entityType, TestUtils.USE_CASE_PEEK_MESSAGE_FROM_SEQUENCE, false);
final String messageId = UUID.randomUUID().toString();
final ServiceBusMessage message = getMessage(messageId, false);
final int maxMessages = 2;
final int fromSequenceNumber = 1;
Mono.when(sendMessage(message), sendMessage(message)).block(TIMEOUT);
StepVerifier.create(receiver.peekMessages(maxMessages, fromSequenceNumber))
.expectNextCount(maxMessages)
.verifyComplete();
StepVerifier.create(receiver.receiveMessages().take(maxMessages))
.assertNext(receivedMessage -> {
receiver.complete(receivedMessage).block(Duration.ofSeconds(15));
})
.assertNext(receivedMessage -> {
receiver.complete(receivedMessage).block(Duration.ofSeconds(15));
})
.expectComplete()
.verify(TIMEOUT);
}
/**
* Verifies that an empty entity does not error when peeking.
*/
@MethodSource("com.azure.messaging.servicebus.IntegrationTestBase
@ParameterizedTest
void peekMessagesFromSequenceEmptyEntity(MessagingEntityType entityType, boolean isSessionEnabled) {
setReceiver(entityType, TestUtils.USE_CASE_EMPTY_ENTITY, isSessionEnabled);
final int maxMessages = 10;
final int fromSequenceNumber = 1;
StepVerifier.create(receiver.peekMessages(maxMessages, fromSequenceNumber))
.verifyComplete();
}
/**
* Verifies that we can dead-letter a message.
*/
@MethodSource("com.azure.messaging.servicebus.IntegrationTestBase
@ParameterizedTest
void deadLetterMessage(MessagingEntityType entityType, boolean isSessionEnabled) {
final int entityIndex = 0;
setSender(entityType, entityIndex, isSessionEnabled);
final String messageId = UUID.randomUUID().toString();
final ServiceBusMessage message = getMessage(messageId, isSessionEnabled);
sendMessage(message).block(TIMEOUT);
setReceiver(entityType, entityIndex, isSessionEnabled);
StepVerifier.create(receiver.receiveMessages()
.flatMap(receivedMessage -> receiver.deadLetter(receivedMessage).thenReturn(receivedMessage)).take(1))
.assertNext(receivedMessage -> {
assertMessageEquals(receivedMessage, messageId, isSessionEnabled);
messagesPending.decrementAndGet();
})
.thenCancel()
.verify();
}
@MethodSource("com.azure.messaging.servicebus.IntegrationTestBase
@ParameterizedTest
void receiveAndComplete(MessagingEntityType entityType, boolean isSessionEnabled) {
setSender(entityType, TestUtils.USE_CASE_DEFAULT, isSessionEnabled);
final String messageId = UUID.randomUUID().toString();
final ServiceBusMessage message = getMessage(messageId, isSessionEnabled);
sendMessage(message).block(TIMEOUT);
setReceiver(entityType, TestUtils.USE_CASE_DEFAULT, isSessionEnabled);
StepVerifier.create(receiver.receiveMessages()
.flatMap(receivedMessage -> receiver.complete(receivedMessage).thenReturn(receivedMessage)).take(1))
.assertNext(receivedMessage -> {
assertMessageEquals(receivedMessage, messageId, isSessionEnabled);
messagesPending.decrementAndGet();
}).verifyComplete();
messagesPending.decrementAndGet();
}
/**
* Verifies that we can renew message lock on a non-session receiver.
*/
@MethodSource("com.azure.messaging.servicebus.IntegrationTestBase
@ParameterizedTest
void receiveAndRenewLock(MessagingEntityType entityType) {
setSender(entityType, TestUtils.USE_CASE_DEFAULT, false);
final String messageId = UUID.randomUUID().toString();
final ServiceBusMessage message = getMessage(messageId, false);
sendMessage(message).block(TIMEOUT);
setReceiver(entityType, TestUtils.USE_CASE_DEFAULT, false);
final ServiceBusReceivedMessage receivedMessage = receiver.receiveMessages().next().block(TIMEOUT);
assertNotNull(receivedMessage);
assertNotNull(receivedMessage.getLockedUntil());
final OffsetDateTime initialLock = receivedMessage.getLockedUntil();
logger.info("Received message. Seq: {}. lockedUntil: {}", receivedMessage.getSequenceNumber(), initialLock);
try {
StepVerifier.create(Mono.delay(Duration.ofSeconds(7))
.then(Mono.defer(() -> receiver.renewMessageLock(receivedMessage))))
.assertNext(lockedUntil -> {
assertTrue(lockedUntil.isAfter(initialLock),
String.format("Updated lock is not after the initial Lock. updated: [%s]. initial:[%s]",
lockedUntil, initialLock));
})
.verifyComplete();
} finally {
logger.info("Completing message. Seq: {}.", receivedMessage.getSequenceNumber());
receiver.complete(receivedMessage)
.doOnSuccess(aVoid -> messagesPending.decrementAndGet())
.block(TIMEOUT);
}
}
/**
* Verifies that the lock can be automatically renewed.
*/
@MethodSource("com.azure.messaging.servicebus.IntegrationTestBase
@ParameterizedTest
void autoRenewLockOnReceiveMessage(MessagingEntityType entityType, boolean isSessionEnabled) {
final AtomicInteger lockRenewCount = new AtomicInteger();
setSender(entityType, TestUtils.USE_CASE_DEFAULT, isSessionEnabled);
final String messageId = UUID.randomUUID().toString();
final ServiceBusMessage message = getMessage(messageId, isSessionEnabled);
sendMessage(message).block(TIMEOUT);
setReceiver(entityType, TestUtils.USE_CASE_DEFAULT, isSessionEnabled);
StepVerifier.create(receiver.receiveMessages().flatMap(received -> {
logger.info("{}: lockToken[{}]. lockedUntil[{}]. now[{}]", received.getSequenceNumber(),
received.getLockToken(), received.getLockedUntil(), OffsetDateTime.now());
while (lockRenewCount.get() < 4) {
lockRenewCount.incrementAndGet();
logger.info("Iteration {}: Curren time {}.", lockRenewCount.get(), OffsetDateTime.now());
try {
TimeUnit.SECONDS.sleep(5);
} catch (InterruptedException error) {
logger.error("Error occurred while sleeping: " + error);
}
}
return receiver.complete(received).thenReturn(received);
}))
.assertNext(received -> {
assertTrue(lockRenewCount.get() > 0);
messagesPending.decrementAndGet();
})
.thenCancel()
.verify();
}
@MethodSource("com.azure.messaging.servicebus.IntegrationTestBase
@ParameterizedTest
void receiveAndAbandon(MessagingEntityType entityType, boolean isSessionEnabled) {
setSender(entityType, TestUtils.USE_CASE_DEFAULT, isSessionEnabled);
final String messageId = UUID.randomUUID().toString();
final ServiceBusMessage message = getMessage(messageId, isSessionEnabled);
sendMessage(message).block(TIMEOUT);
setReceiver(entityType, TestUtils.USE_CASE_DEFAULT, isSessionEnabled);
StepVerifier.create(receiver.receiveMessages()
.flatMap(receivedMessage -> receiver.abandon(receivedMessage).thenReturn(receivedMessage)).take(1))
.assertNext(receivedMessage -> assertMessageEquals(receivedMessage, messageId, isSessionEnabled))
.expectComplete();
}
@MethodSource("com.azure.messaging.servicebus.IntegrationTestBase
@ParameterizedTest
void receiveAndDefer(MessagingEntityType entityType, boolean isSessionEnabled) {
setSender(entityType, TestUtils.USE_CASE_PEEK_RECEIVE_AND_DEFER, isSessionEnabled);
final String messageId = UUID.randomUUID().toString();
final ServiceBusMessage message = getMessage(messageId, isSessionEnabled);
sendMessage(message).block(TIMEOUT);
setReceiver(entityType, TestUtils.USE_CASE_PEEK_RECEIVE_AND_DEFER, isSessionEnabled);
AtomicReference<ServiceBusReceivedMessage> received = new AtomicReference<>();
StepVerifier.create(receiver.receiveMessages()
.flatMap(receivedMessage -> receiver.defer(receivedMessage).thenReturn(receivedMessage)).take(1))
.assertNext(m -> {
received.set(m);
assertMessageEquals(m, messageId, isSessionEnabled);
messagesPending.decrementAndGet();
}).verifyComplete();
/*receiver.receiveDeferredMessage(received.get().getSequenceNumber())
.flatMap(m -> receiver.complete(m))
.block(TIMEOUT);
messagesPending.decrementAndGet();
*/
}
/**
* Test we can receive a deferred message via sequence number and then perform abandon, suspend, or complete on it.
*/
@MethodSource("com.azure.messaging.servicebus.IntegrationTestBase
@ParameterizedTest
void receiveDeferredMessageBySequenceNumber(MessagingEntityType entityType, DispositionStatus dispositionStatus) {
setSenderAndReceiver(entityType, TestUtils.USE_CASE_DEFERRED_MESSAGE_BY_SEQUENCE_NUMBER, false);
final String messageId = UUID.randomUUID().toString();
final ServiceBusMessage message = getMessage(messageId, false);
sendMessage(message).block(TIMEOUT);
final ServiceBusReceivedMessage receivedMessage = receiver.receiveMessages().next().block(TIMEOUT);
assertNotNull(receivedMessage);
receiver.defer(receivedMessage).block(TIMEOUT);
final ServiceBusReceivedMessage receivedDeferredMessage = receiver
.receiveDeferredMessage(receivedMessage.getSequenceNumber())
.block(TIMEOUT);
assertNotNull(receivedDeferredMessage);
assertEquals(receivedMessage.getSequenceNumber(), receivedDeferredMessage.getSequenceNumber());
final Mono<Void> operation;
switch (dispositionStatus) {
case ABANDONED:
operation = receiver.abandon(receivedDeferredMessage);
break;
case SUSPENDED:
operation = receiver.deadLetter(receivedDeferredMessage);
break;
case COMPLETED:
operation = receiver.complete(receivedDeferredMessage);
break;
default:
throw logger.logExceptionAsError(new IllegalArgumentException(
"Disposition status not recognized for this test case: " + dispositionStatus));
}
StepVerifier.create(operation)
.expectComplete()
.verify();
if (dispositionStatus != DispositionStatus.COMPLETED) {
messagesPending.decrementAndGet();
}
}
@MethodSource("com.azure.messaging.servicebus.IntegrationTestBase
@ParameterizedTest
void sendReceiveMessageWithVariousPropertyTypes(MessagingEntityType entityType) {
final boolean isSessionEnabled = true;
setSender(entityType, TestUtils.USE_CASE_SEND_RECEIVE_WITH_PROPERTIES, isSessionEnabled);
final String messageId = UUID.randomUUID().toString();
final ServiceBusMessage messageToSend = getMessage(messageId, isSessionEnabled);
Map<String, Object> sentProperties = messageToSend.getApplicationProperties();
sentProperties.put("NullProperty", null);
sentProperties.put("BooleanProperty", true);
sentProperties.put("ByteProperty", (byte) 1);
sentProperties.put("ShortProperty", (short) 2);
sentProperties.put("IntProperty", 3);
sentProperties.put("LongProperty", 4L);
sentProperties.put("FloatProperty", 5.5f);
sentProperties.put("DoubleProperty", 6.6f);
sentProperties.put("CharProperty", 'z');
sentProperties.put("UUIDProperty", UUID.fromString("38400000-8cf0-11bd-b23e-10b96e4ef00d"));
sentProperties.put("StringProperty", "string");
sendMessage(messageToSend).block(TIMEOUT);
setReceiver(entityType, TestUtils.USE_CASE_SEND_RECEIVE_WITH_PROPERTIES, isSessionEnabled);
StepVerifier.create(receiver.receiveMessages().flatMap(receivedMessage -> receiver.complete(receivedMessage).thenReturn(receivedMessage)).take(1))
.assertNext(receivedMessage -> {
messagesPending.decrementAndGet();
assertMessageEquals(receivedMessage, messageId, isSessionEnabled);
final Map<String, Object> received = receivedMessage.getApplicationProperties();
assertEquals(sentProperties.size(), received.size());
for (Map.Entry<String, Object> sentEntry : sentProperties.entrySet()) {
if (sentEntry.getValue() != null && sentEntry.getValue().getClass().isArray()) {
assertArrayEquals((Object[]) sentEntry.getValue(), (Object[]) received.get(sentEntry.getKey()));
} else {
final Object expected = sentEntry.getValue();
final Object actual = received.get(sentEntry.getKey());
assertEquals(expected, actual, String.format(
"Key '%s' does not match. Expected: '%s'. Actual: '%s'", sentEntry.getKey(), expected,
actual));
}
}
})
.thenCancel()
.verify();
}
@MethodSource("com.azure.messaging.servicebus.IntegrationTestBase
@ParameterizedTest
/**
* Verifies that we can receive a message from dead letter queue.
*/
@MethodSource("com.azure.messaging.servicebus.IntegrationTestBase
@ParameterizedTest
void receiveFromDeadLetter(MessagingEntityType entityType) {
final Duration shortWait = Duration.ofSeconds(2);
final boolean isSessionEnabled = false;
final int entityIndex = 0;
setSender(entityType, entityIndex, isSessionEnabled);
final String messageId = UUID.randomUUID().toString();
final ServiceBusMessage message = getMessage(messageId, isSessionEnabled);
final List<ServiceBusReceivedMessage> receivedMessages = new ArrayList<>();
sendMessage(message).block(TIMEOUT);
setReceiver(entityType, entityIndex, isSessionEnabled);
StepVerifier.create(receiver.receiveMessages().flatMap(receivedMessage -> receiver.deadLetter(receivedMessage).thenReturn(receivedMessage)).take(1))
.assertNext(receivedMessage -> {
assertMessageEquals(receivedMessage, messageId, isSessionEnabled);
messagesPending.decrementAndGet();
}).verifyComplete();
final ServiceBusReceiverAsyncClient deadLetterReceiver;
switch (entityType) {
case QUEUE:
final String queueName = getQueueName(entityIndex);
assertNotNull(queueName, "'queueName' cannot be null.");
deadLetterReceiver = getBuilder(false).receiver()
.queueName(queueName)
.subQueue(SubQueue.DEAD_LETTER_QUEUE)
.buildAsyncClient();
break;
case SUBSCRIPTION:
final String topicName = getTopicName(entityIndex);
final String subscriptionName = getSubscriptionBaseName();
assertNotNull(topicName, "'topicName' cannot be null.");
assertNotNull(subscriptionName, "'subscriptionName' cannot be null.");
deadLetterReceiver = getBuilder(false).receiver()
.topicName(topicName)
.subscriptionName(subscriptionName)
.subQueue(SubQueue.DEAD_LETTER_QUEUE)
.buildAsyncClient();
break;
default:
throw logger.logExceptionAsError(new IllegalArgumentException("Unknown entity type: " + entityType));
}
try {
StepVerifier.create(deadLetterReceiver.receiveMessages())
.assertNext(serviceBusReceivedMessage -> {
receivedMessages.add(serviceBusReceivedMessage);
assertMessageEquals(serviceBusReceivedMessage, messageId, isSessionEnabled);
})
.thenAwait(shortWait)
.thenCancel()
.verify();
} finally {
deadLetterReceiver.close();
}
}
@MethodSource("com.azure.messaging.servicebus.IntegrationTestBase
@ParameterizedTest
void renewMessageLock(MessagingEntityType entityType) {
final boolean isSessionEnabled = false;
setSenderAndReceiver(entityType, TestUtils.USE_CASE_DEFAULT, isSessionEnabled);
final Duration maximumDuration = Duration.ofSeconds(35);
final Duration sleepDuration = maximumDuration.plusMillis(500);
final String messageId = UUID.randomUUID().toString();
final ServiceBusMessage message = getMessage(messageId, isSessionEnabled);
final ServiceBusReceivedMessage receivedMessage = sendMessage(message)
.then(receiver.receiveMessages().next())
.block(TIMEOUT);
assertNotNull(receivedMessage);
final OffsetDateTime lockedUntil = receivedMessage.getLockedUntil();
assertNotNull(lockedUntil);
StepVerifier.create(receiver.renewMessageLock(receivedMessage, maximumDuration))
.thenAwait(sleepDuration)
.then(() -> {
logger.info("Completing message.");
int numberCompleted = completeMessages(receiver, Collections.singletonList(receivedMessage));
messagesPending.addAndGet(-numberCompleted);
})
.expectComplete()
.verify(Duration.ofMinutes(3));
}
/**
* Verifies that we can receive a message which have different section set (i.e header, footer, annotations,
* application properties etc).
*/
@MethodSource("com.azure.messaging.servicebus.IntegrationTestBase
@ParameterizedTest
void receiveAndValidateProperties(MessagingEntityType entityType) {
final boolean isSessionEnabled = false;
final int totalMessages = 1;
final String subject = "subject";
final Map<String, Object> footer = new HashMap<>();
footer.put("footer-key-1", "footer-value-1");
footer.put("footer-key-2", "footer-value-2");
final Map<String, Object> applicationProperties = new HashMap<>();
applicationProperties.put("ap-key-1", "ap-value-1");
applicationProperties.put("ap-key-2", "ap-value-2");
final Map<String, Object> deliveryAnnotation = new HashMap<>();
deliveryAnnotation.put("delivery-annotations-key-1", "delivery-annotations-value-1");
deliveryAnnotation.put("delivery-annotations-key-2", "delivery-annotations-value-2");
final String messageId = UUID.randomUUID().toString();
final AmqpAnnotatedMessage expectedAmqpProperties = new AmqpAnnotatedMessage(
AmqpMessageBody.fromData(CONTENTS_BYTES));
expectedAmqpProperties.getProperties().setSubject(subject);
expectedAmqpProperties.getProperties().setReplyToGroupId("r-gid");
expectedAmqpProperties.getProperties().setReplyTo(new AmqpAddress("reply-to"));
expectedAmqpProperties.getProperties().setContentType("content-type");
expectedAmqpProperties.getProperties().setCorrelationId(new AmqpMessageId("correlation-id"));
expectedAmqpProperties.getProperties().setTo(new AmqpAddress("to"));
expectedAmqpProperties.getProperties().setAbsoluteExpiryTime(OffsetDateTime.now().plusSeconds(60));
expectedAmqpProperties.getProperties().setUserId("user-id-1".getBytes());
expectedAmqpProperties.getProperties().setContentEncoding("string");
expectedAmqpProperties.getProperties().setGroupSequence(2L);
expectedAmqpProperties.getProperties().setCreationTime(OffsetDateTime.now().plusSeconds(30));
expectedAmqpProperties.getHeader().setPriority((short) 2);
expectedAmqpProperties.getHeader().setFirstAcquirer(true);
expectedAmqpProperties.getHeader().setDurable(true);
expectedAmqpProperties.getFooter().putAll(footer);
expectedAmqpProperties.getDeliveryAnnotations().putAll(deliveryAnnotation);
expectedAmqpProperties.getApplicationProperties().putAll(applicationProperties);
final ServiceBusMessage message = TestUtils.getServiceBusMessage(CONTENTS_BYTES, messageId);
final AmqpAnnotatedMessage amqpAnnotatedMessage = message.getRawAmqpMessage();
amqpAnnotatedMessage.getMessageAnnotations().putAll(expectedAmqpProperties.getMessageAnnotations());
amqpAnnotatedMessage.getApplicationProperties().putAll(expectedAmqpProperties.getApplicationProperties());
amqpAnnotatedMessage.getDeliveryAnnotations().putAll(expectedAmqpProperties.getDeliveryAnnotations());
amqpAnnotatedMessage.getFooter().putAll(expectedAmqpProperties.getFooter());
final AmqpMessageHeader header = amqpAnnotatedMessage.getHeader();
header.setFirstAcquirer(expectedAmqpProperties.getHeader().isFirstAcquirer());
header.setTimeToLive(expectedAmqpProperties.getHeader().getTimeToLive());
header.setDurable(expectedAmqpProperties.getHeader().isDurable());
header.setDeliveryCount(expectedAmqpProperties.getHeader().getDeliveryCount());
header.setPriority(expectedAmqpProperties.getHeader().getPriority());
final AmqpMessageProperties amqpMessageProperties = amqpAnnotatedMessage.getProperties();
amqpMessageProperties.setReplyTo((expectedAmqpProperties.getProperties().getReplyTo()));
amqpMessageProperties.setContentEncoding((expectedAmqpProperties.getProperties().getContentEncoding()));
amqpMessageProperties.setAbsoluteExpiryTime((expectedAmqpProperties.getProperties().getAbsoluteExpiryTime()));
amqpMessageProperties.setSubject((expectedAmqpProperties.getProperties().getSubject()));
amqpMessageProperties.setContentType(expectedAmqpProperties.getProperties().getContentType());
amqpMessageProperties.setCorrelationId(expectedAmqpProperties.getProperties().getCorrelationId());
amqpMessageProperties.setTo(expectedAmqpProperties.getProperties().getTo());
amqpMessageProperties.setGroupSequence(expectedAmqpProperties.getProperties().getGroupSequence());
amqpMessageProperties.setUserId(expectedAmqpProperties.getProperties().getUserId());
amqpMessageProperties.setAbsoluteExpiryTime(expectedAmqpProperties.getProperties().getAbsoluteExpiryTime());
amqpMessageProperties.setCreationTime(expectedAmqpProperties.getProperties().getCreationTime());
amqpMessageProperties.setReplyToGroupId(expectedAmqpProperties.getProperties().getReplyToGroupId());
setSender(entityType, TestUtils.USE_CASE_VALIDATE_AMQP_PROPERTIES, isSessionEnabled);
sendMessage(message).block(TIMEOUT);
setReceiver(entityType, TestUtils.USE_CASE_VALIDATE_AMQP_PROPERTIES, isSessionEnabled);
StepVerifier.create(receiver.receiveMessages()/*.take(totalMessages)*/)
.assertNext(received -> {
assertNotNull(received.getLockToken());
AmqpAnnotatedMessage actual = received.getRawAmqpMessage();
try {
assertArrayEquals(CONTENTS_BYTES, message.getBody().toBytes());
assertEquals(expectedAmqpProperties.getHeader().getPriority(), actual.getHeader().getPriority());
assertEquals(expectedAmqpProperties.getHeader().isFirstAcquirer(), actual.getHeader().isFirstAcquirer());
assertEquals(expectedAmqpProperties.getHeader().isDurable(), actual.getHeader().isDurable());
assertEquals(expectedAmqpProperties.getProperties().getSubject(), actual.getProperties().getSubject());
assertEquals(expectedAmqpProperties.getProperties().getReplyToGroupId(), actual.getProperties().getReplyToGroupId());
assertEquals(expectedAmqpProperties.getProperties().getReplyTo(), actual.getProperties().getReplyTo());
assertEquals(expectedAmqpProperties.getProperties().getContentType(), actual.getProperties().getContentType());
assertEquals(expectedAmqpProperties.getProperties().getCorrelationId(), actual.getProperties().getCorrelationId());
assertEquals(expectedAmqpProperties.getProperties().getTo(), actual.getProperties().getTo());
assertEquals(expectedAmqpProperties.getProperties().getAbsoluteExpiryTime().toEpochSecond(), actual.getProperties().getAbsoluteExpiryTime().toEpochSecond());
assertEquals(expectedAmqpProperties.getProperties().getSubject(), actual.getProperties().getSubject());
assertEquals(expectedAmqpProperties.getProperties().getContentEncoding(), actual.getProperties().getContentEncoding());
assertEquals(expectedAmqpProperties.getProperties().getGroupSequence(), actual.getProperties().getGroupSequence());
assertEquals(expectedAmqpProperties.getProperties().getCreationTime().toEpochSecond(), actual.getProperties().getCreationTime().toEpochSecond());
assertArrayEquals(expectedAmqpProperties.getProperties().getUserId(), actual.getProperties().getUserId());
assertMapValues(expectedAmqpProperties.getDeliveryAnnotations(), actual.getDeliveryAnnotations());
assertMapValues(expectedAmqpProperties.getMessageAnnotations(), actual.getMessageAnnotations());
assertMapValues(expectedAmqpProperties.getApplicationProperties(), actual.getApplicationProperties());
assertMapValues(expectedAmqpProperties.getFooter(), actual.getFooter());
} finally {
logger.info("Completing message.");
receiver.complete(received).block(Duration.ofSeconds(15));
messagesPending.decrementAndGet();
}
})
.thenCancel()
.verify(Duration.ofMinutes(2));
}
/**
* Verifies we can autocomplete for a queue.
*
* @param entityType Entity Type.
*/
@MethodSource("com.azure.messaging.servicebus.IntegrationTestBase
@ParameterizedTest
void autoComplete(MessagingEntityType entityType) {
final Duration shortWait = Duration.ofSeconds(2);
final int index = TestUtils.USE_CASE_AUTO_COMPLETE;
setSender(entityType, index, false);
final int numberOfEvents = 3;
final String messageId = UUID.randomUUID().toString();
final List<ServiceBusMessage> messages = getServiceBusMessages(numberOfEvents, messageId);
setReceiver(entityType, index, false);
final ServiceBusReceivedMessage lastMessage = receiver.peekMessage().block(TIMEOUT);
Mono.when(messages.stream().map(this::sendMessage)
.collect(Collectors.toList()))
.block(TIMEOUT);
final ServiceBusReceiverAsyncClient autoCompleteReceiver =
getReceiverBuilder(false, entityType, index, false)
.buildAsyncClient();
try {
StepVerifier.create(autoCompleteReceiver.receiveMessages())
.assertNext(receivedMessage -> {
if (lastMessage != null) {
assertEquals(lastMessage.getMessageId(), receivedMessage.getMessageId());
} else {
assertEquals(messageId, receivedMessage.getMessageId());
}
})
.assertNext(context -> {
if (lastMessage == null) {
assertEquals(messageId, context.getMessageId());
}
})
.assertNext(context -> {
if (lastMessage == null) {
assertEquals(messageId, context.getMessageId());
}
})
.thenAwait(shortWait)
.thenCancel()
.verify(TIMEOUT);
} finally {
autoCompleteReceiver.close();
}
final ServiceBusReceivedMessage newLastMessage = receiver.peekMessage().block(TIMEOUT);
if (lastMessage == null) {
assertNull(newLastMessage,
String.format("Actual messageId[%s]", newLastMessage != null ? newLastMessage.getMessageId() : "n/a"));
} else {
assertNotNull(newLastMessage);
assertEquals(lastMessage.getSequenceNumber(), newLastMessage.getSequenceNumber());
}
}
/**
* Asserts the length and values with in the map.
*/
private void assertMapValues(Map<String, Object> expectedMap, Map<String, Object> actualMap) {
assertTrue(actualMap.size() >= expectedMap.size());
for (String key : expectedMap.keySet()) {
assertEquals(expectedMap.get(key), actualMap.get(key), "Value is not equal for Key " + key);
}
}
/**
* Sets the sender and receiver. If session is enabled, then a single-named session receiver is created.
*/
private void setSenderAndReceiver(MessagingEntityType entityType, int entityIndex, boolean isSessionEnabled) {
setSender(entityType, entityIndex, isSessionEnabled);
setReceiver(entityType, entityIndex, isSessionEnabled);
}
private void setReceiver(MessagingEntityType entityType, int entityIndex, boolean isSessionEnabled) {
final boolean shareConnection = false;
final boolean useCredentials = false;
if (isSessionEnabled) {
assertNotNull(sessionId, "'sessionId' should have been set.");
sessionReceiver = getSessionReceiverBuilder(useCredentials, entityType, entityIndex, shareConnection)
.disableAutoComplete()
.buildAsyncClient();
this.receiver = sessionReceiver.acceptSession(sessionId).block();
} else {
this.receiver = getReceiverBuilder(useCredentials, entityType, entityIndex, shareConnection)
.disableAutoComplete()
.buildAsyncClient();
}
}
private void setSender(MessagingEntityType entityType, int entityIndex, boolean isSessionEnabled) {
final boolean shareConnection = false;
final boolean useCredentials = false;
this.sender = getSenderBuilder(useCredentials, entityType, entityIndex, isSessionEnabled, shareConnection)
.buildAsyncClient();
}
private Mono<Void> sendMessage(ServiceBusMessage message) {
return sender.sendMessage(message).doOnSuccess(aVoid -> {
int number = messagesPending.incrementAndGet();
logger.info("Message Id {}. Number sent: {}", message.getMessageId(), number);
});
}
private int completeMessages(ServiceBusReceiverAsyncClient client, List<ServiceBusReceivedMessage> messages) {
Mono.when(messages.stream().map(e -> client.complete(e))
.collect(Collectors.toList()))
.block(TIMEOUT);
return messages.size();
}
} |
Same here | public SmsClient createSyncClientUsingTokenCredential() {
TokenCredential tokenCredential = new DefaultAzureCredentialBuilder().build();
String endpoint = "https:
HttpClient httpClient = new NettyAsyncHttpClientBuilder().build();
SmsClient smsClient = new SmsClientBuilder().
endpoint(endpoint)
.credential(tokenCredential)
.httpClient(httpClient)
.buildClient();
return smsClient;
} | endpoint(endpoint) | public SmsClient createSyncClientUsingTokenCredential() {
TokenCredential tokenCredential = new DefaultAzureCredentialBuilder().build();
String endpoint = "https:
HttpClient httpClient = new NettyAsyncHttpClientBuilder().build();
SmsClient smsClient = new SmsClientBuilder()
.endpoint(endpoint)
.credential(tokenCredential)
.httpClient(httpClient)
.buildClient();
return smsClient;
} | class ReadmeSamples {
public SmsClient createSmsClientUsingAzureKeyCredential() {
String endpoint = "https:
AzureKeyCredential azureKeyCredential = new AzureKeyCredential("<access-key>");
HttpClient httpClient = new NettyAsyncHttpClientBuilder().build();
SmsClient smsClient = new SmsClientBuilder()
.endpoint(endpoint)
.credential(azureKeyCredential)
.httpClient(httpClient)
.buildClient();
return smsClient;
}
public SmsAsyncClient createSmsAsyncClientUsingAzureKeyCredential() {
String endpoint = "https:
AzureKeyCredential azureKeyCredential = new AzureKeyCredential("<access-key>");
HttpClient httpClient = new NettyAsyncHttpClientBuilder().build();
SmsAsyncClient smsClient = new SmsClientBuilder()
.endpoint(endpoint)
.credential(azureKeyCredential)
.httpClient(httpClient)
.buildAsyncClient();
return smsClient;
}
public SmsClient createSmsClientWithConnectionString() {
String connectionString = "https:
HttpClient httpClient = new NettyAsyncHttpClientBuilder().build();
SmsClient smsClient = new SmsClientBuilder()
.connectionString(connectionString)
.httpClient(httpClient)
.buildClient();
return smsClient;
}
public SmsClient createSmsClientWithAAD() {
String endpoint = "https:
HttpClient httpClient = new NettyAsyncHttpClientBuilder().build();
SmsClient smsClient = new SmsClientBuilder()
.endpoint(endpoint)
.credential(new DefaultAzureCredentialBuilder().build())
.httpClient(httpClient)
.buildClient();
return smsClient;
}
public SmsAsyncClient createAsyncClientUsingTokenCredential() {
TokenCredential tokenCredential = new DefaultAzureCredentialBuilder().build();
String endpoint = "https:
HttpClient httpClient = new NettyAsyncHttpClientBuilder().build();
SmsAsyncClient smsClient = new SmsClientBuilder().
endpoint(endpoint)
.credential(tokenCredential)
.httpClient(httpClient)
.buildAsyncClient();
return smsClient;
}
public void sendMessageToOneRecipient() {
SmsClient smsClient = createSmsClientUsingAzureKeyCredential();
SmsSendResult sendResult = smsClient.send(
"<from-phone-number>",
"<to-phone-number>",
"Hi");
System.out.println("Message Id: " + sendResult.getMessageId());
System.out.println("Recipient Number: " + sendResult.getTo());
System.out.println("Send Result Successful:" + sendResult.isSuccessful());
}
public void sendMessageToGroupWithOptions() {
SmsClient smsClient = createSmsClientUsingAzureKeyCredential();
SmsSendOptions options = new SmsSendOptions();
options.setDeliveryReportEnabled(true);
options.setTag("Tag");
Iterable<SmsSendResult> sendResults = smsClient.sendWithResponse(
"<from-phone-number>",
Arrays.asList("<to-phone-number1>", "<to-phone-number2>"),
"Hi",
options /* Optional */,
Context.NONE).getValue();
for (SmsSendResult result : sendResults) {
System.out.println("Message Id: " + result.getMessageId());
System.out.println("Recipient Number: " + result.getTo());
System.out.println("Send Result Successful:" + result.isSuccessful());
}
}
public void sendMessageAsyncToOneRecipient() {
SmsAsyncClient smsClient = createSmsAsyncClientUsingAzureKeyCredential();
Mono<SmsSendResult> sendResult = smsClient.send(
"<from-phone-number>",
"<to-phone-number>",
"Hi");
Mono<Boolean> isSuccessful = sendResult.flatMap(result -> {
System.out.println("Message Id: " + result.getMessageId());
System.out.println("Recipient Number: " + result.getTo());
System.out.println("Send Result Successful:" + result.isSuccessful());
return Mono.just(result.isSuccessful());
});
}
public void sendMessageAsyncClientToGroup() {
SmsAsyncClient smsClient = createSmsAsyncClientUsingAzureKeyCredential();
SmsSendOptions options = new SmsSendOptions();
options.setDeliveryReportEnabled(true);
options.setTag("Tag");
Mono<Response<Iterable<SmsSendResult>>> sendResults = smsClient.sendWithResponse(
"<from-phone-number>",
Arrays.asList("<to-phone-number1>", "<to-phone-number2>"),
"Hi",
options /* Optional */);
Mono <Iterable<SmsSendResult>> resultOfEachMessage = sendResults.flatMap(response -> {
Iterable<SmsSendResult> iterableResults = response.getValue();
for (SmsSendResult result : iterableResults) {
System.out.println("Message Id: " + result.getMessageId());
System.out.println("Recipient Number: " + result.getTo());
System.out.println("Send Result Successful:" + result.isSuccessful());
}
return Mono.just(iterableResults);
});
}
/**
* Sample code for troubleshooting
*/
public void catchHttpErrorOnRequestSync() {
SmsClient smsClient = createSmsClientUsingAzureKeyCredential();
try {
SmsSendResult sendResult = smsClient.send(
"<from-phone-number>",
"<to-phone-number>",
"Hi"
);
} catch (RuntimeException ex) {
System.out.println(ex.getMessage());
}
}
public void catchHttpErrorOnRequestAsync() {
SmsAsyncClient smsClient = createSmsAsyncClientUsingAzureKeyCredential();
try {
Mono<SmsSendResult> sendResult = smsClient.send(
"<from-phone-number>",
"<to-phone-number>",
"Hi"
);
} catch (RuntimeException ex) {
System.out.println(ex.getMessage());
}
}
public void failedMessagesAsync() {
SmsAsyncClient smsClient = createSmsAsyncClientUsingAzureKeyCredential();
SmsSendOptions options = new SmsSendOptions();
options.setDeliveryReportEnabled(true);
options.setTag("Tag");
Mono<Response<Iterable<SmsSendResult>>> sendResults = smsClient.sendWithResponse(
"<from-phone-number>",
Arrays.asList("<to-phone-number1>", "<to-phone-number2>"),
"Hi",
options /* Optional */);
Mono <Iterable<SmsSendResult>> resultOfEachMessage = sendResults.flatMap(response -> {
Iterable<SmsSendResult> iterableResults = response.getValue();
for (SmsSendResult result : iterableResults) {
if (!result.isSuccessful()) {
System.out.println("Successfully sent this message: " + result.getMessageId() + " to " + result.getTo());
} else {
System.out.println("Something went wrong when trying to send this message " + result.getMessageId() + " to " + result.getTo());
}
}
return Mono.just(iterableResults);
});
}
public void failedMessagesSync() {
SmsClient smsClient = createSmsClientUsingAzureKeyCredential();
SmsSendOptions options = new SmsSendOptions();
options.setDeliveryReportEnabled(true);
options.setTag("Tag");
try {
Response<Iterable<SmsSendResult>> sendResults = smsClient.sendWithResponse(
"<from-phone-number>",
Arrays.asList("<to-phone-number1>", "<to-phone-number2>"),
"Hi",
options /* Optional */,
Context.NONE);
Iterable<SmsSendResult> resultOfEachMessage = sendResults.getValue();
for (SmsSendResult result : resultOfEachMessage) {
if (!result.isSuccessful()) {
System.out.println("Successfully sent this message: " + result.getMessageId() + " to " + result.getTo());
} else {
System.out.println("Something went wrong when trying to send this message " + result.getMessageId() + " to " + result.getTo());
}
}
} catch (RuntimeException ex) {
System.out.println(ex.getMessage());
}
}
} | class ReadmeSamples {
public SmsClient createSmsClientUsingAzureKeyCredential() {
String endpoint = "https:
AzureKeyCredential azureKeyCredential = new AzureKeyCredential("<access-key>");
HttpClient httpClient = new NettyAsyncHttpClientBuilder().build();
SmsClient smsClient = new SmsClientBuilder()
.endpoint(endpoint)
.credential(azureKeyCredential)
.httpClient(httpClient)
.buildClient();
return smsClient;
}
public SmsAsyncClient createSmsAsyncClientUsingAzureKeyCredential() {
String endpoint = "https:
AzureKeyCredential azureKeyCredential = new AzureKeyCredential("<access-key>");
HttpClient httpClient = new NettyAsyncHttpClientBuilder().build();
SmsAsyncClient smsClient = new SmsClientBuilder()
.endpoint(endpoint)
.credential(azureKeyCredential)
.httpClient(httpClient)
.buildAsyncClient();
return smsClient;
}
public SmsClient createSmsClientWithConnectionString() {
String connectionString = "https:
HttpClient httpClient = new NettyAsyncHttpClientBuilder().build();
SmsClient smsClient = new SmsClientBuilder()
.connectionString(connectionString)
.httpClient(httpClient)
.buildClient();
return smsClient;
}
public SmsClient createSmsClientWithAAD() {
String endpoint = "https:
HttpClient httpClient = new NettyAsyncHttpClientBuilder().build();
SmsClient smsClient = new SmsClientBuilder()
.endpoint(endpoint)
.credential(new DefaultAzureCredentialBuilder().build())
.httpClient(httpClient)
.buildClient();
return smsClient;
}
public void sendMessageToOneRecipient() {
SmsClient smsClient = createSmsClientUsingAzureKeyCredential();
SmsSendResult sendResult = smsClient.send(
"<from-phone-number>",
"<to-phone-number>",
"Weekly Promotion");
System.out.println("Message Id: " + sendResult.getMessageId());
System.out.println("Recipient Number: " + sendResult.getTo());
System.out.println("Send Result Successful:" + sendResult.isSuccessful());
}
public void sendMessageToGroupWithOptions() {
SmsClient smsClient = createSmsClientUsingAzureKeyCredential();
SmsSendOptions options = new SmsSendOptions();
options.setDeliveryReportEnabled(true);
options.setTag("Marketing");
Iterable<SmsSendResult> sendResults = smsClient.sendWithResponse(
"<from-phone-number>",
Arrays.asList("<to-phone-number1>", "<to-phone-number2>"),
"Weekly Promotion",
options /* Optional */,
Context.NONE).getValue();
for (SmsSendResult result : sendResults) {
System.out.println("Message Id: " + result.getMessageId());
System.out.println("Recipient Number: " + result.getTo());
System.out.println("Send Result Successful:" + result.isSuccessful());
}
}
/**
* Sample code for troubleshooting
*/
public void catchHttpErrorOnRequest() {
SmsClient smsClient = createSmsClientUsingAzureKeyCredential();
try {
SmsSendResult sendResult = smsClient.send(
"<from-phone-number>",
"<to-phone-number>",
"Weekly Promotion"
);
} catch (RuntimeException ex) {
System.out.println(ex.getMessage());
}
}
public void sendMessageTroubleShooting() {
SmsClient smsClient = createSmsClientUsingAzureKeyCredential();
try {
SmsSendOptions options = new SmsSendOptions();
options.setDeliveryReportEnabled(true);
options.setTag("Marketing");
Response<Iterable<SmsSendResult>> sendResults = smsClient.sendWithResponse(
"<from-phone-number>",
Arrays.asList("<to-phone-number1>", "<to-phone-number2>"),
"Weekly Promotion",
options /* Optional */,
Context.NONE);
Iterable<SmsSendResult> smsSendResults = sendResults.getValue();
for (SmsSendResult result : smsSendResults) {
if (result.isSuccessful()) {
System.out.println("Successfully sent this message: " + result.getMessageId() + " to " + result.getTo());
} else {
System.out.println("Something went wrong when trying to send this message " + result.getMessageId() + " to " + result.getTo());
System.out.println("Status code " + result.getHttpStatusCode() + " and error message " + result.getErrorMessage());
}
}
} catch (RuntimeException ex) {
System.out.println(ex.getMessage());
}
}
} |
Fix comment. | public void sendCustomEventsAsync() {
EventGridPublisherAsyncClient<BinaryData> customEventPublisherClient = new EventGridPublisherClientBuilder()
.endpoint(System.getenv("AZURE_CUSTOM_EVENT_ENDPOINT"))
.credential(new AzureKeyCredential(System.getenv("AZURE_CUSTOM_EVENT_KEY")))
.buildCustomEventPublisherAsyncClient();
User user = new User("John", "James");
Map<String, Object> customEvent = new HashMap<String, Object>() {
{
put("id", UUID.randomUUID().toString());
put("subject", "Test");
put("foo", "bar");
put("type", "Microsoft.MockPublisher.TestEvent");
put("data", 100.0);
put("dataVersion", "0.1");
}
};
customEventPublisherClient.sendEvent(BinaryData.fromObject(customEvent)).block();
customEventPublisherClient.sendEvents(new ArrayList<BinaryData>() {
{
add(BinaryData.fromObject(customEvent));
}
}).block();
} | public void sendCustomEventsAsync() {
EventGridPublisherAsyncClient<BinaryData> customEventPublisherClient = new EventGridPublisherClientBuilder()
.endpoint(System.getenv("AZURE_CUSTOM_EVENT_ENDPOINT"))
.credential(new AzureKeyCredential(System.getenv("AZURE_CUSTOM_EVENT_KEY")))
.buildCustomEventPublisherAsyncClient();
Map<String, Object> customEvent = new HashMap<String, Object>() {
{
put("id", UUID.randomUUID().toString());
put("subject", "Test");
put("foo", "bar");
put("type", "Microsoft.MockPublisher.TestEvent");
put("data", 100.0);
put("dataVersion", "0.1");
}
};
customEventPublisherClient.sendEvent(BinaryData.fromObject(customEvent)).block();
customEventPublisherClient.sendEvents(Arrays.asList(
BinaryData.fromObject(customEvent)
)).block();
} | class EventGridEventJavaDocCodeSnippet {
public void createEventGridEvent() {
User user = new User("Stephen", "James");
EventGridEvent eventGridEventDataObject = new EventGridEvent("/EventGridEvents/example/source",
"Example.EventType", BinaryData.fromObject(user), "0.1");
EventGridEvent eventGridEventDataStr = new EventGridEvent("/EventGridEvents/example/source",
"Example.EventType", BinaryData.fromObject("Hello World"), "0.1");
EventGridEvent eventGridEventDataInt = new EventGridEvent("/EventGridEvents/example/source",
"Example.EventType", BinaryData.fromObject(1), "0.1");
EventGridEvent eventGridEventDataBool = new EventGridEvent("/EventGridEvents/example/source",
"Example.EventType", BinaryData.fromObject(true), "0.1");
EventGridEvent eventGridEventDataNull = new EventGridEvent("/EventGridEvents/example/source",
"Example.EventType", BinaryData.fromObject(null), "0.1");
String jsonStringForData = "\"Hello World\"";
EventGridEvent eventGridEventDataDataJsonStr = new EventGridEvent("/EventGridEvents/example/source",
"Example.EventType", BinaryData.fromString(jsonStringForData), "0.1");
}
public void fromJsonStringWithDataJson() {
String eventGridEventJsonString = "<A EventGridEvent Json String>";
List<EventGridEvent> eventGridEventList = EventGridEvent.fromString(eventGridEventJsonString);
EventGridEvent eventGridEvent = eventGridEventList.get(0);
BinaryData eventGridEventData = eventGridEvent.getData();
User objectValue = eventGridEventData.toObject(User.class);
int intValue = eventGridEventData.toObject(Integer.class);
boolean boolValue = eventGridEventData.toObject(Boolean.class);
String stringValue = eventGridEventData.toObject(String.class);
String jsonStringValue = eventGridEventData.toString();
}
public void sendCloudEventsAsync() {
EventGridPublisherAsyncClient<CloudEvent> cloudEventPublisherClient = new EventGridPublisherClientBuilder()
.endpoint(System.getenv("AZURE_EVENTGRID_CLOUDEVENT_ENDPOINT"))
.credential(new AzureKeyCredential(System.getenv("AZURE_EVENTGRID_CLOUDEVENT_KEY")))
.buildCloudEventPublisherAsyncClient();
User user = new User("Stephen", "James");
CloudEvent cloudEventDataObject = new CloudEvent("/cloudevents/example/source", "Example.EventType",
BinaryData.fromObject(user), CloudEventDataFormat.JSON, "application/json");
cloudEventPublisherClient.sendEvent(cloudEventDataObject).block();
cloudEventPublisherClient.sendEvents(new ArrayList<CloudEvent>() {
{
add(cloudEventDataObject);
}
}).block();
}
public void sendEventGridEventsAsync() {
EventGridPublisherAsyncClient<EventGridEvent> eventGridEventPublisherClient = new EventGridPublisherClientBuilder()
.endpoint(System.getenv("AZURE_EVENTGRID_EVENT_ENDPOINT"))
.credential(new AzureKeyCredential(System.getenv("AZURE_EVENTGRID_EVENT_KEY")))
.buildEventGridEventPublisherAsyncClient();
User user = new User("John", "James");
EventGridEvent eventGridEvent = new EventGridEvent("/EventGridEvents/example/source",
"Example.EventType", BinaryData.fromObject(user), "0.1");
eventGridEventPublisherClient.sendEvent(eventGridEvent).block();
eventGridEventPublisherClient.sendEvents(new ArrayList<EventGridEvent>() {
{
add(eventGridEvent);
}
}).block();
}
public void sendCloudEvents() {
EventGridPublisherClient<CloudEvent> cloudEventPublisherClient = new EventGridPublisherClientBuilder()
.endpoint(System.getenv("AZURE_EVENTGRID_CLOUDEVENT_ENDPOINT"))
.credential(new AzureKeyCredential(System.getenv("AZURE_EVENTGRID_CLOUDEVENT_KEY")))
.buildCloudEventPublisherClient();
User user = new User("Stephen", "James");
CloudEvent cloudEventDataObject = new CloudEvent("/cloudevents/example/source", "Example.EventType",
BinaryData.fromObject(user), CloudEventDataFormat.JSON, "application/json");
cloudEventPublisherClient.sendEvent(cloudEventDataObject);
cloudEventPublisherClient.sendEvents(new ArrayList<CloudEvent>() {
{
add(cloudEventDataObject);
}
});
}
public void sendEventGridEvents() {
EventGridPublisherClient<EventGridEvent> eventGridEventPublisherClient = new EventGridPublisherClientBuilder()
.endpoint(System.getenv("AZURE_EVENTGRID_EVENT_ENDPOINT"))
.credential(new AzureKeyCredential(System.getenv("AZURE_EVENTGRID_EVENT_KEY")))
.buildEventGridEventPublisherClient();
User user = new User("John", "James");
EventGridEvent eventGridEvent = new EventGridEvent("/EventGridEvents/example/source",
"Example.EventType", BinaryData.fromObject(user), "0.1");
eventGridEventPublisherClient.sendEvent(eventGridEvent);
eventGridEventPublisherClient.sendEvents(new ArrayList<EventGridEvent>() {
{
add(eventGridEvent);
}
});
}
public void sendCustomEvents() {
EventGridPublisherClient<BinaryData> customEventPublisherClient = new EventGridPublisherClientBuilder()
.endpoint(System.getenv("AZURE_CUSTOM_EVENT_ENDPOINT"))
.credential(new AzureKeyCredential(System.getenv("AZURE_CUSTOM_EVENT_KEY")))
.buildCustomEventPublisherClient();
User user = new User("John", "James");
Map<String, Object> customEvent = new HashMap<String, Object>() {
{
put("id", UUID.randomUUID().toString());
put("subject", "Test");
put("foo", "bar");
put("type", "Microsoft.MockPublisher.TestEvent");
put("data", 100.0);
put("dataVersion", "0.1");
}
};
customEventPublisherClient.sendEvent(BinaryData.fromObject(customEvent));
customEventPublisherClient.sendEvents(new ArrayList<BinaryData>() {
{
add(BinaryData.fromObject(customEvent));
}
});
}
} | class EventGridEventJavaDocCodeSnippet {
public void createEventGridEvent() {
User user = new User("Stephen", "James");
EventGridEvent eventGridEventDataObject = new EventGridEvent("/EventGridEvents/example/source",
"Example.EventType", BinaryData.fromObject(user), "0.1");
EventGridEvent eventGridEventDataStr = new EventGridEvent("/EventGridEvents/example/source",
"Example.EventType", BinaryData.fromObject("Hello World"), "0.1");
EventGridEvent eventGridEventDataInt = new EventGridEvent("/EventGridEvents/example/source",
"Example.EventType", BinaryData.fromObject(1), "0.1");
EventGridEvent eventGridEventDataBool = new EventGridEvent("/EventGridEvents/example/source",
"Example.EventType", BinaryData.fromObject(true), "0.1");
EventGridEvent eventGridEventDataNull = new EventGridEvent("/EventGridEvents/example/source",
"Example.EventType", BinaryData.fromObject(null), "0.1");
String jsonStringForData = "\"Hello World\"";
EventGridEvent eventGridEventDataDataJsonStr = new EventGridEvent("/EventGridEvents/example/source",
"Example.EventType", BinaryData.fromString(jsonStringForData), "0.1");
}
public void fromJsonStringWithDataJson() {
String eventGridEventJsonString = "<A EventGridEvent Json String>";
List<EventGridEvent> eventGridEventList = EventGridEvent.fromString(eventGridEventJsonString);
EventGridEvent eventGridEvent = eventGridEventList.get(0);
BinaryData eventGridEventData = eventGridEvent.getData();
User objectValue = eventGridEventData.toObject(User.class);
int intValue = eventGridEventData.toObject(Integer.class);
boolean boolValue = eventGridEventData.toObject(Boolean.class);
String stringValue = eventGridEventData.toObject(String.class);
String jsonStringValue = eventGridEventData.toString();
}
public void sendCloudEventsAsync() {
EventGridPublisherAsyncClient<CloudEvent> cloudEventPublisherClient = new EventGridPublisherClientBuilder()
.endpoint(System.getenv("AZURE_EVENTGRID_CLOUDEVENT_ENDPOINT"))
.credential(new AzureKeyCredential(System.getenv("AZURE_EVENTGRID_CLOUDEVENT_KEY")))
.buildCloudEventPublisherAsyncClient();
User user = new User("Stephen", "James");
CloudEvent cloudEventDataObject = new CloudEvent("/cloudevents/example/source", "Example.EventType",
BinaryData.fromObject(user), CloudEventDataFormat.JSON, "application/json");
cloudEventPublisherClient.sendEvent(cloudEventDataObject).block();
cloudEventPublisherClient.sendEvents(Arrays.asList(
cloudEventDataObject
)).block();
}
public void sendEventGridEventsAsync() {
EventGridPublisherAsyncClient<EventGridEvent> eventGridEventPublisherClient = new EventGridPublisherClientBuilder()
.endpoint(System.getenv("AZURE_EVENTGRID_EVENT_ENDPOINT"))
.credential(new AzureKeyCredential(System.getenv("AZURE_EVENTGRID_EVENT_KEY")))
.buildEventGridEventPublisherAsyncClient();
User user = new User("John", "James");
EventGridEvent eventGridEvent = new EventGridEvent("/EventGridEvents/example/source",
"Example.EventType", BinaryData.fromObject(user), "0.1");
eventGridEventPublisherClient.sendEvent(eventGridEvent).block();
eventGridEventPublisherClient.sendEvents(Arrays.asList(
eventGridEvent
)).block();
}
public void sendCloudEvents() {
EventGridPublisherClient<CloudEvent> cloudEventPublisherClient = new EventGridPublisherClientBuilder()
.endpoint(System.getenv("AZURE_EVENTGRID_CLOUDEVENT_ENDPOINT"))
.credential(new AzureKeyCredential(System.getenv("AZURE_EVENTGRID_CLOUDEVENT_KEY")))
.buildCloudEventPublisherClient();
User user = new User("Stephen", "James");
CloudEvent cloudEventDataObject = new CloudEvent("/cloudevents/example/source", "Example.EventType",
BinaryData.fromObject(user), CloudEventDataFormat.JSON, "application/json");
cloudEventPublisherClient.sendEvent(cloudEventDataObject);
cloudEventPublisherClient.sendEvents(Arrays.asList(
cloudEventDataObject
));
}
public void sendEventGridEvents() {
EventGridPublisherClient<EventGridEvent> eventGridEventPublisherClient = new EventGridPublisherClientBuilder()
.endpoint(System.getenv("AZURE_EVENTGRID_EVENT_ENDPOINT"))
.credential(new AzureKeyCredential(System.getenv("AZURE_EVENTGRID_EVENT_KEY")))
.buildEventGridEventPublisherClient();
User user = new User("John", "James");
EventGridEvent eventGridEvent = new EventGridEvent("/EventGridEvents/example/source",
"Example.EventType", BinaryData.fromObject(user), "0.1");
eventGridEventPublisherClient.sendEvent(eventGridEvent);
eventGridEventPublisherClient.sendEvents(Arrays.asList(
eventGridEvent
));
}
public void sendCustomEvents() {
EventGridPublisherClient<BinaryData> customEventPublisherClient = new EventGridPublisherClientBuilder()
.endpoint(System.getenv("AZURE_CUSTOM_EVENT_ENDPOINT"))
.credential(new AzureKeyCredential(System.getenv("AZURE_CUSTOM_EVENT_KEY")))
.buildCustomEventPublisherClient();
Map<String, Object> customEvent = new HashMap<String, Object>() {
{
put("id", UUID.randomUUID().toString());
put("subject", "Test");
put("foo", "bar");
put("type", "Microsoft.MockPublisher.TestEvent");
put("data", 100.0);
put("dataVersion", "0.1");
}
};
customEventPublisherClient.sendEvent(BinaryData.fromObject(customEvent));
customEventPublisherClient.sendEvents(Arrays.asList(
BinaryData.fromObject(customEvent)
));
}
} | |
customEventPublisherClient.sendEvents(Arrays.asList(BinaryData.fromObject(customEvent))); | public void sendCustomEventsAsync() {
EventGridPublisherAsyncClient<BinaryData> customEventPublisherClient = new EventGridPublisherClientBuilder()
.endpoint(System.getenv("AZURE_CUSTOM_EVENT_ENDPOINT"))
.credential(new AzureKeyCredential(System.getenv("AZURE_CUSTOM_EVENT_KEY")))
.buildCustomEventPublisherAsyncClient();
User user = new User("John", "James");
Map<String, Object> customEvent = new HashMap<String, Object>() {
{
put("id", UUID.randomUUID().toString());
put("subject", "Test");
put("foo", "bar");
put("type", "Microsoft.MockPublisher.TestEvent");
put("data", 100.0);
put("dataVersion", "0.1");
}
};
customEventPublisherClient.sendEvent(BinaryData.fromObject(customEvent)).block();
customEventPublisherClient.sendEvents(new ArrayList<BinaryData>() {
{
add(BinaryData.fromObject(customEvent));
}
}).block();
} | } | public void sendCustomEventsAsync() {
EventGridPublisherAsyncClient<BinaryData> customEventPublisherClient = new EventGridPublisherClientBuilder()
.endpoint(System.getenv("AZURE_CUSTOM_EVENT_ENDPOINT"))
.credential(new AzureKeyCredential(System.getenv("AZURE_CUSTOM_EVENT_KEY")))
.buildCustomEventPublisherAsyncClient();
Map<String, Object> customEvent = new HashMap<String, Object>() {
{
put("id", UUID.randomUUID().toString());
put("subject", "Test");
put("foo", "bar");
put("type", "Microsoft.MockPublisher.TestEvent");
put("data", 100.0);
put("dataVersion", "0.1");
}
};
customEventPublisherClient.sendEvent(BinaryData.fromObject(customEvent)).block();
customEventPublisherClient.sendEvents(Arrays.asList(
BinaryData.fromObject(customEvent)
)).block();
} | class EventGridEventJavaDocCodeSnippet {
public void createEventGridEvent() {
User user = new User("Stephen", "James");
EventGridEvent eventGridEventDataObject = new EventGridEvent("/EventGridEvents/example/source",
"Example.EventType", BinaryData.fromObject(user), "0.1");
EventGridEvent eventGridEventDataStr = new EventGridEvent("/EventGridEvents/example/source",
"Example.EventType", BinaryData.fromObject("Hello World"), "0.1");
EventGridEvent eventGridEventDataInt = new EventGridEvent("/EventGridEvents/example/source",
"Example.EventType", BinaryData.fromObject(1), "0.1");
EventGridEvent eventGridEventDataBool = new EventGridEvent("/EventGridEvents/example/source",
"Example.EventType", BinaryData.fromObject(true), "0.1");
EventGridEvent eventGridEventDataNull = new EventGridEvent("/EventGridEvents/example/source",
"Example.EventType", BinaryData.fromObject(null), "0.1");
String jsonStringForData = "\"Hello World\"";
EventGridEvent eventGridEventDataDataJsonStr = new EventGridEvent("/EventGridEvents/example/source",
"Example.EventType", BinaryData.fromString(jsonStringForData), "0.1");
}
public void fromJsonStringWithDataJson() {
String eventGridEventJsonString = "<A EventGridEvent Json String>";
List<EventGridEvent> eventGridEventList = EventGridEvent.fromString(eventGridEventJsonString);
EventGridEvent eventGridEvent = eventGridEventList.get(0);
BinaryData eventGridEventData = eventGridEvent.getData();
User objectValue = eventGridEventData.toObject(User.class);
int intValue = eventGridEventData.toObject(Integer.class);
boolean boolValue = eventGridEventData.toObject(Boolean.class);
String stringValue = eventGridEventData.toObject(String.class);
String jsonStringValue = eventGridEventData.toString();
}
public void sendCloudEventsAsync() {
EventGridPublisherAsyncClient<CloudEvent> cloudEventPublisherClient = new EventGridPublisherClientBuilder()
.endpoint(System.getenv("AZURE_EVENTGRID_CLOUDEVENT_ENDPOINT"))
.credential(new AzureKeyCredential(System.getenv("AZURE_EVENTGRID_CLOUDEVENT_KEY")))
.buildCloudEventPublisherAsyncClient();
User user = new User("Stephen", "James");
CloudEvent cloudEventDataObject = new CloudEvent("/cloudevents/example/source", "Example.EventType",
BinaryData.fromObject(user), CloudEventDataFormat.JSON, "application/json");
cloudEventPublisherClient.sendEvent(cloudEventDataObject).block();
cloudEventPublisherClient.sendEvents(new ArrayList<CloudEvent>() {
{
add(cloudEventDataObject);
}
}).block();
}
public void sendEventGridEventsAsync() {
EventGridPublisherAsyncClient<EventGridEvent> eventGridEventPublisherClient = new EventGridPublisherClientBuilder()
.endpoint(System.getenv("AZURE_EVENTGRID_EVENT_ENDPOINT"))
.credential(new AzureKeyCredential(System.getenv("AZURE_EVENTGRID_EVENT_KEY")))
.buildEventGridEventPublisherAsyncClient();
User user = new User("John", "James");
EventGridEvent eventGridEvent = new EventGridEvent("/EventGridEvents/example/source",
"Example.EventType", BinaryData.fromObject(user), "0.1");
eventGridEventPublisherClient.sendEvent(eventGridEvent).block();
eventGridEventPublisherClient.sendEvents(new ArrayList<EventGridEvent>() {
{
add(eventGridEvent);
}
}).block();
}
public void sendCloudEvents() {
EventGridPublisherClient<CloudEvent> cloudEventPublisherClient = new EventGridPublisherClientBuilder()
.endpoint(System.getenv("AZURE_EVENTGRID_CLOUDEVENT_ENDPOINT"))
.credential(new AzureKeyCredential(System.getenv("AZURE_EVENTGRID_CLOUDEVENT_KEY")))
.buildCloudEventPublisherClient();
User user = new User("Stephen", "James");
CloudEvent cloudEventDataObject = new CloudEvent("/cloudevents/example/source", "Example.EventType",
BinaryData.fromObject(user), CloudEventDataFormat.JSON, "application/json");
cloudEventPublisherClient.sendEvent(cloudEventDataObject);
cloudEventPublisherClient.sendEvents(new ArrayList<CloudEvent>() {
{
add(cloudEventDataObject);
}
});
}
public void sendEventGridEvents() {
EventGridPublisherClient<EventGridEvent> eventGridEventPublisherClient = new EventGridPublisherClientBuilder()
.endpoint(System.getenv("AZURE_EVENTGRID_EVENT_ENDPOINT"))
.credential(new AzureKeyCredential(System.getenv("AZURE_EVENTGRID_EVENT_KEY")))
.buildEventGridEventPublisherClient();
User user = new User("John", "James");
EventGridEvent eventGridEvent = new EventGridEvent("/EventGridEvents/example/source",
"Example.EventType", BinaryData.fromObject(user), "0.1");
eventGridEventPublisherClient.sendEvent(eventGridEvent);
eventGridEventPublisherClient.sendEvents(new ArrayList<EventGridEvent>() {
{
add(eventGridEvent);
}
});
}
public void sendCustomEvents() {
EventGridPublisherClient<BinaryData> customEventPublisherClient = new EventGridPublisherClientBuilder()
.endpoint(System.getenv("AZURE_CUSTOM_EVENT_ENDPOINT"))
.credential(new AzureKeyCredential(System.getenv("AZURE_CUSTOM_EVENT_KEY")))
.buildCustomEventPublisherClient();
User user = new User("John", "James");
Map<String, Object> customEvent = new HashMap<String, Object>() {
{
put("id", UUID.randomUUID().toString());
put("subject", "Test");
put("foo", "bar");
put("type", "Microsoft.MockPublisher.TestEvent");
put("data", 100.0);
put("dataVersion", "0.1");
}
};
customEventPublisherClient.sendEvent(BinaryData.fromObject(customEvent));
customEventPublisherClient.sendEvents(new ArrayList<BinaryData>() {
{
add(BinaryData.fromObject(customEvent));
}
});
}
} | class EventGridEventJavaDocCodeSnippet {
public void createEventGridEvent() {
User user = new User("Stephen", "James");
EventGridEvent eventGridEventDataObject = new EventGridEvent("/EventGridEvents/example/source",
"Example.EventType", BinaryData.fromObject(user), "0.1");
EventGridEvent eventGridEventDataStr = new EventGridEvent("/EventGridEvents/example/source",
"Example.EventType", BinaryData.fromObject("Hello World"), "0.1");
EventGridEvent eventGridEventDataInt = new EventGridEvent("/EventGridEvents/example/source",
"Example.EventType", BinaryData.fromObject(1), "0.1");
EventGridEvent eventGridEventDataBool = new EventGridEvent("/EventGridEvents/example/source",
"Example.EventType", BinaryData.fromObject(true), "0.1");
EventGridEvent eventGridEventDataNull = new EventGridEvent("/EventGridEvents/example/source",
"Example.EventType", BinaryData.fromObject(null), "0.1");
String jsonStringForData = "\"Hello World\"";
EventGridEvent eventGridEventDataDataJsonStr = new EventGridEvent("/EventGridEvents/example/source",
"Example.EventType", BinaryData.fromString(jsonStringForData), "0.1");
}
public void fromJsonStringWithDataJson() {
String eventGridEventJsonString = "<A EventGridEvent Json String>";
List<EventGridEvent> eventGridEventList = EventGridEvent.fromString(eventGridEventJsonString);
EventGridEvent eventGridEvent = eventGridEventList.get(0);
BinaryData eventGridEventData = eventGridEvent.getData();
User objectValue = eventGridEventData.toObject(User.class);
int intValue = eventGridEventData.toObject(Integer.class);
boolean boolValue = eventGridEventData.toObject(Boolean.class);
String stringValue = eventGridEventData.toObject(String.class);
String jsonStringValue = eventGridEventData.toString();
}
public void sendCloudEventsAsync() {
EventGridPublisherAsyncClient<CloudEvent> cloudEventPublisherClient = new EventGridPublisherClientBuilder()
.endpoint(System.getenv("AZURE_EVENTGRID_CLOUDEVENT_ENDPOINT"))
.credential(new AzureKeyCredential(System.getenv("AZURE_EVENTGRID_CLOUDEVENT_KEY")))
.buildCloudEventPublisherAsyncClient();
User user = new User("Stephen", "James");
CloudEvent cloudEventDataObject = new CloudEvent("/cloudevents/example/source", "Example.EventType",
BinaryData.fromObject(user), CloudEventDataFormat.JSON, "application/json");
cloudEventPublisherClient.sendEvent(cloudEventDataObject).block();
cloudEventPublisherClient.sendEvents(Arrays.asList(
cloudEventDataObject
)).block();
}
public void sendEventGridEventsAsync() {
EventGridPublisherAsyncClient<EventGridEvent> eventGridEventPublisherClient = new EventGridPublisherClientBuilder()
.endpoint(System.getenv("AZURE_EVENTGRID_EVENT_ENDPOINT"))
.credential(new AzureKeyCredential(System.getenv("AZURE_EVENTGRID_EVENT_KEY")))
.buildEventGridEventPublisherAsyncClient();
User user = new User("John", "James");
EventGridEvent eventGridEvent = new EventGridEvent("/EventGridEvents/example/source",
"Example.EventType", BinaryData.fromObject(user), "0.1");
eventGridEventPublisherClient.sendEvent(eventGridEvent).block();
eventGridEventPublisherClient.sendEvents(Arrays.asList(
eventGridEvent
)).block();
}
public void sendCloudEvents() {
EventGridPublisherClient<CloudEvent> cloudEventPublisherClient = new EventGridPublisherClientBuilder()
.endpoint(System.getenv("AZURE_EVENTGRID_CLOUDEVENT_ENDPOINT"))
.credential(new AzureKeyCredential(System.getenv("AZURE_EVENTGRID_CLOUDEVENT_KEY")))
.buildCloudEventPublisherClient();
User user = new User("Stephen", "James");
CloudEvent cloudEventDataObject = new CloudEvent("/cloudevents/example/source", "Example.EventType",
BinaryData.fromObject(user), CloudEventDataFormat.JSON, "application/json");
cloudEventPublisherClient.sendEvent(cloudEventDataObject);
cloudEventPublisherClient.sendEvents(Arrays.asList(
cloudEventDataObject
));
}
public void sendEventGridEvents() {
EventGridPublisherClient<EventGridEvent> eventGridEventPublisherClient = new EventGridPublisherClientBuilder()
.endpoint(System.getenv("AZURE_EVENTGRID_EVENT_ENDPOINT"))
.credential(new AzureKeyCredential(System.getenv("AZURE_EVENTGRID_EVENT_KEY")))
.buildEventGridEventPublisherClient();
User user = new User("John", "James");
EventGridEvent eventGridEvent = new EventGridEvent("/EventGridEvents/example/source",
"Example.EventType", BinaryData.fromObject(user), "0.1");
eventGridEventPublisherClient.sendEvent(eventGridEvent);
eventGridEventPublisherClient.sendEvents(Arrays.asList(
eventGridEvent
));
}
public void sendCustomEvents() {
EventGridPublisherClient<BinaryData> customEventPublisherClient = new EventGridPublisherClientBuilder()
.endpoint(System.getenv("AZURE_CUSTOM_EVENT_ENDPOINT"))
.credential(new AzureKeyCredential(System.getenv("AZURE_CUSTOM_EVENT_KEY")))
.buildCustomEventPublisherClient();
Map<String, Object> customEvent = new HashMap<String, Object>() {
{
put("id", UUID.randomUUID().toString());
put("subject", "Test");
put("foo", "bar");
put("type", "Microsoft.MockPublisher.TestEvent");
put("data", 100.0);
put("dataVersion", "0.1");
}
};
customEventPublisherClient.sendEvent(BinaryData.fromObject(customEvent));
customEventPublisherClient.sendEvents(Arrays.asList(
BinaryData.fromObject(customEvent)
));
}
} |
Quick change :), from bull to null. | public ChatClientBuilder retryPolicy(RetryPolicy retryPolicy) {
this.retryPolicy = Objects.requireNonNull(retryPolicy, "The retry policy cannot be bull");
return this;
} | this.retryPolicy = Objects.requireNonNull(retryPolicy, "The retry policy cannot be bull"); | public ChatClientBuilder retryPolicy(RetryPolicy retryPolicy) {
this.retryPolicy = Objects.requireNonNull(retryPolicy, "The retry policy cannot be null");
return this;
} | class ChatClientBuilder {
private String endpoint;
private HttpClient httpClient;
private CommunicationTokenCredential communicationTokenCredential;
private final List<HttpPipelinePolicy> customPolicies = new ArrayList<HttpPipelinePolicy>();
private HttpLogOptions logOptions = new HttpLogOptions();
private HttpPipeline httpPipeline;
private Configuration configuration;
private RetryPolicy retryPolicy;
private static final String APP_CONFIG_PROPERTIES = "azure-communication-chat.properties";
private static final String SDK_NAME = "name";
private static final String SDK_VERSION = "version";
/**
* Set endpoint of the service
*
* @param endpoint url of the service
* @return the updated ChatClientBuilder object
*/
public ChatClientBuilder endpoint(String endpoint) {
this.endpoint = Objects.requireNonNull(endpoint, "'endpoint' cannot be null.");
return this;
}
/**
* Set HttpClient to use
*
* @param httpClient HttpClient to use
* @return the updated ChatClientBuilder object
*/
public ChatClientBuilder httpClient(HttpClient httpClient) {
this.httpClient = Objects.requireNonNull(httpClient, "'httpClient' cannot be null.");
return this;
}
/**
* Set a token credential for authorization
*
* @param communicationTokenCredential valid token credential as a string
* @return the updated ChatClientBuilder object
*/
public ChatClientBuilder credential(CommunicationTokenCredential communicationTokenCredential) {
this.communicationTokenCredential = Objects.requireNonNull(
communicationTokenCredential, "'communicationTokenCredential' cannot be null.");
return this;
}
/**
* Apply additional {@link HttpPipelinePolicy}
*
* @param customPolicy HttpPipelinePolicy objects to be applied after
* AzureKeyCredentialPolicy, UserAgentPolicy, RetryPolicy, and CookiePolicy
* @return the updated ChatClientBuilder object
*/
public ChatClientBuilder addPolicy(HttpPipelinePolicy customPolicy) {
this.customPolicies.add(Objects.requireNonNull(customPolicy, "'customPolicy' cannot be null."));
return this;
}
/**
* Sets the {@link HttpLogOptions} for service requests.
*
* @param logOptions The logging configuration to use when sending and receiving HTTP requests/responses.
* @return the updated ChatClientBuilder object
*/
public ChatClientBuilder httpLogOptions(HttpLogOptions logOptions) {
this.logOptions = Objects.requireNonNull(logOptions, "'logOptions' cannot be null.");
return this;
}
/**
* Sets the {@link ChatServiceVersion} that is used when making API requests.
* <p>
* If a service version is not provided, the service version that will be used will be the latest known service
* version based on the version of the client library being used. If no service version is specified, updating to a
* newer version of the client library will have the result of potentially moving to a newer service version.
* <p>
* Targeting a specific service version may also mean that the service will return an error for newer APIs.
*
* @param version {@link ChatServiceVersion} of the service to be used when making requests.
* @return the updated ChatClientBuilder object
*/
public ChatClientBuilder serviceVersion(ChatServiceVersion version) {
return this;
}
/**
* Sets the {@link HttpPipeline} to use for the service client.
*
* If {@code pipeline} is set, all other settings are ignored, aside from {@link
*
* @param httpPipeline HttpPipeline to use for sending service requests and receiving responses.
* @return the updated BlobServiceClientBuilder object
*/
public ChatClientBuilder pipeline(HttpPipeline httpPipeline) {
this.httpPipeline = httpPipeline;
return this;
}
/**
* Sets the configuration object used to retrieve environment configuration values during building of the client.
*
* @param configuration Configuration store used to retrieve environment configurations.
* @return the updated BlobServiceClientBuilder object
*/
public ChatClientBuilder configuration(Configuration configuration) {
this.configuration = configuration;
return this;
}
/**
* Sets the {@link RetryPolicy} that is used when each request is sent.
* <p>
* The default retry policy will be used in the pipeline, if not provided.
*
* @param retryPolicy User's retry policy applied to each request.
* @return The updated {@link ChatClientBuilder} object.
* @throws NullPointerException If the specified {@code retryPolicy} is null.
*/
/**
* Create synchronous client applying CommunicationTokenCredential, UserAgentPolicy,
* RetryPolicy, and CookiePolicy.
* Additional HttpPolicies specified by additionalPolicies will be applied after them
*
* @return ChatClient instance
*/
public ChatClient buildClient() {
ChatAsyncClient asyncClient = buildAsyncClient();
return new ChatClient(asyncClient);
}
/**
* Create asynchronous client applying CommunicationTokenCredential, UserAgentPolicy,
* RetryPolicy, and CookiePolicy.
* Additional HttpPolicies specified by additionalPolicies will be applied after them
*
* @return ChatAsyncClient instance
*/
public ChatAsyncClient buildAsyncClient() {
Objects.requireNonNull(endpoint);
HttpPipeline pipeline;
if (httpPipeline != null) {
pipeline = httpPipeline;
} else {
Objects.requireNonNull(communicationTokenCredential);
Objects.requireNonNull(httpClient);
CommunicationBearerTokenCredential tokenCredential =
new CommunicationBearerTokenCredential(communicationTokenCredential);
pipeline = createHttpPipeline(httpClient,
new BearerTokenAuthenticationPolicy(tokenCredential, ""),
customPolicies);
}
AzureCommunicationChatServiceImplBuilder clientBuilder = new AzureCommunicationChatServiceImplBuilder();
clientBuilder.endpoint(endpoint)
.pipeline(pipeline);
return new ChatAsyncClient(clientBuilder.buildClient());
}
private HttpPipeline createHttpPipeline(HttpClient httpClient,
HttpPipelinePolicy authorizationPolicy,
List<HttpPipelinePolicy> additionalPolicies) {
List<HttpPipelinePolicy> policies = new ArrayList<HttpPipelinePolicy>();
policies.add(authorizationPolicy);
applyRequiredPolicies(policies);
if (additionalPolicies != null && additionalPolicies.size() > 0) {
policies.addAll(additionalPolicies);
}
return new HttpPipelineBuilder()
.policies(policies.toArray(new HttpPipelinePolicy[0]))
.httpClient(httpClient)
.build();
}
private void applyRequiredPolicies(List<HttpPipelinePolicy> policies) {
policies.add(getUserAgentPolicy());
policies.add(this.retryPolicy == null ? new RetryPolicy() : this.retryPolicy);
policies.add(new CookiePolicy());
policies.add(new HttpLoggingPolicy(logOptions));
}
/*
* Creates a {@link UserAgentPolicy} using the default chat service module name and version.
*
* @return The default {@link UserAgentPolicy} for the module.
*/
private UserAgentPolicy getUserAgentPolicy() {
Map<String, String> properties = CoreUtils.getProperties(APP_CONFIG_PROPERTIES);
String clientName = properties.getOrDefault(SDK_NAME, "UnknownName");
String clientVersion = properties.getOrDefault(SDK_VERSION, "UnknownVersion");
return new UserAgentPolicy(
logOptions.getApplicationId(), clientName, clientVersion, configuration);
}
} | class ChatClientBuilder {
private String endpoint;
private HttpClient httpClient;
private CommunicationTokenCredential communicationTokenCredential;
private final List<HttpPipelinePolicy> customPolicies = new ArrayList<HttpPipelinePolicy>();
private HttpLogOptions logOptions = new HttpLogOptions();
private HttpPipeline httpPipeline;
private Configuration configuration;
private RetryPolicy retryPolicy;
private static final String APP_CONFIG_PROPERTIES = "azure-communication-chat.properties";
private static final String SDK_NAME = "name";
private static final String SDK_VERSION = "version";
/**
* Set endpoint of the service
*
* @param endpoint url of the service
* @return the updated ChatClientBuilder object
*/
public ChatClientBuilder endpoint(String endpoint) {
this.endpoint = Objects.requireNonNull(endpoint, "'endpoint' cannot be null.");
return this;
}
/**
* Set HttpClient to use
*
* @param httpClient HttpClient to use
* @return the updated ChatClientBuilder object
*/
public ChatClientBuilder httpClient(HttpClient httpClient) {
this.httpClient = Objects.requireNonNull(httpClient, "'httpClient' cannot be null.");
return this;
}
/**
* Set a token credential for authorization
*
* @param communicationTokenCredential valid token credential as a string
* @return the updated ChatClientBuilder object
*/
public ChatClientBuilder credential(CommunicationTokenCredential communicationTokenCredential) {
this.communicationTokenCredential = Objects.requireNonNull(
communicationTokenCredential, "'communicationTokenCredential' cannot be null.");
return this;
}
/**
* Apply additional {@link HttpPipelinePolicy}
*
* @param customPolicy HttpPipelinePolicy objects to be applied after
* AzureKeyCredentialPolicy, UserAgentPolicy, RetryPolicy, and CookiePolicy
* @return the updated ChatClientBuilder object
*/
public ChatClientBuilder addPolicy(HttpPipelinePolicy customPolicy) {
this.customPolicies.add(Objects.requireNonNull(customPolicy, "'customPolicy' cannot be null."));
return this;
}
/**
* Sets the {@link HttpLogOptions} for service requests.
*
* @param logOptions The logging configuration to use when sending and receiving HTTP requests/responses.
* @return the updated ChatClientBuilder object
*/
public ChatClientBuilder httpLogOptions(HttpLogOptions logOptions) {
this.logOptions = Objects.requireNonNull(logOptions, "'logOptions' cannot be null.");
return this;
}
/**
* Sets the {@link ChatServiceVersion} that is used when making API requests.
* <p>
* If a service version is not provided, the service version that will be used will be the latest known service
* version based on the version of the client library being used. If no service version is specified, updating to a
* newer version of the client library will have the result of potentially moving to a newer service version.
* <p>
* Targeting a specific service version may also mean that the service will return an error for newer APIs.
*
* @param version {@link ChatServiceVersion} of the service to be used when making requests.
* @return the updated ChatClientBuilder object
*/
public ChatClientBuilder serviceVersion(ChatServiceVersion version) {
return this;
}
/**
* Sets the {@link HttpPipeline} to use for the service client.
*
* If {@code pipeline} is set, all other settings are ignored, aside from {@link
*
* @param httpPipeline HttpPipeline to use for sending service requests and receiving responses.
* @return the updated BlobServiceClientBuilder object
*/
public ChatClientBuilder pipeline(HttpPipeline httpPipeline) {
this.httpPipeline = httpPipeline;
return this;
}
/**
* Sets the configuration object used to retrieve environment configuration values during building of the client.
*
* @param configuration Configuration store used to retrieve environment configurations.
* @return the updated BlobServiceClientBuilder object
*/
public ChatClientBuilder configuration(Configuration configuration) {
this.configuration = configuration;
return this;
}
/**
* Sets the {@link RetryPolicy} that is used when each request is sent.
*
* @param retryPolicy User's retry policy applied to each request.
* @return The updated {@link ChatClientBuilder} object.
* @throws NullPointerException If the specified {@code retryPolicy} is null.
*/
/**
* Create synchronous client applying CommunicationTokenCredential, UserAgentPolicy,
* RetryPolicy, and CookiePolicy.
* Additional HttpPolicies specified by additionalPolicies will be applied after them
*
* @return ChatClient instance
*/
public ChatClient buildClient() {
ChatAsyncClient asyncClient = buildAsyncClient();
return new ChatClient(asyncClient);
}
/**
* Create asynchronous client applying CommunicationTokenCredential, UserAgentPolicy,
* RetryPolicy, and CookiePolicy.
* Additional HttpPolicies specified by additionalPolicies will be applied after them
*
* @return ChatAsyncClient instance
*/
public ChatAsyncClient buildAsyncClient() {
Objects.requireNonNull(endpoint);
HttpPipeline pipeline;
if (httpPipeline != null) {
pipeline = httpPipeline;
} else {
Objects.requireNonNull(communicationTokenCredential);
Objects.requireNonNull(httpClient);
CommunicationBearerTokenCredential tokenCredential =
new CommunicationBearerTokenCredential(communicationTokenCredential);
pipeline = createHttpPipeline(httpClient,
new BearerTokenAuthenticationPolicy(tokenCredential, ""),
customPolicies);
}
AzureCommunicationChatServiceImplBuilder clientBuilder = new AzureCommunicationChatServiceImplBuilder();
clientBuilder.endpoint(endpoint)
.pipeline(pipeline);
return new ChatAsyncClient(clientBuilder.buildClient());
}
private HttpPipeline createHttpPipeline(HttpClient httpClient,
HttpPipelinePolicy authorizationPolicy,
List<HttpPipelinePolicy> additionalPolicies) {
List<HttpPipelinePolicy> policies = new ArrayList<HttpPipelinePolicy>();
policies.add(authorizationPolicy);
applyRequiredPolicies(policies);
if (additionalPolicies != null && additionalPolicies.size() > 0) {
policies.addAll(additionalPolicies);
}
return new HttpPipelineBuilder()
.policies(policies.toArray(new HttpPipelinePolicy[0]))
.httpClient(httpClient)
.build();
}
private void applyRequiredPolicies(List<HttpPipelinePolicy> policies) {
policies.add(getUserAgentPolicy());
policies.add(this.retryPolicy == null ? new RetryPolicy() : this.retryPolicy);
policies.add(new CookiePolicy());
policies.add(new HttpLoggingPolicy(logOptions));
}
/*
* Creates a {@link UserAgentPolicy} using the default chat service module name and version.
*
* @return The default {@link UserAgentPolicy} for the module.
*/
private UserAgentPolicy getUserAgentPolicy() {
Map<String, String> properties = CoreUtils.getProperties(APP_CONFIG_PROPERTIES);
String clientName = properties.getOrDefault(SDK_NAME, "UnknownName");
String clientVersion = properties.getOrDefault(SDK_VERSION, "UnknownVersion");
return new UserAgentPolicy(
logOptions.getApplicationId(), clientName, clientVersion, configuration);
}
} |
Same here :), bull to null. | public PhoneNumbersClientBuilder retryPolicy(RetryPolicy retryPolicy) {
this.retryPolicy = Objects.requireNonNull(retryPolicy, "The retry policy cannot be bull");
return this;
} | this.retryPolicy = Objects.requireNonNull(retryPolicy, "The retry policy cannot be bull"); | public PhoneNumbersClientBuilder retryPolicy(RetryPolicy retryPolicy) {
this.retryPolicy = Objects.requireNonNull(retryPolicy, "The retry policy cannot be null");
return this;
} | class PhoneNumbersClientBuilder {
private static final Map<String, String> PROPERTIES =
CoreUtils.getProperties("azure-communication-phonenumbers.properties");
private static final String SDK_NAME = "name";
private static final String SDK_VERSION = "version";
private final ClientLogger logger = new ClientLogger(PhoneNumbersClientBuilder.class);
private PhoneNumbersServiceVersion version;
private String endpoint;
private HttpPipeline pipeline;
private HttpClient httpClient;
private HttpLogOptions httpLogOptions;
private AzureKeyCredential azureKeyCredential;
private TokenCredential tokenCredential;
private Configuration configuration;
private ClientOptions clientOptions;
private RetryPolicy retryPolicy;
private final List<HttpPipelinePolicy> additionalPolicies = new ArrayList<>();
/**
* Set endpoint of the service
*
* @param endpoint url of the service
* @return The updated {@link PhoneNumbersClientBuilder} object.
* @throws NullPointerException If {@code endpoint} is {@code null}.
*/
public PhoneNumbersClientBuilder endpoint(String endpoint) {
this.endpoint = Objects.requireNonNull(endpoint, "'endpoint' cannot be null.");
return this;
}
/**
* Sets the HTTP pipeline to use for the service client
* <p>
* If {@code pipeline} is set, all other settings aside from
* {@link PhoneNumbersClientBuilder
*
* @param pipeline HttpPipeline to use
* @return The updated {@link PhoneNumbersClientBuilder} object.
*/
public PhoneNumbersClientBuilder pipeline(HttpPipeline pipeline) {
this.pipeline = pipeline;
return this;
}
/**
* Set HttpClient to use
*
* @param httpClient HttpClient to use
* @return The updated {@link PhoneNumbersClientBuilder} object.
* @throws NullPointerException If {@code httpClient} is {@code null}.
*/
public PhoneNumbersClientBuilder httpClient(HttpClient httpClient) {
this.httpClient = httpClient;
return this;
}
/**
* Sets the logging configuration for HTTP requests and responses.
*
* <p> If logLevel is not provided, default value of {@link HttpLogDetailLevel
*
* @param httpLogOptions The logging configuration to use when sending and receiving HTTP requests/responses.
* @return the updated {@link PhoneNumbersClientBuilder} object.
*/
public PhoneNumbersClientBuilder httpLogOptions(HttpLogOptions httpLogOptions) {
this.httpLogOptions = httpLogOptions;
return this;
}
/**
* Sets the {@link AzureKeyCredential} used to authenticate HTTP requests.
*
* @param keyCredential The {@link AzureKeyCredential} used to authenticate HTTP requests.
* @return The updated {@link PhoneNumbersClientBuilder} object.
* @throws NullPointerException If {@code keyCredential} is null.
*/
public PhoneNumbersClientBuilder credential(AzureKeyCredential keyCredential) {
this.azureKeyCredential = Objects.requireNonNull(keyCredential, "'keyCredential' cannot be null.");
return this;
}
/**
* Sets the {@link TokenCredential} used to authenticate HTTP requests.
*
* @param tokenCredential {@link TokenCredential} used to authenticate HTTP requests.
* @return The updated {@link PhoneNumbersClientBuilder} object.
* @throws NullPointerException If {@code tokenCredential} is null.
*/
public PhoneNumbersClientBuilder credential(TokenCredential tokenCredential) {
this.tokenCredential = Objects.requireNonNull(tokenCredential, "'tokenCredential' cannot be null.");
return this;
}
/**
* Set the endpoint and AzureKeyCredential for authorization
*
* @param connectionString connection string for setting endpoint and initalizing AzureKeyCredential
* @return The updated {@link PhoneNumbersClientBuilder} object.
* @throws NullPointerException If {@code connectionString} is {@code null}.
*/
public PhoneNumbersClientBuilder connectionString(String connectionString) {
Objects.requireNonNull(connectionString, "'connectionString' cannot be null.");
CommunicationConnectionString connectionStringObject = new CommunicationConnectionString(connectionString);
String endpoint = connectionStringObject.getEndpoint();
String accessKey = connectionStringObject.getAccessKey();
this
.endpoint(endpoint)
.credential(new AzureKeyCredential(accessKey));
return this;
}
/**
* Sets the configuration object used to retrieve environment configuration values during building of the client.
*
* @param configuration Configuration store used to retrieve environment configurations.
* @return The updated {@link PhoneNumbersClientBuilder} object.
*/
public PhoneNumbersClientBuilder configuration(Configuration configuration) {
this.configuration = configuration;
return this;
}
/**
* Adds a policy to the set of existing policies that are executed after required policies.
*
* @param policy The retry policy for service requests.
* @return The updated {@link PhoneNumbersClientBuilder} object.
* @throws NullPointerException If {@code policy} is {@code null}.
*/
public PhoneNumbersClientBuilder addPolicy(HttpPipelinePolicy policy) {
this.additionalPolicies.add(Objects.requireNonNull(policy, "'policy' cannot be null."));
return this;
}
/**
* Sets the client options for all the requests made through the client.
*
* @param clientOptions {@link ClientOptions}.
* @return The updated {@link PhoneNumbersClientBuilder} object.
* @throws NullPointerException If {@code clientOptions} is {@code null}.
*/
public PhoneNumbersClientBuilder clientOptions(ClientOptions clientOptions) {
this.clientOptions = Objects.requireNonNull(clientOptions, "'clientOptions' cannot be null.");
return this;
}
/**
* Sets the {@link PhoneNumbersServiceVersion} that is used when making API requests.
* <p>
* If a service version is not provided, the service version that will be used will be the latest known service
* version based on the version of the client library being used. If no service version is specified, updating to a
* newer version the client library will have the result of potentially moving to a newer service version.
*
* @param version {@link PhoneNumbersServiceVersion} of the service to be used when making requests.
* @return The updated {@link PhoneNumbersClientBuilder} object.
*/
public PhoneNumbersClientBuilder serviceVersion(PhoneNumbersServiceVersion version) {
this.version = version;
return this;
}
/**
* Sets the {@link RetryPolicy} that is used when each request is sent.
* <p>
* The default retry policy will be used in the pipeline, if not provided.
*
* @param retryPolicy User's retry policy applied to each request.
* @return The updated {@link PhoneNumbersClientBuilder} object.
* @throws NullPointerException If the specified {@code retryPolicy} is null.
*/
/**
* Create synchronous client applying CommunicationClientCredentialPolicy,
* UserAgentPolicy, RetryPolicy, and CookiePolicy.
* Additional HttpPolicies specified by additionalPolicies will be applied after them
*
* @return {@link PhoneNumbersClient} instance
*/
public PhoneNumbersClient buildClient() {
this.validateRequiredFields();
if (this.version != null) {
logger.info("Build client for service version" + this.version.getVersion());
}
PhoneNumberAdminClientImpl adminClient = this.createPhoneNumberAdminClient();
return new PhoneNumbersClient(adminClient, this.createPhoneNumberAsyncClient(adminClient));
}
/**
* Create asynchronous client applying CommunicationClientCredentialPolicy,
* UserAgentPolicy, RetryPolicy, and CookiePolicy.
* Additional HttpPolicies specified by additionalPolicies will be applied after them
*
* @return {@link PhoneNumbersAsyncClient} instance
*/
public PhoneNumbersAsyncClient buildAsyncClient() {
this.validateRequiredFields();
if (this.version != null) {
logger.info("Build client for service version" + this.version.getVersion());
}
return this.createPhoneNumberAsyncClient(this.createPhoneNumberAdminClient());
}
PhoneNumbersAsyncClient createPhoneNumberAsyncClient(PhoneNumberAdminClientImpl phoneNumberAdminClient) {
return new PhoneNumbersAsyncClient(phoneNumberAdminClient);
}
HttpPipelinePolicy createAuthenticationPolicy() {
if (this.tokenCredential != null && this.azureKeyCredential != null) {
throw logger.logExceptionAsError(
new IllegalArgumentException("Both 'credential' and 'keyCredential' are set. Just one may be used."));
}
if (this.tokenCredential != null) {
return new BearerTokenAuthenticationPolicy(
this.tokenCredential, "https:
} else if (this.azureKeyCredential != null) {
return new HmacAuthenticationPolicy(this.azureKeyCredential);
} else {
throw logger.logExceptionAsError(
new NullPointerException("Missing credential information while building a client."));
}
}
UserAgentPolicy createUserAgentPolicy(
String applicationId, String sdkName, String sdkVersion, Configuration configuration) {
return new UserAgentPolicy(applicationId, sdkName, sdkVersion, configuration);
}
RetryPolicy createRetryPolicy() {
return this.retryPolicy == null ? new RetryPolicy() : this.retryPolicy;
}
CookiePolicy createCookiePolicy() {
return new CookiePolicy();
}
HttpLoggingPolicy createHttpLoggingPolicy(HttpLogOptions httpLogOptions) {
return new HttpLoggingPolicy(httpLogOptions);
}
HttpLogOptions createDefaultHttpLogOptions() {
return new HttpLogOptions();
}
private void validateRequiredFields() {
Objects.requireNonNull(this.endpoint);
if (this.pipeline == null) {
Objects.requireNonNull(this.httpClient);
}
}
private PhoneNumberAdminClientImpl createPhoneNumberAdminClient() {
PhoneNumberAdminClientImplBuilder clientBuilder = new PhoneNumberAdminClientImplBuilder();
return clientBuilder
.endpoint(this.endpoint)
.pipeline(this.createHttpPipeline())
.buildClient();
}
private HttpPipeline createHttpPipeline() {
if (this.pipeline != null) {
return this.pipeline;
}
List<HttpPipelinePolicy> policyList = new ArrayList<>();
ClientOptions buildClientOptions = (clientOptions == null) ? new ClientOptions() : clientOptions;
HttpLogOptions buildLogOptions = (httpLogOptions == null) ? new HttpLogOptions() : httpLogOptions;
String applicationId = null;
if (!CoreUtils.isNullOrEmpty(buildClientOptions.getApplicationId())) {
applicationId = buildClientOptions.getApplicationId();
} else if (!CoreUtils.isNullOrEmpty(buildLogOptions.getApplicationId())) {
applicationId = buildLogOptions.getApplicationId();
}
policyList.add(this.createAuthenticationPolicy());
policyList.add(this.createUserAgentPolicy(
applicationId,
PROPERTIES.get(SDK_NAME),
PROPERTIES.get(SDK_VERSION),
this.configuration
));
policyList.add(this.createRetryPolicy());
policyList.add(this.createCookiePolicy());
if (this.additionalPolicies.size() > 0) {
policyList.addAll(this.additionalPolicies);
}
policyList.add(this.createHttpLoggingPolicy(this.getHttpLogOptions()));
return new HttpPipelineBuilder()
.policies(policyList.toArray(new HttpPipelinePolicy[0]))
.httpClient(this.httpClient)
.clientOptions(clientOptions)
.build();
}
private HttpLogOptions getHttpLogOptions() {
if (this.httpLogOptions == null) {
this.httpLogOptions = this.createDefaultHttpLogOptions();
}
return this.httpLogOptions;
}
} | class PhoneNumbersClientBuilder {
private static final Map<String, String> PROPERTIES =
CoreUtils.getProperties("azure-communication-phonenumbers.properties");
private static final String SDK_NAME = "name";
private static final String SDK_VERSION = "version";
private final ClientLogger logger = new ClientLogger(PhoneNumbersClientBuilder.class);
private PhoneNumbersServiceVersion version;
private String endpoint;
private HttpPipeline pipeline;
private HttpClient httpClient;
private HttpLogOptions httpLogOptions;
private AzureKeyCredential azureKeyCredential;
private TokenCredential tokenCredential;
private Configuration configuration;
private ClientOptions clientOptions;
private RetryPolicy retryPolicy;
private final List<HttpPipelinePolicy> additionalPolicies = new ArrayList<>();
/**
* Set endpoint of the service
*
* @param endpoint url of the service
* @return The updated {@link PhoneNumbersClientBuilder} object.
* @throws NullPointerException If {@code endpoint} is {@code null}.
*/
public PhoneNumbersClientBuilder endpoint(String endpoint) {
this.endpoint = Objects.requireNonNull(endpoint, "'endpoint' cannot be null.");
return this;
}
/**
* Sets the HTTP pipeline to use for the service client
* <p>
* If {@code pipeline} is set, all other settings aside from
* {@link PhoneNumbersClientBuilder
*
* @param pipeline HttpPipeline to use
* @return The updated {@link PhoneNumbersClientBuilder} object.
*/
public PhoneNumbersClientBuilder pipeline(HttpPipeline pipeline) {
this.pipeline = pipeline;
return this;
}
/**
* Set HttpClient to use
*
* @param httpClient HttpClient to use
* @return The updated {@link PhoneNumbersClientBuilder} object.
* @throws NullPointerException If {@code httpClient} is {@code null}.
*/
public PhoneNumbersClientBuilder httpClient(HttpClient httpClient) {
this.httpClient = httpClient;
return this;
}
/**
* Sets the logging configuration for HTTP requests and responses.
*
* <p> If logLevel is not provided, default value of {@link HttpLogDetailLevel
*
* @param httpLogOptions The logging configuration to use when sending and receiving HTTP requests/responses.
* @return the updated {@link PhoneNumbersClientBuilder} object.
*/
public PhoneNumbersClientBuilder httpLogOptions(HttpLogOptions httpLogOptions) {
this.httpLogOptions = httpLogOptions;
return this;
}
/**
* Sets the {@link AzureKeyCredential} used to authenticate HTTP requests.
*
* @param keyCredential The {@link AzureKeyCredential} used to authenticate HTTP requests.
* @return The updated {@link PhoneNumbersClientBuilder} object.
* @throws NullPointerException If {@code keyCredential} is null.
*/
public PhoneNumbersClientBuilder credential(AzureKeyCredential keyCredential) {
this.azureKeyCredential = Objects.requireNonNull(keyCredential, "'keyCredential' cannot be null.");
return this;
}
/**
* Sets the {@link TokenCredential} used to authenticate HTTP requests.
*
* @param tokenCredential {@link TokenCredential} used to authenticate HTTP requests.
* @return The updated {@link PhoneNumbersClientBuilder} object.
* @throws NullPointerException If {@code tokenCredential} is null.
*/
public PhoneNumbersClientBuilder credential(TokenCredential tokenCredential) {
this.tokenCredential = Objects.requireNonNull(tokenCredential, "'tokenCredential' cannot be null.");
return this;
}
/**
* Set the endpoint and AzureKeyCredential for authorization
*
* @param connectionString connection string for setting endpoint and initalizing AzureKeyCredential
* @return The updated {@link PhoneNumbersClientBuilder} object.
* @throws NullPointerException If {@code connectionString} is {@code null}.
*/
public PhoneNumbersClientBuilder connectionString(String connectionString) {
Objects.requireNonNull(connectionString, "'connectionString' cannot be null.");
CommunicationConnectionString connectionStringObject = new CommunicationConnectionString(connectionString);
String endpoint = connectionStringObject.getEndpoint();
String accessKey = connectionStringObject.getAccessKey();
this
.endpoint(endpoint)
.credential(new AzureKeyCredential(accessKey));
return this;
}
/**
* Sets the configuration object used to retrieve environment configuration values during building of the client.
*
* @param configuration Configuration store used to retrieve environment configurations.
* @return The updated {@link PhoneNumbersClientBuilder} object.
*/
public PhoneNumbersClientBuilder configuration(Configuration configuration) {
this.configuration = configuration;
return this;
}
/**
* Adds a policy to the set of existing policies that are executed after required policies.
*
* @param policy The retry policy for service requests.
* @return The updated {@link PhoneNumbersClientBuilder} object.
* @throws NullPointerException If {@code policy} is {@code null}.
*/
public PhoneNumbersClientBuilder addPolicy(HttpPipelinePolicy policy) {
this.additionalPolicies.add(Objects.requireNonNull(policy, "'policy' cannot be null."));
return this;
}
/**
* Sets the client options for all the requests made through the client.
*
* @param clientOptions {@link ClientOptions}.
* @return The updated {@link PhoneNumbersClientBuilder} object.
* @throws NullPointerException If {@code clientOptions} is {@code null}.
*/
public PhoneNumbersClientBuilder clientOptions(ClientOptions clientOptions) {
this.clientOptions = Objects.requireNonNull(clientOptions, "'clientOptions' cannot be null.");
return this;
}
/**
* Sets the {@link PhoneNumbersServiceVersion} that is used when making API requests.
* <p>
* If a service version is not provided, the service version that will be used will be the latest known service
* version based on the version of the client library being used. If no service version is specified, updating to a
* newer version the client library will have the result of potentially moving to a newer service version.
*
* @param version {@link PhoneNumbersServiceVersion} of the service to be used when making requests.
* @return The updated {@link PhoneNumbersClientBuilder} object.
*/
public PhoneNumbersClientBuilder serviceVersion(PhoneNumbersServiceVersion version) {
this.version = version;
return this;
}
/**
* Sets the {@link RetryPolicy} that is used when each request is sent.
*
* @param retryPolicy User's retry policy applied to each request.
* @return The updated {@link PhoneNumbersClientBuilder} object.
* @throws NullPointerException If the specified {@code retryPolicy} is null.
*/
/**
* Create synchronous client applying CommunicationClientCredentialPolicy,
* UserAgentPolicy, RetryPolicy, and CookiePolicy.
* Additional HttpPolicies specified by additionalPolicies will be applied after them
*
* @return {@link PhoneNumbersClient} instance
*/
public PhoneNumbersClient buildClient() {
this.validateRequiredFields();
if (this.version != null) {
logger.info("Build client for service version" + this.version.getVersion());
}
PhoneNumberAdminClientImpl adminClient = this.createPhoneNumberAdminClient();
return new PhoneNumbersClient(adminClient, this.createPhoneNumberAsyncClient(adminClient));
}
/**
* Create asynchronous client applying CommunicationClientCredentialPolicy,
* UserAgentPolicy, RetryPolicy, and CookiePolicy.
* Additional HttpPolicies specified by additionalPolicies will be applied after them
*
* @return {@link PhoneNumbersAsyncClient} instance
*/
public PhoneNumbersAsyncClient buildAsyncClient() {
this.validateRequiredFields();
if (this.version != null) {
logger.info("Build client for service version" + this.version.getVersion());
}
return this.createPhoneNumberAsyncClient(this.createPhoneNumberAdminClient());
}
PhoneNumbersAsyncClient createPhoneNumberAsyncClient(PhoneNumberAdminClientImpl phoneNumberAdminClient) {
return new PhoneNumbersAsyncClient(phoneNumberAdminClient);
}
HttpPipelinePolicy createAuthenticationPolicy() {
if (this.tokenCredential != null && this.azureKeyCredential != null) {
throw logger.logExceptionAsError(
new IllegalArgumentException("Both 'credential' and 'keyCredential' are set. Just one may be used."));
}
if (this.tokenCredential != null) {
return new BearerTokenAuthenticationPolicy(
this.tokenCredential, "https:
} else if (this.azureKeyCredential != null) {
return new HmacAuthenticationPolicy(this.azureKeyCredential);
} else {
throw logger.logExceptionAsError(
new NullPointerException("Missing credential information while building a client."));
}
}
UserAgentPolicy createUserAgentPolicy(
String applicationId, String sdkName, String sdkVersion, Configuration configuration) {
return new UserAgentPolicy(applicationId, sdkName, sdkVersion, configuration);
}
CookiePolicy createCookiePolicy() {
return new CookiePolicy();
}
HttpLoggingPolicy createHttpLoggingPolicy(HttpLogOptions httpLogOptions) {
return new HttpLoggingPolicy(httpLogOptions);
}
HttpLogOptions createDefaultHttpLogOptions() {
return new HttpLogOptions();
}
private void validateRequiredFields() {
Objects.requireNonNull(this.endpoint);
if (this.pipeline == null) {
Objects.requireNonNull(this.httpClient);
}
}
private PhoneNumberAdminClientImpl createPhoneNumberAdminClient() {
PhoneNumberAdminClientImplBuilder clientBuilder = new PhoneNumberAdminClientImplBuilder();
return clientBuilder
.endpoint(this.endpoint)
.pipeline(this.createHttpPipeline())
.buildClient();
}
private HttpPipeline createHttpPipeline() {
if (this.pipeline != null) {
return this.pipeline;
}
List<HttpPipelinePolicy> policyList = new ArrayList<>();
ClientOptions buildClientOptions = (clientOptions == null) ? new ClientOptions() : clientOptions;
HttpLogOptions buildLogOptions = (httpLogOptions == null) ? new HttpLogOptions() : httpLogOptions;
String applicationId = null;
if (!CoreUtils.isNullOrEmpty(buildClientOptions.getApplicationId())) {
applicationId = buildClientOptions.getApplicationId();
} else if (!CoreUtils.isNullOrEmpty(buildLogOptions.getApplicationId())) {
applicationId = buildLogOptions.getApplicationId();
}
policyList.add(this.createAuthenticationPolicy());
policyList.add(this.createUserAgentPolicy(
applicationId,
PROPERTIES.get(SDK_NAME),
PROPERTIES.get(SDK_VERSION),
this.configuration
));
policyList.add(this.retryPolicy == null ? new RetryPolicy() : this.retryPolicy);
policyList.add(this.createCookiePolicy());
if (this.additionalPolicies.size() > 0) {
policyList.addAll(this.additionalPolicies);
}
policyList.add(this.createHttpLoggingPolicy(this.getHttpLogOptions()));
return new HttpPipelineBuilder()
.policies(policyList.toArray(new HttpPipelinePolicy[0]))
.httpClient(this.httpClient)
.clientOptions(clientOptions)
.build();
}
private HttpLogOptions getHttpLogOptions() {
if (this.httpLogOptions == null) {
this.httpLogOptions = this.createDefaultHttpLogOptions();
}
return this.httpLogOptions;
}
} |
haha great catch! I dont know how that got there :D | public ChatClientBuilder retryPolicy(RetryPolicy retryPolicy) {
this.retryPolicy = Objects.requireNonNull(retryPolicy, "The retry policy cannot be bull");
return this;
} | this.retryPolicy = Objects.requireNonNull(retryPolicy, "The retry policy cannot be bull"); | public ChatClientBuilder retryPolicy(RetryPolicy retryPolicy) {
this.retryPolicy = Objects.requireNonNull(retryPolicy, "The retry policy cannot be null");
return this;
} | class ChatClientBuilder {
private String endpoint;
private HttpClient httpClient;
private CommunicationTokenCredential communicationTokenCredential;
private final List<HttpPipelinePolicy> customPolicies = new ArrayList<HttpPipelinePolicy>();
private HttpLogOptions logOptions = new HttpLogOptions();
private HttpPipeline httpPipeline;
private Configuration configuration;
private RetryPolicy retryPolicy;
private static final String APP_CONFIG_PROPERTIES = "azure-communication-chat.properties";
private static final String SDK_NAME = "name";
private static final String SDK_VERSION = "version";
/**
* Set endpoint of the service
*
* @param endpoint url of the service
* @return the updated ChatClientBuilder object
*/
public ChatClientBuilder endpoint(String endpoint) {
this.endpoint = Objects.requireNonNull(endpoint, "'endpoint' cannot be null.");
return this;
}
/**
* Set HttpClient to use
*
* @param httpClient HttpClient to use
* @return the updated ChatClientBuilder object
*/
public ChatClientBuilder httpClient(HttpClient httpClient) {
this.httpClient = Objects.requireNonNull(httpClient, "'httpClient' cannot be null.");
return this;
}
/**
* Set a token credential for authorization
*
* @param communicationTokenCredential valid token credential as a string
* @return the updated ChatClientBuilder object
*/
public ChatClientBuilder credential(CommunicationTokenCredential communicationTokenCredential) {
this.communicationTokenCredential = Objects.requireNonNull(
communicationTokenCredential, "'communicationTokenCredential' cannot be null.");
return this;
}
/**
* Apply additional {@link HttpPipelinePolicy}
*
* @param customPolicy HttpPipelinePolicy objects to be applied after
* AzureKeyCredentialPolicy, UserAgentPolicy, RetryPolicy, and CookiePolicy
* @return the updated ChatClientBuilder object
*/
public ChatClientBuilder addPolicy(HttpPipelinePolicy customPolicy) {
this.customPolicies.add(Objects.requireNonNull(customPolicy, "'customPolicy' cannot be null."));
return this;
}
/**
* Sets the {@link HttpLogOptions} for service requests.
*
* @param logOptions The logging configuration to use when sending and receiving HTTP requests/responses.
* @return the updated ChatClientBuilder object
*/
public ChatClientBuilder httpLogOptions(HttpLogOptions logOptions) {
this.logOptions = Objects.requireNonNull(logOptions, "'logOptions' cannot be null.");
return this;
}
/**
* Sets the {@link ChatServiceVersion} that is used when making API requests.
* <p>
* If a service version is not provided, the service version that will be used will be the latest known service
* version based on the version of the client library being used. If no service version is specified, updating to a
* newer version of the client library will have the result of potentially moving to a newer service version.
* <p>
* Targeting a specific service version may also mean that the service will return an error for newer APIs.
*
* @param version {@link ChatServiceVersion} of the service to be used when making requests.
* @return the updated ChatClientBuilder object
*/
public ChatClientBuilder serviceVersion(ChatServiceVersion version) {
return this;
}
/**
* Sets the {@link HttpPipeline} to use for the service client.
*
* If {@code pipeline} is set, all other settings are ignored, aside from {@link
*
* @param httpPipeline HttpPipeline to use for sending service requests and receiving responses.
* @return the updated BlobServiceClientBuilder object
*/
public ChatClientBuilder pipeline(HttpPipeline httpPipeline) {
this.httpPipeline = httpPipeline;
return this;
}
/**
* Sets the configuration object used to retrieve environment configuration values during building of the client.
*
* @param configuration Configuration store used to retrieve environment configurations.
* @return the updated BlobServiceClientBuilder object
*/
public ChatClientBuilder configuration(Configuration configuration) {
this.configuration = configuration;
return this;
}
/**
* Sets the {@link RetryPolicy} that is used when each request is sent.
* <p>
* The default retry policy will be used in the pipeline, if not provided.
*
* @param retryPolicy User's retry policy applied to each request.
* @return The updated {@link ChatClientBuilder} object.
* @throws NullPointerException If the specified {@code retryPolicy} is null.
*/
/**
* Create synchronous client applying CommunicationTokenCredential, UserAgentPolicy,
* RetryPolicy, and CookiePolicy.
* Additional HttpPolicies specified by additionalPolicies will be applied after them
*
* @return ChatClient instance
*/
public ChatClient buildClient() {
ChatAsyncClient asyncClient = buildAsyncClient();
return new ChatClient(asyncClient);
}
/**
* Create asynchronous client applying CommunicationTokenCredential, UserAgentPolicy,
* RetryPolicy, and CookiePolicy.
* Additional HttpPolicies specified by additionalPolicies will be applied after them
*
* @return ChatAsyncClient instance
*/
public ChatAsyncClient buildAsyncClient() {
Objects.requireNonNull(endpoint);
HttpPipeline pipeline;
if (httpPipeline != null) {
pipeline = httpPipeline;
} else {
Objects.requireNonNull(communicationTokenCredential);
Objects.requireNonNull(httpClient);
CommunicationBearerTokenCredential tokenCredential =
new CommunicationBearerTokenCredential(communicationTokenCredential);
pipeline = createHttpPipeline(httpClient,
new BearerTokenAuthenticationPolicy(tokenCredential, ""),
customPolicies);
}
AzureCommunicationChatServiceImplBuilder clientBuilder = new AzureCommunicationChatServiceImplBuilder();
clientBuilder.endpoint(endpoint)
.pipeline(pipeline);
return new ChatAsyncClient(clientBuilder.buildClient());
}
private HttpPipeline createHttpPipeline(HttpClient httpClient,
HttpPipelinePolicy authorizationPolicy,
List<HttpPipelinePolicy> additionalPolicies) {
List<HttpPipelinePolicy> policies = new ArrayList<HttpPipelinePolicy>();
policies.add(authorizationPolicy);
applyRequiredPolicies(policies);
if (additionalPolicies != null && additionalPolicies.size() > 0) {
policies.addAll(additionalPolicies);
}
return new HttpPipelineBuilder()
.policies(policies.toArray(new HttpPipelinePolicy[0]))
.httpClient(httpClient)
.build();
}
private void applyRequiredPolicies(List<HttpPipelinePolicy> policies) {
policies.add(getUserAgentPolicy());
policies.add(this.retryPolicy == null ? new RetryPolicy() : this.retryPolicy);
policies.add(new CookiePolicy());
policies.add(new HttpLoggingPolicy(logOptions));
}
/*
* Creates a {@link UserAgentPolicy} using the default chat service module name and version.
*
* @return The default {@link UserAgentPolicy} for the module.
*/
private UserAgentPolicy getUserAgentPolicy() {
Map<String, String> properties = CoreUtils.getProperties(APP_CONFIG_PROPERTIES);
String clientName = properties.getOrDefault(SDK_NAME, "UnknownName");
String clientVersion = properties.getOrDefault(SDK_VERSION, "UnknownVersion");
return new UserAgentPolicy(
logOptions.getApplicationId(), clientName, clientVersion, configuration);
}
} | class ChatClientBuilder {
private String endpoint;
private HttpClient httpClient;
private CommunicationTokenCredential communicationTokenCredential;
private final List<HttpPipelinePolicy> customPolicies = new ArrayList<HttpPipelinePolicy>();
private HttpLogOptions logOptions = new HttpLogOptions();
private HttpPipeline httpPipeline;
private Configuration configuration;
private RetryPolicy retryPolicy;
private static final String APP_CONFIG_PROPERTIES = "azure-communication-chat.properties";
private static final String SDK_NAME = "name";
private static final String SDK_VERSION = "version";
/**
* Set endpoint of the service
*
* @param endpoint url of the service
* @return the updated ChatClientBuilder object
*/
public ChatClientBuilder endpoint(String endpoint) {
this.endpoint = Objects.requireNonNull(endpoint, "'endpoint' cannot be null.");
return this;
}
/**
* Set HttpClient to use
*
* @param httpClient HttpClient to use
* @return the updated ChatClientBuilder object
*/
public ChatClientBuilder httpClient(HttpClient httpClient) {
this.httpClient = Objects.requireNonNull(httpClient, "'httpClient' cannot be null.");
return this;
}
/**
* Set a token credential for authorization
*
* @param communicationTokenCredential valid token credential as a string
* @return the updated ChatClientBuilder object
*/
public ChatClientBuilder credential(CommunicationTokenCredential communicationTokenCredential) {
this.communicationTokenCredential = Objects.requireNonNull(
communicationTokenCredential, "'communicationTokenCredential' cannot be null.");
return this;
}
/**
* Apply additional {@link HttpPipelinePolicy}
*
* @param customPolicy HttpPipelinePolicy objects to be applied after
* AzureKeyCredentialPolicy, UserAgentPolicy, RetryPolicy, and CookiePolicy
* @return the updated ChatClientBuilder object
*/
public ChatClientBuilder addPolicy(HttpPipelinePolicy customPolicy) {
this.customPolicies.add(Objects.requireNonNull(customPolicy, "'customPolicy' cannot be null."));
return this;
}
/**
* Sets the {@link HttpLogOptions} for service requests.
*
* @param logOptions The logging configuration to use when sending and receiving HTTP requests/responses.
* @return the updated ChatClientBuilder object
*/
public ChatClientBuilder httpLogOptions(HttpLogOptions logOptions) {
this.logOptions = Objects.requireNonNull(logOptions, "'logOptions' cannot be null.");
return this;
}
/**
* Sets the {@link ChatServiceVersion} that is used when making API requests.
* <p>
* If a service version is not provided, the service version that will be used will be the latest known service
* version based on the version of the client library being used. If no service version is specified, updating to a
* newer version of the client library will have the result of potentially moving to a newer service version.
* <p>
* Targeting a specific service version may also mean that the service will return an error for newer APIs.
*
* @param version {@link ChatServiceVersion} of the service to be used when making requests.
* @return the updated ChatClientBuilder object
*/
public ChatClientBuilder serviceVersion(ChatServiceVersion version) {
return this;
}
/**
* Sets the {@link HttpPipeline} to use for the service client.
*
* If {@code pipeline} is set, all other settings are ignored, aside from {@link
*
* @param httpPipeline HttpPipeline to use for sending service requests and receiving responses.
* @return the updated BlobServiceClientBuilder object
*/
public ChatClientBuilder pipeline(HttpPipeline httpPipeline) {
this.httpPipeline = httpPipeline;
return this;
}
/**
* Sets the configuration object used to retrieve environment configuration values during building of the client.
*
* @param configuration Configuration store used to retrieve environment configurations.
* @return the updated BlobServiceClientBuilder object
*/
public ChatClientBuilder configuration(Configuration configuration) {
this.configuration = configuration;
return this;
}
/**
* Sets the {@link RetryPolicy} that is used when each request is sent.
*
* @param retryPolicy User's retry policy applied to each request.
* @return The updated {@link ChatClientBuilder} object.
* @throws NullPointerException If the specified {@code retryPolicy} is null.
*/
/**
* Create synchronous client applying CommunicationTokenCredential, UserAgentPolicy,
* RetryPolicy, and CookiePolicy.
* Additional HttpPolicies specified by additionalPolicies will be applied after them
*
* @return ChatClient instance
*/
public ChatClient buildClient() {
ChatAsyncClient asyncClient = buildAsyncClient();
return new ChatClient(asyncClient);
}
/**
* Create asynchronous client applying CommunicationTokenCredential, UserAgentPolicy,
* RetryPolicy, and CookiePolicy.
* Additional HttpPolicies specified by additionalPolicies will be applied after them
*
* @return ChatAsyncClient instance
*/
public ChatAsyncClient buildAsyncClient() {
Objects.requireNonNull(endpoint);
HttpPipeline pipeline;
if (httpPipeline != null) {
pipeline = httpPipeline;
} else {
Objects.requireNonNull(communicationTokenCredential);
Objects.requireNonNull(httpClient);
CommunicationBearerTokenCredential tokenCredential =
new CommunicationBearerTokenCredential(communicationTokenCredential);
pipeline = createHttpPipeline(httpClient,
new BearerTokenAuthenticationPolicy(tokenCredential, ""),
customPolicies);
}
AzureCommunicationChatServiceImplBuilder clientBuilder = new AzureCommunicationChatServiceImplBuilder();
clientBuilder.endpoint(endpoint)
.pipeline(pipeline);
return new ChatAsyncClient(clientBuilder.buildClient());
}
private HttpPipeline createHttpPipeline(HttpClient httpClient,
HttpPipelinePolicy authorizationPolicy,
List<HttpPipelinePolicy> additionalPolicies) {
List<HttpPipelinePolicy> policies = new ArrayList<HttpPipelinePolicy>();
policies.add(authorizationPolicy);
applyRequiredPolicies(policies);
if (additionalPolicies != null && additionalPolicies.size() > 0) {
policies.addAll(additionalPolicies);
}
return new HttpPipelineBuilder()
.policies(policies.toArray(new HttpPipelinePolicy[0]))
.httpClient(httpClient)
.build();
}
private void applyRequiredPolicies(List<HttpPipelinePolicy> policies) {
policies.add(getUserAgentPolicy());
policies.add(this.retryPolicy == null ? new RetryPolicy() : this.retryPolicy);
policies.add(new CookiePolicy());
policies.add(new HttpLoggingPolicy(logOptions));
}
/*
* Creates a {@link UserAgentPolicy} using the default chat service module name and version.
*
* @return The default {@link UserAgentPolicy} for the module.
*/
private UserAgentPolicy getUserAgentPolicy() {
Map<String, String> properties = CoreUtils.getProperties(APP_CONFIG_PROPERTIES);
String clientName = properties.getOrDefault(SDK_NAME, "UnknownName");
String clientVersion = properties.getOrDefault(SDK_VERSION, "UnknownVersion");
return new UserAgentPolicy(
logOptions.getApplicationId(), clientName, clientVersion, configuration);
}
} |
Just a question here: Is this ever possible for `this.retryPolicy == null`? | private void applyRequiredPolicies(List<HttpPipelinePolicy> policies) {
policies.add(getUserAgentPolicy());
policies.add(this.retryPolicy == null ? new RetryPolicy() : this.retryPolicy);
policies.add(new CookiePolicy());
policies.add(new HttpLoggingPolicy(logOptions));
} | policies.add(this.retryPolicy == null ? new RetryPolicy() : this.retryPolicy); | private void applyRequiredPolicies(List<HttpPipelinePolicy> policies) {
policies.add(getUserAgentPolicy());
policies.add(this.retryPolicy == null ? new RetryPolicy() : this.retryPolicy);
policies.add(new CookiePolicy());
policies.add(new HttpLoggingPolicy(logOptions));
} | class ChatClientBuilder {
private String endpoint;
private HttpClient httpClient;
private CommunicationTokenCredential communicationTokenCredential;
private final List<HttpPipelinePolicy> customPolicies = new ArrayList<HttpPipelinePolicy>();
private HttpLogOptions logOptions = new HttpLogOptions();
private HttpPipeline httpPipeline;
private Configuration configuration;
private RetryPolicy retryPolicy;
private static final String APP_CONFIG_PROPERTIES = "azure-communication-chat.properties";
private static final String SDK_NAME = "name";
private static final String SDK_VERSION = "version";
/**
* Set endpoint of the service
*
* @param endpoint url of the service
* @return the updated ChatClientBuilder object
*/
public ChatClientBuilder endpoint(String endpoint) {
this.endpoint = Objects.requireNonNull(endpoint, "'endpoint' cannot be null.");
return this;
}
/**
* Set HttpClient to use
*
* @param httpClient HttpClient to use
* @return the updated ChatClientBuilder object
*/
public ChatClientBuilder httpClient(HttpClient httpClient) {
this.httpClient = Objects.requireNonNull(httpClient, "'httpClient' cannot be null.");
return this;
}
/**
* Set a token credential for authorization
*
* @param communicationTokenCredential valid token credential as a string
* @return the updated ChatClientBuilder object
*/
public ChatClientBuilder credential(CommunicationTokenCredential communicationTokenCredential) {
this.communicationTokenCredential = Objects.requireNonNull(
communicationTokenCredential, "'communicationTokenCredential' cannot be null.");
return this;
}
/**
* Apply additional {@link HttpPipelinePolicy}
*
* @param customPolicy HttpPipelinePolicy objects to be applied after
* AzureKeyCredentialPolicy, UserAgentPolicy, RetryPolicy, and CookiePolicy
* @return the updated ChatClientBuilder object
*/
public ChatClientBuilder addPolicy(HttpPipelinePolicy customPolicy) {
this.customPolicies.add(Objects.requireNonNull(customPolicy, "'customPolicy' cannot be null."));
return this;
}
/**
* Sets the {@link HttpLogOptions} for service requests.
*
* @param logOptions The logging configuration to use when sending and receiving HTTP requests/responses.
* @return the updated ChatClientBuilder object
*/
public ChatClientBuilder httpLogOptions(HttpLogOptions logOptions) {
this.logOptions = Objects.requireNonNull(logOptions, "'logOptions' cannot be null.");
return this;
}
/**
* Sets the {@link ChatServiceVersion} that is used when making API requests.
* <p>
* If a service version is not provided, the service version that will be used will be the latest known service
* version based on the version of the client library being used. If no service version is specified, updating to a
* newer version of the client library will have the result of potentially moving to a newer service version.
* <p>
* Targeting a specific service version may also mean that the service will return an error for newer APIs.
*
* @param version {@link ChatServiceVersion} of the service to be used when making requests.
* @return the updated ChatClientBuilder object
*/
public ChatClientBuilder serviceVersion(ChatServiceVersion version) {
return this;
}
/**
* Sets the {@link HttpPipeline} to use for the service client.
*
* If {@code pipeline} is set, all other settings are ignored, aside from {@link
*
* @param httpPipeline HttpPipeline to use for sending service requests and receiving responses.
* @return the updated BlobServiceClientBuilder object
*/
public ChatClientBuilder pipeline(HttpPipeline httpPipeline) {
this.httpPipeline = httpPipeline;
return this;
}
/**
* Sets the configuration object used to retrieve environment configuration values during building of the client.
*
* @param configuration Configuration store used to retrieve environment configurations.
* @return the updated BlobServiceClientBuilder object
*/
public ChatClientBuilder configuration(Configuration configuration) {
this.configuration = configuration;
return this;
}
/**
* Sets the {@link RetryPolicy} that is used when each request is sent.
* <p>
* The default retry policy will be used in the pipeline, if not provided.
*
* @param retryPolicy User's retry policy applied to each request.
* @return The updated {@link ChatClientBuilder} object.
* @throws NullPointerException If the specified {@code retryPolicy} is null.
*/
public ChatClientBuilder retryPolicy(RetryPolicy retryPolicy) {
this.retryPolicy = Objects.requireNonNull(retryPolicy, "The retry policy cannot be null");
return this;
}
/**
* Create synchronous client applying CommunicationTokenCredential, UserAgentPolicy,
* RetryPolicy, and CookiePolicy.
* Additional HttpPolicies specified by additionalPolicies will be applied after them
*
* @return ChatClient instance
*/
public ChatClient buildClient() {
ChatAsyncClient asyncClient = buildAsyncClient();
return new ChatClient(asyncClient);
}
/**
* Create asynchronous client applying CommunicationTokenCredential, UserAgentPolicy,
* RetryPolicy, and CookiePolicy.
* Additional HttpPolicies specified by additionalPolicies will be applied after them
*
* @return ChatAsyncClient instance
*/
public ChatAsyncClient buildAsyncClient() {
Objects.requireNonNull(endpoint);
HttpPipeline pipeline;
if (httpPipeline != null) {
pipeline = httpPipeline;
} else {
Objects.requireNonNull(communicationTokenCredential);
Objects.requireNonNull(httpClient);
CommunicationBearerTokenCredential tokenCredential =
new CommunicationBearerTokenCredential(communicationTokenCredential);
pipeline = createHttpPipeline(httpClient,
new BearerTokenAuthenticationPolicy(tokenCredential, ""),
customPolicies);
}
AzureCommunicationChatServiceImplBuilder clientBuilder = new AzureCommunicationChatServiceImplBuilder();
clientBuilder.endpoint(endpoint)
.pipeline(pipeline);
return new ChatAsyncClient(clientBuilder.buildClient());
}
private HttpPipeline createHttpPipeline(HttpClient httpClient,
HttpPipelinePolicy authorizationPolicy,
List<HttpPipelinePolicy> additionalPolicies) {
List<HttpPipelinePolicy> policies = new ArrayList<HttpPipelinePolicy>();
policies.add(authorizationPolicy);
applyRequiredPolicies(policies);
if (additionalPolicies != null && additionalPolicies.size() > 0) {
policies.addAll(additionalPolicies);
}
return new HttpPipelineBuilder()
.policies(policies.toArray(new HttpPipelinePolicy[0]))
.httpClient(httpClient)
.build();
}
/*
* Creates a {@link UserAgentPolicy} using the default chat service module name and version.
*
* @return The default {@link UserAgentPolicy} for the module.
*/
private UserAgentPolicy getUserAgentPolicy() {
Map<String, String> properties = CoreUtils.getProperties(APP_CONFIG_PROPERTIES);
String clientName = properties.getOrDefault(SDK_NAME, "UnknownName");
String clientVersion = properties.getOrDefault(SDK_VERSION, "UnknownVersion");
return new UserAgentPolicy(
logOptions.getApplicationId(), clientName, clientVersion, configuration);
}
} | class ChatClientBuilder {
private String endpoint;
private HttpClient httpClient;
private CommunicationTokenCredential communicationTokenCredential;
private final List<HttpPipelinePolicy> customPolicies = new ArrayList<HttpPipelinePolicy>();
private HttpLogOptions logOptions = new HttpLogOptions();
private HttpPipeline httpPipeline;
private Configuration configuration;
private RetryPolicy retryPolicy;
private static final String APP_CONFIG_PROPERTIES = "azure-communication-chat.properties";
private static final String SDK_NAME = "name";
private static final String SDK_VERSION = "version";
/**
* Set endpoint of the service
*
* @param endpoint url of the service
* @return the updated ChatClientBuilder object
*/
public ChatClientBuilder endpoint(String endpoint) {
this.endpoint = Objects.requireNonNull(endpoint, "'endpoint' cannot be null.");
return this;
}
/**
* Set HttpClient to use
*
* @param httpClient HttpClient to use
* @return the updated ChatClientBuilder object
*/
public ChatClientBuilder httpClient(HttpClient httpClient) {
this.httpClient = Objects.requireNonNull(httpClient, "'httpClient' cannot be null.");
return this;
}
/**
* Set a token credential for authorization
*
* @param communicationTokenCredential valid token credential as a string
* @return the updated ChatClientBuilder object
*/
public ChatClientBuilder credential(CommunicationTokenCredential communicationTokenCredential) {
this.communicationTokenCredential = Objects.requireNonNull(
communicationTokenCredential, "'communicationTokenCredential' cannot be null.");
return this;
}
/**
* Apply additional {@link HttpPipelinePolicy}
*
* @param customPolicy HttpPipelinePolicy objects to be applied after
* AzureKeyCredentialPolicy, UserAgentPolicy, RetryPolicy, and CookiePolicy
* @return the updated ChatClientBuilder object
*/
public ChatClientBuilder addPolicy(HttpPipelinePolicy customPolicy) {
this.customPolicies.add(Objects.requireNonNull(customPolicy, "'customPolicy' cannot be null."));
return this;
}
/**
* Sets the {@link HttpLogOptions} for service requests.
*
* @param logOptions The logging configuration to use when sending and receiving HTTP requests/responses.
* @return the updated ChatClientBuilder object
*/
public ChatClientBuilder httpLogOptions(HttpLogOptions logOptions) {
this.logOptions = Objects.requireNonNull(logOptions, "'logOptions' cannot be null.");
return this;
}
/**
* Sets the {@link ChatServiceVersion} that is used when making API requests.
* <p>
* If a service version is not provided, the service version that will be used will be the latest known service
* version based on the version of the client library being used. If no service version is specified, updating to a
* newer version of the client library will have the result of potentially moving to a newer service version.
* <p>
* Targeting a specific service version may also mean that the service will return an error for newer APIs.
*
* @param version {@link ChatServiceVersion} of the service to be used when making requests.
* @return the updated ChatClientBuilder object
*/
public ChatClientBuilder serviceVersion(ChatServiceVersion version) {
return this;
}
/**
* Sets the {@link HttpPipeline} to use for the service client.
*
* If {@code pipeline} is set, all other settings are ignored, aside from {@link
*
* @param httpPipeline HttpPipeline to use for sending service requests and receiving responses.
* @return the updated BlobServiceClientBuilder object
*/
public ChatClientBuilder pipeline(HttpPipeline httpPipeline) {
this.httpPipeline = httpPipeline;
return this;
}
/**
* Sets the configuration object used to retrieve environment configuration values during building of the client.
*
* @param configuration Configuration store used to retrieve environment configurations.
* @return the updated BlobServiceClientBuilder object
*/
public ChatClientBuilder configuration(Configuration configuration) {
this.configuration = configuration;
return this;
}
/**
* Sets the {@link RetryPolicy} that is used when each request is sent.
*
* @param retryPolicy User's retry policy applied to each request.
* @return The updated {@link ChatClientBuilder} object.
* @throws NullPointerException If the specified {@code retryPolicy} is null.
*/
public ChatClientBuilder retryPolicy(RetryPolicy retryPolicy) {
this.retryPolicy = Objects.requireNonNull(retryPolicy, "The retry policy cannot be null");
return this;
}
/**
* Create synchronous client applying CommunicationTokenCredential, UserAgentPolicy,
* RetryPolicy, and CookiePolicy.
* Additional HttpPolicies specified by additionalPolicies will be applied after them
*
* @return ChatClient instance
*/
public ChatClient buildClient() {
ChatAsyncClient asyncClient = buildAsyncClient();
return new ChatClient(asyncClient);
}
/**
* Create asynchronous client applying CommunicationTokenCredential, UserAgentPolicy,
* RetryPolicy, and CookiePolicy.
* Additional HttpPolicies specified by additionalPolicies will be applied after them
*
* @return ChatAsyncClient instance
*/
public ChatAsyncClient buildAsyncClient() {
Objects.requireNonNull(endpoint);
HttpPipeline pipeline;
if (httpPipeline != null) {
pipeline = httpPipeline;
} else {
Objects.requireNonNull(communicationTokenCredential);
Objects.requireNonNull(httpClient);
CommunicationBearerTokenCredential tokenCredential =
new CommunicationBearerTokenCredential(communicationTokenCredential);
pipeline = createHttpPipeline(httpClient,
new BearerTokenAuthenticationPolicy(tokenCredential, ""),
customPolicies);
}
AzureCommunicationChatServiceImplBuilder clientBuilder = new AzureCommunicationChatServiceImplBuilder();
clientBuilder.endpoint(endpoint)
.pipeline(pipeline);
return new ChatAsyncClient(clientBuilder.buildClient());
}
private HttpPipeline createHttpPipeline(HttpClient httpClient,
HttpPipelinePolicy authorizationPolicy,
List<HttpPipelinePolicy> additionalPolicies) {
List<HttpPipelinePolicy> policies = new ArrayList<HttpPipelinePolicy>();
policies.add(authorizationPolicy);
applyRequiredPolicies(policies);
if (additionalPolicies != null && additionalPolicies.size() > 0) {
policies.addAll(additionalPolicies);
}
return new HttpPipelineBuilder()
.policies(policies.toArray(new HttpPipelinePolicy[0]))
.httpClient(httpClient)
.build();
}
/*
* Creates a {@link UserAgentPolicy} using the default chat service module name and version.
*
* @return The default {@link UserAgentPolicy} for the module.
*/
private UserAgentPolicy getUserAgentPolicy() {
Map<String, String> properties = CoreUtils.getProperties(APP_CONFIG_PROPERTIES);
String clientName = properties.getOrDefault(SDK_NAME, "UnknownName");
String clientVersion = properties.getOrDefault(SDK_VERSION, "UnknownVersion");
return new UserAgentPolicy(
logOptions.getApplicationId(), clientName, clientVersion, configuration);
}
} |
Does it make sense to have this.retryPolicy set to new Retrypolicy() in the constructor of the class. And in the method `public ChatClientBuilder retryPolicy(RetryPolicy retryPolicy)`, it just reset the retryPolicy attribute This way, we can avoid the null checks in the code. | private void applyRequiredPolicies(List<HttpPipelinePolicy> policies) {
policies.add(getUserAgentPolicy());
policies.add(this.retryPolicy == null ? new RetryPolicy() : this.retryPolicy);
policies.add(new CookiePolicy());
policies.add(new HttpLoggingPolicy(logOptions));
} | policies.add(this.retryPolicy == null ? new RetryPolicy() : this.retryPolicy); | private void applyRequiredPolicies(List<HttpPipelinePolicy> policies) {
policies.add(getUserAgentPolicy());
policies.add(this.retryPolicy == null ? new RetryPolicy() : this.retryPolicy);
policies.add(new CookiePolicy());
policies.add(new HttpLoggingPolicy(logOptions));
} | class ChatClientBuilder {
private String endpoint;
private HttpClient httpClient;
private CommunicationTokenCredential communicationTokenCredential;
private final List<HttpPipelinePolicy> customPolicies = new ArrayList<HttpPipelinePolicy>();
private HttpLogOptions logOptions = new HttpLogOptions();
private HttpPipeline httpPipeline;
private Configuration configuration;
private RetryPolicy retryPolicy;
private static final String APP_CONFIG_PROPERTIES = "azure-communication-chat.properties";
private static final String SDK_NAME = "name";
private static final String SDK_VERSION = "version";
/**
* Set endpoint of the service
*
* @param endpoint url of the service
* @return the updated ChatClientBuilder object
*/
public ChatClientBuilder endpoint(String endpoint) {
this.endpoint = Objects.requireNonNull(endpoint, "'endpoint' cannot be null.");
return this;
}
/**
* Set HttpClient to use
*
* @param httpClient HttpClient to use
* @return the updated ChatClientBuilder object
*/
public ChatClientBuilder httpClient(HttpClient httpClient) {
this.httpClient = Objects.requireNonNull(httpClient, "'httpClient' cannot be null.");
return this;
}
/**
* Set a token credential for authorization
*
* @param communicationTokenCredential valid token credential as a string
* @return the updated ChatClientBuilder object
*/
public ChatClientBuilder credential(CommunicationTokenCredential communicationTokenCredential) {
this.communicationTokenCredential = Objects.requireNonNull(
communicationTokenCredential, "'communicationTokenCredential' cannot be null.");
return this;
}
/**
* Apply additional {@link HttpPipelinePolicy}
*
* @param customPolicy HttpPipelinePolicy objects to be applied after
* AzureKeyCredentialPolicy, UserAgentPolicy, RetryPolicy, and CookiePolicy
* @return the updated ChatClientBuilder object
*/
public ChatClientBuilder addPolicy(HttpPipelinePolicy customPolicy) {
this.customPolicies.add(Objects.requireNonNull(customPolicy, "'customPolicy' cannot be null."));
return this;
}
/**
* Sets the {@link HttpLogOptions} for service requests.
*
* @param logOptions The logging configuration to use when sending and receiving HTTP requests/responses.
* @return the updated ChatClientBuilder object
*/
public ChatClientBuilder httpLogOptions(HttpLogOptions logOptions) {
this.logOptions = Objects.requireNonNull(logOptions, "'logOptions' cannot be null.");
return this;
}
/**
* Sets the {@link ChatServiceVersion} that is used when making API requests.
* <p>
* If a service version is not provided, the service version that will be used will be the latest known service
* version based on the version of the client library being used. If no service version is specified, updating to a
* newer version of the client library will have the result of potentially moving to a newer service version.
* <p>
* Targeting a specific service version may also mean that the service will return an error for newer APIs.
*
* @param version {@link ChatServiceVersion} of the service to be used when making requests.
* @return the updated ChatClientBuilder object
*/
public ChatClientBuilder serviceVersion(ChatServiceVersion version) {
return this;
}
/**
* Sets the {@link HttpPipeline} to use for the service client.
*
* If {@code pipeline} is set, all other settings are ignored, aside from {@link
*
* @param httpPipeline HttpPipeline to use for sending service requests and receiving responses.
* @return the updated BlobServiceClientBuilder object
*/
public ChatClientBuilder pipeline(HttpPipeline httpPipeline) {
this.httpPipeline = httpPipeline;
return this;
}
/**
* Sets the configuration object used to retrieve environment configuration values during building of the client.
*
* @param configuration Configuration store used to retrieve environment configurations.
* @return the updated BlobServiceClientBuilder object
*/
public ChatClientBuilder configuration(Configuration configuration) {
this.configuration = configuration;
return this;
}
/**
* Sets the {@link RetryPolicy} that is used when each request is sent.
* <p>
* The default retry policy will be used in the pipeline, if not provided.
*
* @param retryPolicy User's retry policy applied to each request.
* @return The updated {@link ChatClientBuilder} object.
* @throws NullPointerException If the specified {@code retryPolicy} is null.
*/
public ChatClientBuilder retryPolicy(RetryPolicy retryPolicy) {
this.retryPolicy = Objects.requireNonNull(retryPolicy, "The retry policy cannot be null");
return this;
}
/**
* Create synchronous client applying CommunicationTokenCredential, UserAgentPolicy,
* RetryPolicy, and CookiePolicy.
* Additional HttpPolicies specified by additionalPolicies will be applied after them
*
* @return ChatClient instance
*/
public ChatClient buildClient() {
ChatAsyncClient asyncClient = buildAsyncClient();
return new ChatClient(asyncClient);
}
/**
* Create asynchronous client applying CommunicationTokenCredential, UserAgentPolicy,
* RetryPolicy, and CookiePolicy.
* Additional HttpPolicies specified by additionalPolicies will be applied after them
*
* @return ChatAsyncClient instance
*/
public ChatAsyncClient buildAsyncClient() {
Objects.requireNonNull(endpoint);
HttpPipeline pipeline;
if (httpPipeline != null) {
pipeline = httpPipeline;
} else {
Objects.requireNonNull(communicationTokenCredential);
Objects.requireNonNull(httpClient);
CommunicationBearerTokenCredential tokenCredential =
new CommunicationBearerTokenCredential(communicationTokenCredential);
pipeline = createHttpPipeline(httpClient,
new BearerTokenAuthenticationPolicy(tokenCredential, ""),
customPolicies);
}
AzureCommunicationChatServiceImplBuilder clientBuilder = new AzureCommunicationChatServiceImplBuilder();
clientBuilder.endpoint(endpoint)
.pipeline(pipeline);
return new ChatAsyncClient(clientBuilder.buildClient());
}
private HttpPipeline createHttpPipeline(HttpClient httpClient,
HttpPipelinePolicy authorizationPolicy,
List<HttpPipelinePolicy> additionalPolicies) {
List<HttpPipelinePolicy> policies = new ArrayList<HttpPipelinePolicy>();
policies.add(authorizationPolicy);
applyRequiredPolicies(policies);
if (additionalPolicies != null && additionalPolicies.size() > 0) {
policies.addAll(additionalPolicies);
}
return new HttpPipelineBuilder()
.policies(policies.toArray(new HttpPipelinePolicy[0]))
.httpClient(httpClient)
.build();
}
/*
* Creates a {@link UserAgentPolicy} using the default chat service module name and version.
*
* @return The default {@link UserAgentPolicy} for the module.
*/
private UserAgentPolicy getUserAgentPolicy() {
Map<String, String> properties = CoreUtils.getProperties(APP_CONFIG_PROPERTIES);
String clientName = properties.getOrDefault(SDK_NAME, "UnknownName");
String clientVersion = properties.getOrDefault(SDK_VERSION, "UnknownVersion");
return new UserAgentPolicy(
logOptions.getApplicationId(), clientName, clientVersion, configuration);
}
} | class ChatClientBuilder {
private String endpoint;
private HttpClient httpClient;
private CommunicationTokenCredential communicationTokenCredential;
private final List<HttpPipelinePolicy> customPolicies = new ArrayList<HttpPipelinePolicy>();
private HttpLogOptions logOptions = new HttpLogOptions();
private HttpPipeline httpPipeline;
private Configuration configuration;
private RetryPolicy retryPolicy;
private static final String APP_CONFIG_PROPERTIES = "azure-communication-chat.properties";
private static final String SDK_NAME = "name";
private static final String SDK_VERSION = "version";
/**
* Set endpoint of the service
*
* @param endpoint url of the service
* @return the updated ChatClientBuilder object
*/
public ChatClientBuilder endpoint(String endpoint) {
this.endpoint = Objects.requireNonNull(endpoint, "'endpoint' cannot be null.");
return this;
}
/**
* Set HttpClient to use
*
* @param httpClient HttpClient to use
* @return the updated ChatClientBuilder object
*/
public ChatClientBuilder httpClient(HttpClient httpClient) {
this.httpClient = Objects.requireNonNull(httpClient, "'httpClient' cannot be null.");
return this;
}
/**
* Set a token credential for authorization
*
* @param communicationTokenCredential valid token credential as a string
* @return the updated ChatClientBuilder object
*/
public ChatClientBuilder credential(CommunicationTokenCredential communicationTokenCredential) {
this.communicationTokenCredential = Objects.requireNonNull(
communicationTokenCredential, "'communicationTokenCredential' cannot be null.");
return this;
}
/**
* Apply additional {@link HttpPipelinePolicy}
*
* @param customPolicy HttpPipelinePolicy objects to be applied after
* AzureKeyCredentialPolicy, UserAgentPolicy, RetryPolicy, and CookiePolicy
* @return the updated ChatClientBuilder object
*/
public ChatClientBuilder addPolicy(HttpPipelinePolicy customPolicy) {
this.customPolicies.add(Objects.requireNonNull(customPolicy, "'customPolicy' cannot be null."));
return this;
}
/**
* Sets the {@link HttpLogOptions} for service requests.
*
* @param logOptions The logging configuration to use when sending and receiving HTTP requests/responses.
* @return the updated ChatClientBuilder object
*/
public ChatClientBuilder httpLogOptions(HttpLogOptions logOptions) {
this.logOptions = Objects.requireNonNull(logOptions, "'logOptions' cannot be null.");
return this;
}
/**
* Sets the {@link ChatServiceVersion} that is used when making API requests.
* <p>
* If a service version is not provided, the service version that will be used will be the latest known service
* version based on the version of the client library being used. If no service version is specified, updating to a
* newer version of the client library will have the result of potentially moving to a newer service version.
* <p>
* Targeting a specific service version may also mean that the service will return an error for newer APIs.
*
* @param version {@link ChatServiceVersion} of the service to be used when making requests.
* @return the updated ChatClientBuilder object
*/
public ChatClientBuilder serviceVersion(ChatServiceVersion version) {
return this;
}
/**
* Sets the {@link HttpPipeline} to use for the service client.
*
* If {@code pipeline} is set, all other settings are ignored, aside from {@link
*
* @param httpPipeline HttpPipeline to use for sending service requests and receiving responses.
* @return the updated BlobServiceClientBuilder object
*/
public ChatClientBuilder pipeline(HttpPipeline httpPipeline) {
this.httpPipeline = httpPipeline;
return this;
}
/**
* Sets the configuration object used to retrieve environment configuration values during building of the client.
*
* @param configuration Configuration store used to retrieve environment configurations.
* @return the updated BlobServiceClientBuilder object
*/
public ChatClientBuilder configuration(Configuration configuration) {
this.configuration = configuration;
return this;
}
/**
* Sets the {@link RetryPolicy} that is used when each request is sent.
*
* @param retryPolicy User's retry policy applied to each request.
* @return The updated {@link ChatClientBuilder} object.
* @throws NullPointerException If the specified {@code retryPolicy} is null.
*/
public ChatClientBuilder retryPolicy(RetryPolicy retryPolicy) {
this.retryPolicy = Objects.requireNonNull(retryPolicy, "The retry policy cannot be null");
return this;
}
/**
* Create synchronous client applying CommunicationTokenCredential, UserAgentPolicy,
* RetryPolicy, and CookiePolicy.
* Additional HttpPolicies specified by additionalPolicies will be applied after them
*
* @return ChatClient instance
*/
public ChatClient buildClient() {
ChatAsyncClient asyncClient = buildAsyncClient();
return new ChatClient(asyncClient);
}
/**
* Create asynchronous client applying CommunicationTokenCredential, UserAgentPolicy,
* RetryPolicy, and CookiePolicy.
* Additional HttpPolicies specified by additionalPolicies will be applied after them
*
* @return ChatAsyncClient instance
*/
public ChatAsyncClient buildAsyncClient() {
Objects.requireNonNull(endpoint);
HttpPipeline pipeline;
if (httpPipeline != null) {
pipeline = httpPipeline;
} else {
Objects.requireNonNull(communicationTokenCredential);
Objects.requireNonNull(httpClient);
CommunicationBearerTokenCredential tokenCredential =
new CommunicationBearerTokenCredential(communicationTokenCredential);
pipeline = createHttpPipeline(httpClient,
new BearerTokenAuthenticationPolicy(tokenCredential, ""),
customPolicies);
}
AzureCommunicationChatServiceImplBuilder clientBuilder = new AzureCommunicationChatServiceImplBuilder();
clientBuilder.endpoint(endpoint)
.pipeline(pipeline);
return new ChatAsyncClient(clientBuilder.buildClient());
}
private HttpPipeline createHttpPipeline(HttpClient httpClient,
HttpPipelinePolicy authorizationPolicy,
List<HttpPipelinePolicy> additionalPolicies) {
List<HttpPipelinePolicy> policies = new ArrayList<HttpPipelinePolicy>();
policies.add(authorizationPolicy);
applyRequiredPolicies(policies);
if (additionalPolicies != null && additionalPolicies.size() > 0) {
policies.addAll(additionalPolicies);
}
return new HttpPipelineBuilder()
.policies(policies.toArray(new HttpPipelinePolicy[0]))
.httpClient(httpClient)
.build();
}
/*
* Creates a {@link UserAgentPolicy} using the default chat service module name and version.
*
* @return The default {@link UserAgentPolicy} for the module.
*/
private UserAgentPolicy getUserAgentPolicy() {
Map<String, String> properties = CoreUtils.getProperties(APP_CONFIG_PROPERTIES);
String clientName = properties.getOrDefault(SDK_NAME, "UnknownName");
String clientVersion = properties.getOrDefault(SDK_VERSION, "UnknownVersion");
return new UserAgentPolicy(
logOptions.getApplicationId(), clientName, clientVersion, configuration);
}
} |
Yup, if the retryPolicy is not set, then it will be null | private void applyRequiredPolicies(List<HttpPipelinePolicy> policies) {
policies.add(getUserAgentPolicy());
policies.add(this.retryPolicy == null ? new RetryPolicy() : this.retryPolicy);
policies.add(new CookiePolicy());
policies.add(new HttpLoggingPolicy(logOptions));
} | policies.add(this.retryPolicy == null ? new RetryPolicy() : this.retryPolicy); | private void applyRequiredPolicies(List<HttpPipelinePolicy> policies) {
policies.add(getUserAgentPolicy());
policies.add(this.retryPolicy == null ? new RetryPolicy() : this.retryPolicy);
policies.add(new CookiePolicy());
policies.add(new HttpLoggingPolicy(logOptions));
} | class ChatClientBuilder {
private String endpoint;
private HttpClient httpClient;
private CommunicationTokenCredential communicationTokenCredential;
private final List<HttpPipelinePolicy> customPolicies = new ArrayList<HttpPipelinePolicy>();
private HttpLogOptions logOptions = new HttpLogOptions();
private HttpPipeline httpPipeline;
private Configuration configuration;
private RetryPolicy retryPolicy;
private static final String APP_CONFIG_PROPERTIES = "azure-communication-chat.properties";
private static final String SDK_NAME = "name";
private static final String SDK_VERSION = "version";
/**
* Set endpoint of the service
*
* @param endpoint url of the service
* @return the updated ChatClientBuilder object
*/
public ChatClientBuilder endpoint(String endpoint) {
this.endpoint = Objects.requireNonNull(endpoint, "'endpoint' cannot be null.");
return this;
}
/**
* Set HttpClient to use
*
* @param httpClient HttpClient to use
* @return the updated ChatClientBuilder object
*/
public ChatClientBuilder httpClient(HttpClient httpClient) {
this.httpClient = Objects.requireNonNull(httpClient, "'httpClient' cannot be null.");
return this;
}
/**
* Set a token credential for authorization
*
* @param communicationTokenCredential valid token credential as a string
* @return the updated ChatClientBuilder object
*/
public ChatClientBuilder credential(CommunicationTokenCredential communicationTokenCredential) {
this.communicationTokenCredential = Objects.requireNonNull(
communicationTokenCredential, "'communicationTokenCredential' cannot be null.");
return this;
}
/**
* Apply additional {@link HttpPipelinePolicy}
*
* @param customPolicy HttpPipelinePolicy objects to be applied after
* AzureKeyCredentialPolicy, UserAgentPolicy, RetryPolicy, and CookiePolicy
* @return the updated ChatClientBuilder object
*/
public ChatClientBuilder addPolicy(HttpPipelinePolicy customPolicy) {
this.customPolicies.add(Objects.requireNonNull(customPolicy, "'customPolicy' cannot be null."));
return this;
}
/**
* Sets the {@link HttpLogOptions} for service requests.
*
* @param logOptions The logging configuration to use when sending and receiving HTTP requests/responses.
* @return the updated ChatClientBuilder object
*/
public ChatClientBuilder httpLogOptions(HttpLogOptions logOptions) {
this.logOptions = Objects.requireNonNull(logOptions, "'logOptions' cannot be null.");
return this;
}
/**
* Sets the {@link ChatServiceVersion} that is used when making API requests.
* <p>
* If a service version is not provided, the service version that will be used will be the latest known service
* version based on the version of the client library being used. If no service version is specified, updating to a
* newer version of the client library will have the result of potentially moving to a newer service version.
* <p>
* Targeting a specific service version may also mean that the service will return an error for newer APIs.
*
* @param version {@link ChatServiceVersion} of the service to be used when making requests.
* @return the updated ChatClientBuilder object
*/
public ChatClientBuilder serviceVersion(ChatServiceVersion version) {
return this;
}
/**
* Sets the {@link HttpPipeline} to use for the service client.
*
* If {@code pipeline} is set, all other settings are ignored, aside from {@link
*
* @param httpPipeline HttpPipeline to use for sending service requests and receiving responses.
* @return the updated BlobServiceClientBuilder object
*/
public ChatClientBuilder pipeline(HttpPipeline httpPipeline) {
this.httpPipeline = httpPipeline;
return this;
}
/**
* Sets the configuration object used to retrieve environment configuration values during building of the client.
*
* @param configuration Configuration store used to retrieve environment configurations.
* @return the updated BlobServiceClientBuilder object
*/
public ChatClientBuilder configuration(Configuration configuration) {
this.configuration = configuration;
return this;
}
/**
* Sets the {@link RetryPolicy} that is used when each request is sent.
* <p>
* The default retry policy will be used in the pipeline, if not provided.
*
* @param retryPolicy User's retry policy applied to each request.
* @return The updated {@link ChatClientBuilder} object.
* @throws NullPointerException If the specified {@code retryPolicy} is null.
*/
public ChatClientBuilder retryPolicy(RetryPolicy retryPolicy) {
this.retryPolicy = Objects.requireNonNull(retryPolicy, "The retry policy cannot be null");
return this;
}
/**
* Create synchronous client applying CommunicationTokenCredential, UserAgentPolicy,
* RetryPolicy, and CookiePolicy.
* Additional HttpPolicies specified by additionalPolicies will be applied after them
*
* @return ChatClient instance
*/
public ChatClient buildClient() {
ChatAsyncClient asyncClient = buildAsyncClient();
return new ChatClient(asyncClient);
}
/**
* Create asynchronous client applying CommunicationTokenCredential, UserAgentPolicy,
* RetryPolicy, and CookiePolicy.
* Additional HttpPolicies specified by additionalPolicies will be applied after them
*
* @return ChatAsyncClient instance
*/
public ChatAsyncClient buildAsyncClient() {
Objects.requireNonNull(endpoint);
HttpPipeline pipeline;
if (httpPipeline != null) {
pipeline = httpPipeline;
} else {
Objects.requireNonNull(communicationTokenCredential);
Objects.requireNonNull(httpClient);
CommunicationBearerTokenCredential tokenCredential =
new CommunicationBearerTokenCredential(communicationTokenCredential);
pipeline = createHttpPipeline(httpClient,
new BearerTokenAuthenticationPolicy(tokenCredential, ""),
customPolicies);
}
AzureCommunicationChatServiceImplBuilder clientBuilder = new AzureCommunicationChatServiceImplBuilder();
clientBuilder.endpoint(endpoint)
.pipeline(pipeline);
return new ChatAsyncClient(clientBuilder.buildClient());
}
private HttpPipeline createHttpPipeline(HttpClient httpClient,
HttpPipelinePolicy authorizationPolicy,
List<HttpPipelinePolicy> additionalPolicies) {
List<HttpPipelinePolicy> policies = new ArrayList<HttpPipelinePolicy>();
policies.add(authorizationPolicy);
applyRequiredPolicies(policies);
if (additionalPolicies != null && additionalPolicies.size() > 0) {
policies.addAll(additionalPolicies);
}
return new HttpPipelineBuilder()
.policies(policies.toArray(new HttpPipelinePolicy[0]))
.httpClient(httpClient)
.build();
}
/*
* Creates a {@link UserAgentPolicy} using the default chat service module name and version.
*
* @return The default {@link UserAgentPolicy} for the module.
*/
private UserAgentPolicy getUserAgentPolicy() {
Map<String, String> properties = CoreUtils.getProperties(APP_CONFIG_PROPERTIES);
String clientName = properties.getOrDefault(SDK_NAME, "UnknownName");
String clientVersion = properties.getOrDefault(SDK_VERSION, "UnknownVersion");
return new UserAgentPolicy(
logOptions.getApplicationId(), clientName, clientVersion, configuration);
}
} | class ChatClientBuilder {
private String endpoint;
private HttpClient httpClient;
private CommunicationTokenCredential communicationTokenCredential;
private final List<HttpPipelinePolicy> customPolicies = new ArrayList<HttpPipelinePolicy>();
private HttpLogOptions logOptions = new HttpLogOptions();
private HttpPipeline httpPipeline;
private Configuration configuration;
private RetryPolicy retryPolicy;
private static final String APP_CONFIG_PROPERTIES = "azure-communication-chat.properties";
private static final String SDK_NAME = "name";
private static final String SDK_VERSION = "version";
/**
* Set endpoint of the service
*
* @param endpoint url of the service
* @return the updated ChatClientBuilder object
*/
public ChatClientBuilder endpoint(String endpoint) {
this.endpoint = Objects.requireNonNull(endpoint, "'endpoint' cannot be null.");
return this;
}
/**
* Set HttpClient to use
*
* @param httpClient HttpClient to use
* @return the updated ChatClientBuilder object
*/
public ChatClientBuilder httpClient(HttpClient httpClient) {
this.httpClient = Objects.requireNonNull(httpClient, "'httpClient' cannot be null.");
return this;
}
/**
* Set a token credential for authorization
*
* @param communicationTokenCredential valid token credential as a string
* @return the updated ChatClientBuilder object
*/
public ChatClientBuilder credential(CommunicationTokenCredential communicationTokenCredential) {
this.communicationTokenCredential = Objects.requireNonNull(
communicationTokenCredential, "'communicationTokenCredential' cannot be null.");
return this;
}
/**
* Apply additional {@link HttpPipelinePolicy}
*
* @param customPolicy HttpPipelinePolicy objects to be applied after
* AzureKeyCredentialPolicy, UserAgentPolicy, RetryPolicy, and CookiePolicy
* @return the updated ChatClientBuilder object
*/
public ChatClientBuilder addPolicy(HttpPipelinePolicy customPolicy) {
this.customPolicies.add(Objects.requireNonNull(customPolicy, "'customPolicy' cannot be null."));
return this;
}
/**
* Sets the {@link HttpLogOptions} for service requests.
*
* @param logOptions The logging configuration to use when sending and receiving HTTP requests/responses.
* @return the updated ChatClientBuilder object
*/
public ChatClientBuilder httpLogOptions(HttpLogOptions logOptions) {
this.logOptions = Objects.requireNonNull(logOptions, "'logOptions' cannot be null.");
return this;
}
/**
* Sets the {@link ChatServiceVersion} that is used when making API requests.
* <p>
* If a service version is not provided, the service version that will be used will be the latest known service
* version based on the version of the client library being used. If no service version is specified, updating to a
* newer version of the client library will have the result of potentially moving to a newer service version.
* <p>
* Targeting a specific service version may also mean that the service will return an error for newer APIs.
*
* @param version {@link ChatServiceVersion} of the service to be used when making requests.
* @return the updated ChatClientBuilder object
*/
public ChatClientBuilder serviceVersion(ChatServiceVersion version) {
return this;
}
/**
* Sets the {@link HttpPipeline} to use for the service client.
*
* If {@code pipeline} is set, all other settings are ignored, aside from {@link
*
* @param httpPipeline HttpPipeline to use for sending service requests and receiving responses.
* @return the updated BlobServiceClientBuilder object
*/
public ChatClientBuilder pipeline(HttpPipeline httpPipeline) {
this.httpPipeline = httpPipeline;
return this;
}
/**
* Sets the configuration object used to retrieve environment configuration values during building of the client.
*
* @param configuration Configuration store used to retrieve environment configurations.
* @return the updated BlobServiceClientBuilder object
*/
public ChatClientBuilder configuration(Configuration configuration) {
this.configuration = configuration;
return this;
}
/**
* Sets the {@link RetryPolicy} that is used when each request is sent.
*
* @param retryPolicy User's retry policy applied to each request.
* @return The updated {@link ChatClientBuilder} object.
* @throws NullPointerException If the specified {@code retryPolicy} is null.
*/
public ChatClientBuilder retryPolicy(RetryPolicy retryPolicy) {
this.retryPolicy = Objects.requireNonNull(retryPolicy, "The retry policy cannot be null");
return this;
}
/**
* Create synchronous client applying CommunicationTokenCredential, UserAgentPolicy,
* RetryPolicy, and CookiePolicy.
* Additional HttpPolicies specified by additionalPolicies will be applied after them
*
* @return ChatClient instance
*/
public ChatClient buildClient() {
ChatAsyncClient asyncClient = buildAsyncClient();
return new ChatClient(asyncClient);
}
/**
* Create asynchronous client applying CommunicationTokenCredential, UserAgentPolicy,
* RetryPolicy, and CookiePolicy.
* Additional HttpPolicies specified by additionalPolicies will be applied after them
*
* @return ChatAsyncClient instance
*/
public ChatAsyncClient buildAsyncClient() {
Objects.requireNonNull(endpoint);
HttpPipeline pipeline;
if (httpPipeline != null) {
pipeline = httpPipeline;
} else {
Objects.requireNonNull(communicationTokenCredential);
Objects.requireNonNull(httpClient);
CommunicationBearerTokenCredential tokenCredential =
new CommunicationBearerTokenCredential(communicationTokenCredential);
pipeline = createHttpPipeline(httpClient,
new BearerTokenAuthenticationPolicy(tokenCredential, ""),
customPolicies);
}
AzureCommunicationChatServiceImplBuilder clientBuilder = new AzureCommunicationChatServiceImplBuilder();
clientBuilder.endpoint(endpoint)
.pipeline(pipeline);
return new ChatAsyncClient(clientBuilder.buildClient());
}
private HttpPipeline createHttpPipeline(HttpClient httpClient,
HttpPipelinePolicy authorizationPolicy,
List<HttpPipelinePolicy> additionalPolicies) {
List<HttpPipelinePolicy> policies = new ArrayList<HttpPipelinePolicy>();
policies.add(authorizationPolicy);
applyRequiredPolicies(policies);
if (additionalPolicies != null && additionalPolicies.size() > 0) {
policies.addAll(additionalPolicies);
}
return new HttpPipelineBuilder()
.policies(policies.toArray(new HttpPipelinePolicy[0]))
.httpClient(httpClient)
.build();
}
/*
* Creates a {@link UserAgentPolicy} using the default chat service module name and version.
*
* @return The default {@link UserAgentPolicy} for the module.
*/
private UserAgentPolicy getUserAgentPolicy() {
Map<String, String> properties = CoreUtils.getProperties(APP_CONFIG_PROPERTIES);
String clientName = properties.getOrDefault(SDK_NAME, "UnknownName");
String clientVersion = properties.getOrDefault(SDK_VERSION, "UnknownVersion");
return new UserAgentPolicy(
logOptions.getApplicationId(), clientName, clientVersion, configuration);
}
} |
Yea, I think that would be possible. But I checked a few other SDKs and the common pattern is to do a null check like we have here. I would prefer to keep this consistent with other SDKs :) | private void applyRequiredPolicies(List<HttpPipelinePolicy> policies) {
policies.add(getUserAgentPolicy());
policies.add(this.retryPolicy == null ? new RetryPolicy() : this.retryPolicy);
policies.add(new CookiePolicy());
policies.add(new HttpLoggingPolicy(logOptions));
} | policies.add(this.retryPolicy == null ? new RetryPolicy() : this.retryPolicy); | private void applyRequiredPolicies(List<HttpPipelinePolicy> policies) {
policies.add(getUserAgentPolicy());
policies.add(this.retryPolicy == null ? new RetryPolicy() : this.retryPolicy);
policies.add(new CookiePolicy());
policies.add(new HttpLoggingPolicy(logOptions));
} | class ChatClientBuilder {
private String endpoint;
private HttpClient httpClient;
private CommunicationTokenCredential communicationTokenCredential;
private final List<HttpPipelinePolicy> customPolicies = new ArrayList<HttpPipelinePolicy>();
private HttpLogOptions logOptions = new HttpLogOptions();
private HttpPipeline httpPipeline;
private Configuration configuration;
private RetryPolicy retryPolicy;
private static final String APP_CONFIG_PROPERTIES = "azure-communication-chat.properties";
private static final String SDK_NAME = "name";
private static final String SDK_VERSION = "version";
/**
* Set endpoint of the service
*
* @param endpoint url of the service
* @return the updated ChatClientBuilder object
*/
public ChatClientBuilder endpoint(String endpoint) {
this.endpoint = Objects.requireNonNull(endpoint, "'endpoint' cannot be null.");
return this;
}
/**
* Set HttpClient to use
*
* @param httpClient HttpClient to use
* @return the updated ChatClientBuilder object
*/
public ChatClientBuilder httpClient(HttpClient httpClient) {
this.httpClient = Objects.requireNonNull(httpClient, "'httpClient' cannot be null.");
return this;
}
/**
* Set a token credential for authorization
*
* @param communicationTokenCredential valid token credential as a string
* @return the updated ChatClientBuilder object
*/
public ChatClientBuilder credential(CommunicationTokenCredential communicationTokenCredential) {
this.communicationTokenCredential = Objects.requireNonNull(
communicationTokenCredential, "'communicationTokenCredential' cannot be null.");
return this;
}
/**
* Apply additional {@link HttpPipelinePolicy}
*
* @param customPolicy HttpPipelinePolicy objects to be applied after
* AzureKeyCredentialPolicy, UserAgentPolicy, RetryPolicy, and CookiePolicy
* @return the updated ChatClientBuilder object
*/
public ChatClientBuilder addPolicy(HttpPipelinePolicy customPolicy) {
this.customPolicies.add(Objects.requireNonNull(customPolicy, "'customPolicy' cannot be null."));
return this;
}
/**
* Sets the {@link HttpLogOptions} for service requests.
*
* @param logOptions The logging configuration to use when sending and receiving HTTP requests/responses.
* @return the updated ChatClientBuilder object
*/
public ChatClientBuilder httpLogOptions(HttpLogOptions logOptions) {
this.logOptions = Objects.requireNonNull(logOptions, "'logOptions' cannot be null.");
return this;
}
/**
* Sets the {@link ChatServiceVersion} that is used when making API requests.
* <p>
* If a service version is not provided, the service version that will be used will be the latest known service
* version based on the version of the client library being used. If no service version is specified, updating to a
* newer version of the client library will have the result of potentially moving to a newer service version.
* <p>
* Targeting a specific service version may also mean that the service will return an error for newer APIs.
*
* @param version {@link ChatServiceVersion} of the service to be used when making requests.
* @return the updated ChatClientBuilder object
*/
public ChatClientBuilder serviceVersion(ChatServiceVersion version) {
return this;
}
/**
* Sets the {@link HttpPipeline} to use for the service client.
*
* If {@code pipeline} is set, all other settings are ignored, aside from {@link
*
* @param httpPipeline HttpPipeline to use for sending service requests and receiving responses.
* @return the updated BlobServiceClientBuilder object
*/
public ChatClientBuilder pipeline(HttpPipeline httpPipeline) {
this.httpPipeline = httpPipeline;
return this;
}
/**
* Sets the configuration object used to retrieve environment configuration values during building of the client.
*
* @param configuration Configuration store used to retrieve environment configurations.
* @return the updated BlobServiceClientBuilder object
*/
public ChatClientBuilder configuration(Configuration configuration) {
this.configuration = configuration;
return this;
}
/**
* Sets the {@link RetryPolicy} that is used when each request is sent.
* <p>
* The default retry policy will be used in the pipeline, if not provided.
*
* @param retryPolicy User's retry policy applied to each request.
* @return The updated {@link ChatClientBuilder} object.
* @throws NullPointerException If the specified {@code retryPolicy} is null.
*/
public ChatClientBuilder retryPolicy(RetryPolicy retryPolicy) {
this.retryPolicy = Objects.requireNonNull(retryPolicy, "The retry policy cannot be null");
return this;
}
/**
* Create synchronous client applying CommunicationTokenCredential, UserAgentPolicy,
* RetryPolicy, and CookiePolicy.
* Additional HttpPolicies specified by additionalPolicies will be applied after them
*
* @return ChatClient instance
*/
public ChatClient buildClient() {
ChatAsyncClient asyncClient = buildAsyncClient();
return new ChatClient(asyncClient);
}
/**
* Create asynchronous client applying CommunicationTokenCredential, UserAgentPolicy,
* RetryPolicy, and CookiePolicy.
* Additional HttpPolicies specified by additionalPolicies will be applied after them
*
* @return ChatAsyncClient instance
*/
public ChatAsyncClient buildAsyncClient() {
Objects.requireNonNull(endpoint);
HttpPipeline pipeline;
if (httpPipeline != null) {
pipeline = httpPipeline;
} else {
Objects.requireNonNull(communicationTokenCredential);
Objects.requireNonNull(httpClient);
CommunicationBearerTokenCredential tokenCredential =
new CommunicationBearerTokenCredential(communicationTokenCredential);
pipeline = createHttpPipeline(httpClient,
new BearerTokenAuthenticationPolicy(tokenCredential, ""),
customPolicies);
}
AzureCommunicationChatServiceImplBuilder clientBuilder = new AzureCommunicationChatServiceImplBuilder();
clientBuilder.endpoint(endpoint)
.pipeline(pipeline);
return new ChatAsyncClient(clientBuilder.buildClient());
}
private HttpPipeline createHttpPipeline(HttpClient httpClient,
HttpPipelinePolicy authorizationPolicy,
List<HttpPipelinePolicy> additionalPolicies) {
List<HttpPipelinePolicy> policies = new ArrayList<HttpPipelinePolicy>();
policies.add(authorizationPolicy);
applyRequiredPolicies(policies);
if (additionalPolicies != null && additionalPolicies.size() > 0) {
policies.addAll(additionalPolicies);
}
return new HttpPipelineBuilder()
.policies(policies.toArray(new HttpPipelinePolicy[0]))
.httpClient(httpClient)
.build();
}
/*
* Creates a {@link UserAgentPolicy} using the default chat service module name and version.
*
* @return The default {@link UserAgentPolicy} for the module.
*/
private UserAgentPolicy getUserAgentPolicy() {
Map<String, String> properties = CoreUtils.getProperties(APP_CONFIG_PROPERTIES);
String clientName = properties.getOrDefault(SDK_NAME, "UnknownName");
String clientVersion = properties.getOrDefault(SDK_VERSION, "UnknownVersion");
return new UserAgentPolicy(
logOptions.getApplicationId(), clientName, clientVersion, configuration);
}
} | class ChatClientBuilder {
private String endpoint;
private HttpClient httpClient;
private CommunicationTokenCredential communicationTokenCredential;
private final List<HttpPipelinePolicy> customPolicies = new ArrayList<HttpPipelinePolicy>();
private HttpLogOptions logOptions = new HttpLogOptions();
private HttpPipeline httpPipeline;
private Configuration configuration;
private RetryPolicy retryPolicy;
private static final String APP_CONFIG_PROPERTIES = "azure-communication-chat.properties";
private static final String SDK_NAME = "name";
private static final String SDK_VERSION = "version";
/**
* Set endpoint of the service
*
* @param endpoint url of the service
* @return the updated ChatClientBuilder object
*/
public ChatClientBuilder endpoint(String endpoint) {
this.endpoint = Objects.requireNonNull(endpoint, "'endpoint' cannot be null.");
return this;
}
/**
* Set HttpClient to use
*
* @param httpClient HttpClient to use
* @return the updated ChatClientBuilder object
*/
public ChatClientBuilder httpClient(HttpClient httpClient) {
this.httpClient = Objects.requireNonNull(httpClient, "'httpClient' cannot be null.");
return this;
}
/**
* Set a token credential for authorization
*
* @param communicationTokenCredential valid token credential as a string
* @return the updated ChatClientBuilder object
*/
public ChatClientBuilder credential(CommunicationTokenCredential communicationTokenCredential) {
this.communicationTokenCredential = Objects.requireNonNull(
communicationTokenCredential, "'communicationTokenCredential' cannot be null.");
return this;
}
/**
* Apply additional {@link HttpPipelinePolicy}
*
* @param customPolicy HttpPipelinePolicy objects to be applied after
* AzureKeyCredentialPolicy, UserAgentPolicy, RetryPolicy, and CookiePolicy
* @return the updated ChatClientBuilder object
*/
public ChatClientBuilder addPolicy(HttpPipelinePolicy customPolicy) {
this.customPolicies.add(Objects.requireNonNull(customPolicy, "'customPolicy' cannot be null."));
return this;
}
/**
* Sets the {@link HttpLogOptions} for service requests.
*
* @param logOptions The logging configuration to use when sending and receiving HTTP requests/responses.
* @return the updated ChatClientBuilder object
*/
public ChatClientBuilder httpLogOptions(HttpLogOptions logOptions) {
this.logOptions = Objects.requireNonNull(logOptions, "'logOptions' cannot be null.");
return this;
}
/**
* Sets the {@link ChatServiceVersion} that is used when making API requests.
* <p>
* If a service version is not provided, the service version that will be used will be the latest known service
* version based on the version of the client library being used. If no service version is specified, updating to a
* newer version of the client library will have the result of potentially moving to a newer service version.
* <p>
* Targeting a specific service version may also mean that the service will return an error for newer APIs.
*
* @param version {@link ChatServiceVersion} of the service to be used when making requests.
* @return the updated ChatClientBuilder object
*/
public ChatClientBuilder serviceVersion(ChatServiceVersion version) {
return this;
}
/**
* Sets the {@link HttpPipeline} to use for the service client.
*
* If {@code pipeline} is set, all other settings are ignored, aside from {@link
*
* @param httpPipeline HttpPipeline to use for sending service requests and receiving responses.
* @return the updated BlobServiceClientBuilder object
*/
public ChatClientBuilder pipeline(HttpPipeline httpPipeline) {
this.httpPipeline = httpPipeline;
return this;
}
/**
* Sets the configuration object used to retrieve environment configuration values during building of the client.
*
* @param configuration Configuration store used to retrieve environment configurations.
* @return the updated BlobServiceClientBuilder object
*/
public ChatClientBuilder configuration(Configuration configuration) {
this.configuration = configuration;
return this;
}
/**
* Sets the {@link RetryPolicy} that is used when each request is sent.
*
* @param retryPolicy User's retry policy applied to each request.
* @return The updated {@link ChatClientBuilder} object.
* @throws NullPointerException If the specified {@code retryPolicy} is null.
*/
public ChatClientBuilder retryPolicy(RetryPolicy retryPolicy) {
this.retryPolicy = Objects.requireNonNull(retryPolicy, "The retry policy cannot be null");
return this;
}
/**
* Create synchronous client applying CommunicationTokenCredential, UserAgentPolicy,
* RetryPolicy, and CookiePolicy.
* Additional HttpPolicies specified by additionalPolicies will be applied after them
*
* @return ChatClient instance
*/
public ChatClient buildClient() {
ChatAsyncClient asyncClient = buildAsyncClient();
return new ChatClient(asyncClient);
}
/**
* Create asynchronous client applying CommunicationTokenCredential, UserAgentPolicy,
* RetryPolicy, and CookiePolicy.
* Additional HttpPolicies specified by additionalPolicies will be applied after them
*
* @return ChatAsyncClient instance
*/
public ChatAsyncClient buildAsyncClient() {
Objects.requireNonNull(endpoint);
HttpPipeline pipeline;
if (httpPipeline != null) {
pipeline = httpPipeline;
} else {
Objects.requireNonNull(communicationTokenCredential);
Objects.requireNonNull(httpClient);
CommunicationBearerTokenCredential tokenCredential =
new CommunicationBearerTokenCredential(communicationTokenCredential);
pipeline = createHttpPipeline(httpClient,
new BearerTokenAuthenticationPolicy(tokenCredential, ""),
customPolicies);
}
AzureCommunicationChatServiceImplBuilder clientBuilder = new AzureCommunicationChatServiceImplBuilder();
clientBuilder.endpoint(endpoint)
.pipeline(pipeline);
return new ChatAsyncClient(clientBuilder.buildClient());
}
private HttpPipeline createHttpPipeline(HttpClient httpClient,
HttpPipelinePolicy authorizationPolicy,
List<HttpPipelinePolicy> additionalPolicies) {
List<HttpPipelinePolicy> policies = new ArrayList<HttpPipelinePolicy>();
policies.add(authorizationPolicy);
applyRequiredPolicies(policies);
if (additionalPolicies != null && additionalPolicies.size() > 0) {
policies.addAll(additionalPolicies);
}
return new HttpPipelineBuilder()
.policies(policies.toArray(new HttpPipelinePolicy[0]))
.httpClient(httpClient)
.build();
}
/*
* Creates a {@link UserAgentPolicy} using the default chat service module name and version.
*
* @return The default {@link UserAgentPolicy} for the module.
*/
private UserAgentPolicy getUserAgentPolicy() {
Map<String, String> properties = CoreUtils.getProperties(APP_CONFIG_PROPERTIES);
String clientName = properties.getOrDefault(SDK_NAME, "UnknownName");
String clientVersion = properties.getOrDefault(SDK_VERSION, "UnknownVersion");
return new UserAgentPolicy(
logOptions.getApplicationId(), clientName, clientVersion, configuration);
}
} |
The builder methods should be chained to demonstrate a better pattern when not sharing connections. | public void instantiateSessionReceiver() {
ServiceBusClientBuilder builder = new ServiceBusClientBuilder()
.connectionString(connectionString);
ServiceBusSessionReceiverAsyncClient sessionReceiver = builder
.sessionReceiver()
.receiveMode(ServiceBusReceiveMode.PEEK_LOCK)
.topicName(topicName)
.subscriptionName(subscriptionName)
.buildAsyncClient();
Mono<ServiceBusReceiverAsyncClient> receiverMono = sessionReceiver.acceptNextSession();
Disposable subscription = Flux.usingWhen(receiverMono,
receiver -> receiver.receiveMessages(),
receiver -> Mono.fromRunnable(receiver::close))
.subscribe(message -> System.out.println(message.getBody().toString()));
subscription.dispose();
} | ServiceBusSessionReceiverAsyncClient sessionReceiver = builder | public void instantiateSessionReceiver() {
ServiceBusSessionReceiverAsyncClient sessionReceiver = new ServiceBusClientBuilder()
.connectionString(connectionString)
.sessionReceiver()
.receiveMode(ServiceBusReceiveMode.PEEK_LOCK)
.topicName(topicName)
.subscriptionName(subscriptionName)
.buildAsyncClient();
Mono<ServiceBusReceiverAsyncClient> receiverMono = sessionReceiver.acceptNextSession();
Flux.usingWhen(receiverMono,
receiver -> receiver.receiveMessages(),
receiver -> Mono.fromRunnable(receiver::close))
.subscribe(message -> System.out.println(message.getBody().toString()));
} | class ServiceBusClientBuilderJavaDocCodeSamples {
String connectionString = System.getenv("AZURE_SERVICEBUS_NAMESPACE_CONNECTION_STRING");
String queueName = System.getenv("AZURE_SERVICEBUS_SAMPLE_QUEUE_NAME");
String topicName = System.getenv("AZURE_SERVICEBUS_SAMPLE_TOPIC_NAME");
String subscriptionName = System.getenv("AZURE_SERVICEBUS_SAMPLE_SUBSCRIPTION_NAME");
@Test
public void instantiateReceiverAsync() {
ServiceBusClientBuilder builder = new ServiceBusClientBuilder()
.connectionString(connectionString);
ServiceBusReceiverAsyncClient receiver = builder
.receiver()
.disableAutoComplete()
.topicName(topicName)
.subscriptionName(subscriptionName)
.buildAsyncClient();
receiver.receiveMessages().blockFirst(Duration.ofSeconds(1));
}
@Test
public void instantiateSenderSync() {
ServiceBusClientBuilder builder = new ServiceBusClientBuilder()
.connectionString(connectionString);
ServiceBusSenderClient sender = builder
.sender()
.queueName(queueName)
.buildClient();
sender.sendMessage(new ServiceBusMessage("payload"));
}
@Test
public void instantiateProcessor() {
ServiceBusClientBuilder builder = new ServiceBusClientBuilder()
.connectionString(connectionString);
ServiceBusProcessorClient processor = builder
.processor()
.queueName(queueName)
.processMessage(System.out::println)
.processError(context -> System.err.println(context.getErrorSource()))
.buildProcessorClient();
processor.start();
processor.stop();
}
@Test
public void connectionSharingAcrossClients() {
ServiceBusClientBuilder sharedConnectionBuilder = new ServiceBusClientBuilder()
.connectionString(connectionString);
ServiceBusReceiverClient receiver = sharedConnectionBuilder
.receiver()
.queueName(queueName)
.buildClient();
ServiceBusSenderClient sender = sharedConnectionBuilder
.sender()
.queueName(queueName)
.buildClient();
sender.sendMessage(new ServiceBusMessage("payload"));
receiver.receiveMessages(1);
}
} | class ServiceBusClientBuilderJavaDocCodeSamples {
String connectionString = System.getenv("AZURE_SERVICEBUS_NAMESPACE_CONNECTION_STRING");
String queueName = System.getenv("AZURE_SERVICEBUS_SAMPLE_QUEUE_NAME");
String topicName = System.getenv("AZURE_SERVICEBUS_SAMPLE_TOPIC_NAME");
String subscriptionName = System.getenv("AZURE_SERVICEBUS_SAMPLE_SUBSCRIPTION_NAME");
@Test
public void instantiateReceiverAsync() {
ServiceBusClientBuilder builder = new ServiceBusClientBuilder()
.connectionString(connectionString);
ServiceBusReceiverAsyncClient receiver = builder
.receiver()
.disableAutoComplete()
.topicName(topicName)
.subscriptionName(subscriptionName)
.buildAsyncClient();
receiver.receiveMessages().blockFirst(Duration.ofSeconds(1));
}
@Test
public void instantiateSenderSync() {
ServiceBusClientBuilder builder = new ServiceBusClientBuilder()
.connectionString(connectionString);
ServiceBusSenderClient sender = builder
.sender()
.queueName(queueName)
.buildClient();
sender.sendMessage(new ServiceBusMessage("payload"));
}
@Test
public void instantiateProcessor() {
ServiceBusClientBuilder builder = new ServiceBusClientBuilder()
.connectionString(connectionString);
ServiceBusProcessorClient processor = builder
.processor()
.queueName(queueName)
.processMessage(System.out::println)
.processError(context -> System.err.println(context.getErrorSource()))
.buildProcessorClient();
processor.start();
processor.stop();
}
@Test
public void connectionSharingAcrossClients() {
ServiceBusClientBuilder sharedConnectionBuilder = new ServiceBusClientBuilder()
.connectionString(connectionString);
ServiceBusReceiverClient receiver = sharedConnectionBuilder
.receiver()
.queueName(queueName)
.buildClient();
ServiceBusSenderClient sender = sharedConnectionBuilder
.sender()
.queueName(queueName)
.buildClient();
sender.sendMessage(new ServiceBusMessage("payload"));
receiver.receiveMessages(1);
}
} |
In intentionally kept it this way , so it promotes sharing of connection. | public void instantiateProcessor() {
ServiceBusClientBuilder builder = new ServiceBusClientBuilder()
.connectionString(connectionString);
ServiceBusProcessorClient processor = builder
.processor()
.queueName(queueName)
.processMessage(System.out::println)
.processError(context -> System.err.println(context.getErrorSource()))
.buildProcessorClient();
processor.start();
processor.stop();
} | ServiceBusProcessorClient processor = builder | public void instantiateProcessor() {
ServiceBusClientBuilder builder = new ServiceBusClientBuilder()
.connectionString(connectionString);
ServiceBusProcessorClient processor = builder
.processor()
.queueName(queueName)
.processMessage(System.out::println)
.processError(context -> System.err.println(context.getErrorSource()))
.buildProcessorClient();
processor.start();
processor.stop();
} | class ServiceBusClientBuilderJavaDocCodeSamples {
String connectionString = System.getenv("AZURE_SERVICEBUS_NAMESPACE_CONNECTION_STRING");
String queueName = System.getenv("AZURE_SERVICEBUS_SAMPLE_QUEUE_NAME");
String topicName = System.getenv("AZURE_SERVICEBUS_SAMPLE_TOPIC_NAME");
String subscriptionName = System.getenv("AZURE_SERVICEBUS_SAMPLE_SUBSCRIPTION_NAME");
@Test
public void instantiateReceiverAsync() {
ServiceBusClientBuilder builder = new ServiceBusClientBuilder()
.connectionString(connectionString);
ServiceBusReceiverAsyncClient receiver = builder
.receiver()
.disableAutoComplete()
.topicName(topicName)
.subscriptionName(subscriptionName)
.buildAsyncClient();
receiver.receiveMessages().blockFirst(Duration.ofSeconds(1));
}
public void instantiateSessionReceiver() {
ServiceBusClientBuilder builder = new ServiceBusClientBuilder()
.connectionString(connectionString);
ServiceBusSessionReceiverAsyncClient sessionReceiver = builder
.sessionReceiver()
.receiveMode(ServiceBusReceiveMode.PEEK_LOCK)
.topicName(topicName)
.subscriptionName(subscriptionName)
.buildAsyncClient();
Mono<ServiceBusReceiverAsyncClient> receiverMono = sessionReceiver.acceptNextSession();
Disposable subscription = Flux.usingWhen(receiverMono,
receiver -> receiver.receiveMessages(),
receiver -> Mono.fromRunnable(receiver::close))
.subscribe(message -> System.out.println(message.getBody().toString()));
subscription.dispose();
}
@Test
public void instantiateSenderSync() {
ServiceBusClientBuilder builder = new ServiceBusClientBuilder()
.connectionString(connectionString);
ServiceBusSenderClient sender = builder
.sender()
.queueName(queueName)
.buildClient();
sender.sendMessage(new ServiceBusMessage("payload"));
}
@Test
@Test
public void connectionSharingAcrossClients() {
ServiceBusClientBuilder sharedConnectionBuilder = new ServiceBusClientBuilder()
.connectionString(connectionString);
ServiceBusReceiverClient receiver = sharedConnectionBuilder
.receiver()
.queueName(queueName)
.buildClient();
ServiceBusSenderClient sender = sharedConnectionBuilder
.sender()
.queueName(queueName)
.buildClient();
sender.sendMessage(new ServiceBusMessage("payload"));
receiver.receiveMessages(1);
}
} | class ServiceBusClientBuilderJavaDocCodeSamples {
String connectionString = System.getenv("AZURE_SERVICEBUS_NAMESPACE_CONNECTION_STRING");
String queueName = System.getenv("AZURE_SERVICEBUS_SAMPLE_QUEUE_NAME");
String topicName = System.getenv("AZURE_SERVICEBUS_SAMPLE_TOPIC_NAME");
String subscriptionName = System.getenv("AZURE_SERVICEBUS_SAMPLE_SUBSCRIPTION_NAME");
@Test
public void instantiateReceiverAsync() {
ServiceBusClientBuilder builder = new ServiceBusClientBuilder()
.connectionString(connectionString);
ServiceBusReceiverAsyncClient receiver = builder
.receiver()
.disableAutoComplete()
.topicName(topicName)
.subscriptionName(subscriptionName)
.buildAsyncClient();
receiver.receiveMessages().blockFirst(Duration.ofSeconds(1));
}
public void instantiateSessionReceiver() {
ServiceBusSessionReceiverAsyncClient sessionReceiver = new ServiceBusClientBuilder()
.connectionString(connectionString)
.sessionReceiver()
.receiveMode(ServiceBusReceiveMode.PEEK_LOCK)
.topicName(topicName)
.subscriptionName(subscriptionName)
.buildAsyncClient();
Mono<ServiceBusReceiverAsyncClient> receiverMono = sessionReceiver.acceptNextSession();
Flux.usingWhen(receiverMono,
receiver -> receiver.receiveMessages(),
receiver -> Mono.fromRunnable(receiver::close))
.subscribe(message -> System.out.println(message.getBody().toString()));
}
@Test
public void instantiateSenderSync() {
ServiceBusClientBuilder builder = new ServiceBusClientBuilder()
.connectionString(connectionString);
ServiceBusSenderClient sender = builder
.sender()
.queueName(queueName)
.buildClient();
sender.sendMessage(new ServiceBusMessage("payload"));
}
@Test
@Test
public void connectionSharingAcrossClients() {
ServiceBusClientBuilder sharedConnectionBuilder = new ServiceBusClientBuilder()
.connectionString(connectionString);
ServiceBusReceiverClient receiver = sharedConnectionBuilder
.receiver()
.queueName(queueName)
.buildClient();
ServiceBusSenderClient sender = sharedConnectionBuilder
.sender()
.queueName(queueName)
.buildClient();
sender.sendMessage(new ServiceBusMessage("payload"));
receiver.receiveMessages(1);
}
} |
Same here with the message, lets update to match the C# README | public void sendMessageToGroupWithOptions() {
SmsClient smsClient = createSmsClientUsingAzureKeyCredential();
SmsSendOptions options = new SmsSendOptions();
options.setDeliveryReportEnabled(true);
options.setTag("Marketing");
Iterable<SmsSendResult> sendResults = smsClient.sendWithResponse(
"<from-phone-number>",
Arrays.asList("<to-phone-number1>", "<to-phone-number2>"),
"Hi",
options /* Optional */,
Context.NONE).getValue();
for (SmsSendResult result : sendResults) {
System.out.println("Message Id: " + result.getMessageId());
System.out.println("Recipient Number: " + result.getTo());
System.out.println("Send Result Successful:" + result.isSuccessful());
}
} | "<from-phone-number>", | public void sendMessageToGroupWithOptions() {
SmsClient smsClient = createSmsClientUsingAzureKeyCredential();
SmsSendOptions options = new SmsSendOptions();
options.setDeliveryReportEnabled(true);
options.setTag("Marketing");
Iterable<SmsSendResult> sendResults = smsClient.sendWithResponse(
"<from-phone-number>",
Arrays.asList("<to-phone-number1>", "<to-phone-number2>"),
"Weekly Promotion",
options /* Optional */,
Context.NONE).getValue();
for (SmsSendResult result : sendResults) {
System.out.println("Message Id: " + result.getMessageId());
System.out.println("Recipient Number: " + result.getTo());
System.out.println("Send Result Successful:" + result.isSuccessful());
}
} | class ReadmeSamples {
public SmsClient createSmsClientUsingAzureKeyCredential() {
String endpoint = "https:
AzureKeyCredential azureKeyCredential = new AzureKeyCredential("<access-key>");
HttpClient httpClient = new NettyAsyncHttpClientBuilder().build();
SmsClient smsClient = new SmsClientBuilder()
.endpoint(endpoint)
.credential(azureKeyCredential)
.httpClient(httpClient)
.buildClient();
return smsClient;
}
public SmsAsyncClient createSmsAsyncClientUsingAzureKeyCredential() {
String endpoint = "https:
AzureKeyCredential azureKeyCredential = new AzureKeyCredential("<access-key>");
HttpClient httpClient = new NettyAsyncHttpClientBuilder().build();
SmsAsyncClient smsClient = new SmsClientBuilder()
.endpoint(endpoint)
.credential(azureKeyCredential)
.httpClient(httpClient)
.buildAsyncClient();
return smsClient;
}
public SmsClient createSmsClientWithConnectionString() {
String connectionString = "https:
HttpClient httpClient = new NettyAsyncHttpClientBuilder().build();
SmsClient smsClient = new SmsClientBuilder()
.connectionString(connectionString)
.httpClient(httpClient)
.buildClient();
return smsClient;
}
public SmsClient createSmsClientWithAAD() {
String endpoint = "https:
HttpClient httpClient = new NettyAsyncHttpClientBuilder().build();
SmsClient smsClient = new SmsClientBuilder()
.endpoint(endpoint)
.credential(new DefaultAzureCredentialBuilder().build())
.httpClient(httpClient)
.buildClient();
return smsClient;
}
public SmsClient createSyncClientUsingTokenCredential() {
TokenCredential tokenCredential = new DefaultAzureCredentialBuilder().build();
String endpoint = "https:
HttpClient httpClient = new NettyAsyncHttpClientBuilder().build();
SmsClient smsClient = new SmsClientBuilder()
.endpoint(endpoint)
.credential(tokenCredential)
.httpClient(httpClient)
.buildClient();
return smsClient;
}
public void sendMessageToOneRecipient() {
SmsClient smsClient = createSmsClientUsingAzureKeyCredential();
SmsSendResult sendResult = smsClient.send(
"<from-phone-number>",
"<to-phone-number>",
"Hi");
System.out.println("Message Id: " + sendResult.getMessageId());
System.out.println("Recipient Number: " + sendResult.getTo());
System.out.println("Send Result Successful:" + sendResult.isSuccessful());
}
/**
* Sample code for troubleshooting
*/
public void catchHttpErrorOnRequest() {
SmsClient smsClient = createSmsClientUsingAzureKeyCredential();
try {
SmsSendResult sendResult = smsClient.send(
"<from-phone-number>",
"<to-phone-number>",
"Hi"
);
} catch (RuntimeException ex) {
System.out.println(ex.getMessage());
}
}
public void sendMessageTroubleShooting() {
SmsClient smsClient = createSmsClientUsingAzureKeyCredential();
try {
SmsSendOptions options = new SmsSendOptions();
options.setDeliveryReportEnabled(true);
options.setTag("Marketing");
Response<Iterable<SmsSendResult>> sendResults = smsClient.sendWithResponse(
"<from-phone-number>",
Arrays.asList("<to-phone-number1>", "<to-phone-number2>"),
"Hi",
options /* Optional */,
Context.NONE);
Iterable<SmsSendResult> smsSendResults = sendResults.getValue();
for (SmsSendResult result : smsSendResults) {
if (result.isSuccessful()) {
System.out.println("Successfully sent this message: " + result.getMessageId() + " to " + result.getTo());
} else {
System.out.println("Something went wrong when trying to send this message " + result.getMessageId() + " to " + result.getTo());
System.out.println("Status code " + result.getHttpStatusCode() + " and error message " + result.getErrorMessage());
}
}
} catch (RuntimeException ex) {
System.out.println(ex.getMessage());
}
}
} | class ReadmeSamples {
public SmsClient createSmsClientUsingAzureKeyCredential() {
String endpoint = "https:
AzureKeyCredential azureKeyCredential = new AzureKeyCredential("<access-key>");
HttpClient httpClient = new NettyAsyncHttpClientBuilder().build();
SmsClient smsClient = new SmsClientBuilder()
.endpoint(endpoint)
.credential(azureKeyCredential)
.httpClient(httpClient)
.buildClient();
return smsClient;
}
public SmsAsyncClient createSmsAsyncClientUsingAzureKeyCredential() {
String endpoint = "https:
AzureKeyCredential azureKeyCredential = new AzureKeyCredential("<access-key>");
HttpClient httpClient = new NettyAsyncHttpClientBuilder().build();
SmsAsyncClient smsClient = new SmsClientBuilder()
.endpoint(endpoint)
.credential(azureKeyCredential)
.httpClient(httpClient)
.buildAsyncClient();
return smsClient;
}
public SmsClient createSmsClientWithConnectionString() {
String connectionString = "https:
HttpClient httpClient = new NettyAsyncHttpClientBuilder().build();
SmsClient smsClient = new SmsClientBuilder()
.connectionString(connectionString)
.httpClient(httpClient)
.buildClient();
return smsClient;
}
public SmsClient createSmsClientWithAAD() {
String endpoint = "https:
HttpClient httpClient = new NettyAsyncHttpClientBuilder().build();
SmsClient smsClient = new SmsClientBuilder()
.endpoint(endpoint)
.credential(new DefaultAzureCredentialBuilder().build())
.httpClient(httpClient)
.buildClient();
return smsClient;
}
public SmsClient createSyncClientUsingTokenCredential() {
TokenCredential tokenCredential = new DefaultAzureCredentialBuilder().build();
String endpoint = "https:
HttpClient httpClient = new NettyAsyncHttpClientBuilder().build();
SmsClient smsClient = new SmsClientBuilder()
.endpoint(endpoint)
.credential(tokenCredential)
.httpClient(httpClient)
.buildClient();
return smsClient;
}
public void sendMessageToOneRecipient() {
SmsClient smsClient = createSmsClientUsingAzureKeyCredential();
SmsSendResult sendResult = smsClient.send(
"<from-phone-number>",
"<to-phone-number>",
"Weekly Promotion");
System.out.println("Message Id: " + sendResult.getMessageId());
System.out.println("Recipient Number: " + sendResult.getTo());
System.out.println("Send Result Successful:" + sendResult.isSuccessful());
}
/**
* Sample code for troubleshooting
*/
public void catchHttpErrorOnRequest() {
SmsClient smsClient = createSmsClientUsingAzureKeyCredential();
try {
SmsSendResult sendResult = smsClient.send(
"<from-phone-number>",
"<to-phone-number>",
"Weekly Promotion"
);
} catch (RuntimeException ex) {
System.out.println(ex.getMessage());
}
}
public void sendMessageTroubleShooting() {
SmsClient smsClient = createSmsClientUsingAzureKeyCredential();
try {
SmsSendOptions options = new SmsSendOptions();
options.setDeliveryReportEnabled(true);
options.setTag("Marketing");
Response<Iterable<SmsSendResult>> sendResults = smsClient.sendWithResponse(
"<from-phone-number>",
Arrays.asList("<to-phone-number1>", "<to-phone-number2>"),
"Weekly Promotion",
options /* Optional */,
Context.NONE);
Iterable<SmsSendResult> smsSendResults = sendResults.getValue();
for (SmsSendResult result : smsSendResults) {
if (result.isSuccessful()) {
System.out.println("Successfully sent this message: " + result.getMessageId() + " to " + result.getTo());
} else {
System.out.println("Something went wrong when trying to send this message " + result.getMessageId() + " to " + result.getTo());
System.out.println("Status code " + result.getHttpStatusCode() + " and error message " + result.getErrorMessage());
}
}
} catch (RuntimeException ex) {
System.out.println(ex.getMessage());
}
}
} |
The builder methods can be chained instead. ```java ServiceBusProcessorClient processor = new ServiceBusClientBuilder() .connectionString(connectionString) .processor() .queueName(queueName) .processMessage(System.out::println) .processError(context -> System.err.println(context.getErrorSource())) .buildProcessorClient(); ``` | public void instantiateProcessor() {
ServiceBusClientBuilder builder = new ServiceBusClientBuilder()
.connectionString(connectionString);
ServiceBusProcessorClient processor = builder
.processor()
.queueName(queueName)
.processMessage(System.out::println)
.processError(context -> System.err.println(context.getErrorSource()))
.buildProcessorClient();
processor.start();
processor.stop();
} | ServiceBusProcessorClient processor = builder | public void instantiateProcessor() {
ServiceBusClientBuilder builder = new ServiceBusClientBuilder()
.connectionString(connectionString);
ServiceBusProcessorClient processor = builder
.processor()
.queueName(queueName)
.processMessage(System.out::println)
.processError(context -> System.err.println(context.getErrorSource()))
.buildProcessorClient();
processor.start();
processor.stop();
} | class ServiceBusClientBuilderJavaDocCodeSamples {
String connectionString = System.getenv("AZURE_SERVICEBUS_NAMESPACE_CONNECTION_STRING");
String queueName = System.getenv("AZURE_SERVICEBUS_SAMPLE_QUEUE_NAME");
String topicName = System.getenv("AZURE_SERVICEBUS_SAMPLE_TOPIC_NAME");
String subscriptionName = System.getenv("AZURE_SERVICEBUS_SAMPLE_SUBSCRIPTION_NAME");
@Test
public void instantiateReceiverAsync() {
ServiceBusClientBuilder builder = new ServiceBusClientBuilder()
.connectionString(connectionString);
ServiceBusReceiverAsyncClient receiver = builder
.receiver()
.disableAutoComplete()
.topicName(topicName)
.subscriptionName(subscriptionName)
.buildAsyncClient();
receiver.receiveMessages().blockFirst(Duration.ofSeconds(1));
}
public void instantiateSessionReceiver() {
ServiceBusClientBuilder builder = new ServiceBusClientBuilder()
.connectionString(connectionString);
ServiceBusSessionReceiverAsyncClient sessionReceiver = builder
.sessionReceiver()
.receiveMode(ServiceBusReceiveMode.PEEK_LOCK)
.topicName(topicName)
.subscriptionName(subscriptionName)
.buildAsyncClient();
Mono<ServiceBusReceiverAsyncClient> receiverMono = sessionReceiver.acceptNextSession();
Disposable subscription = Flux.usingWhen(receiverMono,
receiver -> receiver.receiveMessages(),
receiver -> Mono.fromRunnable(receiver::close))
.subscribe(message -> System.out.println(message.getBody().toString()));
subscription.dispose();
}
@Test
public void instantiateSenderSync() {
ServiceBusClientBuilder builder = new ServiceBusClientBuilder()
.connectionString(connectionString);
ServiceBusSenderClient sender = builder
.sender()
.queueName(queueName)
.buildClient();
sender.sendMessage(new ServiceBusMessage("payload"));
}
@Test
@Test
public void connectionSharingAcrossClients() {
ServiceBusClientBuilder sharedConnectionBuilder = new ServiceBusClientBuilder()
.connectionString(connectionString);
ServiceBusReceiverClient receiver = sharedConnectionBuilder
.receiver()
.queueName(queueName)
.buildClient();
ServiceBusSenderClient sender = sharedConnectionBuilder
.sender()
.queueName(queueName)
.buildClient();
sender.sendMessage(new ServiceBusMessage("payload"));
receiver.receiveMessages(1);
}
} | class ServiceBusClientBuilderJavaDocCodeSamples {
String connectionString = System.getenv("AZURE_SERVICEBUS_NAMESPACE_CONNECTION_STRING");
String queueName = System.getenv("AZURE_SERVICEBUS_SAMPLE_QUEUE_NAME");
String topicName = System.getenv("AZURE_SERVICEBUS_SAMPLE_TOPIC_NAME");
String subscriptionName = System.getenv("AZURE_SERVICEBUS_SAMPLE_SUBSCRIPTION_NAME");
@Test
public void instantiateReceiverAsync() {
ServiceBusClientBuilder builder = new ServiceBusClientBuilder()
.connectionString(connectionString);
ServiceBusReceiverAsyncClient receiver = builder
.receiver()
.disableAutoComplete()
.topicName(topicName)
.subscriptionName(subscriptionName)
.buildAsyncClient();
receiver.receiveMessages().blockFirst(Duration.ofSeconds(1));
}
public void instantiateSessionReceiver() {
ServiceBusSessionReceiverAsyncClient sessionReceiver = new ServiceBusClientBuilder()
.connectionString(connectionString)
.sessionReceiver()
.receiveMode(ServiceBusReceiveMode.PEEK_LOCK)
.topicName(topicName)
.subscriptionName(subscriptionName)
.buildAsyncClient();
Mono<ServiceBusReceiverAsyncClient> receiverMono = sessionReceiver.acceptNextSession();
Flux.usingWhen(receiverMono,
receiver -> receiver.receiveMessages(),
receiver -> Mono.fromRunnable(receiver::close))
.subscribe(message -> System.out.println(message.getBody().toString()));
}
@Test
public void instantiateSenderSync() {
ServiceBusClientBuilder builder = new ServiceBusClientBuilder()
.connectionString(connectionString);
ServiceBusSenderClient sender = builder
.sender()
.queueName(queueName)
.buildClient();
sender.sendMessage(new ServiceBusMessage("payload"));
}
@Test
@Test
public void connectionSharingAcrossClients() {
ServiceBusClientBuilder sharedConnectionBuilder = new ServiceBusClientBuilder()
.connectionString(connectionString);
ServiceBusReceiverClient receiver = sharedConnectionBuilder
.receiver()
.queueName(queueName)
.buildClient();
ServiceBusSenderClient sender = sharedConnectionBuilder
.sender()
.queueName(queueName)
.buildClient();
sender.sendMessage(new ServiceBusMessage("payload"));
receiver.receiveMessages(1);
}
} |
Why do we assign this to a subscription? ` subscription.dispose();` is not part of the snippet so, the assignment may not be required. | public void instantiateSessionReceiver() {
ServiceBusClientBuilder builder = new ServiceBusClientBuilder()
.connectionString(connectionString);
ServiceBusSessionReceiverAsyncClient sessionReceiver = builder
.sessionReceiver()
.receiveMode(ServiceBusReceiveMode.PEEK_LOCK)
.topicName(topicName)
.subscriptionName(subscriptionName)
.buildAsyncClient();
Mono<ServiceBusReceiverAsyncClient> receiverMono = sessionReceiver.acceptNextSession();
Disposable subscription = Flux.usingWhen(receiverMono,
receiver -> receiver.receiveMessages(),
receiver -> Mono.fromRunnable(receiver::close))
.subscribe(message -> System.out.println(message.getBody().toString()));
subscription.dispose();
} | Disposable subscription = Flux.usingWhen(receiverMono, | public void instantiateSessionReceiver() {
ServiceBusSessionReceiverAsyncClient sessionReceiver = new ServiceBusClientBuilder()
.connectionString(connectionString)
.sessionReceiver()
.receiveMode(ServiceBusReceiveMode.PEEK_LOCK)
.topicName(topicName)
.subscriptionName(subscriptionName)
.buildAsyncClient();
Mono<ServiceBusReceiverAsyncClient> receiverMono = sessionReceiver.acceptNextSession();
Flux.usingWhen(receiverMono,
receiver -> receiver.receiveMessages(),
receiver -> Mono.fromRunnable(receiver::close))
.subscribe(message -> System.out.println(message.getBody().toString()));
} | class ServiceBusClientBuilderJavaDocCodeSamples {
String connectionString = System.getenv("AZURE_SERVICEBUS_NAMESPACE_CONNECTION_STRING");
String queueName = System.getenv("AZURE_SERVICEBUS_SAMPLE_QUEUE_NAME");
String topicName = System.getenv("AZURE_SERVICEBUS_SAMPLE_TOPIC_NAME");
String subscriptionName = System.getenv("AZURE_SERVICEBUS_SAMPLE_SUBSCRIPTION_NAME");
@Test
public void instantiateReceiverAsync() {
ServiceBusClientBuilder builder = new ServiceBusClientBuilder()
.connectionString(connectionString);
ServiceBusReceiverAsyncClient receiver = builder
.receiver()
.disableAutoComplete()
.topicName(topicName)
.subscriptionName(subscriptionName)
.buildAsyncClient();
receiver.receiveMessages().blockFirst(Duration.ofSeconds(1));
}
@Test
public void instantiateSenderSync() {
ServiceBusClientBuilder builder = new ServiceBusClientBuilder()
.connectionString(connectionString);
ServiceBusSenderClient sender = builder
.sender()
.queueName(queueName)
.buildClient();
sender.sendMessage(new ServiceBusMessage("payload"));
}
@Test
public void instantiateProcessor() {
ServiceBusClientBuilder builder = new ServiceBusClientBuilder()
.connectionString(connectionString);
ServiceBusProcessorClient processor = builder
.processor()
.queueName(queueName)
.processMessage(System.out::println)
.processError(context -> System.err.println(context.getErrorSource()))
.buildProcessorClient();
processor.start();
processor.stop();
}
@Test
public void connectionSharingAcrossClients() {
ServiceBusClientBuilder sharedConnectionBuilder = new ServiceBusClientBuilder()
.connectionString(connectionString);
ServiceBusReceiverClient receiver = sharedConnectionBuilder
.receiver()
.queueName(queueName)
.buildClient();
ServiceBusSenderClient sender = sharedConnectionBuilder
.sender()
.queueName(queueName)
.buildClient();
sender.sendMessage(new ServiceBusMessage("payload"));
receiver.receiveMessages(1);
}
} | class ServiceBusClientBuilderJavaDocCodeSamples {
String connectionString = System.getenv("AZURE_SERVICEBUS_NAMESPACE_CONNECTION_STRING");
String queueName = System.getenv("AZURE_SERVICEBUS_SAMPLE_QUEUE_NAME");
String topicName = System.getenv("AZURE_SERVICEBUS_SAMPLE_TOPIC_NAME");
String subscriptionName = System.getenv("AZURE_SERVICEBUS_SAMPLE_SUBSCRIPTION_NAME");
@Test
public void instantiateReceiverAsync() {
ServiceBusClientBuilder builder = new ServiceBusClientBuilder()
.connectionString(connectionString);
ServiceBusReceiverAsyncClient receiver = builder
.receiver()
.disableAutoComplete()
.topicName(topicName)
.subscriptionName(subscriptionName)
.buildAsyncClient();
receiver.receiveMessages().blockFirst(Duration.ofSeconds(1));
}
@Test
public void instantiateSenderSync() {
ServiceBusClientBuilder builder = new ServiceBusClientBuilder()
.connectionString(connectionString);
ServiceBusSenderClient sender = builder
.sender()
.queueName(queueName)
.buildClient();
sender.sendMessage(new ServiceBusMessage("payload"));
}
@Test
public void instantiateProcessor() {
ServiceBusClientBuilder builder = new ServiceBusClientBuilder()
.connectionString(connectionString);
ServiceBusProcessorClient processor = builder
.processor()
.queueName(queueName)
.processMessage(System.out::println)
.processError(context -> System.err.println(context.getErrorSource()))
.buildProcessorClient();
processor.start();
processor.stop();
}
@Test
public void connectionSharingAcrossClients() {
ServiceBusClientBuilder sharedConnectionBuilder = new ServiceBusClientBuilder()
.connectionString(connectionString);
ServiceBusReceiverClient receiver = sharedConnectionBuilder
.receiver()
.queueName(queueName)
.buildClient();
ServiceBusSenderClient sender = sharedConnectionBuilder
.sender()
.queueName(queueName)
.buildClient();
sender.sendMessage(new ServiceBusMessage("payload"));
receiver.receiveMessages(1);
}
} |
nit: rename the variable since it's no longer a response | public void sendSmsToSingleNumberWithOptions(HttpClient httpClient) {
SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient);
client = setupSyncClient(builder, "sendSmsToSingleNumberWithOptionsSync");
SmsSendOptions options = new SmsSendOptions();
options.setDeliveryReportEnabled(true);
options.setTag("New Tag");
SmsSendResult response = client.send(FROM_PHONE_NUMBER, TO_PHONE_NUMBER, MESSAGE, options, Context.NONE);
assertHappyPath(response);
} | SmsSendResult response = client.send(FROM_PHONE_NUMBER, TO_PHONE_NUMBER, MESSAGE, options, Context.NONE); | public void sendSmsToSingleNumberWithOptions(HttpClient httpClient) {
SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient);
client = setupSyncClient(builder, "sendSmsToSingleNumberWithOptionsSync");
SmsSendOptions options = new SmsSendOptions();
options.setDeliveryReportEnabled(true);
options.setTag("New Tag");
SmsSendResult sendResult = client.send(FROM_PHONE_NUMBER, TO_PHONE_NUMBER, MESSAGE, options, Context.NONE);
assertHappyPath(sendResult);
} | class SmsClientTests extends SmsTestBase {
private SmsClient client;
@Override
protected void beforeTest() {
super.beforeTest();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void sendSmsUsingConnectionString(HttpClient httpClient) {
SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient);
client = setupSyncClient(builder, "sendSmsUsingConnectionStringSync");
SmsSendResult sendResult = client.send(FROM_PHONE_NUMBER, TO_PHONE_NUMBER, MESSAGE);
assertHappyPath(sendResult);
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void sendSmsUsingTokenCredential(HttpClient httpClient) {
TokenCredential tokenCredential = new DefaultAzureCredentialBuilder().build();
SmsClientBuilder builder = getSmsClientWithToken(httpClient, tokenCredential);
client = setupSyncClient(builder, "sendSmsUsingTokenCredentialSync");
SmsSendResult sendResult = client.send(FROM_PHONE_NUMBER, TO_PHONE_NUMBER, MESSAGE);
assertHappyPath(sendResult);
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void sendSmsToGroup(HttpClient httpClient) {
SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient);
client = setupSyncClient(builder, "sendSmsToGroupSync");
Iterable<SmsSendResult> sendResults = client.send(FROM_PHONE_NUMBER, Arrays.asList(TO_PHONE_NUMBER, TO_PHONE_NUMBER), MESSAGE);
for (SmsSendResult result : sendResults) {
assertHappyPath(result);
}
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void sendSmsToGroupWithOptions(HttpClient httpClient) {
SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient);
client = setupSyncClient(builder, "sendSmsToGroupWithOptionsSync");
SmsSendOptions options = new SmsSendOptions();
options.setDeliveryReportEnabled(true);
options.setTag("New Tag");
Response<Iterable<SmsSendResult>> sendResults = client.sendWithResponse(FROM_PHONE_NUMBER, Arrays.asList(TO_PHONE_NUMBER, TO_PHONE_NUMBER), MESSAGE, options, Context.NONE);
for (SmsSendResult result : sendResults.getValue()) {
assertHappyPath(result);
}
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void sendSmsToSingleNumber(HttpClient httpClient) {
SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient);
client = setupSyncClient(builder, "sendSmsToSingleNumberSync");
SmsSendResult sendResult = client.send(FROM_PHONE_NUMBER, TO_PHONE_NUMBER, MESSAGE);
assertHappyPath(sendResult);
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void sendFromFakeNumber(HttpClient httpClient) {
SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient);
client = setupSyncClient(builder, "sendFromFakeNumberSync");
try {
client.send("+15550000000", TO_PHONE_NUMBER, MESSAGE);
} catch (Exception exception) {
assertEquals(400, ((HttpResponseException) exception).getResponse().getStatusCode());
}
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void sendFromUnauthorizedNumber(HttpClient httpClient) {
SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient);
client = setupSyncClient(builder, "sendFromUnauthorizedNumberSync");
try {
SmsSendResult response = client.send("+18007342577", TO_PHONE_NUMBER, MESSAGE);
} catch (Exception exception) {
assertEquals(404, ((HttpResponseException) exception).getResponse().getStatusCode());
}
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void sendToFakePhoneNumber(HttpClient httpClient) {
SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient);
client = setupSyncClient(builder, "sendToFakePhoneNumberSync");
SmsSendResult sendResult = client.send(FROM_PHONE_NUMBER, "+15550000000", MESSAGE);
assertFalse(sendResult.isSuccessful());
assertEquals(sendResult.getHttpStatusCode(), 400);
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void sendTwoMessages(HttpClient httpClient) {
SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient);
client = setupSyncClient(builder, "sendTwoMessagesSync");
SmsSendResult firstResponse = client.send(FROM_PHONE_NUMBER, TO_PHONE_NUMBER, MESSAGE);
SmsSendResult secondResponse = client.send(FROM_PHONE_NUMBER, TO_PHONE_NUMBER, MESSAGE);
assertNotEquals(firstResponse.getMessageId(), secondResponse.getMessageId());
assertHappyPath(firstResponse);
assertHappyPath(secondResponse);
}
private SmsClient setupSyncClient(SmsClientBuilder builder, String testName) {
return addLoggingPolicy(builder, testName).buildClient();
}
private void assertHappyPath(SmsSendResult sendResult) {
assertTrue(sendResult.isSuccessful());
assertEquals(sendResult.getHttpStatusCode(), 202);
assertNotNull(sendResult.getMessageId());
}
} | class SmsClientTests extends SmsTestBase {
private SmsClient client;
@Override
protected void beforeTest() {
super.beforeTest();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void sendSmsUsingConnectionString(HttpClient httpClient) {
SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient);
client = setupSyncClient(builder, "sendSmsUsingConnectionStringSync");
SmsSendResult sendResult = client.send(FROM_PHONE_NUMBER, TO_PHONE_NUMBER, MESSAGE);
assertHappyPath(sendResult);
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void sendSmsUsingTokenCredential(HttpClient httpClient) {
TokenCredential tokenCredential = new DefaultAzureCredentialBuilder().build();
SmsClientBuilder builder = getSmsClientWithToken(httpClient, tokenCredential);
client = setupSyncClient(builder, "sendSmsUsingTokenCredentialSync");
SmsSendResult sendResult = client.send(FROM_PHONE_NUMBER, TO_PHONE_NUMBER, MESSAGE);
assertHappyPath(sendResult);
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void sendSmsToGroup(HttpClient httpClient) {
SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient);
client = setupSyncClient(builder, "sendSmsToGroupSync");
Iterable<SmsSendResult> sendResults = client.send(FROM_PHONE_NUMBER, Arrays.asList(TO_PHONE_NUMBER, TO_PHONE_NUMBER), MESSAGE);
for (SmsSendResult result : sendResults) {
assertHappyPath(result);
}
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void sendSmsToGroupWithOptions(HttpClient httpClient) {
SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient);
client = setupSyncClient(builder, "sendSmsToGroupWithOptionsSync");
SmsSendOptions options = new SmsSendOptions();
options.setDeliveryReportEnabled(true);
options.setTag("New Tag");
Response<Iterable<SmsSendResult>> sendResults = client.sendWithResponse(FROM_PHONE_NUMBER, Arrays.asList(TO_PHONE_NUMBER, TO_PHONE_NUMBER), MESSAGE, options, Context.NONE);
for (SmsSendResult result : sendResults.getValue()) {
assertHappyPath(result);
}
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void sendSmsToSingleNumber(HttpClient httpClient) {
SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient);
client = setupSyncClient(builder, "sendSmsToSingleNumberSync");
SmsSendResult sendResult = client.send(FROM_PHONE_NUMBER, TO_PHONE_NUMBER, MESSAGE);
assertHappyPath(sendResult);
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void sendFromFakeNumber(HttpClient httpClient) {
SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient);
client = setupSyncClient(builder, "sendFromFakeNumberSync");
try {
client.send("+15550000000", TO_PHONE_NUMBER, MESSAGE);
} catch (Exception exception) {
assertEquals(400, ((HttpResponseException) exception).getResponse().getStatusCode());
}
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void sendFromUnauthorizedNumber(HttpClient httpClient) {
SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient);
client = setupSyncClient(builder, "sendFromUnauthorizedNumberSync");
try {
SmsSendResult response = client.send("+18007342577", TO_PHONE_NUMBER, MESSAGE);
} catch (Exception exception) {
assertEquals(404, ((HttpResponseException) exception).getResponse().getStatusCode());
}
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void sendToFakePhoneNumber(HttpClient httpClient) {
SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient);
client = setupSyncClient(builder, "sendToFakePhoneNumberSync");
SmsSendResult sendResult = client.send(FROM_PHONE_NUMBER, "+15550000000", MESSAGE);
assertFalse(sendResult.isSuccessful());
assertEquals(sendResult.getHttpStatusCode(), 400);
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void sendTwoMessages(HttpClient httpClient) {
SmsClientBuilder builder = getSmsClientUsingConnectionString(httpClient);
client = setupSyncClient(builder, "sendTwoMessagesSync");
SmsSendResult firstResponse = client.send(FROM_PHONE_NUMBER, TO_PHONE_NUMBER, MESSAGE);
SmsSendResult secondResponse = client.send(FROM_PHONE_NUMBER, TO_PHONE_NUMBER, MESSAGE);
assertNotEquals(firstResponse.getMessageId(), secondResponse.getMessageId());
assertHappyPath(firstResponse);
assertHappyPath(secondResponse);
}
private SmsClient setupSyncClient(SmsClientBuilder builder, String testName) {
return addLoggingPolicy(builder, testName).buildClient();
}
private void assertHappyPath(SmsSendResult sendResult) {
assertTrue(sendResult.isSuccessful());
assertEquals(sendResult.getHttpStatusCode(), 202);
assertNotNull(sendResult.getMessageId());
}
} |
Good call on the HMAC, we have separate tests for them. I have a couple of suggestions though. These comments have their way of getting out of sync with the code. So I would recommend extracting the checks into a method and using that for both tests though. Calling such a method as explicit like `assertHMACHeadersExist`. Also I do not think we need to check if UserAgent exist, I am pretty sure there are some tests in AzureCore for that | public void buildAsyncClientTestUsingConnectionStringAndClientOptions() {
builder
.connectionString(MOCK_CONNECTION_STRING)
.httpClient(new NoOpHttpClient() {
@Override
public Mono<HttpResponse> send(HttpRequest request) {
Map<String, String> headers = request.getHeaders().toMap();
assertTrue(headers.containsKey("Authorization"));
assertTrue(headers.containsKey("User-Agent"));
assertTrue(headers.containsKey("x-ms-content-sha256"));
assertNotNull(headers.get("Authorization"));
assertNotNull(headers.get("x-ms-content-sha256"));
return Mono.just(CommunicationIdentityResponseMocker.createUserResult(request));
}
});
CommunicationIdentityAsyncClient asyncClient = builder
.clientOptions(new ClientOptions().setApplicationId("testApplicationId"))
.buildAsyncClient();
assertNotNull(asyncClient);
} | public void buildAsyncClientTestUsingConnectionStringAndClientOptions() {
builder
.connectionString(MOCK_CONNECTION_STRING)
.httpClient(new NoOpHttpClient() {
@Override
public Mono<HttpResponse> send(HttpRequest request) {
Map<String, String> headers = request.getHeaders().toMap();
assertHMACHeadersExist(headers);
return Mono.just(CommunicationIdentityResponseMocker.createUserResult(request));
}
});
CommunicationIdentityAsyncClient asyncClient = builder
.clientOptions(new ClientOptions().setApplicationId("testApplicationId"))
.buildAsyncClient();
assertNotNull(asyncClient);
} | class NoOpHttpClient implements HttpClient {
@Override
public Mono<HttpResponse> send(HttpRequest request) {
return Mono.empty();
}
} | class NoOpHttpClient implements HttpClient {
@Override
public Mono<HttpResponse> send(HttpRequest request) {
return Mono.empty();
}
} | |
nit: "get" sounds like it existed before, maybe we should call it "create". Also it creates a builder not a client. We can call it `createClientBuilder` (We are in the CommunicationIdentity test, so I think that sets the context and we do not need to explictly call out what type of clients we are building in the name). | public void deleteUserWithResponseWithNullContext(HttpClient httpClient) {
CommunicationIdentityClientBuilder builder = getCommunicationIdentityClient(httpClient);
client = setupClient(builder, "deleteUserWithResponseSync");
CommunicationUserIdentifier communicationUser = client.createUser();
Response<Void> response = client.deleteUserWithResponse(communicationUser, null);
assertEquals(204, response.getStatusCode(), "Expect status code to be 204");
} | CommunicationIdentityClientBuilder builder = getCommunicationIdentityClient(httpClient); | public void deleteUserWithResponseWithNullContext(HttpClient httpClient) {
CommunicationIdentityClientBuilder builder = createClientBuilder(httpClient);
client = setupClient(builder, "deleteUserWithResponseSync");
CommunicationUserIdentifier communicationUser = client.createUser();
Response<Void> response = client.deleteUserWithResponse(communicationUser, null);
assertEquals(204, response.getStatusCode(), "Expect status code to be 204");
} | class CommunicationIdentityTests extends CommunicationIdentityClientTestBase {
private CommunicationIdentityClient client;
@Override
protected void beforeTest() {
super.beforeTest();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void createIdentityClientUsingManagedIdentity(HttpClient httpClient) {
CommunicationIdentityClientBuilder builder = getCommunicationIdentityClientBuilderUsingManagedIdentity(httpClient);
client = setupClient(builder, "createIdentityClientUsingManagedIdentitySync");
assertNotNull(client);
CommunicationUserIdentifier communicationUser = client.createUser();
assertNotNull(communicationUser.getId());
assertFalse(communicationUser.getId().isEmpty());
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void createIdentityClientUsingConnectionString(HttpClient httpClient) {
CommunicationIdentityClientBuilder builder = getCommunicationIdentityClientUsingConnectionString(httpClient);
client = setupClient(builder, "createIdentityClientUsingConnectionStringSync");
assertNotNull(client);
CommunicationUserIdentifier communicationUser = client.createUser();
assertNotNull(communicationUser.getId());
assertFalse(communicationUser.getId().isEmpty());
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void createUser(HttpClient httpClient) {
CommunicationIdentityClientBuilder builder = getCommunicationIdentityClient(httpClient);
client = setupClient(builder, "createUserSync");
CommunicationUserIdentifier communicationUser = client.createUser();
assertNotNull(communicationUser.getId());
assertFalse(communicationUser.getId().isEmpty());
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void createUserWithResponse(HttpClient httpClient) {
CommunicationIdentityClientBuilder builder = getCommunicationIdentityClient(httpClient);
client = setupClient(builder, "createUserWithResponseSync");
Response<CommunicationUserIdentifier> response = client.createUserWithResponse(Context.NONE);
assertNotNull(response.getValue().getId());
assertFalse(response.getValue().getId().isEmpty());
assertEquals(201, response.getStatusCode(), "Expect status code to be 201");
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void createUserAndToken(HttpClient httpClient) {
CommunicationIdentityClientBuilder builder = getCommunicationIdentityClient(httpClient);
client = setupClient(builder, "createUserAndTokenSync");
List<CommunicationTokenScope> scopes = Arrays.asList(CommunicationTokenScope.CHAT);
CommunicationUserIdentifierAndToken result = client.createUserAndToken(scopes);
assertNotNull(result.getUser().getId());
assertNotNull(result.getUserToken());
assertFalse(result.getUser().getId().isEmpty());
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void createUserAndTokenWithResponse(HttpClient httpClient) {
CommunicationIdentityClientBuilder builder = getCommunicationIdentityClient(httpClient);
client = setupClient(builder, "createUserAndTokenWithResponseSync");
List<CommunicationTokenScope> scopes = Arrays.asList(CommunicationTokenScope.CHAT);
Response<CommunicationUserIdentifierAndToken> response =
client.createUserAndTokenWithResponse(scopes, Context.NONE);
CommunicationUserIdentifierAndToken result = response.getValue();
assertEquals(201, response.getStatusCode());
assertNotNull(result.getUser().getId());
assertNotNull(result.getUserToken());
assertFalse(result.getUser().getId().isEmpty());
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void createUserAndTokenWithResponseNullContext(HttpClient httpClient) {
CommunicationIdentityClientBuilder builder = getCommunicationIdentityClient(httpClient);
client = setupClient(builder, "createUserAndTokenWithResponseSync");
List<CommunicationTokenScope> scopes = Arrays.asList(CommunicationTokenScope.CHAT);
Response<CommunicationUserIdentifierAndToken> response =
client.createUserAndTokenWithResponse(scopes, null);
CommunicationUserIdentifierAndToken result = response.getValue();
assertEquals(201, response.getStatusCode());
assertNotNull(result.getUser().getId());
assertNotNull(result.getUserToken());
assertFalse(result.getUser().getId().isEmpty());
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void deleteUser(HttpClient httpClient) {
CommunicationIdentityClientBuilder builder = getCommunicationIdentityClient(httpClient);
client = setupClient(builder, "deleteUserSync");
CommunicationUserIdentifier communicationUser = client.createUser();
assertNotNull(communicationUser.getId());
client.deleteUser(communicationUser);
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void deleteUserWithResponse(HttpClient httpClient) {
CommunicationIdentityClientBuilder builder = getCommunicationIdentityClient(httpClient);
client = setupClient(builder, "deleteUserWithResponseSync");
CommunicationUserIdentifier communicationUser = client.createUser();
Response<Void> response = client.deleteUserWithResponse(communicationUser, Context.NONE);
assertEquals(204, response.getStatusCode(), "Expect status code to be 204");
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void revokeToken(HttpClient httpClient) {
CommunicationIdentityClientBuilder builder = getCommunicationIdentityClient(httpClient);
client = setupClient(builder, "revokeTokenSync");
CommunicationUserIdentifier communicationUser = client.createUser();
assertNotNull(communicationUser.getId());
List<CommunicationTokenScope> scopes = Arrays.asList(CommunicationTokenScope.CHAT);
client.getToken(communicationUser, scopes);
client.revokeTokens(communicationUser);
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void revokeTokenWithResponse(HttpClient httpClient) {
CommunicationIdentityClientBuilder builder = getCommunicationIdentityClient(httpClient);
client = setupClient(builder, "revokeTokenWithResponseSync");
CommunicationUserIdentifier communicationUser = client.createUser();
List<CommunicationTokenScope> scopes = Arrays.asList(CommunicationTokenScope.CHAT);
client.getToken(communicationUser, scopes);
Response<Void> response = client.revokeTokensWithResponse(communicationUser, Context.NONE);
assertEquals(204, response.getStatusCode(), "Expect status code to be 204");
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void revokeTokenWithResponseNullContext(HttpClient httpClient) {
CommunicationIdentityClientBuilder builder = getCommunicationIdentityClient(httpClient);
client = setupClient(builder, "revokeTokenWithResponseSync");
CommunicationUserIdentifier communicationUser = client.createUser();
List<CommunicationTokenScope> scopes = Arrays.asList(CommunicationTokenScope.CHAT);
client.getToken(communicationUser, scopes);
Response<Void> response = client.revokeTokensWithResponse(communicationUser, null);
assertEquals(204, response.getStatusCode(), "Expect status code to be 204");
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void getToken(HttpClient httpClient) {
CommunicationIdentityClientBuilder builder = getCommunicationIdentityClient(httpClient);
client = setupClient(builder, "getTokenSync");
CommunicationUserIdentifier communicationUser = client.createUser();
List<CommunicationTokenScope> scopes = Arrays.asList(CommunicationTokenScope.CHAT);
AccessToken issuedToken = client.getToken(communicationUser, scopes);
assertNotNull(issuedToken.getToken());
assertFalse(issuedToken.getToken().isEmpty());
assertNotNull(issuedToken.getExpiresAt());
assertFalse(issuedToken.getExpiresAt().toString().isEmpty());
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void getTokenWithResponse(HttpClient httpClient) {
CommunicationIdentityClientBuilder builder = getCommunicationIdentityClient(httpClient);
client = setupClient(builder, "getTokenWithResponseSync");
CommunicationUserIdentifier communicationUser = client.createUser();
List<CommunicationTokenScope> scopes = Arrays.asList(CommunicationTokenScope.CHAT);
Response<AccessToken> issuedTokenResponse = client.getTokenWithResponse(communicationUser, scopes, Context.NONE);
AccessToken issuedToken = issuedTokenResponse.getValue();
assertEquals(200, issuedTokenResponse.getStatusCode(), "Expect status code to be 200");
assertNotNull(issuedToken.getToken());
assertFalse(issuedToken.getToken().isEmpty());
assertNotNull(issuedToken.getExpiresAt());
assertFalse(issuedToken.getExpiresAt().toString().isEmpty());
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void getTokenWithResponseNullContext(HttpClient httpClient) {
CommunicationIdentityClientBuilder builder = getCommunicationIdentityClient(httpClient);
client = setupClient(builder, "getTokenWithResponseSync");
CommunicationUserIdentifier communicationUser = client.createUser();
List<CommunicationTokenScope> scopes = Arrays.asList(CommunicationTokenScope.CHAT);
Response<AccessToken> issuedTokenResponse = client.getTokenWithResponse(communicationUser, scopes, null);
AccessToken issuedToken = issuedTokenResponse.getValue();
assertEquals(200, issuedTokenResponse.getStatusCode(), "Expect status code to be 200");
assertNotNull(issuedToken.getToken());
assertFalse(issuedToken.getToken().isEmpty());
assertNotNull(issuedToken.getExpiresAt());
assertFalse(issuedToken.getExpiresAt().toString().isEmpty());
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void createUserWithResponseUsingManagedIdentity(HttpClient httpClient) {
CommunicationIdentityClientBuilder builder = getCommunicationIdentityClientBuilderUsingManagedIdentity(httpClient);
client = setupClient(builder, "createUserWithResponseUsingManagedIdentitySync");
Response<CommunicationUserIdentifier> response = client.createUserWithResponse(Context.NONE);
assertNotNull(response.getValue().getId());
assertFalse(response.getValue().getId().isEmpty());
assertEquals(201, response.getStatusCode(), "Expect status code to be 201");
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void deleteUserUsingManagedIdentity(HttpClient httpClient) {
CommunicationIdentityClientBuilder builder = getCommunicationIdentityClientBuilderUsingManagedIdentity(httpClient);
client = setupClient(builder, "deleteUserUsingManagedIdentitySync");
CommunicationUserIdentifier communicationUser = client.createUser();
assertNotNull(communicationUser.getId());
client.deleteUser(communicationUser);
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void deleteUserWithResponseUsingManagedIdentity(HttpClient httpClient) {
CommunicationIdentityClientBuilder builder = getCommunicationIdentityClientBuilderUsingManagedIdentity(httpClient);
client = setupClient(builder, "deleteUserWithResponseUsingManagedIdentitySync");
CommunicationUserIdentifier communicationUser = client.createUser();
Response<Void> response = client.deleteUserWithResponse(communicationUser, Context.NONE);
assertEquals(204, response.getStatusCode(), "Expect status code to be 204");
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void revokeTokenUsingManagedIdentity(HttpClient httpClient) {
CommunicationIdentityClientBuilder builder = getCommunicationIdentityClientBuilderUsingManagedIdentity(httpClient);
client = setupClient(builder, "revokeTokenUsingManagedIdentitySync");
CommunicationUserIdentifier communicationUser = client.createUser();
assertNotNull(communicationUser.getId());
List<CommunicationTokenScope> scopes = Arrays.asList(CommunicationTokenScope.CHAT);
client.getToken(communicationUser, scopes);
client.revokeTokens(communicationUser);
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void revokeTokenWithResponseUsingManagedIdentity(HttpClient httpClient) {
CommunicationIdentityClientBuilder builder = getCommunicationIdentityClientBuilderUsingManagedIdentity(httpClient);
client = setupClient(builder, "revokeTokenWithResponseUsingManagedIdentitySync");
CommunicationUserIdentifier communicationUser = client.createUser();
List<CommunicationTokenScope> scopes = Arrays.asList(CommunicationTokenScope.CHAT);
client.getToken(communicationUser, scopes);
Response<Void> response = client.revokeTokensWithResponse(communicationUser, Context.NONE);
assertEquals(204, response.getStatusCode(), "Expect status code to be 204");
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void getTokenUsingManagedIdentity(HttpClient httpClient) {
CommunicationIdentityClientBuilder builder = getCommunicationIdentityClientBuilderUsingManagedIdentity(httpClient);
client = setupClient(builder, "getTokenUsingManagedIdentitySync");
CommunicationUserIdentifier communicationUser = client.createUser();
List<CommunicationTokenScope> scopes = Arrays.asList(CommunicationTokenScope.CHAT);
AccessToken issuedToken = client.getToken(communicationUser, scopes);
assertNotNull(issuedToken.getToken());
assertFalse(issuedToken.getToken().isEmpty());
assertNotNull(issuedToken.getExpiresAt());
assertFalse(issuedToken.getExpiresAt().toString().isEmpty());
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void getTokenWithResponseUsingManagedIdentity(HttpClient httpClient) {
CommunicationIdentityClientBuilder builder = getCommunicationIdentityClientBuilderUsingManagedIdentity(httpClient);
client = setupClient(builder, "getTokenWithResponseUsingManagedIdentitySync");
CommunicationUserIdentifier communicationUser = client.createUser();
List<CommunicationTokenScope> scopes = Arrays.asList(CommunicationTokenScope.CHAT);
Response<AccessToken> response = client.getTokenWithResponse(communicationUser, scopes, Context.NONE);
AccessToken issuedToken = response.getValue();
assertEquals(200, response.getStatusCode(), "Expect status code to be 200");
assertNotNull(issuedToken.getToken());
assertFalse(issuedToken.getToken().isEmpty());
assertNotNull(issuedToken.getExpiresAt());
assertFalse(issuedToken.getExpiresAt().toString().isEmpty());
}
private CommunicationIdentityClient setupClient(CommunicationIdentityClientBuilder builder, String testName) {
return addLoggingPolicy(builder, testName).buildClient();
}
} | class CommunicationIdentityTests extends CommunicationIdentityClientTestBase {
private CommunicationIdentityClient client;
@Override
protected void beforeTest() {
super.beforeTest();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void createIdentityClientUsingManagedIdentity(HttpClient httpClient) {
CommunicationIdentityClientBuilder builder = createClientBuilderUsingManagedIdentity(httpClient);
client = setupClient(builder, "createIdentityClientUsingManagedIdentitySync");
assertNotNull(client);
CommunicationUserIdentifier communicationUser = client.createUser();
assertNotNull(communicationUser.getId());
assertFalse(communicationUser.getId().isEmpty());
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void createIdentityClientUsingConnectionString(HttpClient httpClient) {
CommunicationIdentityClientBuilder builder = createClientBuilderUsingConnectionString(httpClient);
client = setupClient(builder, "createIdentityClientUsingConnectionStringSync");
assertNotNull(client);
CommunicationUserIdentifier communicationUser = client.createUser();
assertNotNull(communicationUser.getId());
assertFalse(communicationUser.getId().isEmpty());
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void createUser(HttpClient httpClient) {
CommunicationIdentityClientBuilder builder = createClientBuilder(httpClient);
client = setupClient(builder, "createUserSync");
CommunicationUserIdentifier communicationUser = client.createUser();
assertNotNull(communicationUser.getId());
assertFalse(communicationUser.getId().isEmpty());
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void createUserWithResponse(HttpClient httpClient) {
CommunicationIdentityClientBuilder builder = createClientBuilder(httpClient);
client = setupClient(builder, "createUserWithResponseSync");
Response<CommunicationUserIdentifier> response = client.createUserWithResponse(Context.NONE);
assertNotNull(response.getValue().getId());
assertFalse(response.getValue().getId().isEmpty());
assertEquals(201, response.getStatusCode(), "Expect status code to be 201");
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void createUserAndToken(HttpClient httpClient) {
CommunicationIdentityClientBuilder builder = createClientBuilder(httpClient);
client = setupClient(builder, "createUserAndTokenSync");
List<CommunicationTokenScope> scopes = Arrays.asList(CommunicationTokenScope.CHAT);
CommunicationUserIdentifierAndToken result = client.createUserAndToken(scopes);
assertNotNull(result.getUser().getId());
assertNotNull(result.getUserToken());
assertFalse(result.getUser().getId().isEmpty());
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void createUserAndTokenWithResponse(HttpClient httpClient) {
CommunicationIdentityClientBuilder builder = createClientBuilder(httpClient);
client = setupClient(builder, "createUserAndTokenWithResponseSync");
List<CommunicationTokenScope> scopes = Arrays.asList(CommunicationTokenScope.CHAT);
Response<CommunicationUserIdentifierAndToken> response =
client.createUserAndTokenWithResponse(scopes, Context.NONE);
CommunicationUserIdentifierAndToken result = response.getValue();
assertEquals(201, response.getStatusCode());
assertNotNull(result.getUser().getId());
assertNotNull(result.getUserToken());
assertFalse(result.getUser().getId().isEmpty());
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void createUserAndTokenWithResponseNullContext(HttpClient httpClient) {
CommunicationIdentityClientBuilder builder = createClientBuilder(httpClient);
client = setupClient(builder, "createUserAndTokenWithResponseSync");
List<CommunicationTokenScope> scopes = Arrays.asList(CommunicationTokenScope.CHAT);
Response<CommunicationUserIdentifierAndToken> response =
client.createUserAndTokenWithResponse(scopes, null);
CommunicationUserIdentifierAndToken result = response.getValue();
assertEquals(201, response.getStatusCode());
assertNotNull(result.getUser().getId());
assertNotNull(result.getUserToken());
assertFalse(result.getUser().getId().isEmpty());
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void deleteUser(HttpClient httpClient) {
CommunicationIdentityClientBuilder builder = createClientBuilder(httpClient);
client = setupClient(builder, "deleteUserSync");
CommunicationUserIdentifier communicationUser = client.createUser();
assertNotNull(communicationUser.getId());
client.deleteUser(communicationUser);
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void deleteUserWithResponse(HttpClient httpClient) {
CommunicationIdentityClientBuilder builder = createClientBuilder(httpClient);
client = setupClient(builder, "deleteUserWithResponseSync");
CommunicationUserIdentifier communicationUser = client.createUser();
Response<Void> response = client.deleteUserWithResponse(communicationUser, Context.NONE);
assertEquals(204, response.getStatusCode(), "Expect status code to be 204");
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void revokeToken(HttpClient httpClient) {
CommunicationIdentityClientBuilder builder = createClientBuilder(httpClient);
client = setupClient(builder, "revokeTokenSync");
CommunicationUserIdentifier communicationUser = client.createUser();
assertNotNull(communicationUser.getId());
List<CommunicationTokenScope> scopes = Arrays.asList(CommunicationTokenScope.CHAT);
client.getToken(communicationUser, scopes);
client.revokeTokens(communicationUser);
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void revokeTokenWithResponse(HttpClient httpClient) {
CommunicationIdentityClientBuilder builder = createClientBuilder(httpClient);
client = setupClient(builder, "revokeTokenWithResponseSync");
CommunicationUserIdentifier communicationUser = client.createUser();
List<CommunicationTokenScope> scopes = Arrays.asList(CommunicationTokenScope.CHAT);
client.getToken(communicationUser, scopes);
Response<Void> response = client.revokeTokensWithResponse(communicationUser, Context.NONE);
assertEquals(204, response.getStatusCode(), "Expect status code to be 204");
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void revokeTokenWithResponseNullContext(HttpClient httpClient) {
CommunicationIdentityClientBuilder builder = createClientBuilder(httpClient);
client = setupClient(builder, "revokeTokenWithResponseSync");
CommunicationUserIdentifier communicationUser = client.createUser();
List<CommunicationTokenScope> scopes = Arrays.asList(CommunicationTokenScope.CHAT);
client.getToken(communicationUser, scopes);
Response<Void> response = client.revokeTokensWithResponse(communicationUser, null);
assertEquals(204, response.getStatusCode(), "Expect status code to be 204");
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void getToken(HttpClient httpClient) {
CommunicationIdentityClientBuilder builder = createClientBuilder(httpClient);
client = setupClient(builder, "getTokenSync");
CommunicationUserIdentifier communicationUser = client.createUser();
List<CommunicationTokenScope> scopes = Arrays.asList(CommunicationTokenScope.CHAT);
AccessToken issuedToken = client.getToken(communicationUser, scopes);
assertNotNull(issuedToken.getToken());
assertFalse(issuedToken.getToken().isEmpty());
assertNotNull(issuedToken.getExpiresAt());
assertFalse(issuedToken.getExpiresAt().toString().isEmpty());
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void getTokenWithResponse(HttpClient httpClient) {
CommunicationIdentityClientBuilder builder = createClientBuilder(httpClient);
client = setupClient(builder, "getTokenWithResponseSync");
CommunicationUserIdentifier communicationUser = client.createUser();
List<CommunicationTokenScope> scopes = Arrays.asList(CommunicationTokenScope.CHAT);
Response<AccessToken> issuedTokenResponse = client.getTokenWithResponse(communicationUser, scopes, Context.NONE);
AccessToken issuedToken = issuedTokenResponse.getValue();
assertEquals(200, issuedTokenResponse.getStatusCode(), "Expect status code to be 200");
assertNotNull(issuedToken.getToken());
assertFalse(issuedToken.getToken().isEmpty());
assertNotNull(issuedToken.getExpiresAt());
assertFalse(issuedToken.getExpiresAt().toString().isEmpty());
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void getTokenWithResponseNullContext(HttpClient httpClient) {
CommunicationIdentityClientBuilder builder = createClientBuilder(httpClient);
client = setupClient(builder, "getTokenWithResponseSync");
CommunicationUserIdentifier communicationUser = client.createUser();
List<CommunicationTokenScope> scopes = Arrays.asList(CommunicationTokenScope.CHAT);
Response<AccessToken> issuedTokenResponse = client.getTokenWithResponse(communicationUser, scopes, null);
AccessToken issuedToken = issuedTokenResponse.getValue();
assertEquals(200, issuedTokenResponse.getStatusCode(), "Expect status code to be 200");
assertNotNull(issuedToken.getToken());
assertFalse(issuedToken.getToken().isEmpty());
assertNotNull(issuedToken.getExpiresAt());
assertFalse(issuedToken.getExpiresAt().toString().isEmpty());
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void createUserWithResponseUsingManagedIdentity(HttpClient httpClient) {
CommunicationIdentityClientBuilder builder = createClientBuilderUsingManagedIdentity(httpClient);
client = setupClient(builder, "createUserWithResponseUsingManagedIdentitySync");
Response<CommunicationUserIdentifier> response = client.createUserWithResponse(Context.NONE);
assertNotNull(response.getValue().getId());
assertFalse(response.getValue().getId().isEmpty());
assertEquals(201, response.getStatusCode(), "Expect status code to be 201");
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void deleteUserUsingManagedIdentity(HttpClient httpClient) {
CommunicationIdentityClientBuilder builder = createClientBuilderUsingManagedIdentity(httpClient);
client = setupClient(builder, "deleteUserUsingManagedIdentitySync");
CommunicationUserIdentifier communicationUser = client.createUser();
assertNotNull(communicationUser.getId());
client.deleteUser(communicationUser);
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void deleteUserWithResponseUsingManagedIdentity(HttpClient httpClient) {
CommunicationIdentityClientBuilder builder = createClientBuilderUsingManagedIdentity(httpClient);
client = setupClient(builder, "deleteUserWithResponseUsingManagedIdentitySync");
CommunicationUserIdentifier communicationUser = client.createUser();
Response<Void> response = client.deleteUserWithResponse(communicationUser, Context.NONE);
assertEquals(204, response.getStatusCode(), "Expect status code to be 204");
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void revokeTokenUsingManagedIdentity(HttpClient httpClient) {
CommunicationIdentityClientBuilder builder = createClientBuilderUsingManagedIdentity(httpClient);
client = setupClient(builder, "revokeTokenUsingManagedIdentitySync");
CommunicationUserIdentifier communicationUser = client.createUser();
assertNotNull(communicationUser.getId());
List<CommunicationTokenScope> scopes = Arrays.asList(CommunicationTokenScope.CHAT);
client.getToken(communicationUser, scopes);
client.revokeTokens(communicationUser);
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void revokeTokenWithResponseUsingManagedIdentity(HttpClient httpClient) {
CommunicationIdentityClientBuilder builder = createClientBuilderUsingManagedIdentity(httpClient);
client = setupClient(builder, "revokeTokenWithResponseUsingManagedIdentitySync");
CommunicationUserIdentifier communicationUser = client.createUser();
List<CommunicationTokenScope> scopes = Arrays.asList(CommunicationTokenScope.CHAT);
client.getToken(communicationUser, scopes);
Response<Void> response = client.revokeTokensWithResponse(communicationUser, Context.NONE);
assertEquals(204, response.getStatusCode(), "Expect status code to be 204");
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void getTokenUsingManagedIdentity(HttpClient httpClient) {
CommunicationIdentityClientBuilder builder = createClientBuilderUsingManagedIdentity(httpClient);
client = setupClient(builder, "getTokenUsingManagedIdentitySync");
CommunicationUserIdentifier communicationUser = client.createUser();
List<CommunicationTokenScope> scopes = Arrays.asList(CommunicationTokenScope.CHAT);
AccessToken issuedToken = client.getToken(communicationUser, scopes);
assertNotNull(issuedToken.getToken());
assertFalse(issuedToken.getToken().isEmpty());
assertNotNull(issuedToken.getExpiresAt());
assertFalse(issuedToken.getExpiresAt().toString().isEmpty());
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void getTokenWithResponseUsingManagedIdentity(HttpClient httpClient) {
CommunicationIdentityClientBuilder builder = createClientBuilderUsingManagedIdentity(httpClient);
client = setupClient(builder, "getTokenWithResponseUsingManagedIdentitySync");
CommunicationUserIdentifier communicationUser = client.createUser();
List<CommunicationTokenScope> scopes = Arrays.asList(CommunicationTokenScope.CHAT);
Response<AccessToken> response = client.getTokenWithResponse(communicationUser, scopes, Context.NONE);
AccessToken issuedToken = response.getValue();
assertEquals(200, response.getStatusCode(), "Expect status code to be 200");
assertNotNull(issuedToken.getToken());
assertFalse(issuedToken.getToken().isEmpty());
assertNotNull(issuedToken.getExpiresAt());
assertFalse(issuedToken.getExpiresAt().toString().isEmpty());
}
private CommunicationIdentityClient setupClient(CommunicationIdentityClientBuilder builder, String testName) {
return addLoggingPolicy(builder, testName).buildClient();
}
} |
Thanks for catching this! This makes a lot of sense | public void deleteUserWithResponseWithNullContext(HttpClient httpClient) {
CommunicationIdentityClientBuilder builder = getCommunicationIdentityClient(httpClient);
client = setupClient(builder, "deleteUserWithResponseSync");
CommunicationUserIdentifier communicationUser = client.createUser();
Response<Void> response = client.deleteUserWithResponse(communicationUser, null);
assertEquals(204, response.getStatusCode(), "Expect status code to be 204");
} | CommunicationIdentityClientBuilder builder = getCommunicationIdentityClient(httpClient); | public void deleteUserWithResponseWithNullContext(HttpClient httpClient) {
CommunicationIdentityClientBuilder builder = createClientBuilder(httpClient);
client = setupClient(builder, "deleteUserWithResponseSync");
CommunicationUserIdentifier communicationUser = client.createUser();
Response<Void> response = client.deleteUserWithResponse(communicationUser, null);
assertEquals(204, response.getStatusCode(), "Expect status code to be 204");
} | class CommunicationIdentityTests extends CommunicationIdentityClientTestBase {
private CommunicationIdentityClient client;
@Override
protected void beforeTest() {
super.beforeTest();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void createIdentityClientUsingManagedIdentity(HttpClient httpClient) {
CommunicationIdentityClientBuilder builder = getCommunicationIdentityClientBuilderUsingManagedIdentity(httpClient);
client = setupClient(builder, "createIdentityClientUsingManagedIdentitySync");
assertNotNull(client);
CommunicationUserIdentifier communicationUser = client.createUser();
assertNotNull(communicationUser.getId());
assertFalse(communicationUser.getId().isEmpty());
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void createIdentityClientUsingConnectionString(HttpClient httpClient) {
CommunicationIdentityClientBuilder builder = getCommunicationIdentityClientUsingConnectionString(httpClient);
client = setupClient(builder, "createIdentityClientUsingConnectionStringSync");
assertNotNull(client);
CommunicationUserIdentifier communicationUser = client.createUser();
assertNotNull(communicationUser.getId());
assertFalse(communicationUser.getId().isEmpty());
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void createUser(HttpClient httpClient) {
CommunicationIdentityClientBuilder builder = getCommunicationIdentityClient(httpClient);
client = setupClient(builder, "createUserSync");
CommunicationUserIdentifier communicationUser = client.createUser();
assertNotNull(communicationUser.getId());
assertFalse(communicationUser.getId().isEmpty());
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void createUserWithResponse(HttpClient httpClient) {
CommunicationIdentityClientBuilder builder = getCommunicationIdentityClient(httpClient);
client = setupClient(builder, "createUserWithResponseSync");
Response<CommunicationUserIdentifier> response = client.createUserWithResponse(Context.NONE);
assertNotNull(response.getValue().getId());
assertFalse(response.getValue().getId().isEmpty());
assertEquals(201, response.getStatusCode(), "Expect status code to be 201");
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void createUserAndToken(HttpClient httpClient) {
CommunicationIdentityClientBuilder builder = getCommunicationIdentityClient(httpClient);
client = setupClient(builder, "createUserAndTokenSync");
List<CommunicationTokenScope> scopes = Arrays.asList(CommunicationTokenScope.CHAT);
CommunicationUserIdentifierAndToken result = client.createUserAndToken(scopes);
assertNotNull(result.getUser().getId());
assertNotNull(result.getUserToken());
assertFalse(result.getUser().getId().isEmpty());
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void createUserAndTokenWithResponse(HttpClient httpClient) {
CommunicationIdentityClientBuilder builder = getCommunicationIdentityClient(httpClient);
client = setupClient(builder, "createUserAndTokenWithResponseSync");
List<CommunicationTokenScope> scopes = Arrays.asList(CommunicationTokenScope.CHAT);
Response<CommunicationUserIdentifierAndToken> response =
client.createUserAndTokenWithResponse(scopes, Context.NONE);
CommunicationUserIdentifierAndToken result = response.getValue();
assertEquals(201, response.getStatusCode());
assertNotNull(result.getUser().getId());
assertNotNull(result.getUserToken());
assertFalse(result.getUser().getId().isEmpty());
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void createUserAndTokenWithResponseNullContext(HttpClient httpClient) {
CommunicationIdentityClientBuilder builder = getCommunicationIdentityClient(httpClient);
client = setupClient(builder, "createUserAndTokenWithResponseSync");
List<CommunicationTokenScope> scopes = Arrays.asList(CommunicationTokenScope.CHAT);
Response<CommunicationUserIdentifierAndToken> response =
client.createUserAndTokenWithResponse(scopes, null);
CommunicationUserIdentifierAndToken result = response.getValue();
assertEquals(201, response.getStatusCode());
assertNotNull(result.getUser().getId());
assertNotNull(result.getUserToken());
assertFalse(result.getUser().getId().isEmpty());
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void deleteUser(HttpClient httpClient) {
CommunicationIdentityClientBuilder builder = getCommunicationIdentityClient(httpClient);
client = setupClient(builder, "deleteUserSync");
CommunicationUserIdentifier communicationUser = client.createUser();
assertNotNull(communicationUser.getId());
client.deleteUser(communicationUser);
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void deleteUserWithResponse(HttpClient httpClient) {
CommunicationIdentityClientBuilder builder = getCommunicationIdentityClient(httpClient);
client = setupClient(builder, "deleteUserWithResponseSync");
CommunicationUserIdentifier communicationUser = client.createUser();
Response<Void> response = client.deleteUserWithResponse(communicationUser, Context.NONE);
assertEquals(204, response.getStatusCode(), "Expect status code to be 204");
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void revokeToken(HttpClient httpClient) {
CommunicationIdentityClientBuilder builder = getCommunicationIdentityClient(httpClient);
client = setupClient(builder, "revokeTokenSync");
CommunicationUserIdentifier communicationUser = client.createUser();
assertNotNull(communicationUser.getId());
List<CommunicationTokenScope> scopes = Arrays.asList(CommunicationTokenScope.CHAT);
client.getToken(communicationUser, scopes);
client.revokeTokens(communicationUser);
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void revokeTokenWithResponse(HttpClient httpClient) {
CommunicationIdentityClientBuilder builder = getCommunicationIdentityClient(httpClient);
client = setupClient(builder, "revokeTokenWithResponseSync");
CommunicationUserIdentifier communicationUser = client.createUser();
List<CommunicationTokenScope> scopes = Arrays.asList(CommunicationTokenScope.CHAT);
client.getToken(communicationUser, scopes);
Response<Void> response = client.revokeTokensWithResponse(communicationUser, Context.NONE);
assertEquals(204, response.getStatusCode(), "Expect status code to be 204");
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void revokeTokenWithResponseNullContext(HttpClient httpClient) {
CommunicationIdentityClientBuilder builder = getCommunicationIdentityClient(httpClient);
client = setupClient(builder, "revokeTokenWithResponseSync");
CommunicationUserIdentifier communicationUser = client.createUser();
List<CommunicationTokenScope> scopes = Arrays.asList(CommunicationTokenScope.CHAT);
client.getToken(communicationUser, scopes);
Response<Void> response = client.revokeTokensWithResponse(communicationUser, null);
assertEquals(204, response.getStatusCode(), "Expect status code to be 204");
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void getToken(HttpClient httpClient) {
CommunicationIdentityClientBuilder builder = getCommunicationIdentityClient(httpClient);
client = setupClient(builder, "getTokenSync");
CommunicationUserIdentifier communicationUser = client.createUser();
List<CommunicationTokenScope> scopes = Arrays.asList(CommunicationTokenScope.CHAT);
AccessToken issuedToken = client.getToken(communicationUser, scopes);
assertNotNull(issuedToken.getToken());
assertFalse(issuedToken.getToken().isEmpty());
assertNotNull(issuedToken.getExpiresAt());
assertFalse(issuedToken.getExpiresAt().toString().isEmpty());
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void getTokenWithResponse(HttpClient httpClient) {
CommunicationIdentityClientBuilder builder = getCommunicationIdentityClient(httpClient);
client = setupClient(builder, "getTokenWithResponseSync");
CommunicationUserIdentifier communicationUser = client.createUser();
List<CommunicationTokenScope> scopes = Arrays.asList(CommunicationTokenScope.CHAT);
Response<AccessToken> issuedTokenResponse = client.getTokenWithResponse(communicationUser, scopes, Context.NONE);
AccessToken issuedToken = issuedTokenResponse.getValue();
assertEquals(200, issuedTokenResponse.getStatusCode(), "Expect status code to be 200");
assertNotNull(issuedToken.getToken());
assertFalse(issuedToken.getToken().isEmpty());
assertNotNull(issuedToken.getExpiresAt());
assertFalse(issuedToken.getExpiresAt().toString().isEmpty());
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void getTokenWithResponseNullContext(HttpClient httpClient) {
CommunicationIdentityClientBuilder builder = getCommunicationIdentityClient(httpClient);
client = setupClient(builder, "getTokenWithResponseSync");
CommunicationUserIdentifier communicationUser = client.createUser();
List<CommunicationTokenScope> scopes = Arrays.asList(CommunicationTokenScope.CHAT);
Response<AccessToken> issuedTokenResponse = client.getTokenWithResponse(communicationUser, scopes, null);
AccessToken issuedToken = issuedTokenResponse.getValue();
assertEquals(200, issuedTokenResponse.getStatusCode(), "Expect status code to be 200");
assertNotNull(issuedToken.getToken());
assertFalse(issuedToken.getToken().isEmpty());
assertNotNull(issuedToken.getExpiresAt());
assertFalse(issuedToken.getExpiresAt().toString().isEmpty());
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void createUserWithResponseUsingManagedIdentity(HttpClient httpClient) {
CommunicationIdentityClientBuilder builder = getCommunicationIdentityClientBuilderUsingManagedIdentity(httpClient);
client = setupClient(builder, "createUserWithResponseUsingManagedIdentitySync");
Response<CommunicationUserIdentifier> response = client.createUserWithResponse(Context.NONE);
assertNotNull(response.getValue().getId());
assertFalse(response.getValue().getId().isEmpty());
assertEquals(201, response.getStatusCode(), "Expect status code to be 201");
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void deleteUserUsingManagedIdentity(HttpClient httpClient) {
CommunicationIdentityClientBuilder builder = getCommunicationIdentityClientBuilderUsingManagedIdentity(httpClient);
client = setupClient(builder, "deleteUserUsingManagedIdentitySync");
CommunicationUserIdentifier communicationUser = client.createUser();
assertNotNull(communicationUser.getId());
client.deleteUser(communicationUser);
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void deleteUserWithResponseUsingManagedIdentity(HttpClient httpClient) {
CommunicationIdentityClientBuilder builder = getCommunicationIdentityClientBuilderUsingManagedIdentity(httpClient);
client = setupClient(builder, "deleteUserWithResponseUsingManagedIdentitySync");
CommunicationUserIdentifier communicationUser = client.createUser();
Response<Void> response = client.deleteUserWithResponse(communicationUser, Context.NONE);
assertEquals(204, response.getStatusCode(), "Expect status code to be 204");
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void revokeTokenUsingManagedIdentity(HttpClient httpClient) {
CommunicationIdentityClientBuilder builder = getCommunicationIdentityClientBuilderUsingManagedIdentity(httpClient);
client = setupClient(builder, "revokeTokenUsingManagedIdentitySync");
CommunicationUserIdentifier communicationUser = client.createUser();
assertNotNull(communicationUser.getId());
List<CommunicationTokenScope> scopes = Arrays.asList(CommunicationTokenScope.CHAT);
client.getToken(communicationUser, scopes);
client.revokeTokens(communicationUser);
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void revokeTokenWithResponseUsingManagedIdentity(HttpClient httpClient) {
CommunicationIdentityClientBuilder builder = getCommunicationIdentityClientBuilderUsingManagedIdentity(httpClient);
client = setupClient(builder, "revokeTokenWithResponseUsingManagedIdentitySync");
CommunicationUserIdentifier communicationUser = client.createUser();
List<CommunicationTokenScope> scopes = Arrays.asList(CommunicationTokenScope.CHAT);
client.getToken(communicationUser, scopes);
Response<Void> response = client.revokeTokensWithResponse(communicationUser, Context.NONE);
assertEquals(204, response.getStatusCode(), "Expect status code to be 204");
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void getTokenUsingManagedIdentity(HttpClient httpClient) {
CommunicationIdentityClientBuilder builder = getCommunicationIdentityClientBuilderUsingManagedIdentity(httpClient);
client = setupClient(builder, "getTokenUsingManagedIdentitySync");
CommunicationUserIdentifier communicationUser = client.createUser();
List<CommunicationTokenScope> scopes = Arrays.asList(CommunicationTokenScope.CHAT);
AccessToken issuedToken = client.getToken(communicationUser, scopes);
assertNotNull(issuedToken.getToken());
assertFalse(issuedToken.getToken().isEmpty());
assertNotNull(issuedToken.getExpiresAt());
assertFalse(issuedToken.getExpiresAt().toString().isEmpty());
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void getTokenWithResponseUsingManagedIdentity(HttpClient httpClient) {
CommunicationIdentityClientBuilder builder = getCommunicationIdentityClientBuilderUsingManagedIdentity(httpClient);
client = setupClient(builder, "getTokenWithResponseUsingManagedIdentitySync");
CommunicationUserIdentifier communicationUser = client.createUser();
List<CommunicationTokenScope> scopes = Arrays.asList(CommunicationTokenScope.CHAT);
Response<AccessToken> response = client.getTokenWithResponse(communicationUser, scopes, Context.NONE);
AccessToken issuedToken = response.getValue();
assertEquals(200, response.getStatusCode(), "Expect status code to be 200");
assertNotNull(issuedToken.getToken());
assertFalse(issuedToken.getToken().isEmpty());
assertNotNull(issuedToken.getExpiresAt());
assertFalse(issuedToken.getExpiresAt().toString().isEmpty());
}
private CommunicationIdentityClient setupClient(CommunicationIdentityClientBuilder builder, String testName) {
return addLoggingPolicy(builder, testName).buildClient();
}
} | class CommunicationIdentityTests extends CommunicationIdentityClientTestBase {
private CommunicationIdentityClient client;
@Override
protected void beforeTest() {
super.beforeTest();
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void createIdentityClientUsingManagedIdentity(HttpClient httpClient) {
CommunicationIdentityClientBuilder builder = createClientBuilderUsingManagedIdentity(httpClient);
client = setupClient(builder, "createIdentityClientUsingManagedIdentitySync");
assertNotNull(client);
CommunicationUserIdentifier communicationUser = client.createUser();
assertNotNull(communicationUser.getId());
assertFalse(communicationUser.getId().isEmpty());
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void createIdentityClientUsingConnectionString(HttpClient httpClient) {
CommunicationIdentityClientBuilder builder = createClientBuilderUsingConnectionString(httpClient);
client = setupClient(builder, "createIdentityClientUsingConnectionStringSync");
assertNotNull(client);
CommunicationUserIdentifier communicationUser = client.createUser();
assertNotNull(communicationUser.getId());
assertFalse(communicationUser.getId().isEmpty());
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void createUser(HttpClient httpClient) {
CommunicationIdentityClientBuilder builder = createClientBuilder(httpClient);
client = setupClient(builder, "createUserSync");
CommunicationUserIdentifier communicationUser = client.createUser();
assertNotNull(communicationUser.getId());
assertFalse(communicationUser.getId().isEmpty());
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void createUserWithResponse(HttpClient httpClient) {
CommunicationIdentityClientBuilder builder = createClientBuilder(httpClient);
client = setupClient(builder, "createUserWithResponseSync");
Response<CommunicationUserIdentifier> response = client.createUserWithResponse(Context.NONE);
assertNotNull(response.getValue().getId());
assertFalse(response.getValue().getId().isEmpty());
assertEquals(201, response.getStatusCode(), "Expect status code to be 201");
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void createUserAndToken(HttpClient httpClient) {
CommunicationIdentityClientBuilder builder = createClientBuilder(httpClient);
client = setupClient(builder, "createUserAndTokenSync");
List<CommunicationTokenScope> scopes = Arrays.asList(CommunicationTokenScope.CHAT);
CommunicationUserIdentifierAndToken result = client.createUserAndToken(scopes);
assertNotNull(result.getUser().getId());
assertNotNull(result.getUserToken());
assertFalse(result.getUser().getId().isEmpty());
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void createUserAndTokenWithResponse(HttpClient httpClient) {
CommunicationIdentityClientBuilder builder = createClientBuilder(httpClient);
client = setupClient(builder, "createUserAndTokenWithResponseSync");
List<CommunicationTokenScope> scopes = Arrays.asList(CommunicationTokenScope.CHAT);
Response<CommunicationUserIdentifierAndToken> response =
client.createUserAndTokenWithResponse(scopes, Context.NONE);
CommunicationUserIdentifierAndToken result = response.getValue();
assertEquals(201, response.getStatusCode());
assertNotNull(result.getUser().getId());
assertNotNull(result.getUserToken());
assertFalse(result.getUser().getId().isEmpty());
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void createUserAndTokenWithResponseNullContext(HttpClient httpClient) {
CommunicationIdentityClientBuilder builder = createClientBuilder(httpClient);
client = setupClient(builder, "createUserAndTokenWithResponseSync");
List<CommunicationTokenScope> scopes = Arrays.asList(CommunicationTokenScope.CHAT);
Response<CommunicationUserIdentifierAndToken> response =
client.createUserAndTokenWithResponse(scopes, null);
CommunicationUserIdentifierAndToken result = response.getValue();
assertEquals(201, response.getStatusCode());
assertNotNull(result.getUser().getId());
assertNotNull(result.getUserToken());
assertFalse(result.getUser().getId().isEmpty());
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void deleteUser(HttpClient httpClient) {
CommunicationIdentityClientBuilder builder = createClientBuilder(httpClient);
client = setupClient(builder, "deleteUserSync");
CommunicationUserIdentifier communicationUser = client.createUser();
assertNotNull(communicationUser.getId());
client.deleteUser(communicationUser);
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void deleteUserWithResponse(HttpClient httpClient) {
CommunicationIdentityClientBuilder builder = createClientBuilder(httpClient);
client = setupClient(builder, "deleteUserWithResponseSync");
CommunicationUserIdentifier communicationUser = client.createUser();
Response<Void> response = client.deleteUserWithResponse(communicationUser, Context.NONE);
assertEquals(204, response.getStatusCode(), "Expect status code to be 204");
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void revokeToken(HttpClient httpClient) {
CommunicationIdentityClientBuilder builder = createClientBuilder(httpClient);
client = setupClient(builder, "revokeTokenSync");
CommunicationUserIdentifier communicationUser = client.createUser();
assertNotNull(communicationUser.getId());
List<CommunicationTokenScope> scopes = Arrays.asList(CommunicationTokenScope.CHAT);
client.getToken(communicationUser, scopes);
client.revokeTokens(communicationUser);
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void revokeTokenWithResponse(HttpClient httpClient) {
CommunicationIdentityClientBuilder builder = createClientBuilder(httpClient);
client = setupClient(builder, "revokeTokenWithResponseSync");
CommunicationUserIdentifier communicationUser = client.createUser();
List<CommunicationTokenScope> scopes = Arrays.asList(CommunicationTokenScope.CHAT);
client.getToken(communicationUser, scopes);
Response<Void> response = client.revokeTokensWithResponse(communicationUser, Context.NONE);
assertEquals(204, response.getStatusCode(), "Expect status code to be 204");
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void revokeTokenWithResponseNullContext(HttpClient httpClient) {
CommunicationIdentityClientBuilder builder = createClientBuilder(httpClient);
client = setupClient(builder, "revokeTokenWithResponseSync");
CommunicationUserIdentifier communicationUser = client.createUser();
List<CommunicationTokenScope> scopes = Arrays.asList(CommunicationTokenScope.CHAT);
client.getToken(communicationUser, scopes);
Response<Void> response = client.revokeTokensWithResponse(communicationUser, null);
assertEquals(204, response.getStatusCode(), "Expect status code to be 204");
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void getToken(HttpClient httpClient) {
CommunicationIdentityClientBuilder builder = createClientBuilder(httpClient);
client = setupClient(builder, "getTokenSync");
CommunicationUserIdentifier communicationUser = client.createUser();
List<CommunicationTokenScope> scopes = Arrays.asList(CommunicationTokenScope.CHAT);
AccessToken issuedToken = client.getToken(communicationUser, scopes);
assertNotNull(issuedToken.getToken());
assertFalse(issuedToken.getToken().isEmpty());
assertNotNull(issuedToken.getExpiresAt());
assertFalse(issuedToken.getExpiresAt().toString().isEmpty());
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void getTokenWithResponse(HttpClient httpClient) {
CommunicationIdentityClientBuilder builder = createClientBuilder(httpClient);
client = setupClient(builder, "getTokenWithResponseSync");
CommunicationUserIdentifier communicationUser = client.createUser();
List<CommunicationTokenScope> scopes = Arrays.asList(CommunicationTokenScope.CHAT);
Response<AccessToken> issuedTokenResponse = client.getTokenWithResponse(communicationUser, scopes, Context.NONE);
AccessToken issuedToken = issuedTokenResponse.getValue();
assertEquals(200, issuedTokenResponse.getStatusCode(), "Expect status code to be 200");
assertNotNull(issuedToken.getToken());
assertFalse(issuedToken.getToken().isEmpty());
assertNotNull(issuedToken.getExpiresAt());
assertFalse(issuedToken.getExpiresAt().toString().isEmpty());
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void getTokenWithResponseNullContext(HttpClient httpClient) {
CommunicationIdentityClientBuilder builder = createClientBuilder(httpClient);
client = setupClient(builder, "getTokenWithResponseSync");
CommunicationUserIdentifier communicationUser = client.createUser();
List<CommunicationTokenScope> scopes = Arrays.asList(CommunicationTokenScope.CHAT);
Response<AccessToken> issuedTokenResponse = client.getTokenWithResponse(communicationUser, scopes, null);
AccessToken issuedToken = issuedTokenResponse.getValue();
assertEquals(200, issuedTokenResponse.getStatusCode(), "Expect status code to be 200");
assertNotNull(issuedToken.getToken());
assertFalse(issuedToken.getToken().isEmpty());
assertNotNull(issuedToken.getExpiresAt());
assertFalse(issuedToken.getExpiresAt().toString().isEmpty());
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void createUserWithResponseUsingManagedIdentity(HttpClient httpClient) {
CommunicationIdentityClientBuilder builder = createClientBuilderUsingManagedIdentity(httpClient);
client = setupClient(builder, "createUserWithResponseUsingManagedIdentitySync");
Response<CommunicationUserIdentifier> response = client.createUserWithResponse(Context.NONE);
assertNotNull(response.getValue().getId());
assertFalse(response.getValue().getId().isEmpty());
assertEquals(201, response.getStatusCode(), "Expect status code to be 201");
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void deleteUserUsingManagedIdentity(HttpClient httpClient) {
CommunicationIdentityClientBuilder builder = createClientBuilderUsingManagedIdentity(httpClient);
client = setupClient(builder, "deleteUserUsingManagedIdentitySync");
CommunicationUserIdentifier communicationUser = client.createUser();
assertNotNull(communicationUser.getId());
client.deleteUser(communicationUser);
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void deleteUserWithResponseUsingManagedIdentity(HttpClient httpClient) {
CommunicationIdentityClientBuilder builder = createClientBuilderUsingManagedIdentity(httpClient);
client = setupClient(builder, "deleteUserWithResponseUsingManagedIdentitySync");
CommunicationUserIdentifier communicationUser = client.createUser();
Response<Void> response = client.deleteUserWithResponse(communicationUser, Context.NONE);
assertEquals(204, response.getStatusCode(), "Expect status code to be 204");
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void revokeTokenUsingManagedIdentity(HttpClient httpClient) {
CommunicationIdentityClientBuilder builder = createClientBuilderUsingManagedIdentity(httpClient);
client = setupClient(builder, "revokeTokenUsingManagedIdentitySync");
CommunicationUserIdentifier communicationUser = client.createUser();
assertNotNull(communicationUser.getId());
List<CommunicationTokenScope> scopes = Arrays.asList(CommunicationTokenScope.CHAT);
client.getToken(communicationUser, scopes);
client.revokeTokens(communicationUser);
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void revokeTokenWithResponseUsingManagedIdentity(HttpClient httpClient) {
CommunicationIdentityClientBuilder builder = createClientBuilderUsingManagedIdentity(httpClient);
client = setupClient(builder, "revokeTokenWithResponseUsingManagedIdentitySync");
CommunicationUserIdentifier communicationUser = client.createUser();
List<CommunicationTokenScope> scopes = Arrays.asList(CommunicationTokenScope.CHAT);
client.getToken(communicationUser, scopes);
Response<Void> response = client.revokeTokensWithResponse(communicationUser, Context.NONE);
assertEquals(204, response.getStatusCode(), "Expect status code to be 204");
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void getTokenUsingManagedIdentity(HttpClient httpClient) {
CommunicationIdentityClientBuilder builder = createClientBuilderUsingManagedIdentity(httpClient);
client = setupClient(builder, "getTokenUsingManagedIdentitySync");
CommunicationUserIdentifier communicationUser = client.createUser();
List<CommunicationTokenScope> scopes = Arrays.asList(CommunicationTokenScope.CHAT);
AccessToken issuedToken = client.getToken(communicationUser, scopes);
assertNotNull(issuedToken.getToken());
assertFalse(issuedToken.getToken().isEmpty());
assertNotNull(issuedToken.getExpiresAt());
assertFalse(issuedToken.getExpiresAt().toString().isEmpty());
}
@ParameterizedTest
@MethodSource("com.azure.core.test.TestBase
public void getTokenWithResponseUsingManagedIdentity(HttpClient httpClient) {
CommunicationIdentityClientBuilder builder = createClientBuilderUsingManagedIdentity(httpClient);
client = setupClient(builder, "getTokenWithResponseUsingManagedIdentitySync");
CommunicationUserIdentifier communicationUser = client.createUser();
List<CommunicationTokenScope> scopes = Arrays.asList(CommunicationTokenScope.CHAT);
Response<AccessToken> response = client.getTokenWithResponse(communicationUser, scopes, Context.NONE);
AccessToken issuedToken = response.getValue();
assertEquals(200, response.getStatusCode(), "Expect status code to be 200");
assertNotNull(issuedToken.getToken());
assertFalse(issuedToken.getToken().isEmpty());
assertNotNull(issuedToken.getExpiresAt());
assertFalse(issuedToken.getExpiresAt().toString().isEmpty());
}
private CommunicationIdentityClient setupClient(CommunicationIdentityClientBuilder builder, String testName) {
return addLoggingPolicy(builder, testName).buildClient();
}
} |
Include the root exception when creating a new exception instance. ```suggestion throw logger.logExceptionAsWarning(new IllegalArgumentException("'endpoint' must be a valid URL", ex)); ``` | public EventGridPublisherClientBuilder endpoint(String endpoint) {
try {
new URL(Objects.requireNonNull(endpoint, "'endpoint' cannot be null."));
} catch (MalformedURLException ex) {
throw logger.logExceptionAsWarning(new IllegalArgumentException("'endpoint' must be a valid URL"));
}
this.endpoint = endpoint;
return this;
} | throw logger.logExceptionAsWarning(new IllegalArgumentException("'endpoint' must be a valid URL")); | public EventGridPublisherClientBuilder endpoint(String endpoint) {
try {
new URL(Objects.requireNonNull(endpoint, "'endpoint' cannot be null."));
} catch (MalformedURLException ex) {
throw logger.logExceptionAsWarning(new IllegalArgumentException("'endpoint' must be a valid URL", ex));
}
this.endpoint = endpoint;
return this;
} | class EventGridPublisherClientBuilder {
private static final String AEG_SAS_KEY = "aeg-sas-key";
private static final String AEG_SAS_TOKEN = "aeg-sas-token";
private static final String EVENTGRID_PROPERTIES = "azure-messaging-eventgrid.properties";
private static final String NAME = "name";
private static final String VERSION = "version";
private final String clientName;
private final String clientVersion;
private final ClientLogger logger = new ClientLogger(EventGridPublisherClientBuilder.class);
private final List<HttpPipelinePolicy> policies = new ArrayList<>();
private ClientOptions clientOptions;
private Configuration configuration;
private AzureKeyCredential keyCredential;
private AzureSasCredential sasToken;
private EventGridServiceVersion serviceVersion;
private String endpoint;
private HttpClient httpClient;
private HttpLogOptions httpLogOptions;
private HttpPipeline httpPipeline;
private RetryPolicy retryPolicy;
/**
* Construct a new instance with default building settings. The endpoint and one credential method must be set
* in order for the client to be built.
*/
public EventGridPublisherClientBuilder() {
this.httpLogOptions = new HttpLogOptions();
Map<String, String> properties = CoreUtils.getProperties(EVENTGRID_PROPERTIES);
clientName = properties.getOrDefault(NAME, "UnknownName");
clientVersion = properties.getOrDefault(VERSION, "UnknownVersion");
}
/**
* Build a publisher client with asynchronous publishing methods and the current settings. An endpoint must be set,
* and either a pipeline with correct authentication must be set, or a credential must be set in the form of
* an {@link AzureSasCredential} or a {@link AzureKeyCredential} at the respective methods.
* All other settings have defaults and are optional.
* @return a publisher client with asynchronous publishing methods.
* @throws NullPointerException if {@code endpoint} is null.
*/
private <T> EventGridPublisherAsyncClient<T> buildAsyncClient(Class<T> eventClass) {
Objects.requireNonNull(endpoint, "'endpoint' is required and can not be null.");
EventGridServiceVersion buildServiceVersion = serviceVersion == null
? EventGridServiceVersion.getLatest()
: serviceVersion;
if (httpPipeline != null) {
return new EventGridPublisherAsyncClient<T>(httpPipeline, endpoint, buildServiceVersion, eventClass);
}
Configuration buildConfiguration = (configuration == null)
? Configuration.getGlobalConfiguration()
: configuration;
final List<HttpPipelinePolicy> httpPipelinePolicies = new ArrayList<>();
String applicationId =
clientOptions == null ? httpLogOptions.getApplicationId() : clientOptions.getApplicationId();
httpPipelinePolicies.add(new UserAgentPolicy(applicationId, clientName, clientVersion,
buildConfiguration));
httpPipelinePolicies.add(new RequestIdPolicy());
HttpPolicyProviders.addBeforeRetryPolicies(httpPipelinePolicies);
httpPipelinePolicies.add(retryPolicy == null ? new RetryPolicy() : retryPolicy);
httpPipelinePolicies.add(new AddDatePolicy());
if (sasToken != null) {
httpPipelinePolicies.add((context, next) -> {
context.getHttpRequest().getHeaders().set(AEG_SAS_TOKEN, sasToken.getSignature());
return next.process();
});
} else {
httpPipelinePolicies.add(new AzureKeyCredentialPolicy(AEG_SAS_KEY, keyCredential));
}
httpPipelinePolicies.addAll(policies);
if (clientOptions != null) {
List<HttpHeader> httpHeaderList = new ArrayList<>();
clientOptions.getHeaders().forEach(header ->
httpHeaderList.add(new HttpHeader(header.getName(), header.getValue())));
policies.add(new AddHeadersPolicy(new HttpHeaders(httpHeaderList)));
}
HttpPolicyProviders.addAfterRetryPolicies(httpPipelinePolicies);
if (TracerProxy.isTracingEnabled()) {
httpPipelinePolicies.add(new CloudEventTracingPipelinePolicy());
}
httpPipelinePolicies.add(new HttpLoggingPolicy(httpLogOptions));
HttpPipeline buildPipeline = new HttpPipelineBuilder()
.httpClient(httpClient)
.policies(httpPipelinePolicies.toArray(new HttpPipelinePolicy[0]))
.build();
return new EventGridPublisherAsyncClient<T>(buildPipeline, endpoint, buildServiceVersion, eventClass);
}
/**
* Build a publisher client with synchronous publishing methods and the current settings. Endpoint and a credential
* must be set (either keyCredential or sharedAccessSignatureCredential), all other settings have defaults and/or are optional.
* Note that currently the asynchronous client created by the method above is the recommended version for higher
* performance, as the synchronous client simply blocks on the same asynchronous calls.
* @return a publisher client with synchronous publishing methods.
*/
private <T> EventGridPublisherClient<T> buildClient(Class<T> eventClass) {
return new EventGridPublisherClient<T>(buildAsyncClient(eventClass));
}
/**
* Add a policy to the current pipeline.
* @param httpPipelinePolicy the policy to add.
*
* @return the builder itself.
*/
public EventGridPublisherClientBuilder addPolicy(HttpPipelinePolicy httpPipelinePolicy) {
this.policies.add(Objects.requireNonNull(httpPipelinePolicy));
return this;
}
/**
* Add a custom retry policy to the pipeline. The default is {@link RetryPolicy
* @param retryPolicy the retry policy to add.
*
* @return the builder itself.
*/
public EventGridPublisherClientBuilder retryPolicy(RetryPolicy retryPolicy) {
this.retryPolicy = retryPolicy;
return this;
}
/**
* Sets the {@link ClientOptions} which enables various options to be set on the client. For example setting an
* {@code applicationId} using {@link ClientOptions
* the {@link UserAgentPolicy} for telemetry/monitoring purposes.
*
* <p>More About <a href="https:
*
* @param clientOptions the {@link ClientOptions} to be set on the client.
* @return The updated EventGridPublisherClientBuilder object.
*/
public EventGridPublisherClientBuilder clientOptions(ClientOptions clientOptions) {
this.clientOptions = clientOptions;
return this;
}
/**
* Set the configuration of HTTP and Azure values. A default is already set.
* @param configuration the configuration to use.
*
* @return the builder itself.
*/
public EventGridPublisherClientBuilder configuration(Configuration configuration) {
this.configuration = configuration;
return this;
}
/**
* Set the domain or topic authentication using a key obtained from Azure CLI, Azure portal, or the ARM SDKs.
* @param credential the key credential to use to authorize the publisher client.
*
* @return the builder itself.
*/
public EventGridPublisherClientBuilder credential(AzureKeyCredential credential) {
this.keyCredential = credential;
return this;
}
/**
* Set the domain or topic authentication using an already obtained Shared Access Signature token.
* @param credential the token credential to use.
*
* @return the builder itself.
*/
public EventGridPublisherClientBuilder credential(AzureSasCredential credential) {
this.sasToken = credential;
return this;
}
/**
* Set the domain or topic endpoint. This is the address to publish events to.
* It must be the full url of the endpoint instead of just the hostname.
* @param endpoint the endpoint as a url.
*
* @return the builder itself.
* @throws NullPointerException if {@code endpoint} is null.
* @throws IllegalArgumentException if {@code endpoint} cannot be parsed into a valid URL.
*/
/**
* Set the HTTP Client that sends requests. Will use default if not set.
* @param httpClient the HTTP Client to use.
*
* @return the builder itself.
*/
public EventGridPublisherClientBuilder httpClient(HttpClient httpClient) {
if (this.httpClient != null && httpClient == null) {
logger.info("Http client is set to null when it was not previously null");
}
this.httpClient = httpClient;
return this;
}
/**
* Configure the logging of the HTTP requests and pipeline.
* @param httpLogOptions the log options to use.
*
* @return the builder itself.
*/
public EventGridPublisherClientBuilder httpLogOptions(HttpLogOptions httpLogOptions) {
this.httpLogOptions = httpLogOptions;
return this;
}
/**
* Set the HTTP pipeline to use when sending calls to the service.
* @param httpPipeline the pipeline to use.
*
* @return the builder itself.
*/
public EventGridPublisherClientBuilder pipeline(HttpPipeline httpPipeline) {
if (this.httpPipeline != null && httpPipeline == null) {
logger.info("Http client is set to null when it was not previously null");
}
this.httpPipeline = httpPipeline;
return this;
}
/**
* Set the service version to use for requests to the event grid service. See {@link EventGridServiceVersion} for
* more information about possible service versions.
* @param serviceVersion the service version to set. By default this will use the latest available version.
*
* @return the builder itself
*/
public EventGridPublisherClientBuilder serviceVersion(EventGridServiceVersion serviceVersion) {
this.serviceVersion = serviceVersion;
return this;
}
/**
* Build a {@link CloudEvent} publisher client with asynchronous publishing methods and the current settings. An endpoint must be set,
* and either a pipeline with correct authentication must be set, or a credential must be set in the form of
* an {@link AzureSasCredential} or a {@link AzureKeyCredential} at the respective methods.
* All other settings have defaults and are optional.
* @return a publisher client with asynchronous publishing methods.
*/
public EventGridPublisherAsyncClient<CloudEvent> buildCloudEventPublisherAsyncClient() {
return this.buildAsyncClient(CloudEvent.class);
}
/**
* Build an {@link EventGridEvent} publisher client with asynchronous publishing methods and the current settings. An endpoint must be set,
* and either a pipeline with correct authentication must be set, or a credential must be set in the form of
* an {@link AzureSasCredential} or a {@link AzureKeyCredential} at the respective methods.
* All other settings have defaults and are optional.
* @return a publisher client with asynchronous publishing methods.
*/
public EventGridPublisherAsyncClient<EventGridEvent> buildEventGridEventPublisherAsyncClient() {
return this.buildAsyncClient(EventGridEvent.class);
}
/**
* Build a custom event publisher client with asynchronous publishing methods and the current settings. An endpoint must be set,
* and either a pipeline with correct authentication must be set, or a credential must be set in the form of
* an {@link AzureSasCredential} or a {@link AzureKeyCredential} at the respective methods.
* All other settings have defaults and are optional.
* @return a publisher client with asynchronous publishing methods.
*/
public EventGridPublisherAsyncClient<BinaryData> buildCustomEventPublisherAsyncClient() {
return this.buildAsyncClient(BinaryData.class);
}
/**
* Build a {@link CloudEvent} publisher client with synchronous publishing methods and the current settings. Endpoint and a credential
* must be set (either keyCredential or sharedAccessSignatureCredential), all other settings have defaults and/or are optional.
* @return a publisher client with synchronous publishing methods.
*/
public EventGridPublisherClient<CloudEvent> buildCloudEventPublisherClient() {
return this.buildClient(CloudEvent.class);
}
/**
* Build an {@link EventGridEvent} publisher client with synchronous publishing methods and the current settings. Endpoint and a credential
* must be set (either keyCredential or sharedAccessSignatureCredential), all other settings have defaults and/or are optional.
* @return a publisher client with synchronous publishing methods.
*/
public EventGridPublisherClient<EventGridEvent> buildEventGridEventPublisherClient() {
return this.buildClient(EventGridEvent.class);
}
/**
* Build a custom event publisher client with synchronous publishing methods and the current settings. Endpoint and a credential
* must be set (either keyCredential or sharedAccessSignatureCredential), all other settings have defaults and/or are optional.
* @return a publisher client with synchronous publishing methods.
*/
public EventGridPublisherClient<BinaryData> buildCustomEventPublisherClient() {
return this.buildClient(BinaryData.class);
}
} | class EventGridPublisherClientBuilder {
private static final String AEG_SAS_KEY = "aeg-sas-key";
private static final String AEG_SAS_TOKEN = "aeg-sas-token";
private static final String EVENTGRID_PROPERTIES = "azure-messaging-eventgrid.properties";
private static final String NAME = "name";
private static final String VERSION = "version";
private final String clientName;
private final String clientVersion;
private final ClientLogger logger = new ClientLogger(EventGridPublisherClientBuilder.class);
private final List<HttpPipelinePolicy> policies = new ArrayList<>();
private ClientOptions clientOptions;
private Configuration configuration;
private AzureKeyCredential keyCredential;
private AzureSasCredential sasToken;
private EventGridServiceVersion serviceVersion;
private String endpoint;
private HttpClient httpClient;
private HttpLogOptions httpLogOptions;
private HttpPipeline httpPipeline;
private RetryPolicy retryPolicy;
/**
* Construct a new instance with default building settings. The endpoint and one credential method must be set
* in order for the client to be built.
*/
public EventGridPublisherClientBuilder() {
this.httpLogOptions = new HttpLogOptions();
Map<String, String> properties = CoreUtils.getProperties(EVENTGRID_PROPERTIES);
clientName = properties.getOrDefault(NAME, "UnknownName");
clientVersion = properties.getOrDefault(VERSION, "UnknownVersion");
}
/**
* Build a publisher client with asynchronous publishing methods and the current settings. An endpoint must be set,
* and either a pipeline with correct authentication must be set, or a credential must be set in the form of
* an {@link AzureSasCredential} or a {@link AzureKeyCredential} at the respective methods.
* All other settings have defaults and are optional.
* @return a publisher client with asynchronous publishing methods.
* @throws NullPointerException if {@code endpoint} is null.
*/
private <T> EventGridPublisherAsyncClient<T> buildAsyncClient(Class<T> eventClass) {
Objects.requireNonNull(endpoint, "'endpoint' is required and can not be null.");
EventGridServiceVersion buildServiceVersion = serviceVersion == null
? EventGridServiceVersion.getLatest()
: serviceVersion;
if (httpPipeline != null) {
return new EventGridPublisherAsyncClient<T>(httpPipeline, endpoint, buildServiceVersion, eventClass);
}
Configuration buildConfiguration = (configuration == null)
? Configuration.getGlobalConfiguration()
: configuration;
final List<HttpPipelinePolicy> httpPipelinePolicies = new ArrayList<>();
String applicationId =
clientOptions == null ? httpLogOptions.getApplicationId() : clientOptions.getApplicationId();
httpPipelinePolicies.add(new UserAgentPolicy(applicationId, clientName, clientVersion,
buildConfiguration));
httpPipelinePolicies.add(new RequestIdPolicy());
HttpPolicyProviders.addBeforeRetryPolicies(httpPipelinePolicies);
httpPipelinePolicies.add(retryPolicy == null ? new RetryPolicy() : retryPolicy);
httpPipelinePolicies.add(new AddDatePolicy());
if (sasToken != null) {
httpPipelinePolicies.add((context, next) -> {
context.getHttpRequest().getHeaders().set(AEG_SAS_TOKEN, sasToken.getSignature());
return next.process();
});
} else {
httpPipelinePolicies.add(new AzureKeyCredentialPolicy(AEG_SAS_KEY, keyCredential));
}
httpPipelinePolicies.addAll(policies);
if (clientOptions != null) {
List<HttpHeader> httpHeaderList = new ArrayList<>();
clientOptions.getHeaders().forEach(header ->
httpHeaderList.add(new HttpHeader(header.getName(), header.getValue())));
policies.add(new AddHeadersPolicy(new HttpHeaders(httpHeaderList)));
}
HttpPolicyProviders.addAfterRetryPolicies(httpPipelinePolicies);
if (TracerProxy.isTracingEnabled()) {
httpPipelinePolicies.add(new CloudEventTracingPipelinePolicy());
}
httpPipelinePolicies.add(new HttpLoggingPolicy(httpLogOptions));
HttpPipeline buildPipeline = new HttpPipelineBuilder()
.httpClient(httpClient)
.policies(httpPipelinePolicies.toArray(new HttpPipelinePolicy[0]))
.build();
return new EventGridPublisherAsyncClient<T>(buildPipeline, endpoint, buildServiceVersion, eventClass);
}
/**
* Build a publisher client with synchronous publishing methods and the current settings. Endpoint and a credential
* must be set (either keyCredential or sharedAccessSignatureCredential), all other settings have defaults and/or are optional.
* Note that currently the asynchronous client created by the method above is the recommended version for higher
* performance, as the synchronous client simply blocks on the same asynchronous calls.
* @return a publisher client with synchronous publishing methods.
*/
private <T> EventGridPublisherClient<T> buildClient(Class<T> eventClass) {
return new EventGridPublisherClient<T>(buildAsyncClient(eventClass));
}
/**
* Add a policy to the current pipeline.
* @param httpPipelinePolicy the policy to add.
*
* @return the builder itself.
*/
public EventGridPublisherClientBuilder addPolicy(HttpPipelinePolicy httpPipelinePolicy) {
this.policies.add(Objects.requireNonNull(httpPipelinePolicy));
return this;
}
/**
* Add a custom retry policy to the pipeline. The default is {@link RetryPolicy
* @param retryPolicy the retry policy to add.
*
* @return the builder itself.
*/
public EventGridPublisherClientBuilder retryPolicy(RetryPolicy retryPolicy) {
this.retryPolicy = retryPolicy;
return this;
}
/**
* Sets the {@link ClientOptions} which enables various options to be set on the client. For example setting an
* {@code applicationId} using {@link ClientOptions
* the {@link UserAgentPolicy} for telemetry/monitoring purposes.
*
* <p>More About <a href="https:
*
* @param clientOptions the {@link ClientOptions} to be set on the client.
* @return The updated EventGridPublisherClientBuilder object.
*/
public EventGridPublisherClientBuilder clientOptions(ClientOptions clientOptions) {
this.clientOptions = clientOptions;
return this;
}
/**
* Set the configuration of HTTP and Azure values. A default is already set.
* @param configuration the configuration to use.
*
* @return the builder itself.
*/
public EventGridPublisherClientBuilder configuration(Configuration configuration) {
this.configuration = configuration;
return this;
}
/**
* Set the domain or topic authentication using a key obtained from Azure CLI, Azure portal, or the ARM SDKs.
* @param credential the key credential to use to authorize the publisher client.
*
* @return the builder itself.
*/
public EventGridPublisherClientBuilder credential(AzureKeyCredential credential) {
this.keyCredential = credential;
return this;
}
/**
* Set the domain or topic authentication using an already obtained Shared Access Signature token.
* @param credential the token credential to use.
*
* @return the builder itself.
*/
public EventGridPublisherClientBuilder credential(AzureSasCredential credential) {
this.sasToken = credential;
return this;
}
/**
* Set the domain or topic endpoint. This is the address to publish events to.
* It must be the full url of the endpoint instead of just the hostname.
* @param endpoint the endpoint as a url.
*
* @return the builder itself.
* @throws NullPointerException if {@code endpoint} is null.
* @throws IllegalArgumentException if {@code endpoint} cannot be parsed into a valid URL.
*/
/**
* Set the HTTP Client that sends requests. Will use default if not set.
* @param httpClient the HTTP Client to use.
*
* @return the builder itself.
*/
public EventGridPublisherClientBuilder httpClient(HttpClient httpClient) {
if (this.httpClient != null && httpClient == null) {
logger.info("Http client is set to null when it was not previously null");
}
this.httpClient = httpClient;
return this;
}
/**
* Configure the logging of the HTTP requests and pipeline.
* @param httpLogOptions the log options to use.
*
* @return the builder itself.
*/
public EventGridPublisherClientBuilder httpLogOptions(HttpLogOptions httpLogOptions) {
this.httpLogOptions = httpLogOptions;
return this;
}
/**
* Set the HTTP pipeline to use when sending calls to the service.
* @param httpPipeline the pipeline to use.
*
* @return the builder itself.
*/
public EventGridPublisherClientBuilder pipeline(HttpPipeline httpPipeline) {
if (this.httpPipeline != null && httpPipeline == null) {
logger.info("Http client is set to null when it was not previously null");
}
this.httpPipeline = httpPipeline;
return this;
}
/**
* Set the service version to use for requests to the event grid service. See {@link EventGridServiceVersion} for
* more information about possible service versions.
* @param serviceVersion the service version to set. By default this will use the latest available version.
*
* @return the builder itself
*/
public EventGridPublisherClientBuilder serviceVersion(EventGridServiceVersion serviceVersion) {
this.serviceVersion = serviceVersion;
return this;
}
/**
* Build a {@link CloudEvent} publisher client with asynchronous publishing methods and the current settings. An endpoint must be set,
* and either a pipeline with correct authentication must be set, or a credential must be set in the form of
* an {@link AzureSasCredential} or a {@link AzureKeyCredential} at the respective methods.
* All other settings have defaults and are optional.
* @return a publisher client with asynchronous publishing methods.
*/
public EventGridPublisherAsyncClient<CloudEvent> buildCloudEventPublisherAsyncClient() {
return this.buildAsyncClient(CloudEvent.class);
}
/**
* Build an {@link EventGridEvent} publisher client with asynchronous publishing methods and the current settings. An endpoint must be set,
* and either a pipeline with correct authentication must be set, or a credential must be set in the form of
* an {@link AzureSasCredential} or a {@link AzureKeyCredential} at the respective methods.
* All other settings have defaults and are optional.
* @return a publisher client with asynchronous publishing methods.
*/
public EventGridPublisherAsyncClient<EventGridEvent> buildEventGridEventPublisherAsyncClient() {
return this.buildAsyncClient(EventGridEvent.class);
}
/**
* Build a custom event publisher client with asynchronous publishing methods and the current settings. An endpoint must be set,
* and either a pipeline with correct authentication must be set, or a credential must be set in the form of
* an {@link AzureSasCredential} or a {@link AzureKeyCredential} at the respective methods.
* All other settings have defaults and are optional.
* @return a publisher client with asynchronous publishing methods.
*/
public EventGridPublisherAsyncClient<BinaryData> buildCustomEventPublisherAsyncClient() {
return this.buildAsyncClient(BinaryData.class);
}
/**
* Build a {@link CloudEvent} publisher client with synchronous publishing methods and the current settings. Endpoint and a credential
* must be set (either keyCredential or sharedAccessSignatureCredential), all other settings have defaults and/or are optional.
* @return a publisher client with synchronous publishing methods.
*/
public EventGridPublisherClient<CloudEvent> buildCloudEventPublisherClient() {
return this.buildClient(CloudEvent.class);
}
/**
* Build an {@link EventGridEvent} publisher client with synchronous publishing methods and the current settings. Endpoint and a credential
* must be set (either keyCredential or sharedAccessSignatureCredential), all other settings have defaults and/or are optional.
* @return a publisher client with synchronous publishing methods.
*/
public EventGridPublisherClient<EventGridEvent> buildEventGridEventPublisherClient() {
return this.buildClient(EventGridEvent.class);
}
/**
* Build a custom event publisher client with synchronous publishing methods and the current settings. Endpoint and a credential
* must be set (either keyCredential or sharedAccessSignatureCredential), all other settings have defaults and/or are optional.
* @return a publisher client with synchronous publishing methods.
*/
public EventGridPublisherClient<BinaryData> buildCustomEventPublisherClient() {
return this.buildClient(BinaryData.class);
}
} |
Currently use raw REST API to approve the connection. Later should be switched to fluent API. | public void testPrivateEndpoint() {
String saName = generateRandomResourceName("sa", 10);
String vnName = generateRandomResourceName("vn", 10);
String subnetName = "default";
String peName = generateRandomResourceName("pe", 10);
String peName2 = generateRandomResourceName("pe", 10);
String pecName = generateRandomResourceName("pec", 10);
Region region = Region.US_EAST;
StorageAccount storageAccount = azureResourceManager.storageAccounts().define(saName)
.withRegion(region)
.withNewResourceGroup(rgName)
.create();
Network network = azureResourceManager.networks().define(vnName)
.withRegion(region)
.withExistingResourceGroup(rgName)
.withAddressSpace("10.0.0.0/28")
.defineSubnet("default")
.withAddressPrefix("10.0.0.0/28")
.disableNetworkPoliciesOnPrivateEndpoint()
.attach()
.create();
PrivateEndpoint privateEndpoint = azureResourceManager.privateEndpoints().define(peName)
.withRegion(region)
.withExistingResourceGroup(rgName)
.withSubnet(network.subnets().get(subnetName))
.definePrivateLinkServiceConnection(pecName)
.withResource(storageAccount)
.withSubResource(PrivateLinkSubResourceName.STORAGE_BLOB)
.withManualApproval("request message")
.attach()
.create();
Assertions.assertNotNull(privateEndpoint.subnet());
Assertions.assertEquals(network.subnets().get(subnetName).innerModel().id(), privateEndpoint.subnet().id());
Assertions.assertEquals(1, privateEndpoint.networkInterfaces().size());
Assertions.assertEquals(1, privateEndpoint.privateLinkServiceConnections().size());
Assertions.assertTrue(privateEndpoint.privateLinkServiceConnections().values().iterator().next().isManualApproval());
Assertions.assertEquals("Pending", privateEndpoint.privateLinkServiceConnections().get(pecName).state().status());
Assertions.assertEquals("request message", privateEndpoint.privateLinkServiceConnections().get(pecName).requestMessage());
List<PrivateEndpointConnectionInner> storageAccountConnections = azureResourceManager.storageAccounts().manager().serviceClient().getPrivateEndpointConnections().list(rgName, saName).stream().collect(Collectors.toList());
Assertions.assertEquals(1, storageAccountConnections.size());
PrivateEndpointConnectionInner storageAccountConnection = storageAccountConnections.iterator().next();
Response<PrivateEndpointConnectionInner> approvalResponse = azureResourceManager.storageAccounts().manager().serviceClient().getPrivateEndpointConnections()
.putWithResponse(rgName, saName, storageAccountConnection.name(),
storageAccountConnection.privateEndpoint(),
storageAccountConnection.privateLinkServiceConnectionState().withStatus(PrivateEndpointServiceConnectionStatus.APPROVED),
Context.NONE);
Assertions.assertEquals(200, approvalResponse.getStatusCode());
privateEndpoint.refresh();
Assertions.assertEquals("Approved", privateEndpoint.privateLinkServiceConnections().get(pecName).state().status());
azureResourceManager.privateEndpoints().deleteById(privateEndpoint.id());
privateEndpoint = azureResourceManager.privateEndpoints().define(peName2)
.withRegion(region)
.withExistingResourceGroup(rgName)
.withSubnet(network.subnets().get(subnetName).innerModel().id())
.definePrivateLinkServiceConnection(pecName)
.withResource(storageAccount.id())
.withSubResource(PrivateLinkSubResourceName.STORAGE_BLOB)
.attach()
.create();
Assertions.assertNotNull(privateEndpoint.subnet());
Assertions.assertEquals(network.subnets().get(subnetName).innerModel().id(), privateEndpoint.subnet().id());
Assertions.assertEquals(1, privateEndpoint.networkInterfaces().size());
Assertions.assertEquals(1, privateEndpoint.privateLinkServiceConnections().size());
Assertions.assertEquals(storageAccount.id(), privateEndpoint.privateLinkServiceConnections().get(pecName).privateLinkResourceId());
Assertions.assertEquals(Collections.singletonList(PrivateLinkSubResourceName.STORAGE_BLOB), privateEndpoint.privateLinkServiceConnections().get(pecName).subResourceNames());
Assertions.assertFalse(privateEndpoint.privateLinkServiceConnections().values().iterator().next().isManualApproval());
Assertions.assertEquals("Approved", privateEndpoint.privateLinkServiceConnections().get(pecName).state().status());
List<PrivateEndpoint> privateEndpoints = azureResourceManager.privateEndpoints().listByResourceGroup(rgName).stream().collect(Collectors.toList());
Assertions.assertEquals(1, privateEndpoints.size());
Assertions.assertEquals(peName2, privateEndpoints.get(0).name());
} | Assertions.assertEquals(200, approvalResponse.getStatusCode()); | public void testPrivateEndpoint() {
String saName2 = generateRandomResourceName("sa", 10);
String peName2 = generateRandomResourceName("pe", 10);
String pecName2 = generateRandomResourceName("pec", 10);
String saDomainName = saName + ".blob.core.windows.net";
System.out.println("storage account domain name: " + saDomainName);
StorageAccount storageAccount = azureResourceManager.storageAccounts().define(saName)
.withRegion(region)
.withNewResourceGroup(rgName)
.create();
Network network = azureResourceManager.networks().define(vnName)
.withRegion(region)
.withExistingResourceGroup(rgName)
.withAddressSpace(vnAddressSpace)
.defineSubnet(subnetName)
.withAddressPrefix(vnAddressSpace)
.disableNetworkPoliciesOnPrivateEndpoint()
.attach()
.create();
PrivateEndpoint privateEndpoint = azureResourceManager.privateEndpoints().define(peName)
.withRegion(region)
.withExistingResourceGroup(rgName)
.withSubnet(network.subnets().get(subnetName))
.definePrivateLinkServiceConnection(pecName)
.withResource(storageAccount)
.withSubResource(PrivateLinkSubResourceName.STORAGE_BLOB)
.withManualApproval("request message")
.attach()
.create();
Assertions.assertNotNull(privateEndpoint.subnet());
Assertions.assertEquals(network.subnets().get(subnetName).id(), privateEndpoint.subnet().id());
Assertions.assertEquals(1, privateEndpoint.networkInterfaces().size());
Assertions.assertEquals(1, privateEndpoint.privateLinkServiceConnections().size());
Assertions.assertTrue(privateEndpoint.privateLinkServiceConnections().values().iterator().next().isManualApproval());
Assertions.assertEquals(Collections.singletonList(PrivateLinkSubResourceName.STORAGE_BLOB), privateEndpoint.privateLinkServiceConnections().get(pecName).subResourceNames());
Assertions.assertEquals("Pending", privateEndpoint.privateLinkServiceConnections().get(pecName).state().status());
Assertions.assertEquals("request message", privateEndpoint.privateLinkServiceConnections().get(pecName).requestMessage());
List<PrivateEndpointConnectionInner> storageAccountConnections = azureResourceManager.storageAccounts().manager().serviceClient().getPrivateEndpointConnections().list(rgName, saName).stream().collect(Collectors.toList());
Assertions.assertEquals(1, storageAccountConnections.size());
PrivateEndpointConnectionInner storageAccountConnection = storageAccountConnections.iterator().next();
Response<PrivateEndpointConnectionInner> approvalResponse = azureResourceManager.storageAccounts().manager().serviceClient().getPrivateEndpointConnections()
.putWithResponse(rgName, saName, storageAccountConnection.name(),
storageAccountConnection.privateEndpoint(),
storageAccountConnection.privateLinkServiceConnectionState().withStatus(PrivateEndpointServiceConnectionStatus.APPROVED),
Context.NONE);
Assertions.assertEquals(200, approvalResponse.getStatusCode());
privateEndpoint.refresh();
Assertions.assertEquals("Approved", privateEndpoint.privateLinkServiceConnections().get(pecName).state().status());
StorageAccount storageAccount2 = azureResourceManager.storageAccounts().define(saName2)
.withRegion(region)
.withNewResourceGroup(rgName)
.create();
privateEndpoint.update()
.updatePrivateLinkServiceConnection(pecName)
.withRequestMessage("request2")
.parent()
.apply();
Assertions.assertEquals("Pending", privateEndpoint.privateLinkServiceConnections().get(pecName).state().status());
Assertions.assertEquals("request2", privateEndpoint.privateLinkServiceConnections().get(pecName).requestMessage());
privateEndpoint.update()
.withoutPrivateLinkServiceConnection(pecName)
.definePrivateLinkServiceConnection(pecName2)
.withResource(storageAccount2)
.withSubResource(PrivateLinkSubResourceName.STORAGE_FILE)
.attach()
.apply();
Assertions.assertEquals(Collections.singletonList(PrivateLinkSubResourceName.STORAGE_FILE), privateEndpoint.privateLinkServiceConnections().get(pecName2).subResourceNames());
Assertions.assertEquals("Approved", privateEndpoint.privateLinkServiceConnections().get(pecName2).state().status());
azureResourceManager.privateEndpoints().deleteById(privateEndpoint.id());
privateEndpoint = azureResourceManager.privateEndpoints().define(peName2)
.withRegion(region)
.withExistingResourceGroup(rgName)
.withSubnetId(network.subnets().get(subnetName).id())
.definePrivateLinkServiceConnection(pecName)
.withResourceId(storageAccount.id())
.withSubResource(PrivateLinkSubResourceName.STORAGE_BLOB)
.attach()
.create();
Assertions.assertNotNull(privateEndpoint.subnet());
Assertions.assertEquals(network.subnets().get(subnetName).id(), privateEndpoint.subnet().id());
Assertions.assertEquals(1, privateEndpoint.networkInterfaces().size());
Assertions.assertEquals(1, privateEndpoint.privateLinkServiceConnections().size());
Assertions.assertEquals(storageAccount.id(), privateEndpoint.privateLinkServiceConnections().get(pecName).privateLinkResourceId());
Assertions.assertEquals(Collections.singletonList(PrivateLinkSubResourceName.STORAGE_BLOB), privateEndpoint.privateLinkServiceConnections().get(pecName).subResourceNames());
Assertions.assertNotNull(privateEndpoint.customDnsConfigurations());
Assertions.assertFalse(privateEndpoint.customDnsConfigurations().isEmpty());
Assertions.assertFalse(privateEndpoint.privateLinkServiceConnections().values().iterator().next().isManualApproval());
Assertions.assertEquals("Approved", privateEndpoint.privateLinkServiceConnections().get(pecName).state().status());
String saPrivateIp = privateEndpoint.customDnsConfigurations().get(0).ipAddresses().get(0);
System.out.println("storage account private ip: " + saPrivateIp);
List<PrivateEndpoint> privateEndpoints = azureResourceManager.privateEndpoints().listByResourceGroup(rgName).stream().collect(Collectors.toList());
Assertions.assertEquals(1, privateEndpoints.size());
Assertions.assertEquals(peName2, privateEndpoints.get(0).name());
} | class PrivateLinkTests extends ResourceManagerTestBase {
private AzureResourceManager azureResourceManager;
private String rgName;
@Override
protected HttpPipeline buildHttpPipeline(
TokenCredential credential,
AzureProfile profile,
HttpLogOptions httpLogOptions,
List<HttpPipelinePolicy> policies,
HttpClient httpClient) {
return HttpPipelineProvider.buildHttpPipeline(
credential,
profile,
null,
httpLogOptions,
null,
new RetryPolicy("Retry-After", ChronoUnit.SECONDS),
policies,
httpClient);
}
@Override
protected void initializeClients(HttpPipeline httpPipeline, AzureProfile profile) {
ResourceManagerUtils.InternalRuntimeContext.setDelayProvider(new TestDelayProvider(!isPlaybackMode()));
ResourceManagerUtils.InternalRuntimeContext internalContext = new ResourceManagerUtils.InternalRuntimeContext();
internalContext.setIdentifierFunction(name -> new TestIdentifierProvider(testResourceNamer));
azureResourceManager = buildManager(AzureResourceManager.class, httpPipeline, profile);
setInternalContext(internalContext, azureResourceManager);
rgName = generateRandomResourceName("javacsmrg", 15);
}
@Override
protected void cleanUpResources() {
try {
azureResourceManager.resourceGroups().beginDeleteByName(rgName);
} catch (Exception e) {
}
}
@Test
} | class PrivateLinkTests extends ResourceManagerTestBase {
private AzureResourceManager azureResourceManager;
private String rgName;
private String saName;
private String peName;
private String vnName;
private String subnetName;
private String pecName;
private final Region region = Region.US_EAST;
private final String vnAddressSpace = "10.0.0.0/28";
@Override
protected HttpPipeline buildHttpPipeline(
TokenCredential credential,
AzureProfile profile,
HttpLogOptions httpLogOptions,
List<HttpPipelinePolicy> policies,
HttpClient httpClient) {
return HttpPipelineProvider.buildHttpPipeline(
credential,
profile,
null,
httpLogOptions,
null,
new RetryPolicy("Retry-After", ChronoUnit.SECONDS),
policies,
httpClient);
}
@Override
protected void initializeClients(HttpPipeline httpPipeline, AzureProfile profile) {
ResourceManagerUtils.InternalRuntimeContext.setDelayProvider(new TestDelayProvider(!isPlaybackMode()));
ResourceManagerUtils.InternalRuntimeContext internalContext = new ResourceManagerUtils.InternalRuntimeContext();
internalContext.setIdentifierFunction(name -> new TestIdentifierProvider(testResourceNamer));
azureResourceManager = buildManager(AzureResourceManager.class, httpPipeline, profile);
setInternalContext(internalContext, azureResourceManager);
rgName = generateRandomResourceName("javacsmrg", 15);
saName = generateRandomResourceName("sa", 10);
vnName = generateRandomResourceName("vn", 10);
subnetName = "default";
peName = generateRandomResourceName("pe", 10);
pecName = generateRandomResourceName("pec", 10);
}
@Override
protected void cleanUpResources() {
try {
azureResourceManager.resourceGroups().beginDeleteByName(rgName);
} catch (Exception e) {
}
}
@Test
@Test
public void testPrivateEndpointE2E() {
final boolean validateOnVirtualMachine = true;
String vnlName = generateRandomResourceName("vnl", 10);
String pdzgName = "default";
String pdzcName = generateRandomResourceName("pdzcName", 10);
String pdzcName2 = generateRandomResourceName("pdzcName", 10);
String vmName = generateRandomResourceName("vm", 10);
String saDomainName = saName + ".blob.core.windows.net";
System.out.println("storage account domain name: " + saDomainName);
StorageAccount storageAccount = azureResourceManager.storageAccounts().define(saName)
.withRegion(region)
.withNewResourceGroup(rgName)
.create();
Network network = azureResourceManager.networks().define(vnName)
.withRegion(region)
.withExistingResourceGroup(rgName)
.withAddressSpace(vnAddressSpace)
.defineSubnet(subnetName)
.withAddressPrefix(vnAddressSpace)
.disableNetworkPoliciesOnPrivateEndpoint()
.attach()
.create();
PrivateEndpoint privateEndpoint = azureResourceManager.privateEndpoints().define(peName)
.withRegion(region)
.withExistingResourceGroup(rgName)
.withSubnetId(network.subnets().get(subnetName).id())
.definePrivateLinkServiceConnection(pecName)
.withResourceId(storageAccount.id())
.withSubResource(PrivateLinkSubResourceName.STORAGE_BLOB)
.attach()
.create();
Assertions.assertNotNull(privateEndpoint.subnet());
Assertions.assertEquals(network.subnets().get(subnetName).id(), privateEndpoint.subnet().id());
Assertions.assertEquals(1, privateEndpoint.networkInterfaces().size());
Assertions.assertEquals(1, privateEndpoint.privateLinkServiceConnections().size());
Assertions.assertEquals(storageAccount.id(), privateEndpoint.privateLinkServiceConnections().get(pecName).privateLinkResourceId());
Assertions.assertEquals(Collections.singletonList(PrivateLinkSubResourceName.STORAGE_BLOB), privateEndpoint.privateLinkServiceConnections().get(pecName).subResourceNames());
Assertions.assertNotNull(privateEndpoint.customDnsConfigurations());
Assertions.assertFalse(privateEndpoint.customDnsConfigurations().isEmpty());
Assertions.assertFalse(privateEndpoint.privateLinkServiceConnections().values().iterator().next().isManualApproval());
Assertions.assertEquals("Approved", privateEndpoint.privateLinkServiceConnections().get(pecName).state().status());
String saPrivateIp = privateEndpoint.customDnsConfigurations().get(0).ipAddresses().get(0);
System.out.println("storage account private ip: " + saPrivateIp);
VirtualMachine virtualMachine = null;
if (validateOnVirtualMachine) {
virtualMachine = azureResourceManager.virtualMachines().define(vmName)
.withRegion(region)
.withExistingResourceGroup(rgName)
.withExistingPrimaryNetwork(network)
.withSubnet(subnetName)
.withPrimaryPrivateIPAddressDynamic()
.withoutPrimaryPublicIPAddress()
.withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_18_04_LTS)
.withRootUsername("testUser")
.withSsh(sshPublicKey())
.withSize(VirtualMachineSizeTypes.fromString("Standard_D2as_v4"))
.create();
RunCommandResult commandResult = virtualMachine.runShellScript(Collections.singletonList("nslookup " + saDomainName), null);
for (InstanceViewStatus status : commandResult.value()) {
System.out.println(status.message());
}
Assertions.assertFalse(commandResult.value().stream().anyMatch(status -> status.message().contains(saPrivateIp)));
}
PrivateDnsZone privateDnsZone = azureResourceManager.privateDnsZones().define("privatelink.blob.core.windows.net")
.withExistingResourceGroup(rgName)
.defineARecordSet(saName)
.withIPv4Address(privateEndpoint.customDnsConfigurations().get(0).ipAddresses().get(0))
.attach()
.defineVirtualNetworkLink(vnlName)
.withVirtualNetworkId(network.id())
.attach()
.create();
PrivateDnsZoneGroup privateDnsZoneGroup = privateEndpoint.privateDnsZoneGroups().define(pdzgName)
.withPrivateDnsZoneConfigure(pdzcName, privateDnsZone.id())
.create();
if (validateOnVirtualMachine) {
RunCommandResult commandResult = virtualMachine.runShellScript(Collections.singletonList("nslookup " + saDomainName), null);
for (InstanceViewStatus status : commandResult.value()) {
System.out.println(status.message());
}
Assertions.assertTrue(commandResult.value().stream().anyMatch(status -> status.message().contains(saPrivateIp)));
}
Assertions.assertEquals(1, privateEndpoint.privateDnsZoneGroups().list().stream().count());
Assertions.assertEquals(pdzgName, privateEndpoint.privateDnsZoneGroups().getById(privateDnsZoneGroup.id()).name());
PrivateDnsZone privateDnsZone2 = azureResourceManager.privateDnsZones().define("link.blob.core.windows.net")
.withExistingResourceGroup(rgName)
.create();
privateDnsZoneGroup.update()
.withoutPrivateDnsZoneConfigure(pdzcName)
.withPrivateDnsZoneConfigure(pdzcName2, privateDnsZone2.id())
.apply();
privateEndpoint.privateDnsZoneGroups().deleteById(privateDnsZoneGroup.id());
}
} |
check for NPE | public Update withoutPrivateDnsZoneConfigure(String name) {
innerModel().privateDnsZoneConfigs().removeIf(config -> config.name().equals(name));
return this;
} | innerModel().privateDnsZoneConfigs().removeIf(config -> config.name().equals(name)); | public Update withoutPrivateDnsZoneConfigure(String name) {
if (innerModel().privateDnsZoneConfigs() != null) {
innerModel().privateDnsZoneConfigs().removeIf(config -> config.name().equals(name));
}
return this;
} | class PrivateDnsZoneGroupImpl extends IndependentChildImpl<
PrivateDnsZoneGroup, PrivateEndpoint, PrivateDnsZoneGroupInner, PrivateDnsZoneGroupImpl, NetworkManager>
implements PrivateDnsZoneGroup, PrivateDnsZoneGroup.Definition, PrivateDnsZoneGroup.Update {
private final PrivateEndpointImpl parent;
protected PrivateDnsZoneGroupImpl(String name, PrivateDnsZoneGroupInner innerModel, PrivateEndpointImpl parent) {
super(name, innerModel, parent.manager());
this.parent = parent;
}
@Override
public PrivateDnsZoneGroupImpl withPrivateDnsZoneConfigure(
String name, String privateDnsZoneId) {
if (innerModel().privateDnsZoneConfigs() == null) {
innerModel().withPrivateDnsZoneConfigs(new ArrayList<>());
}
innerModel().privateDnsZoneConfigs().add(
new PrivateDnsZoneConfig()
.withName(name)
.withPrivateDnsZoneId(privateDnsZoneId));
return this;
}
@Override
@Override
public String id() {
return this.innerModel().id();
}
@Override
protected Mono<PrivateDnsZoneGroup> createChildResourceAsync() {
return this.manager().serviceClient().getPrivateDnsZoneGroups()
.createOrUpdateAsync(parent.resourceGroupName(), parent.name(), this.name(), this.innerModel())
.map(innerToFluentMap(this));
}
@Override
protected Mono<PrivateDnsZoneGroupInner> getInnerAsync() {
return this.manager().serviceClient().getPrivateDnsZoneGroups()
.getAsync(parent.resourceGroupName(), parent.name(), this.name());
}
@Override
public ProvisioningState provisioningState() {
return this.innerModel().provisioningState();
}
@Override
public List<PrivateDnsZoneConfig> privateDnsZoneConfigures() {
if (this.innerModel().privateDnsZoneConfigs() == null) {
return Collections.emptyList();
}
return Collections.unmodifiableList(this.innerModel().privateDnsZoneConfigs());
}
} | class PrivateDnsZoneGroupImpl extends IndependentChildImpl<
PrivateDnsZoneGroup, PrivateEndpoint, PrivateDnsZoneGroupInner, PrivateDnsZoneGroupImpl, NetworkManager>
implements PrivateDnsZoneGroup, PrivateDnsZoneGroup.Definition, PrivateDnsZoneGroup.Update {
private final PrivateEndpointImpl parent;
protected PrivateDnsZoneGroupImpl(String name, PrivateDnsZoneGroupInner innerModel, PrivateEndpointImpl parent) {
super(name, innerModel, parent.manager());
this.parent = parent;
}
@Override
public PrivateDnsZoneGroupImpl withPrivateDnsZoneConfigure(
String name, String privateDnsZoneId) {
if (innerModel().privateDnsZoneConfigs() == null) {
innerModel().withPrivateDnsZoneConfigs(new ArrayList<>());
}
innerModel().privateDnsZoneConfigs().add(
new PrivateDnsZoneConfig()
.withName(name)
.withPrivateDnsZoneId(privateDnsZoneId));
return this;
}
@Override
@Override
public String id() {
return this.innerModel().id();
}
@Override
protected Mono<PrivateDnsZoneGroup> createChildResourceAsync() {
return this.manager().serviceClient().getPrivateDnsZoneGroups()
.createOrUpdateAsync(parent.resourceGroupName(), parent.name(), this.name(), this.innerModel())
.map(innerToFluentMap(this));
}
@Override
protected Mono<PrivateDnsZoneGroupInner> getInnerAsync() {
return this.manager().serviceClient().getPrivateDnsZoneGroups()
.getAsync(parent.resourceGroupName(), parent.name(), this.name());
}
@Override
public ProvisioningState provisioningState() {
return this.innerModel().provisioningState();
}
@Override
public List<PrivateDnsZoneConfig> privateDnsZoneConfigures() {
if (this.innerModel().privateDnsZoneConfigs() == null) {
return Collections.emptyList();
}
return Collections.unmodifiableList(this.innerModel().privateDnsZoneConfigs());
}
} |
fixed | public Update withoutPrivateDnsZoneConfigure(String name) {
innerModel().privateDnsZoneConfigs().removeIf(config -> config.name().equals(name));
return this;
} | innerModel().privateDnsZoneConfigs().removeIf(config -> config.name().equals(name)); | public Update withoutPrivateDnsZoneConfigure(String name) {
if (innerModel().privateDnsZoneConfigs() != null) {
innerModel().privateDnsZoneConfigs().removeIf(config -> config.name().equals(name));
}
return this;
} | class PrivateDnsZoneGroupImpl extends IndependentChildImpl<
PrivateDnsZoneGroup, PrivateEndpoint, PrivateDnsZoneGroupInner, PrivateDnsZoneGroupImpl, NetworkManager>
implements PrivateDnsZoneGroup, PrivateDnsZoneGroup.Definition, PrivateDnsZoneGroup.Update {
private final PrivateEndpointImpl parent;
protected PrivateDnsZoneGroupImpl(String name, PrivateDnsZoneGroupInner innerModel, PrivateEndpointImpl parent) {
super(name, innerModel, parent.manager());
this.parent = parent;
}
@Override
public PrivateDnsZoneGroupImpl withPrivateDnsZoneConfigure(
String name, String privateDnsZoneId) {
if (innerModel().privateDnsZoneConfigs() == null) {
innerModel().withPrivateDnsZoneConfigs(new ArrayList<>());
}
innerModel().privateDnsZoneConfigs().add(
new PrivateDnsZoneConfig()
.withName(name)
.withPrivateDnsZoneId(privateDnsZoneId));
return this;
}
@Override
@Override
public String id() {
return this.innerModel().id();
}
@Override
protected Mono<PrivateDnsZoneGroup> createChildResourceAsync() {
return this.manager().serviceClient().getPrivateDnsZoneGroups()
.createOrUpdateAsync(parent.resourceGroupName(), parent.name(), this.name(), this.innerModel())
.map(innerToFluentMap(this));
}
@Override
protected Mono<PrivateDnsZoneGroupInner> getInnerAsync() {
return this.manager().serviceClient().getPrivateDnsZoneGroups()
.getAsync(parent.resourceGroupName(), parent.name(), this.name());
}
@Override
public ProvisioningState provisioningState() {
return this.innerModel().provisioningState();
}
@Override
public List<PrivateDnsZoneConfig> privateDnsZoneConfigures() {
if (this.innerModel().privateDnsZoneConfigs() == null) {
return Collections.emptyList();
}
return Collections.unmodifiableList(this.innerModel().privateDnsZoneConfigs());
}
} | class PrivateDnsZoneGroupImpl extends IndependentChildImpl<
PrivateDnsZoneGroup, PrivateEndpoint, PrivateDnsZoneGroupInner, PrivateDnsZoneGroupImpl, NetworkManager>
implements PrivateDnsZoneGroup, PrivateDnsZoneGroup.Definition, PrivateDnsZoneGroup.Update {
private final PrivateEndpointImpl parent;
protected PrivateDnsZoneGroupImpl(String name, PrivateDnsZoneGroupInner innerModel, PrivateEndpointImpl parent) {
super(name, innerModel, parent.manager());
this.parent = parent;
}
@Override
public PrivateDnsZoneGroupImpl withPrivateDnsZoneConfigure(
String name, String privateDnsZoneId) {
if (innerModel().privateDnsZoneConfigs() == null) {
innerModel().withPrivateDnsZoneConfigs(new ArrayList<>());
}
innerModel().privateDnsZoneConfigs().add(
new PrivateDnsZoneConfig()
.withName(name)
.withPrivateDnsZoneId(privateDnsZoneId));
return this;
}
@Override
@Override
public String id() {
return this.innerModel().id();
}
@Override
protected Mono<PrivateDnsZoneGroup> createChildResourceAsync() {
return this.manager().serviceClient().getPrivateDnsZoneGroups()
.createOrUpdateAsync(parent.resourceGroupName(), parent.name(), this.name(), this.innerModel())
.map(innerToFluentMap(this));
}
@Override
protected Mono<PrivateDnsZoneGroupInner> getInnerAsync() {
return this.manager().serviceClient().getPrivateDnsZoneGroups()
.getAsync(parent.resourceGroupName(), parent.name(), this.name());
}
@Override
public ProvisioningState provisioningState() {
return this.innerModel().provisioningState();
}
@Override
public List<PrivateDnsZoneConfig> privateDnsZoneConfigures() {
if (this.innerModel().privateDnsZoneConfigs() == null) {
return Collections.emptyList();
}
return Collections.unmodifiableList(this.innerModel().privateDnsZoneConfigs());
}
} |
Breaking Change | public Mono<Void> addParticipants(Iterable<ChatParticipant> participants) {
try {
Objects.requireNonNull(participants, "'participants' cannot be null.");
return withContext(context -> addParticipants(participants, context)
.flatMap((Response<AddChatParticipantsResult> res) -> {
return Mono.empty();
}));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
} | try { | public Mono<Void> addParticipants(Iterable<ChatParticipant> participants) {
try {
Objects.requireNonNull(participants, "'participants' cannot be null.");
return withContext(context -> addParticipants(participants, context)
.flatMap((Response<AddChatParticipantsResult> res) -> {
return Mono.empty();
}));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
} | class ChatThreadAsyncClient {
private final ClientLogger logger = new ClientLogger(ChatThreadAsyncClient.class);
private final AzureCommunicationChatServiceImpl chatServiceClient;
private final ChatThreadsImpl chatThreadClient;
private final String chatThreadId;
ChatThreadAsyncClient(AzureCommunicationChatServiceImpl chatServiceClient, String chatThreadId) {
this.chatServiceClient = chatServiceClient;
this.chatThreadClient = chatServiceClient.getChatThreads();
this.chatThreadId = chatThreadId;
}
/**
* Get the thread id property.
*
* @return the thread id value.
*/
public String getChatThreadId() {
return chatThreadId;
}
/**
* Updates a thread's topic.
*
* @param topic The new topic.
* @return the completion.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Void> updateTopic(String topic) {
try {
Objects.requireNonNull(topic, "'topic' cannot be null.");
return withContext(context -> updateTopic(topic, context)
.flatMap((Response<Void> res) -> {
return Mono.empty();
}));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Updates a thread's properties.
*
* @param topic The new topic.
* @return the completion.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Void>> updateTopicWithResponse(String topic) {
try {
Objects.requireNonNull(topic, "'topic' cannot be null.");
return withContext(context -> updateTopic(topic, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Updates a thread's topic.
*
* @param topic The new topic.
* @param context The context to associate with this operation.
* @return the completion.
*/
Mono<Response<Void>> updateTopic(String topic, Context context) {
context = context == null ? Context.NONE : context;
return this.chatThreadClient.updateChatThreadPropertiesWithResponseAsync(
chatThreadId,
new UpdateChatThreadOptions()
.setTopic(topic),
context
);
}
/**
* Adds participants to a thread. If participants already exist, no change occurs.
*
* @param participants Collection of participants to add.
* @return the result.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
/**
* Adds participants to a thread. If participants already exist, no change occurs.
*
* @param participants Collection of participants to add.
* @return the result.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<AddChatParticipantsResult>> addParticipantsWithResponse(Iterable<ChatParticipant> participants) {
try {
Objects.requireNonNull(participants, "'participants' cannot be null.");
return withContext(context -> addParticipants(participants, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Adds a participant to a thread. If the participant already exists, no change occurs.
*
* @param participant The new participant.
* @return the result.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Void> addParticipant(ChatParticipant participant) {
try {
return withContext(context -> addParticipants(Collections.singletonList(participant), context)
.flatMap((Response<AddChatParticipantsResult> res) -> {
return Mono.empty();
}));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Adds a participant to a thread. If the participant already exists, no change occurs.
*
* @param participant The new participant.
* @return the result.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<AddChatParticipantsResult>> addParticipantWithResponse(ChatParticipant participant) {
try {
return withContext(context -> addParticipants(Collections.singletonList(participant), context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Adds participants to a thread. If participants already exist, no change occurs.
*
* @param participants Collection of participants to add.
* @param context The context to associate with this operation.
* @return the result.
*/
Mono<Response<AddChatParticipantsResult>> addParticipants(Iterable<ChatParticipant> participants, Context context) {
context = context == null ? Context.NONE : context;
return this.chatThreadClient.addChatParticipantsWithResponseAsync(
chatThreadId, AddChatParticipantsOptionsConverter.convert(participants), context)
.map(result -> new SimpleResponse<AddChatParticipantsResult>(
result, AddChatParticipantsResultConverter.convert(result.getValue())));
}
/**
* Remove a participant from a thread.
*
* @param identifier Identity of the participant to remove from the thread.
* @return the completion.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Void> removeParticipant(CommunicationIdentifier identifier) {
try {
Objects.requireNonNull(identifier, "'identifier' cannot be null.");
return withContext(context -> removeParticipant(identifier, context)
.flatMap((Response<Void> res) -> {
return Mono.empty();
}));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Remove a participant from a thread.
*
* @param identifier Identity of the participant to remove from the thread.
* @return the completion.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Void>> removeParticipantWithResponse(CommunicationIdentifier identifier) {
try {
Objects.requireNonNull(identifier, "'identifier' cannot be null.");
return withContext(context -> removeParticipant(identifier, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Remove a participant from a thread.
*
* @param identifier Identity of the participant to remove from the thread.
* @param context The context to associate with this operation.
* @return the completion.
*/
Mono<Response<Void>> removeParticipant(CommunicationIdentifier identifier, Context context) {
context = context == null ? Context.NONE : context;
return this.chatThreadClient.removeChatParticipantWithResponseAsync(
chatThreadId, CommunicationIdentifierConverter.convert(identifier), context);
}
/**
* Gets the participants of a thread.
*
* @return the participants of a thread.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux<ChatParticipant> listParticipants() {
ListParticipantsOptions listParticipantsOptions = new ListParticipantsOptions();
return listParticipants(listParticipantsOptions, Context.NONE);
}
/**
* Gets the participants of a thread.
*
* @param context The context to associate with this operation.
* @param listParticipantsOptions The request options.
* @return the participants of a thread.
*/
PagedFlux<ChatParticipant> listParticipants(ListParticipantsOptions listParticipantsOptions, Context context) {
final Context serviceContext = context == null ? Context.NONE : context;
final ListParticipantsOptions serviceListParticipantsOptions =
listParticipantsOptions == null ? new ListParticipantsOptions() : listParticipantsOptions;
try {
return pagedFluxConvert(new PagedFlux<>(
() ->
this.chatThreadClient.listChatParticipantsSinglePageAsync(
chatThreadId,
serviceListParticipantsOptions.getMaxPageSize(),
serviceListParticipantsOptions.getSkip(),
serviceContext),
nextLink ->
this.chatThreadClient.listChatParticipantsNextSinglePageAsync(nextLink, serviceContext)),
f -> ChatParticipantConverter.convert(f));
} catch (RuntimeException ex) {
return new PagedFlux<>(() -> monoError(logger, ex));
}
}
/**
* Sends a message to a thread.
*
* @param options Options for sending the message.
* @return the SendChatMessageResult.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<SendChatMessageResult> sendMessage(SendChatMessageOptions options) {
try {
Objects.requireNonNull(options, "'options' cannot be null.");
return withContext(context -> sendMessage(options, context)
.flatMap(
res -> Mono.just(res.getValue())));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Sends a message to a thread.
*
* @param options Options for sending the message.
* @return the SendChatMessageResult.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<SendChatMessageResult>> sendMessageWithResponse(SendChatMessageOptions options) {
try {
Objects.requireNonNull(options, "'options' cannot be null.");
return withContext(context -> sendMessage(options, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Sends a message to a thread.
*
* @param options Options for sending the message.
* @param context The context to associate with this operation.
* @return the SendChatMessageResult.
*/
Mono<Response<SendChatMessageResult>> sendMessage(SendChatMessageOptions options, Context context) {
context = context == null ? Context.NONE : context;
return this.chatThreadClient.sendChatMessageWithResponseAsync(
chatThreadId, options, context).map(
result -> new SimpleResponse<SendChatMessageResult>(result, (result.getValue())));
}
/**
* Gets a message by id.
*
* @param chatMessageId The message id.
* @return a message by id.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<ChatMessage> getMessage(String chatMessageId) {
try {
Objects.requireNonNull(chatMessageId, "'chatMessageId' cannot be null.");
return withContext(context -> getMessage(chatMessageId, context)
.flatMap(
(Response<ChatMessage> res) -> {
if (res.getValue() != null) {
return Mono.just(res.getValue());
} else {
return Mono.empty();
}
}));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Gets a message by id.
*
* @param chatMessageId The message id.
* @return a message by id.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<ChatMessage>> getMessageWithResponse(String chatMessageId) {
try {
Objects.requireNonNull(chatMessageId, "'chatMessageId' cannot be null.");
return withContext(context -> getMessage(chatMessageId, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Gets a message by id.
*
* @param chatMessageId The message id.
* @param context The context to associate with this operation.
* @return a message by id.
*/
Mono<Response<ChatMessage>> getMessage(String chatMessageId, Context context) {
context = context == null ? Context.NONE : context;
return this.chatThreadClient.getChatMessageWithResponseAsync(chatThreadId, chatMessageId, context).map(
result -> new SimpleResponse<ChatMessage>(
result, ChatMessageConverter.convert(result.getValue())));
}
/**
* Gets a list of messages from a thread.
*
* @return a paged list of messages from a thread.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux<ChatMessage> listMessages() {
ListChatMessagesOptions listMessagesOptions = new ListChatMessagesOptions();
try {
return pagedFluxConvert(new PagedFlux<>(
() -> withContext(context -> this.chatThreadClient.listChatMessagesSinglePageAsync(
chatThreadId, listMessagesOptions.getMaxPageSize(), listMessagesOptions.getStartTime(), context)),
nextLink -> withContext(context -> this.chatThreadClient.listChatMessagesNextSinglePageAsync(
nextLink, context))),
f -> ChatMessageConverter.convert(f));
} catch (RuntimeException ex) {
return new PagedFlux<>(() -> monoError(logger, ex));
}
}
/**
* Gets a list of messages from a thread.
*
* @param listMessagesOptions The request options.
* @return a paged list of messages from a thread.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux<ChatMessage> listMessages(ListChatMessagesOptions listMessagesOptions) {
final ListChatMessagesOptions serviceListMessagesOptions =
listMessagesOptions == null ? new ListChatMessagesOptions() : listMessagesOptions;
try {
return pagedFluxConvert(new PagedFlux<>(
() -> withContext(context -> this.chatThreadClient.listChatMessagesSinglePageAsync(
chatThreadId,
serviceListMessagesOptions.getMaxPageSize(),
serviceListMessagesOptions.getStartTime(),
context)),
nextLink -> withContext(context -> this.chatThreadClient.listChatMessagesNextSinglePageAsync(
nextLink, context))),
f -> ChatMessageConverter.convert(f));
} catch (RuntimeException ex) {
return new PagedFlux<>(() -> monoError(logger, ex));
}
}
/**
* Gets a list of messages from a thread.
*
* @param listMessagesOptions The request options.
* @param context The context to associate with this operation.
* @return a paged list of messages from a thread.
*/
PagedFlux<ChatMessage> listMessages(ListChatMessagesOptions listMessagesOptions, Context context) {
final ListChatMessagesOptions serviceListMessagesOptions
= listMessagesOptions == null ? new ListChatMessagesOptions() : listMessagesOptions;
final Context serviceContext = context == null ? Context.NONE : context;
try {
return pagedFluxConvert(new PagedFlux<>(
() -> this.chatThreadClient.listChatMessagesSinglePageAsync(
chatThreadId,
serviceListMessagesOptions.getMaxPageSize(),
serviceListMessagesOptions.getStartTime(),
serviceContext),
nextLink -> this.chatThreadClient.listChatMessagesNextSinglePageAsync(
nextLink, serviceContext)),
f -> ChatMessageConverter.convert(f));
} catch (RuntimeException ex) {
return new PagedFlux<>(() -> monoError(logger, ex));
}
}
/**
* Updates a message.
*
* @param chatMessageId The message id.
* @param options Options for updating the message.
* @return the completion.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Void> updateMessage(String chatMessageId, UpdateChatMessageOptions options) {
try {
Objects.requireNonNull(chatMessageId, "'chatMessageId' cannot be null.");
Objects.requireNonNull(options, "'options' cannot be null.");
return withContext(context -> updateMessage(chatMessageId, options, context)
.flatMap((Response<Void> res) -> {
return Mono.empty();
}));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Updates a message.
*
* @param chatMessageId The message id.
* @param options Options for updating the message.
* @return the completion.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Void>> updateMessageWithResponse(String chatMessageId, UpdateChatMessageOptions options) {
try {
Objects.requireNonNull(chatMessageId, "'chatMessageId' cannot be null.");
Objects.requireNonNull(options, "'options' cannot be null.");
return withContext(context -> updateMessage(chatMessageId, options, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Updates a message.
*
* @param chatMessageId The message id.
* @param options Options for updating the message.
* @param context The context to associate with this operation.
* @return the completion.
*/
Mono<Response<Void>> updateMessage(String chatMessageId, UpdateChatMessageOptions options, Context context) {
context = context == null ? Context.NONE : context;
return this.chatThreadClient.updateChatMessageWithResponseAsync(chatThreadId, chatMessageId, options, context);
}
/**
* Deletes a message.
*
* @param chatMessageId The message id.
* @return the completion.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Void> deleteMessage(String chatMessageId) {
try {
Objects.requireNonNull(chatMessageId, "'chatMessageId' cannot be null.");
return withContext(context -> deleteMessage(chatMessageId, context)
.flatMap((Response<Void> res) -> {
return Mono.empty();
}));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Deletes a message.
*
* @param chatMessageId The message id.
* @return the completion.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Void>> deleteMessageWithResponse(String chatMessageId) {
try {
Objects.requireNonNull(chatMessageId, "'chatMessageId' cannot be null.");
return withContext(context -> deleteMessage(chatMessageId, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Deletes a message.
*
* @param chatMessageId The message id.
* @param context The context to associate with this operation.
* @return the completion.
*/
Mono<Response<Void>> deleteMessage(String chatMessageId, Context context) {
context = context == null ? Context.NONE : context;
return this.chatThreadClient.deleteChatMessageWithResponseAsync(chatThreadId, chatMessageId, context);
}
/**
* Posts a typing event to a thread, on behalf of a user.
*
* @return the completion.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Void> sendTypingNotification() {
try {
return withContext(context -> sendTypingNotification(context)
.flatMap((Response<Void> res) -> {
return Mono.empty();
}));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Posts a typing event to a thread, on behalf of a user.
*
* @return the completion.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Void>> sendTypingNotificationWithResponse() {
try {
return withContext(context -> sendTypingNotification(context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Posts a typing event to a thread, on behalf of a user.
*
* @param context The context to associate with this operation.
* @return the completion.
*/
Mono<Response<Void>> sendTypingNotification(Context context) {
context = context == null ? Context.NONE : context;
return this.chatThreadClient.sendTypingNotificationWithResponseAsync(chatThreadId, context);
}
/**
* Posts a read receipt event to a thread, on behalf of a user.
*
* @param chatMessageId The id of the chat message that was read.
* @return the completion.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Void> sendReadReceipt(String chatMessageId) {
try {
Objects.requireNonNull(chatMessageId, "'chatMessageId' cannot be null.");
return withContext(context -> sendReadReceipt(chatMessageId, context)
.flatMap((Response<Void> res) -> {
return Mono.empty();
}));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Posts a read receipt event to a thread, on behalf of a user.
*
* @param chatMessageId The id of the chat message that was read.
* @return the completion.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Void>> sendReadReceiptWithResponse(String chatMessageId) {
try {
Objects.requireNonNull(chatMessageId, "'chatMessageId' cannot be null.");
return withContext(context -> sendReadReceipt(chatMessageId, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Posts a read receipt event to a thread, on behalf of a user.
*
* @param chatMessageId The id of the chat message that was read.
* @param context The context to associate with this operation.
* @return the completion.
*/
Mono<Response<Void>> sendReadReceipt(String chatMessageId, Context context) {
context = context == null ? Context.NONE : context;
SendReadReceiptRequest request = new SendReadReceiptRequest()
.setChatMessageId(chatMessageId);
return this.chatThreadClient.sendChatReadReceiptWithResponseAsync(chatThreadId, request, context);
}
/**
* Gets read receipts for a thread.
*
* @return read receipts for a thread.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux<ChatMessageReadReceipt> listReadReceipts() {
ListReadReceiptOptions listReadReceiptOptions = new ListReadReceiptOptions();
return listReadReceipts(listReadReceiptOptions, Context.NONE);
}
/**
* Gets read receipts for a thread.
*
* @param listReadReceiptOptions The additional options for this operation.
* @param context The context to associate with this operation.
* @return read receipts for a thread.
*/
PagedFlux<ChatMessageReadReceipt> listReadReceipts(ListReadReceiptOptions listReadReceiptOptions, Context context) {
final Context serviceContext = context == null ? Context.NONE : context;
final ListReadReceiptOptions serviceListReadReceiptOptions =
listReadReceiptOptions == null ? new ListReadReceiptOptions() : listReadReceiptOptions;
try {
return pagedFluxConvert(new PagedFlux<>(
() -> this.chatThreadClient.listChatReadReceiptsSinglePageAsync(
chatThreadId,
serviceListReadReceiptOptions.getMaxPageSize(),
serviceListReadReceiptOptions.getSkip(),
serviceContext),
nextLink -> this.chatThreadClient.listChatReadReceiptsNextSinglePageAsync(
nextLink, serviceContext)),
f -> ChatMessageReadReceiptConverter.convert(f));
} catch (RuntimeException ex) {
return new PagedFlux<>(() -> monoError(logger, ex));
}
}
/**
* Gets chat thread properties.
*
* @return chat thread properties.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<ChatThreadProperties> getProperties() {
try {
Objects.requireNonNull(chatThreadId, "'chatThreadId' cannot be null.");
return withContext(context -> getProperties(context)
.flatMap(
(Response<ChatThreadProperties> res) -> {
if (res.getValue() != null) {
return Mono.just(res.getValue());
} else {
return Mono.empty();
}
}));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Gets chat thread properties.
*
* @return chat thread properties.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<ChatThreadProperties>> getPropertiesWithResponse() {
try {
Objects.requireNonNull(chatThreadId, "'chatThreadId' cannot be null.");
return withContext(context -> getProperties(context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Gets chat thread properties.
*
* @param context The context to associate with this operation.
* @return chat thread properties.
*/
Mono<Response<ChatThreadProperties>> getProperties(Context context) {
context = context == null ? Context.NONE : context;
return this.chatThreadClient.getChatThreadPropertiesWithResponseAsync(this.chatThreadId, context)
.flatMap(
(Response<com.azure.communication.chat.implementation.models.ChatThreadProperties> res) -> {
return Mono.just(new SimpleResponse<ChatThreadProperties>(
res, ChatThreadPropertiesConverter.convert(res.getValue())));
});
}
private <T1, T2> PagedFlux<T1> pagedFluxConvert(PagedFlux<T2> originalPagedFlux, Function<T2, T1> func) {
final Function<PagedResponse<T2>,
PagedResponse<T1>> responseMapper
= response -> new PagedResponseBase<Void, T1>(response.getRequest(),
response.getStatusCode(),
response.getHeaders(),
response.getValue()
.stream()
.map(value -> func.apply(value)).collect(Collectors.toList()),
response.getContinuationToken(),
null);
final Supplier<PageRetriever<String, PagedResponse<T1>>> provider = () ->
(continuationToken, pageSize) -> {
Flux<PagedResponse<T2>> flux
= (continuationToken == null)
? originalPagedFlux.byPage()
: originalPagedFlux.byPage(continuationToken);
return flux.map(responseMapper);
};
return PagedFlux.create(provider);
}
} | class ChatThreadAsyncClient {
private final ClientLogger logger = new ClientLogger(ChatThreadAsyncClient.class);
private final AzureCommunicationChatServiceImpl chatServiceClient;
private final ChatThreadsImpl chatThreadClient;
private final String chatThreadId;
ChatThreadAsyncClient(AzureCommunicationChatServiceImpl chatServiceClient, String chatThreadId) {
this.chatServiceClient = chatServiceClient;
this.chatThreadClient = chatServiceClient.getChatThreads();
this.chatThreadId = chatThreadId;
}
/**
* Get the thread id property.
*
* @return the thread id value.
*/
public String getChatThreadId() {
return chatThreadId;
}
/**
* Updates a thread's topic.
*
* @param topic The new topic.
* @return the completion.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Void> updateTopic(String topic) {
try {
Objects.requireNonNull(topic, "'topic' cannot be null.");
return withContext(context -> updateTopic(topic, context)
.flatMap((Response<Void> res) -> {
return Mono.empty();
}));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Updates a thread's properties.
*
* @param topic The new topic.
* @return the completion.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Void>> updateTopicWithResponse(String topic) {
try {
Objects.requireNonNull(topic, "'topic' cannot be null.");
return withContext(context -> updateTopic(topic, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Updates a thread's topic.
*
* @param topic The new topic.
* @param context The context to associate with this operation.
* @return the completion.
*/
Mono<Response<Void>> updateTopic(String topic, Context context) {
context = context == null ? Context.NONE : context;
try {
return this.chatThreadClient.updateChatThreadPropertiesWithResponseAsync(
chatThreadId,
new UpdateChatThreadOptions()
.setTopic(topic),
context
);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Adds participants to a thread. If participants already exist, no change occurs.
*
* @param participants Collection of participants to add.
* @return the result.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
/**
* Adds participants to a thread. If participants already exist, no change occurs.
*
* @param participants Collection of participants to add.
* @return the result.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<AddChatParticipantsResult>> addParticipantsWithResponse(Iterable<ChatParticipant> participants) {
try {
Objects.requireNonNull(participants, "'participants' cannot be null.");
return withContext(context -> addParticipants(participants, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Adds a participant to a thread. If the participant already exists, no change occurs.
*
* @param participant The new participant.
* @return nothing.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Void> addParticipant(ChatParticipant participant) {
return withContext(context -> {
addParticipantWithResponse(participant, context);
return Mono.empty();
});
}
/**
* Adds a participant to a thread. If the participant already exists, no change occurs.
*
* @param participant The new participant.
* @return the response.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Void>> addParticipantWithResponse(ChatParticipant participant) {
try {
return withContext(context -> addParticipantWithResponse(participant, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Adds a participant to a thread. If the participant already exists, no change occurs.
*
* @param participant The new participant.
* @param context The context to associate with this operation.
* @return the response.
*/
Mono<Response<Void>> addParticipantWithResponse(ChatParticipant participant, Context context) {
context = context == null ? Context.NONE : context;
try {
return addParticipants(Collections.singletonList(participant), context)
.flatMap((Response<AddChatParticipantsResult> res) -> {
if (res.getValue().getInvalidParticipants() != null) {
if (res.getValue().getInvalidParticipants().size() > 0) {
ChatError error = res.getValue().getInvalidParticipants()
.stream()
.findFirst()
.get();
return Mono.error(new InvalidParticipantException(error));
}
}
return Mono.empty();
});
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Adds participants to a thread. If participants already exist, no change occurs.
*
* @param participants Collection of participants to add.
* @param context The context to associate with this operation.
* @return the result.
*/
Mono<Response<AddChatParticipantsResult>> addParticipants(Iterable<ChatParticipant> participants, Context context) {
context = context == null ? Context.NONE : context;
try {
return this.chatThreadClient.addChatParticipantsWithResponseAsync(
chatThreadId, AddChatParticipantsOptionsConverter.convert(participants), context)
.map(result -> new SimpleResponse<AddChatParticipantsResult>(
result, AddChatParticipantsResultConverter.convert(result.getValue())));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Remove a participant from a thread.
*
* @param identifier Identity of the participant to remove from the thread.
* @return the completion.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Void> removeParticipant(CommunicationIdentifier identifier) {
try {
Objects.requireNonNull(identifier, "'identifier' cannot be null.");
return withContext(context -> removeParticipant(identifier, context)
.flatMap((Response<Void> res) -> {
return Mono.empty();
}));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Remove a participant from a thread.
*
* @param identifier Identity of the participant to remove from the thread.
* @return the completion.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Void>> removeParticipantWithResponse(CommunicationIdentifier identifier) {
try {
Objects.requireNonNull(identifier, "'identifier' cannot be null.");
return withContext(context -> removeParticipant(identifier, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Remove a participant from a thread.
*
* @param identifier Identity of the participant to remove from the thread.
* @param context The context to associate with this operation.
* @return the completion.
*/
Mono<Response<Void>> removeParticipant(CommunicationIdentifier identifier, Context context) {
context = context == null ? Context.NONE : context;
try {
return this.chatThreadClient.removeChatParticipantWithResponseAsync(
chatThreadId, CommunicationIdentifierConverter.convert(identifier), context);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Gets the participants of a thread.
*
* @return the participants of a thread.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux<ChatParticipant> listParticipants() {
ListParticipantsOptions listParticipantsOptions = new ListParticipantsOptions();
return listParticipants(listParticipantsOptions, Context.NONE);
}
/**
* Gets the participants of a thread.
*
* @param context The context to associate with this operation.
* @param listParticipantsOptions The request options.
* @return the participants of a thread.
*/
PagedFlux<ChatParticipant> listParticipants(ListParticipantsOptions listParticipantsOptions, Context context) {
final Context serviceContext = context == null ? Context.NONE : context;
final ListParticipantsOptions serviceListParticipantsOptions =
listParticipantsOptions == null ? new ListParticipantsOptions() : listParticipantsOptions;
try {
return pagedFluxConvert(new PagedFlux<>(
() ->
this.chatThreadClient.listChatParticipantsSinglePageAsync(
chatThreadId,
serviceListParticipantsOptions.getMaxPageSize(),
serviceListParticipantsOptions.getSkip(),
serviceContext),
nextLink ->
this.chatThreadClient.listChatParticipantsNextSinglePageAsync(nextLink, serviceContext)),
f -> ChatParticipantConverter.convert(f));
} catch (RuntimeException ex) {
return new PagedFlux<>(() -> monoError(logger, ex));
}
}
/**
* Sends a message to a thread.
*
* @param options Options for sending the message.
* @return the SendChatMessageResult.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<SendChatMessageResult> sendMessage(SendChatMessageOptions options) {
try {
Objects.requireNonNull(options, "'options' cannot be null.");
return withContext(context -> sendMessage(options, context)
.flatMap(
res -> Mono.just(res.getValue())));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Sends a message to a thread.
*
* @param options Options for sending the message.
* @return the SendChatMessageResult.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<SendChatMessageResult>> sendMessageWithResponse(SendChatMessageOptions options) {
try {
Objects.requireNonNull(options, "'options' cannot be null.");
return withContext(context -> sendMessage(options, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Sends a message to a thread.
*
* @param options Options for sending the message.
* @param context The context to associate with this operation.
* @return the SendChatMessageResult.
*/
Mono<Response<SendChatMessageResult>> sendMessage(SendChatMessageOptions options, Context context) {
context = context == null ? Context.NONE : context;
try {
return this.chatThreadClient.sendChatMessageWithResponseAsync(
chatThreadId, options, context).map(
result -> new SimpleResponse<SendChatMessageResult>(result, (result.getValue())));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Gets a message by id.
*
* @param chatMessageId The message id.
* @return a message by id.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<ChatMessage> getMessage(String chatMessageId) {
try {
Objects.requireNonNull(chatMessageId, "'chatMessageId' cannot be null.");
return withContext(context -> getMessage(chatMessageId, context)
.flatMap(
(Response<ChatMessage> res) -> {
if (res.getValue() != null) {
return Mono.just(res.getValue());
} else {
return Mono.empty();
}
}));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Gets a message by id.
*
* @param chatMessageId The message id.
* @return a message by id.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<ChatMessage>> getMessageWithResponse(String chatMessageId) {
try {
Objects.requireNonNull(chatMessageId, "'chatMessageId' cannot be null.");
return withContext(context -> getMessage(chatMessageId, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Gets a message by id.
*
* @param chatMessageId The message id.
* @param context The context to associate with this operation.
* @return a message by id.
*/
Mono<Response<ChatMessage>> getMessage(String chatMessageId, Context context) {
context = context == null ? Context.NONE : context;
try {
return this.chatThreadClient.getChatMessageWithResponseAsync(chatThreadId, chatMessageId, context).map(
result -> new SimpleResponse<ChatMessage>(
result, ChatMessageConverter.convert(result.getValue())));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Gets a list of messages from a thread.
*
* @return a paged list of messages from a thread.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux<ChatMessage> listMessages() {
ListChatMessagesOptions listMessagesOptions = new ListChatMessagesOptions();
try {
return pagedFluxConvert(new PagedFlux<>(
() -> withContext(context -> this.chatThreadClient.listChatMessagesSinglePageAsync(
chatThreadId, listMessagesOptions.getMaxPageSize(), listMessagesOptions.getStartTime(), context)),
nextLink -> withContext(context -> this.chatThreadClient.listChatMessagesNextSinglePageAsync(
nextLink, context))),
f -> ChatMessageConverter.convert(f));
} catch (RuntimeException ex) {
return new PagedFlux<>(() -> monoError(logger, ex));
}
}
/**
* Gets a list of messages from a thread.
*
* @param listMessagesOptions The request options.
* @return a paged list of messages from a thread.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux<ChatMessage> listMessages(ListChatMessagesOptions listMessagesOptions) {
final ListChatMessagesOptions serviceListMessagesOptions =
listMessagesOptions == null ? new ListChatMessagesOptions() : listMessagesOptions;
try {
return pagedFluxConvert(new PagedFlux<>(
() -> withContext(context -> this.chatThreadClient.listChatMessagesSinglePageAsync(
chatThreadId,
serviceListMessagesOptions.getMaxPageSize(),
serviceListMessagesOptions.getStartTime(),
context)),
nextLink -> withContext(context -> this.chatThreadClient.listChatMessagesNextSinglePageAsync(
nextLink, context))),
f -> ChatMessageConverter.convert(f));
} catch (RuntimeException ex) {
return new PagedFlux<>(() -> monoError(logger, ex));
}
}
/**
* Gets a list of messages from a thread.
*
* @param listMessagesOptions The request options.
* @param context The context to associate with this operation.
* @return a paged list of messages from a thread.
*/
PagedFlux<ChatMessage> listMessages(ListChatMessagesOptions listMessagesOptions, Context context) {
final ListChatMessagesOptions serviceListMessagesOptions
= listMessagesOptions == null ? new ListChatMessagesOptions() : listMessagesOptions;
final Context serviceContext = context == null ? Context.NONE : context;
try {
return pagedFluxConvert(new PagedFlux<>(
() -> this.chatThreadClient.listChatMessagesSinglePageAsync(
chatThreadId,
serviceListMessagesOptions.getMaxPageSize(),
serviceListMessagesOptions.getStartTime(),
serviceContext),
nextLink -> this.chatThreadClient.listChatMessagesNextSinglePageAsync(
nextLink, serviceContext)),
f -> ChatMessageConverter.convert(f));
} catch (RuntimeException ex) {
return new PagedFlux<>(() -> monoError(logger, ex));
}
}
/**
* Updates a message.
*
* @param chatMessageId The message id.
* @param options Options for updating the message.
* @return the completion.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Void> updateMessage(String chatMessageId, UpdateChatMessageOptions options) {
try {
Objects.requireNonNull(chatMessageId, "'chatMessageId' cannot be null.");
Objects.requireNonNull(options, "'options' cannot be null.");
return withContext(context -> updateMessage(chatMessageId, options, context)
.flatMap((Response<Void> res) -> {
return Mono.empty();
}));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Updates a message.
*
* @param chatMessageId The message id.
* @param options Options for updating the message.
* @return the completion.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Void>> updateMessageWithResponse(String chatMessageId, UpdateChatMessageOptions options) {
try {
Objects.requireNonNull(chatMessageId, "'chatMessageId' cannot be null.");
Objects.requireNonNull(options, "'options' cannot be null.");
return withContext(context -> updateMessage(chatMessageId, options, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Updates a message.
*
* @param chatMessageId The message id.
* @param options Options for updating the message.
* @param context The context to associate with this operation.
* @return the completion.
*/
Mono<Response<Void>> updateMessage(String chatMessageId, UpdateChatMessageOptions options, Context context) {
context = context == null ? Context.NONE : context;
try {
return this.chatThreadClient.updateChatMessageWithResponseAsync(chatThreadId, chatMessageId, options, context);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Deletes a message.
*
* @param chatMessageId The message id.
* @return the completion.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Void> deleteMessage(String chatMessageId) {
try {
Objects.requireNonNull(chatMessageId, "'chatMessageId' cannot be null.");
return withContext(context -> deleteMessage(chatMessageId, context)
.flatMap((Response<Void> res) -> {
return Mono.empty();
}));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Deletes a message.
*
* @param chatMessageId The message id.
* @return the completion.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Void>> deleteMessageWithResponse(String chatMessageId) {
try {
Objects.requireNonNull(chatMessageId, "'chatMessageId' cannot be null.");
return withContext(context -> deleteMessage(chatMessageId, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Deletes a message.
*
* @param chatMessageId The message id.
* @param context The context to associate with this operation.
* @return the completion.
*/
Mono<Response<Void>> deleteMessage(String chatMessageId, Context context) {
context = context == null ? Context.NONE : context;
try {
return this.chatThreadClient.deleteChatMessageWithResponseAsync(chatThreadId, chatMessageId, context);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Posts a typing event to a thread, on behalf of a user.
*
* @return the completion.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Void> sendTypingNotification() {
try {
return withContext(context -> sendTypingNotification(context)
.flatMap((Response<Void> res) -> {
return Mono.empty();
}));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Posts a typing event to a thread, on behalf of a user.
*
* @return the completion.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Void>> sendTypingNotificationWithResponse() {
try {
return withContext(context -> sendTypingNotification(context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Posts a typing event to a thread, on behalf of a user.
*
* @param context The context to associate with this operation.
* @return the completion.
*/
Mono<Response<Void>> sendTypingNotification(Context context) {
context = context == null ? Context.NONE : context;
try {
return this.chatThreadClient.sendTypingNotificationWithResponseAsync(chatThreadId, context);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Posts a read receipt event to a thread, on behalf of a user.
*
* @param chatMessageId The id of the chat message that was read.
* @return the completion.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Void> sendReadReceipt(String chatMessageId) {
try {
Objects.requireNonNull(chatMessageId, "'chatMessageId' cannot be null.");
return withContext(context -> sendReadReceipt(chatMessageId, context)
.flatMap((Response<Void> res) -> {
return Mono.empty();
}));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Posts a read receipt event to a thread, on behalf of a user.
*
* @param chatMessageId The id of the chat message that was read.
* @return the completion.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<Void>> sendReadReceiptWithResponse(String chatMessageId) {
try {
Objects.requireNonNull(chatMessageId, "'chatMessageId' cannot be null.");
return withContext(context -> sendReadReceipt(chatMessageId, context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Posts a read receipt event to a thread, on behalf of a user.
*
* @param chatMessageId The id of the chat message that was read.
* @param context The context to associate with this operation.
* @return the completion.
*/
Mono<Response<Void>> sendReadReceipt(String chatMessageId, Context context) {
context = context == null ? Context.NONE : context;
try {
SendReadReceiptRequest request = new SendReadReceiptRequest()
.setChatMessageId(chatMessageId);
return this.chatThreadClient.sendChatReadReceiptWithResponseAsync(chatThreadId, request, context);
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Gets read receipts for a thread.
*
* @return read receipts for a thread.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux<ChatMessageReadReceipt> listReadReceipts() {
try {
ListReadReceiptOptions listReadReceiptOptions = new ListReadReceiptOptions();
return listReadReceipts(listReadReceiptOptions, Context.NONE);
} catch (RuntimeException ex) {
return new PagedFlux<>(() -> monoError(logger, ex));
}
}
/**
* Gets read receipts for a thread.
*
* @param listReadReceiptOptions The additional options for this operation.
* @param context The context to associate with this operation.
* @return read receipts for a thread.
*/
PagedFlux<ChatMessageReadReceipt> listReadReceipts(ListReadReceiptOptions listReadReceiptOptions, Context context) {
final Context serviceContext = context == null ? Context.NONE : context;
final ListReadReceiptOptions serviceListReadReceiptOptions =
listReadReceiptOptions == null ? new ListReadReceiptOptions() : listReadReceiptOptions;
try {
return pagedFluxConvert(new PagedFlux<>(
() -> this.chatThreadClient.listChatReadReceiptsSinglePageAsync(
chatThreadId,
serviceListReadReceiptOptions.getMaxPageSize(),
serviceListReadReceiptOptions.getSkip(),
serviceContext),
nextLink -> this.chatThreadClient.listChatReadReceiptsNextSinglePageAsync(
nextLink, serviceContext)),
f -> ChatMessageReadReceiptConverter.convert(f));
} catch (RuntimeException ex) {
return new PagedFlux<>(() -> monoError(logger, ex));
}
}
/**
* Gets chat thread properties.
*
* @return chat thread properties.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<ChatThreadProperties> getProperties() {
try {
Objects.requireNonNull(chatThreadId, "'chatThreadId' cannot be null.");
return withContext(context -> getProperties(context)
.flatMap(
(Response<ChatThreadProperties> res) -> {
if (res.getValue() != null) {
return Mono.just(res.getValue());
} else {
return Mono.empty();
}
}));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Gets chat thread properties.
*
* @return chat thread properties.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<ChatThreadProperties>> getPropertiesWithResponse() {
try {
Objects.requireNonNull(chatThreadId, "'chatThreadId' cannot be null.");
return withContext(context -> getProperties(context));
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
/**
* Gets chat thread properties.
*
* @param context The context to associate with this operation.
* @return chat thread properties.
*/
Mono<Response<ChatThreadProperties>> getProperties(Context context) {
context = context == null ? Context.NONE : context;
try {
return this.chatThreadClient.getChatThreadPropertiesWithResponseAsync(this.chatThreadId, context)
.flatMap(
(Response<com.azure.communication.chat.implementation.models.ChatThreadProperties> res) -> {
return Mono.just(new SimpleResponse<ChatThreadProperties>(
res, ChatThreadPropertiesConverter.convert(res.getValue())));
});
} catch (RuntimeException ex) {
return monoError(logger, ex);
}
}
private <T1, T2> PagedFlux<T1> pagedFluxConvert(PagedFlux<T2> originalPagedFlux, Function<T2, T1> func) {
final Function<PagedResponse<T2>,
PagedResponse<T1>> responseMapper
= response -> new PagedResponseBase<Void, T1>(response.getRequest(),
response.getStatusCode(),
response.getHeaders(),
response.getValue()
.stream()
.map(value -> func.apply(value)).collect(Collectors.toList()),
response.getContinuationToken(),
null);
final Supplier<PageRetriever<String, PagedResponse<T1>>> provider = () ->
(continuationToken, pageSize) -> {
Flux<PagedResponse<T2>> flux
= (continuationToken == null)
? originalPagedFlux.byPage()
: originalPagedFlux.byPage(continuationToken);
return flux.map(responseMapper);
};
return PagedFlux.create(provider);
}
} |
Isn't ChatThreadClient created by the builder now? Please be consistent: eight getChatThreadClient from chatClient or get it from the builder NOT both | public void getChatThread() {
ChatClient chatClient = createChatClient();
ChatThreadClient chatThreadClient = chatClient.getChatThreadClient("Id");
ChatThreadProperties chatThreadProperties = chatThreadClient.getProperties();
} | ChatThreadClient chatThreadClient = chatClient.getChatThreadClient("Id"); | public void getChatThread() {
ChatClient chatClient = createChatClient();
ChatThreadClient chatThreadClient = chatClient.getChatThreadClient("Id");
ChatThreadProperties chatThreadProperties = chatThreadClient.getProperties();
} | class ReadmeSamples {
/**
* Sample code for creating a sync chat client.
*
* @return the chat client.
*/
public ChatClient createChatClient() {
String endpoint = "https:
NettyAsyncHttpClientBuilder httpClientBuilder = new NettyAsyncHttpClientBuilder();
HttpClient httpClient = httpClientBuilder.build();
String token = "SECRET";
CommunicationTokenCredential credential = new CommunicationTokenCredential(token);
final ChatClientBuilder builder = new ChatClientBuilder();
builder.endpoint(endpoint)
.credential(credential)
.httpClient(httpClient);
ChatClient chatClient = builder.buildChatClient();
return chatClient;
}
/**
* Sample code for creating a chat thread using the sync chat client.
*/
public void createChatThread() {
ChatClient chatClient = createChatClient();
CommunicationUserIdentifier user1 = new CommunicationUserIdentifier("Id 1");
CommunicationUserIdentifier user2 = new CommunicationUserIdentifier("Id 2");
List<ChatParticipant> participants = new ArrayList<ChatParticipant>();
ChatParticipant firstParticipant = new ChatParticipant()
.setCommunicationIdentifier(user1)
.setDisplayName("Participant Display Name 1");
ChatParticipant secondParticipant = new ChatParticipant()
.setCommunicationIdentifier(user2)
.setDisplayName("Participant Display Name 2");
participants.add(firstParticipant);
participants.add(secondParticipant);
CreateChatThreadOptions createChatThreadOptions = new CreateChatThreadOptions()
.setTopic("Topic")
.setParticipants(participants);
CreateChatThreadResult result = chatClient.createChatThread(createChatThreadOptions);
String chatThreadId = result.getChatThread().getId();
}
/**
* Sample code for getting a chat thread using the sync chat client.
*/
/**
* Sample code for deleting a chat thread using the sync chat client.
*/
public void deleteChatThread() {
ChatClient chatClient = createChatClient();
String chatThreadId = "Id";
chatClient.deleteChatThread(chatThreadId);
}
/**
* Sample code for getting a sync chat thread client using the sync chat client.
*
* @return the chat thread client.
*/
public ChatThreadClient getChatThreadClient() {
ChatClient chatClient = createChatClient();
String chatThreadId = "Id";
ChatThreadClient chatThreadClient = chatClient.getChatThreadClient(chatThreadId);
return chatThreadClient;
}
/**
* Sample code for updating a chat thread topic using the sync chat thread client.
*/
public void updateTopic() {
ChatThreadClient chatThreadClient = getChatThreadClient();
chatThreadClient.updateTopic("New Topic");
}
/**
* Sample code for sending a chat message using the sync chat thread client.
*/
public void sendChatMessage() {
ChatThreadClient chatThreadClient = getChatThreadClient();
SendChatMessageOptions sendChatMessageOptions = new SendChatMessageOptions()
.setContent("Message content")
.setSenderDisplayName("Sender Display Name");
SendChatMessageResult sendResult = chatThreadClient.sendMessage(sendChatMessageOptions);
}
/**
* Sample code for getting a chat message using the sync chat thread client.
*/
public void getChatMessage() {
ChatThreadClient chatThreadClient = getChatThreadClient();
String chatMessageId = "Id";
ChatMessage chatMessage = chatThreadClient.getMessage(chatMessageId);
}
/**
* Sample code getting the thread messages using the sync chat thread client.
*/
public void getChatMessages() {
ChatThreadClient chatThreadClient = getChatThreadClient();
PagedIterable<ChatMessage> chatMessagesResponse = chatThreadClient.listMessages();
chatMessagesResponse.iterableByPage().forEach(resp -> {
System.out.printf("Response headers are %s. Url %s and status code %d %n", resp.getHeaders(),
resp.getRequest().getUrl(), resp.getStatusCode());
resp.getItems().forEach(message -> {
System.out.printf("Message id is %s.", message.getId());
});
});
}
/**
* Sample code updating a thread message using the sync chat thread client.
*/
public void updateChatMessage() {
ChatThreadClient chatThreadClient = getChatThreadClient();
String chatMessageId = "Id";
UpdateChatMessageOptions updateChatMessageOptions = new UpdateChatMessageOptions()
.setContent("Updated message content");
chatThreadClient.updateMessage(chatMessageId, updateChatMessageOptions);
}
/**
* Sample code deleting a thread message using the sync chat thread client.
*/
public void deleteChatMessage() {
ChatThreadClient chatThreadClient = getChatThreadClient();
String chatMessageId = "Id";
chatThreadClient.deleteMessage(chatMessageId);
}
/**
* Sample code listing chat participants using the sync chat thread client.
*/
public void listChatParticipants() {
ChatThreadClient chatThreadClient = getChatThreadClient();
PagedIterable<ChatParticipant> chatParticipantsResponse = chatThreadClient.listParticipants();
chatParticipantsResponse.iterableByPage().forEach(resp -> {
System.out.printf("Response headers are %s. Url %s and status code %d %n", resp.getHeaders(),
resp.getRequest().getUrl(), resp.getStatusCode());
resp.getItems().forEach(chatParticipant -> {
System.out.printf("Participant id is %s.", ((CommunicationUserIdentifier) chatParticipant.getCommunicationIdentifier()).getId());
});
});
}
/**
* Sample code adding chat participants using the sync chat thread client.
*/
public void addChatParticipants() {
ChatThreadClient chatThreadClient = getChatThreadClient();
CommunicationUserIdentifier user1 = new CommunicationUserIdentifier("Id 1");
CommunicationUserIdentifier user2 = new CommunicationUserIdentifier("Id 2");
List<ChatParticipant> participants = new ArrayList<ChatParticipant>();
ChatParticipant firstParticipant = new ChatParticipant()
.setCommunicationIdentifier(user1)
.setDisplayName("Display Name 1");
ChatParticipant secondParticipant = new ChatParticipant()
.setCommunicationIdentifier(user2)
.setDisplayName("Display Name 2");
participants.add(firstParticipant);
participants.add(secondParticipant);
chatThreadClient.addParticipants(participants);
}
/**
* Sample code removing a chat participant using the sync chat thread client.
*/
public void removeChatParticipant() {
ChatThreadClient chatThreadClient = getChatThreadClient();
CommunicationUserIdentifier user = new CommunicationUserIdentifier("Id");
chatThreadClient.removeParticipant(user);
}
/**
* Sample code sending a read receipt using the sync chat thread client.
*/
public void sendReadReceipt() {
ChatThreadClient chatThreadClient = getChatThreadClient();
String chatMessageId = "Id";
chatThreadClient.sendReadReceipt(chatMessageId);
}
/**
* Sample code listing read receipts using the sync chat thread client.
*/
public void listReadReceipts() {
ChatThreadClient chatThreadClient = getChatThreadClient();
PagedIterable<ChatMessageReadReceipt> readReceiptsResponse = chatThreadClient.listReadReceipts();
readReceiptsResponse.iterableByPage().forEach(resp -> {
System.out.printf("Response headers are %s. Url %s and status code %d %n", resp.getHeaders(),
resp.getRequest().getUrl(), resp.getStatusCode());
resp.getItems().forEach(readReceipt -> {
System.out.printf("Read message id is %s.", readReceipt.getChatMessageId());
});
});
}
/**
* Sample code sending a read receipt using the sync chat thread client.
*/
public void sendTypingNotification() {
ChatThreadClient chatThreadClient = getChatThreadClient();
chatThreadClient.sendTypingNotification();
}
} | class ReadmeSamples {
/**
* Sample code for creating a sync chat client.
*
* @return the chat client.
*/
public ChatClient createChatClient() {
String endpoint = "https:
NettyAsyncHttpClientBuilder httpClientBuilder = new NettyAsyncHttpClientBuilder();
HttpClient httpClient = httpClientBuilder.build();
String token = "SECRET";
CommunicationTokenCredential credential = new CommunicationTokenCredential(token);
final ChatClientBuilder builder = new ChatClientBuilder();
builder.endpoint(endpoint)
.credential(credential)
.httpClient(httpClient);
ChatClient chatClient = builder.buildClient();
return chatClient;
}
/**
* Sample code for creating a chat thread using the sync chat client.
*/
public void createChatThread() {
ChatClient chatClient = createChatClient();
CommunicationUserIdentifier user1 = new CommunicationUserIdentifier("Id 1");
CommunicationUserIdentifier user2 = new CommunicationUserIdentifier("Id 2");
List<ChatParticipant> participants = new ArrayList<ChatParticipant>();
ChatParticipant firstParticipant = new ChatParticipant()
.setCommunicationIdentifier(user1)
.setDisplayName("Participant Display Name 1");
ChatParticipant secondParticipant = new ChatParticipant()
.setCommunicationIdentifier(user2)
.setDisplayName("Participant Display Name 2");
participants.add(firstParticipant);
participants.add(secondParticipant);
CreateChatThreadOptions createChatThreadOptions = new CreateChatThreadOptions("Topic")
.setParticipants(participants);
CreateChatThreadResult result = chatClient.createChatThread(createChatThreadOptions);
String chatThreadId = result.getChatThread().getId();
}
/**
* Sample code for getting a chat thread using the sync chat client.
*/
/**
* Sample code for deleting a chat thread using the sync chat client.
*/
public void deleteChatThread() {
ChatClient chatClient = createChatClient();
String chatThreadId = "Id";
chatClient.deleteChatThread(chatThreadId);
}
/**
* Sample code for getting a sync chat thread client using the sync chat client.
*
* @return the chat thread client.
*/
public ChatThreadClient getChatThreadClient() {
ChatClient chatClient = createChatClient();
String chatThreadId = "Id";
ChatThreadClient chatThreadClient = chatClient.getChatThreadClient(chatThreadId);
return chatThreadClient;
}
/**
* Sample code for updating a chat thread topic using the sync chat thread client.
*/
public void updateTopic() {
ChatThreadClient chatThreadClient = getChatThreadClient();
chatThreadClient.updateTopic("New Topic");
}
/**
* Sample code for sending a chat message using the sync chat thread client.
*/
public void sendChatMessage() {
ChatThreadClient chatThreadClient = getChatThreadClient();
SendChatMessageOptions sendChatMessageOptions = new SendChatMessageOptions()
.setContent("Message content")
.setSenderDisplayName("Sender Display Name");
SendChatMessageResult sendResult = chatThreadClient.sendMessage(sendChatMessageOptions);
}
/**
* Sample code for getting a chat message using the sync chat thread client.
*/
public void getChatMessage() {
ChatThreadClient chatThreadClient = getChatThreadClient();
String chatMessageId = "Id";
ChatMessage chatMessage = chatThreadClient.getMessage(chatMessageId);
}
/**
* Sample code getting the thread messages using the sync chat thread client.
*/
public void getChatMessages() {
ChatThreadClient chatThreadClient = getChatThreadClient();
PagedIterable<ChatMessage> chatMessagesResponse = chatThreadClient.listMessages();
chatMessagesResponse.iterableByPage().forEach(resp -> {
System.out.printf("Response headers are %s. Url %s and status code %d %n", resp.getHeaders(),
resp.getRequest().getUrl(), resp.getStatusCode());
resp.getItems().forEach(message -> {
System.out.printf("Message id is %s.", message.getId());
});
});
}
/**
* Sample code updating a thread message using the sync chat thread client.
*/
public void updateChatMessage() {
ChatThreadClient chatThreadClient = getChatThreadClient();
String chatMessageId = "Id";
UpdateChatMessageOptions updateChatMessageOptions = new UpdateChatMessageOptions()
.setContent("Updated message content");
chatThreadClient.updateMessage(chatMessageId, updateChatMessageOptions);
}
/**
* Sample code deleting a thread message using the sync chat thread client.
*/
public void deleteChatMessage() {
ChatThreadClient chatThreadClient = getChatThreadClient();
String chatMessageId = "Id";
chatThreadClient.deleteMessage(chatMessageId);
}
/**
* Sample code listing chat participants using the sync chat thread client.
*/
public void listChatParticipants() {
ChatThreadClient chatThreadClient = getChatThreadClient();
PagedIterable<ChatParticipant> chatParticipantsResponse = chatThreadClient.listParticipants();
chatParticipantsResponse.iterableByPage().forEach(resp -> {
System.out.printf("Response headers are %s. Url %s and status code %d %n", resp.getHeaders(),
resp.getRequest().getUrl(), resp.getStatusCode());
resp.getItems().forEach(chatParticipant -> {
System.out.printf("Participant id is %s.", ((CommunicationUserIdentifier) chatParticipant.getCommunicationIdentifier()).getId());
});
});
}
/**
* Sample code adding chat participants using the sync chat thread client.
*/
public void addChatParticipants() {
ChatThreadClient chatThreadClient = getChatThreadClient();
CommunicationUserIdentifier user1 = new CommunicationUserIdentifier("Id 1");
CommunicationUserIdentifier user2 = new CommunicationUserIdentifier("Id 2");
List<ChatParticipant> participants = new ArrayList<ChatParticipant>();
ChatParticipant firstParticipant = new ChatParticipant()
.setCommunicationIdentifier(user1)
.setDisplayName("Display Name 1");
ChatParticipant secondParticipant = new ChatParticipant()
.setCommunicationIdentifier(user2)
.setDisplayName("Display Name 2");
participants.add(firstParticipant);
participants.add(secondParticipant);
chatThreadClient.addParticipants(participants);
}
/**
* Sample code removing a chat participant using the sync chat thread client.
*/
public void removeChatParticipant() {
ChatThreadClient chatThreadClient = getChatThreadClient();
CommunicationUserIdentifier user = new CommunicationUserIdentifier("Id");
chatThreadClient.removeParticipant(user);
}
/**
* Sample code sending a read receipt using the sync chat thread client.
*/
public void sendReadReceipt() {
ChatThreadClient chatThreadClient = getChatThreadClient();
String chatMessageId = "Id";
chatThreadClient.sendReadReceipt(chatMessageId);
}
/**
* Sample code listing read receipts using the sync chat thread client.
*/
public void listReadReceipts() {
ChatThreadClient chatThreadClient = getChatThreadClient();
PagedIterable<ChatMessageReadReceipt> readReceiptsResponse = chatThreadClient.listReadReceipts();
readReceiptsResponse.iterableByPage().forEach(resp -> {
System.out.printf("Response headers are %s. Url %s and status code %d %n", resp.getHeaders(),
resp.getRequest().getUrl(), resp.getStatusCode());
resp.getItems().forEach(readReceipt -> {
System.out.printf("Read message id is %s.", readReceipt.getChatMessageId());
});
});
}
/**
* Sample code sending a read receipt using the sync chat thread client.
*/
public void sendTypingNotification() {
ChatThreadClient chatThreadClient = getChatThreadClient();
chatThreadClient.sendTypingNotification();
}
} |
The Azure review requested we also be able to create it with the builder, but no mention of exclusivity. | public void getChatThread() {
ChatClient chatClient = createChatClient();
ChatThreadClient chatThreadClient = chatClient.getChatThreadClient("Id");
ChatThreadProperties chatThreadProperties = chatThreadClient.getProperties();
} | ChatThreadClient chatThreadClient = chatClient.getChatThreadClient("Id"); | public void getChatThread() {
ChatClient chatClient = createChatClient();
ChatThreadClient chatThreadClient = chatClient.getChatThreadClient("Id");
ChatThreadProperties chatThreadProperties = chatThreadClient.getProperties();
} | class ReadmeSamples {
/**
* Sample code for creating a sync chat client.
*
* @return the chat client.
*/
public ChatClient createChatClient() {
String endpoint = "https:
NettyAsyncHttpClientBuilder httpClientBuilder = new NettyAsyncHttpClientBuilder();
HttpClient httpClient = httpClientBuilder.build();
String token = "SECRET";
CommunicationTokenCredential credential = new CommunicationTokenCredential(token);
final ChatClientBuilder builder = new ChatClientBuilder();
builder.endpoint(endpoint)
.credential(credential)
.httpClient(httpClient);
ChatClient chatClient = builder.buildChatClient();
return chatClient;
}
/**
* Sample code for creating a chat thread using the sync chat client.
*/
public void createChatThread() {
ChatClient chatClient = createChatClient();
CommunicationUserIdentifier user1 = new CommunicationUserIdentifier("Id 1");
CommunicationUserIdentifier user2 = new CommunicationUserIdentifier("Id 2");
List<ChatParticipant> participants = new ArrayList<ChatParticipant>();
ChatParticipant firstParticipant = new ChatParticipant()
.setCommunicationIdentifier(user1)
.setDisplayName("Participant Display Name 1");
ChatParticipant secondParticipant = new ChatParticipant()
.setCommunicationIdentifier(user2)
.setDisplayName("Participant Display Name 2");
participants.add(firstParticipant);
participants.add(secondParticipant);
CreateChatThreadOptions createChatThreadOptions = new CreateChatThreadOptions()
.setTopic("Topic")
.setParticipants(participants);
CreateChatThreadResult result = chatClient.createChatThread(createChatThreadOptions);
String chatThreadId = result.getChatThread().getId();
}
/**
* Sample code for getting a chat thread using the sync chat client.
*/
/**
* Sample code for deleting a chat thread using the sync chat client.
*/
public void deleteChatThread() {
ChatClient chatClient = createChatClient();
String chatThreadId = "Id";
chatClient.deleteChatThread(chatThreadId);
}
/**
* Sample code for getting a sync chat thread client using the sync chat client.
*
* @return the chat thread client.
*/
public ChatThreadClient getChatThreadClient() {
ChatClient chatClient = createChatClient();
String chatThreadId = "Id";
ChatThreadClient chatThreadClient = chatClient.getChatThreadClient(chatThreadId);
return chatThreadClient;
}
/**
* Sample code for updating a chat thread topic using the sync chat thread client.
*/
public void updateTopic() {
ChatThreadClient chatThreadClient = getChatThreadClient();
chatThreadClient.updateTopic("New Topic");
}
/**
* Sample code for sending a chat message using the sync chat thread client.
*/
public void sendChatMessage() {
ChatThreadClient chatThreadClient = getChatThreadClient();
SendChatMessageOptions sendChatMessageOptions = new SendChatMessageOptions()
.setContent("Message content")
.setSenderDisplayName("Sender Display Name");
SendChatMessageResult sendResult = chatThreadClient.sendMessage(sendChatMessageOptions);
}
/**
* Sample code for getting a chat message using the sync chat thread client.
*/
public void getChatMessage() {
ChatThreadClient chatThreadClient = getChatThreadClient();
String chatMessageId = "Id";
ChatMessage chatMessage = chatThreadClient.getMessage(chatMessageId);
}
/**
* Sample code getting the thread messages using the sync chat thread client.
*/
public void getChatMessages() {
ChatThreadClient chatThreadClient = getChatThreadClient();
PagedIterable<ChatMessage> chatMessagesResponse = chatThreadClient.listMessages();
chatMessagesResponse.iterableByPage().forEach(resp -> {
System.out.printf("Response headers are %s. Url %s and status code %d %n", resp.getHeaders(),
resp.getRequest().getUrl(), resp.getStatusCode());
resp.getItems().forEach(message -> {
System.out.printf("Message id is %s.", message.getId());
});
});
}
/**
* Sample code updating a thread message using the sync chat thread client.
*/
public void updateChatMessage() {
ChatThreadClient chatThreadClient = getChatThreadClient();
String chatMessageId = "Id";
UpdateChatMessageOptions updateChatMessageOptions = new UpdateChatMessageOptions()
.setContent("Updated message content");
chatThreadClient.updateMessage(chatMessageId, updateChatMessageOptions);
}
/**
* Sample code deleting a thread message using the sync chat thread client.
*/
public void deleteChatMessage() {
ChatThreadClient chatThreadClient = getChatThreadClient();
String chatMessageId = "Id";
chatThreadClient.deleteMessage(chatMessageId);
}
/**
* Sample code listing chat participants using the sync chat thread client.
*/
public void listChatParticipants() {
ChatThreadClient chatThreadClient = getChatThreadClient();
PagedIterable<ChatParticipant> chatParticipantsResponse = chatThreadClient.listParticipants();
chatParticipantsResponse.iterableByPage().forEach(resp -> {
System.out.printf("Response headers are %s. Url %s and status code %d %n", resp.getHeaders(),
resp.getRequest().getUrl(), resp.getStatusCode());
resp.getItems().forEach(chatParticipant -> {
System.out.printf("Participant id is %s.", ((CommunicationUserIdentifier) chatParticipant.getCommunicationIdentifier()).getId());
});
});
}
/**
* Sample code adding chat participants using the sync chat thread client.
*/
public void addChatParticipants() {
ChatThreadClient chatThreadClient = getChatThreadClient();
CommunicationUserIdentifier user1 = new CommunicationUserIdentifier("Id 1");
CommunicationUserIdentifier user2 = new CommunicationUserIdentifier("Id 2");
List<ChatParticipant> participants = new ArrayList<ChatParticipant>();
ChatParticipant firstParticipant = new ChatParticipant()
.setCommunicationIdentifier(user1)
.setDisplayName("Display Name 1");
ChatParticipant secondParticipant = new ChatParticipant()
.setCommunicationIdentifier(user2)
.setDisplayName("Display Name 2");
participants.add(firstParticipant);
participants.add(secondParticipant);
chatThreadClient.addParticipants(participants);
}
/**
* Sample code removing a chat participant using the sync chat thread client.
*/
public void removeChatParticipant() {
ChatThreadClient chatThreadClient = getChatThreadClient();
CommunicationUserIdentifier user = new CommunicationUserIdentifier("Id");
chatThreadClient.removeParticipant(user);
}
/**
* Sample code sending a read receipt using the sync chat thread client.
*/
public void sendReadReceipt() {
ChatThreadClient chatThreadClient = getChatThreadClient();
String chatMessageId = "Id";
chatThreadClient.sendReadReceipt(chatMessageId);
}
/**
* Sample code listing read receipts using the sync chat thread client.
*/
public void listReadReceipts() {
ChatThreadClient chatThreadClient = getChatThreadClient();
PagedIterable<ChatMessageReadReceipt> readReceiptsResponse = chatThreadClient.listReadReceipts();
readReceiptsResponse.iterableByPage().forEach(resp -> {
System.out.printf("Response headers are %s. Url %s and status code %d %n", resp.getHeaders(),
resp.getRequest().getUrl(), resp.getStatusCode());
resp.getItems().forEach(readReceipt -> {
System.out.printf("Read message id is %s.", readReceipt.getChatMessageId());
});
});
}
/**
* Sample code sending a read receipt using the sync chat thread client.
*/
public void sendTypingNotification() {
ChatThreadClient chatThreadClient = getChatThreadClient();
chatThreadClient.sendTypingNotification();
}
} | class ReadmeSamples {
/**
* Sample code for creating a sync chat client.
*
* @return the chat client.
*/
public ChatClient createChatClient() {
String endpoint = "https:
NettyAsyncHttpClientBuilder httpClientBuilder = new NettyAsyncHttpClientBuilder();
HttpClient httpClient = httpClientBuilder.build();
String token = "SECRET";
CommunicationTokenCredential credential = new CommunicationTokenCredential(token);
final ChatClientBuilder builder = new ChatClientBuilder();
builder.endpoint(endpoint)
.credential(credential)
.httpClient(httpClient);
ChatClient chatClient = builder.buildClient();
return chatClient;
}
/**
* Sample code for creating a chat thread using the sync chat client.
*/
public void createChatThread() {
ChatClient chatClient = createChatClient();
CommunicationUserIdentifier user1 = new CommunicationUserIdentifier("Id 1");
CommunicationUserIdentifier user2 = new CommunicationUserIdentifier("Id 2");
List<ChatParticipant> participants = new ArrayList<ChatParticipant>();
ChatParticipant firstParticipant = new ChatParticipant()
.setCommunicationIdentifier(user1)
.setDisplayName("Participant Display Name 1");
ChatParticipant secondParticipant = new ChatParticipant()
.setCommunicationIdentifier(user2)
.setDisplayName("Participant Display Name 2");
participants.add(firstParticipant);
participants.add(secondParticipant);
CreateChatThreadOptions createChatThreadOptions = new CreateChatThreadOptions("Topic")
.setParticipants(participants);
CreateChatThreadResult result = chatClient.createChatThread(createChatThreadOptions);
String chatThreadId = result.getChatThread().getId();
}
/**
* Sample code for getting a chat thread using the sync chat client.
*/
/**
* Sample code for deleting a chat thread using the sync chat client.
*/
public void deleteChatThread() {
ChatClient chatClient = createChatClient();
String chatThreadId = "Id";
chatClient.deleteChatThread(chatThreadId);
}
/**
* Sample code for getting a sync chat thread client using the sync chat client.
*
* @return the chat thread client.
*/
public ChatThreadClient getChatThreadClient() {
ChatClient chatClient = createChatClient();
String chatThreadId = "Id";
ChatThreadClient chatThreadClient = chatClient.getChatThreadClient(chatThreadId);
return chatThreadClient;
}
/**
* Sample code for updating a chat thread topic using the sync chat thread client.
*/
public void updateTopic() {
ChatThreadClient chatThreadClient = getChatThreadClient();
chatThreadClient.updateTopic("New Topic");
}
/**
* Sample code for sending a chat message using the sync chat thread client.
*/
public void sendChatMessage() {
ChatThreadClient chatThreadClient = getChatThreadClient();
SendChatMessageOptions sendChatMessageOptions = new SendChatMessageOptions()
.setContent("Message content")
.setSenderDisplayName("Sender Display Name");
SendChatMessageResult sendResult = chatThreadClient.sendMessage(sendChatMessageOptions);
}
/**
* Sample code for getting a chat message using the sync chat thread client.
*/
public void getChatMessage() {
ChatThreadClient chatThreadClient = getChatThreadClient();
String chatMessageId = "Id";
ChatMessage chatMessage = chatThreadClient.getMessage(chatMessageId);
}
/**
* Sample code getting the thread messages using the sync chat thread client.
*/
public void getChatMessages() {
ChatThreadClient chatThreadClient = getChatThreadClient();
PagedIterable<ChatMessage> chatMessagesResponse = chatThreadClient.listMessages();
chatMessagesResponse.iterableByPage().forEach(resp -> {
System.out.printf("Response headers are %s. Url %s and status code %d %n", resp.getHeaders(),
resp.getRequest().getUrl(), resp.getStatusCode());
resp.getItems().forEach(message -> {
System.out.printf("Message id is %s.", message.getId());
});
});
}
/**
* Sample code updating a thread message using the sync chat thread client.
*/
public void updateChatMessage() {
ChatThreadClient chatThreadClient = getChatThreadClient();
String chatMessageId = "Id";
UpdateChatMessageOptions updateChatMessageOptions = new UpdateChatMessageOptions()
.setContent("Updated message content");
chatThreadClient.updateMessage(chatMessageId, updateChatMessageOptions);
}
/**
* Sample code deleting a thread message using the sync chat thread client.
*/
public void deleteChatMessage() {
ChatThreadClient chatThreadClient = getChatThreadClient();
String chatMessageId = "Id";
chatThreadClient.deleteMessage(chatMessageId);
}
/**
* Sample code listing chat participants using the sync chat thread client.
*/
public void listChatParticipants() {
ChatThreadClient chatThreadClient = getChatThreadClient();
PagedIterable<ChatParticipant> chatParticipantsResponse = chatThreadClient.listParticipants();
chatParticipantsResponse.iterableByPage().forEach(resp -> {
System.out.printf("Response headers are %s. Url %s and status code %d %n", resp.getHeaders(),
resp.getRequest().getUrl(), resp.getStatusCode());
resp.getItems().forEach(chatParticipant -> {
System.out.printf("Participant id is %s.", ((CommunicationUserIdentifier) chatParticipant.getCommunicationIdentifier()).getId());
});
});
}
/**
* Sample code adding chat participants using the sync chat thread client.
*/
public void addChatParticipants() {
ChatThreadClient chatThreadClient = getChatThreadClient();
CommunicationUserIdentifier user1 = new CommunicationUserIdentifier("Id 1");
CommunicationUserIdentifier user2 = new CommunicationUserIdentifier("Id 2");
List<ChatParticipant> participants = new ArrayList<ChatParticipant>();
ChatParticipant firstParticipant = new ChatParticipant()
.setCommunicationIdentifier(user1)
.setDisplayName("Display Name 1");
ChatParticipant secondParticipant = new ChatParticipant()
.setCommunicationIdentifier(user2)
.setDisplayName("Display Name 2");
participants.add(firstParticipant);
participants.add(secondParticipant);
chatThreadClient.addParticipants(participants);
}
/**
* Sample code removing a chat participant using the sync chat thread client.
*/
public void removeChatParticipant() {
ChatThreadClient chatThreadClient = getChatThreadClient();
CommunicationUserIdentifier user = new CommunicationUserIdentifier("Id");
chatThreadClient.removeParticipant(user);
}
/**
* Sample code sending a read receipt using the sync chat thread client.
*/
public void sendReadReceipt() {
ChatThreadClient chatThreadClient = getChatThreadClient();
String chatMessageId = "Id";
chatThreadClient.sendReadReceipt(chatMessageId);
}
/**
* Sample code listing read receipts using the sync chat thread client.
*/
public void listReadReceipts() {
ChatThreadClient chatThreadClient = getChatThreadClient();
PagedIterable<ChatMessageReadReceipt> readReceiptsResponse = chatThreadClient.listReadReceipts();
readReceiptsResponse.iterableByPage().forEach(resp -> {
System.out.printf("Response headers are %s. Url %s and status code %d %n", resp.getHeaders(),
resp.getRequest().getUrl(), resp.getStatusCode());
resp.getItems().forEach(readReceipt -> {
System.out.printf("Read message id is %s.", readReceipt.getChatMessageId());
});
});
}
/**
* Sample code sending a read receipt using the sync chat thread client.
*/
public void sendTypingNotification() {
ChatThreadClient chatThreadClient = getChatThreadClient();
chatThreadClient.sendTypingNotification();
}
} |
The builder does not replace this method, all the other SDKs have this method, so I don't think we should remove it. The Azure review board asked us to also be able to create it with the builder. | public void getChatThread() {
ChatClient chatClient = createChatClient();
ChatThreadClient chatThreadClient = chatClient.getChatThreadClient("Id");
ChatThreadProperties chatThreadProperties = chatThreadClient.getProperties();
} | ChatThreadClient chatThreadClient = chatClient.getChatThreadClient("Id"); | public void getChatThread() {
ChatClient chatClient = createChatClient();
ChatThreadClient chatThreadClient = chatClient.getChatThreadClient("Id");
ChatThreadProperties chatThreadProperties = chatThreadClient.getProperties();
} | class ReadmeSamples {
/**
* Sample code for creating a sync chat client.
*
* @return the chat client.
*/
public ChatClient createChatClient() {
String endpoint = "https:
NettyAsyncHttpClientBuilder httpClientBuilder = new NettyAsyncHttpClientBuilder();
HttpClient httpClient = httpClientBuilder.build();
String token = "SECRET";
CommunicationTokenCredential credential = new CommunicationTokenCredential(token);
final ChatClientBuilder builder = new ChatClientBuilder();
builder.endpoint(endpoint)
.credential(credential)
.httpClient(httpClient);
ChatClient chatClient = builder.buildChatClient();
return chatClient;
}
/**
* Sample code for creating a chat thread using the sync chat client.
*/
public void createChatThread() {
ChatClient chatClient = createChatClient();
CommunicationUserIdentifier user1 = new CommunicationUserIdentifier("Id 1");
CommunicationUserIdentifier user2 = new CommunicationUserIdentifier("Id 2");
List<ChatParticipant> participants = new ArrayList<ChatParticipant>();
ChatParticipant firstParticipant = new ChatParticipant()
.setCommunicationIdentifier(user1)
.setDisplayName("Participant Display Name 1");
ChatParticipant secondParticipant = new ChatParticipant()
.setCommunicationIdentifier(user2)
.setDisplayName("Participant Display Name 2");
participants.add(firstParticipant);
participants.add(secondParticipant);
CreateChatThreadOptions createChatThreadOptions = new CreateChatThreadOptions()
.setTopic("Topic")
.setParticipants(participants);
CreateChatThreadResult result = chatClient.createChatThread(createChatThreadOptions);
String chatThreadId = result.getChatThread().getId();
}
/**
* Sample code for getting a chat thread using the sync chat client.
*/
/**
* Sample code for deleting a chat thread using the sync chat client.
*/
public void deleteChatThread() {
ChatClient chatClient = createChatClient();
String chatThreadId = "Id";
chatClient.deleteChatThread(chatThreadId);
}
/**
* Sample code for getting a sync chat thread client using the sync chat client.
*
* @return the chat thread client.
*/
public ChatThreadClient getChatThreadClient() {
ChatClient chatClient = createChatClient();
String chatThreadId = "Id";
ChatThreadClient chatThreadClient = chatClient.getChatThreadClient(chatThreadId);
return chatThreadClient;
}
/**
* Sample code for updating a chat thread topic using the sync chat thread client.
*/
public void updateTopic() {
ChatThreadClient chatThreadClient = getChatThreadClient();
chatThreadClient.updateTopic("New Topic");
}
/**
* Sample code for sending a chat message using the sync chat thread client.
*/
public void sendChatMessage() {
ChatThreadClient chatThreadClient = getChatThreadClient();
SendChatMessageOptions sendChatMessageOptions = new SendChatMessageOptions()
.setContent("Message content")
.setSenderDisplayName("Sender Display Name");
SendChatMessageResult sendResult = chatThreadClient.sendMessage(sendChatMessageOptions);
}
/**
* Sample code for getting a chat message using the sync chat thread client.
*/
public void getChatMessage() {
ChatThreadClient chatThreadClient = getChatThreadClient();
String chatMessageId = "Id";
ChatMessage chatMessage = chatThreadClient.getMessage(chatMessageId);
}
/**
* Sample code getting the thread messages using the sync chat thread client.
*/
public void getChatMessages() {
ChatThreadClient chatThreadClient = getChatThreadClient();
PagedIterable<ChatMessage> chatMessagesResponse = chatThreadClient.listMessages();
chatMessagesResponse.iterableByPage().forEach(resp -> {
System.out.printf("Response headers are %s. Url %s and status code %d %n", resp.getHeaders(),
resp.getRequest().getUrl(), resp.getStatusCode());
resp.getItems().forEach(message -> {
System.out.printf("Message id is %s.", message.getId());
});
});
}
/**
* Sample code updating a thread message using the sync chat thread client.
*/
public void updateChatMessage() {
ChatThreadClient chatThreadClient = getChatThreadClient();
String chatMessageId = "Id";
UpdateChatMessageOptions updateChatMessageOptions = new UpdateChatMessageOptions()
.setContent("Updated message content");
chatThreadClient.updateMessage(chatMessageId, updateChatMessageOptions);
}
/**
* Sample code deleting a thread message using the sync chat thread client.
*/
public void deleteChatMessage() {
ChatThreadClient chatThreadClient = getChatThreadClient();
String chatMessageId = "Id";
chatThreadClient.deleteMessage(chatMessageId);
}
/**
* Sample code listing chat participants using the sync chat thread client.
*/
public void listChatParticipants() {
ChatThreadClient chatThreadClient = getChatThreadClient();
PagedIterable<ChatParticipant> chatParticipantsResponse = chatThreadClient.listParticipants();
chatParticipantsResponse.iterableByPage().forEach(resp -> {
System.out.printf("Response headers are %s. Url %s and status code %d %n", resp.getHeaders(),
resp.getRequest().getUrl(), resp.getStatusCode());
resp.getItems().forEach(chatParticipant -> {
System.out.printf("Participant id is %s.", ((CommunicationUserIdentifier) chatParticipant.getCommunicationIdentifier()).getId());
});
});
}
/**
* Sample code adding chat participants using the sync chat thread client.
*/
public void addChatParticipants() {
ChatThreadClient chatThreadClient = getChatThreadClient();
CommunicationUserIdentifier user1 = new CommunicationUserIdentifier("Id 1");
CommunicationUserIdentifier user2 = new CommunicationUserIdentifier("Id 2");
List<ChatParticipant> participants = new ArrayList<ChatParticipant>();
ChatParticipant firstParticipant = new ChatParticipant()
.setCommunicationIdentifier(user1)
.setDisplayName("Display Name 1");
ChatParticipant secondParticipant = new ChatParticipant()
.setCommunicationIdentifier(user2)
.setDisplayName("Display Name 2");
participants.add(firstParticipant);
participants.add(secondParticipant);
chatThreadClient.addParticipants(participants);
}
/**
* Sample code removing a chat participant using the sync chat thread client.
*/
public void removeChatParticipant() {
ChatThreadClient chatThreadClient = getChatThreadClient();
CommunicationUserIdentifier user = new CommunicationUserIdentifier("Id");
chatThreadClient.removeParticipant(user);
}
/**
* Sample code sending a read receipt using the sync chat thread client.
*/
public void sendReadReceipt() {
ChatThreadClient chatThreadClient = getChatThreadClient();
String chatMessageId = "Id";
chatThreadClient.sendReadReceipt(chatMessageId);
}
/**
* Sample code listing read receipts using the sync chat thread client.
*/
public void listReadReceipts() {
ChatThreadClient chatThreadClient = getChatThreadClient();
PagedIterable<ChatMessageReadReceipt> readReceiptsResponse = chatThreadClient.listReadReceipts();
readReceiptsResponse.iterableByPage().forEach(resp -> {
System.out.printf("Response headers are %s. Url %s and status code %d %n", resp.getHeaders(),
resp.getRequest().getUrl(), resp.getStatusCode());
resp.getItems().forEach(readReceipt -> {
System.out.printf("Read message id is %s.", readReceipt.getChatMessageId());
});
});
}
/**
* Sample code sending a read receipt using the sync chat thread client.
*/
public void sendTypingNotification() {
ChatThreadClient chatThreadClient = getChatThreadClient();
chatThreadClient.sendTypingNotification();
}
} | class ReadmeSamples {
/**
* Sample code for creating a sync chat client.
*
* @return the chat client.
*/
public ChatClient createChatClient() {
String endpoint = "https:
NettyAsyncHttpClientBuilder httpClientBuilder = new NettyAsyncHttpClientBuilder();
HttpClient httpClient = httpClientBuilder.build();
String token = "SECRET";
CommunicationTokenCredential credential = new CommunicationTokenCredential(token);
final ChatClientBuilder builder = new ChatClientBuilder();
builder.endpoint(endpoint)
.credential(credential)
.httpClient(httpClient);
ChatClient chatClient = builder.buildClient();
return chatClient;
}
/**
* Sample code for creating a chat thread using the sync chat client.
*/
public void createChatThread() {
ChatClient chatClient = createChatClient();
CommunicationUserIdentifier user1 = new CommunicationUserIdentifier("Id 1");
CommunicationUserIdentifier user2 = new CommunicationUserIdentifier("Id 2");
List<ChatParticipant> participants = new ArrayList<ChatParticipant>();
ChatParticipant firstParticipant = new ChatParticipant()
.setCommunicationIdentifier(user1)
.setDisplayName("Participant Display Name 1");
ChatParticipant secondParticipant = new ChatParticipant()
.setCommunicationIdentifier(user2)
.setDisplayName("Participant Display Name 2");
participants.add(firstParticipant);
participants.add(secondParticipant);
CreateChatThreadOptions createChatThreadOptions = new CreateChatThreadOptions("Topic")
.setParticipants(participants);
CreateChatThreadResult result = chatClient.createChatThread(createChatThreadOptions);
String chatThreadId = result.getChatThread().getId();
}
/**
* Sample code for getting a chat thread using the sync chat client.
*/
/**
* Sample code for deleting a chat thread using the sync chat client.
*/
public void deleteChatThread() {
ChatClient chatClient = createChatClient();
String chatThreadId = "Id";
chatClient.deleteChatThread(chatThreadId);
}
/**
* Sample code for getting a sync chat thread client using the sync chat client.
*
* @return the chat thread client.
*/
public ChatThreadClient getChatThreadClient() {
ChatClient chatClient = createChatClient();
String chatThreadId = "Id";
ChatThreadClient chatThreadClient = chatClient.getChatThreadClient(chatThreadId);
return chatThreadClient;
}
/**
* Sample code for updating a chat thread topic using the sync chat thread client.
*/
public void updateTopic() {
ChatThreadClient chatThreadClient = getChatThreadClient();
chatThreadClient.updateTopic("New Topic");
}
/**
* Sample code for sending a chat message using the sync chat thread client.
*/
public void sendChatMessage() {
ChatThreadClient chatThreadClient = getChatThreadClient();
SendChatMessageOptions sendChatMessageOptions = new SendChatMessageOptions()
.setContent("Message content")
.setSenderDisplayName("Sender Display Name");
SendChatMessageResult sendResult = chatThreadClient.sendMessage(sendChatMessageOptions);
}
/**
* Sample code for getting a chat message using the sync chat thread client.
*/
public void getChatMessage() {
ChatThreadClient chatThreadClient = getChatThreadClient();
String chatMessageId = "Id";
ChatMessage chatMessage = chatThreadClient.getMessage(chatMessageId);
}
/**
* Sample code getting the thread messages using the sync chat thread client.
*/
public void getChatMessages() {
ChatThreadClient chatThreadClient = getChatThreadClient();
PagedIterable<ChatMessage> chatMessagesResponse = chatThreadClient.listMessages();
chatMessagesResponse.iterableByPage().forEach(resp -> {
System.out.printf("Response headers are %s. Url %s and status code %d %n", resp.getHeaders(),
resp.getRequest().getUrl(), resp.getStatusCode());
resp.getItems().forEach(message -> {
System.out.printf("Message id is %s.", message.getId());
});
});
}
/**
* Sample code updating a thread message using the sync chat thread client.
*/
public void updateChatMessage() {
ChatThreadClient chatThreadClient = getChatThreadClient();
String chatMessageId = "Id";
UpdateChatMessageOptions updateChatMessageOptions = new UpdateChatMessageOptions()
.setContent("Updated message content");
chatThreadClient.updateMessage(chatMessageId, updateChatMessageOptions);
}
/**
* Sample code deleting a thread message using the sync chat thread client.
*/
public void deleteChatMessage() {
ChatThreadClient chatThreadClient = getChatThreadClient();
String chatMessageId = "Id";
chatThreadClient.deleteMessage(chatMessageId);
}
/**
* Sample code listing chat participants using the sync chat thread client.
*/
public void listChatParticipants() {
ChatThreadClient chatThreadClient = getChatThreadClient();
PagedIterable<ChatParticipant> chatParticipantsResponse = chatThreadClient.listParticipants();
chatParticipantsResponse.iterableByPage().forEach(resp -> {
System.out.printf("Response headers are %s. Url %s and status code %d %n", resp.getHeaders(),
resp.getRequest().getUrl(), resp.getStatusCode());
resp.getItems().forEach(chatParticipant -> {
System.out.printf("Participant id is %s.", ((CommunicationUserIdentifier) chatParticipant.getCommunicationIdentifier()).getId());
});
});
}
/**
* Sample code adding chat participants using the sync chat thread client.
*/
public void addChatParticipants() {
ChatThreadClient chatThreadClient = getChatThreadClient();
CommunicationUserIdentifier user1 = new CommunicationUserIdentifier("Id 1");
CommunicationUserIdentifier user2 = new CommunicationUserIdentifier("Id 2");
List<ChatParticipant> participants = new ArrayList<ChatParticipant>();
ChatParticipant firstParticipant = new ChatParticipant()
.setCommunicationIdentifier(user1)
.setDisplayName("Display Name 1");
ChatParticipant secondParticipant = new ChatParticipant()
.setCommunicationIdentifier(user2)
.setDisplayName("Display Name 2");
participants.add(firstParticipant);
participants.add(secondParticipant);
chatThreadClient.addParticipants(participants);
}
/**
* Sample code removing a chat participant using the sync chat thread client.
*/
public void removeChatParticipant() {
ChatThreadClient chatThreadClient = getChatThreadClient();
CommunicationUserIdentifier user = new CommunicationUserIdentifier("Id");
chatThreadClient.removeParticipant(user);
}
/**
* Sample code sending a read receipt using the sync chat thread client.
*/
public void sendReadReceipt() {
ChatThreadClient chatThreadClient = getChatThreadClient();
String chatMessageId = "Id";
chatThreadClient.sendReadReceipt(chatMessageId);
}
/**
* Sample code listing read receipts using the sync chat thread client.
*/
public void listReadReceipts() {
ChatThreadClient chatThreadClient = getChatThreadClient();
PagedIterable<ChatMessageReadReceipt> readReceiptsResponse = chatThreadClient.listReadReceipts();
readReceiptsResponse.iterableByPage().forEach(resp -> {
System.out.printf("Response headers are %s. Url %s and status code %d %n", resp.getHeaders(),
resp.getRequest().getUrl(), resp.getStatusCode());
resp.getItems().forEach(readReceipt -> {
System.out.printf("Read message id is %s.", readReceipt.getChatMessageId());
});
});
}
/**
* Sample code sending a read receipt using the sync chat thread client.
*/
public void sendTypingNotification() {
ChatThreadClient chatThreadClient = getChatThreadClient();
chatThreadClient.sendTypingNotification();
}
} |
Yes, this has been discussed in the arch board review - https://github.com/Azure/azure-sdk/issues/1895 Also, refer to the guideline here - https://azure.github.io/azure-sdk/dotnet_introduction.html#dotnet-client-hierarchy | public void getChatThread() {
ChatClient chatClient = createChatClient();
ChatThreadClient chatThreadClient = chatClient.getChatThreadClient("Id");
ChatThreadProperties chatThreadProperties = chatThreadClient.getProperties();
} | ChatThreadClient chatThreadClient = chatClient.getChatThreadClient("Id"); | public void getChatThread() {
ChatClient chatClient = createChatClient();
ChatThreadClient chatThreadClient = chatClient.getChatThreadClient("Id");
ChatThreadProperties chatThreadProperties = chatThreadClient.getProperties();
} | class ReadmeSamples {
/**
* Sample code for creating a sync chat client.
*
* @return the chat client.
*/
public ChatClient createChatClient() {
String endpoint = "https:
NettyAsyncHttpClientBuilder httpClientBuilder = new NettyAsyncHttpClientBuilder();
HttpClient httpClient = httpClientBuilder.build();
String token = "SECRET";
CommunicationTokenCredential credential = new CommunicationTokenCredential(token);
final ChatClientBuilder builder = new ChatClientBuilder();
builder.endpoint(endpoint)
.credential(credential)
.httpClient(httpClient);
ChatClient chatClient = builder.buildChatClient();
return chatClient;
}
/**
* Sample code for creating a chat thread using the sync chat client.
*/
public void createChatThread() {
ChatClient chatClient = createChatClient();
CommunicationUserIdentifier user1 = new CommunicationUserIdentifier("Id 1");
CommunicationUserIdentifier user2 = new CommunicationUserIdentifier("Id 2");
List<ChatParticipant> participants = new ArrayList<ChatParticipant>();
ChatParticipant firstParticipant = new ChatParticipant()
.setCommunicationIdentifier(user1)
.setDisplayName("Participant Display Name 1");
ChatParticipant secondParticipant = new ChatParticipant()
.setCommunicationIdentifier(user2)
.setDisplayName("Participant Display Name 2");
participants.add(firstParticipant);
participants.add(secondParticipant);
CreateChatThreadOptions createChatThreadOptions = new CreateChatThreadOptions()
.setTopic("Topic")
.setParticipants(participants);
CreateChatThreadResult result = chatClient.createChatThread(createChatThreadOptions);
String chatThreadId = result.getChatThread().getId();
}
/**
* Sample code for getting a chat thread using the sync chat client.
*/
/**
* Sample code for deleting a chat thread using the sync chat client.
*/
public void deleteChatThread() {
ChatClient chatClient = createChatClient();
String chatThreadId = "Id";
chatClient.deleteChatThread(chatThreadId);
}
/**
* Sample code for getting a sync chat thread client using the sync chat client.
*
* @return the chat thread client.
*/
public ChatThreadClient getChatThreadClient() {
ChatClient chatClient = createChatClient();
String chatThreadId = "Id";
ChatThreadClient chatThreadClient = chatClient.getChatThreadClient(chatThreadId);
return chatThreadClient;
}
/**
* Sample code for updating a chat thread topic using the sync chat thread client.
*/
public void updateTopic() {
ChatThreadClient chatThreadClient = getChatThreadClient();
chatThreadClient.updateTopic("New Topic");
}
/**
* Sample code for sending a chat message using the sync chat thread client.
*/
public void sendChatMessage() {
ChatThreadClient chatThreadClient = getChatThreadClient();
SendChatMessageOptions sendChatMessageOptions = new SendChatMessageOptions()
.setContent("Message content")
.setSenderDisplayName("Sender Display Name");
SendChatMessageResult sendResult = chatThreadClient.sendMessage(sendChatMessageOptions);
}
/**
* Sample code for getting a chat message using the sync chat thread client.
*/
public void getChatMessage() {
ChatThreadClient chatThreadClient = getChatThreadClient();
String chatMessageId = "Id";
ChatMessage chatMessage = chatThreadClient.getMessage(chatMessageId);
}
/**
* Sample code getting the thread messages using the sync chat thread client.
*/
public void getChatMessages() {
ChatThreadClient chatThreadClient = getChatThreadClient();
PagedIterable<ChatMessage> chatMessagesResponse = chatThreadClient.listMessages();
chatMessagesResponse.iterableByPage().forEach(resp -> {
System.out.printf("Response headers are %s. Url %s and status code %d %n", resp.getHeaders(),
resp.getRequest().getUrl(), resp.getStatusCode());
resp.getItems().forEach(message -> {
System.out.printf("Message id is %s.", message.getId());
});
});
}
/**
* Sample code updating a thread message using the sync chat thread client.
*/
public void updateChatMessage() {
ChatThreadClient chatThreadClient = getChatThreadClient();
String chatMessageId = "Id";
UpdateChatMessageOptions updateChatMessageOptions = new UpdateChatMessageOptions()
.setContent("Updated message content");
chatThreadClient.updateMessage(chatMessageId, updateChatMessageOptions);
}
/**
* Sample code deleting a thread message using the sync chat thread client.
*/
public void deleteChatMessage() {
ChatThreadClient chatThreadClient = getChatThreadClient();
String chatMessageId = "Id";
chatThreadClient.deleteMessage(chatMessageId);
}
/**
* Sample code listing chat participants using the sync chat thread client.
*/
public void listChatParticipants() {
ChatThreadClient chatThreadClient = getChatThreadClient();
PagedIterable<ChatParticipant> chatParticipantsResponse = chatThreadClient.listParticipants();
chatParticipantsResponse.iterableByPage().forEach(resp -> {
System.out.printf("Response headers are %s. Url %s and status code %d %n", resp.getHeaders(),
resp.getRequest().getUrl(), resp.getStatusCode());
resp.getItems().forEach(chatParticipant -> {
System.out.printf("Participant id is %s.", ((CommunicationUserIdentifier) chatParticipant.getCommunicationIdentifier()).getId());
});
});
}
/**
* Sample code adding chat participants using the sync chat thread client.
*/
public void addChatParticipants() {
ChatThreadClient chatThreadClient = getChatThreadClient();
CommunicationUserIdentifier user1 = new CommunicationUserIdentifier("Id 1");
CommunicationUserIdentifier user2 = new CommunicationUserIdentifier("Id 2");
List<ChatParticipant> participants = new ArrayList<ChatParticipant>();
ChatParticipant firstParticipant = new ChatParticipant()
.setCommunicationIdentifier(user1)
.setDisplayName("Display Name 1");
ChatParticipant secondParticipant = new ChatParticipant()
.setCommunicationIdentifier(user2)
.setDisplayName("Display Name 2");
participants.add(firstParticipant);
participants.add(secondParticipant);
chatThreadClient.addParticipants(participants);
}
/**
* Sample code removing a chat participant using the sync chat thread client.
*/
public void removeChatParticipant() {
ChatThreadClient chatThreadClient = getChatThreadClient();
CommunicationUserIdentifier user = new CommunicationUserIdentifier("Id");
chatThreadClient.removeParticipant(user);
}
/**
* Sample code sending a read receipt using the sync chat thread client.
*/
public void sendReadReceipt() {
ChatThreadClient chatThreadClient = getChatThreadClient();
String chatMessageId = "Id";
chatThreadClient.sendReadReceipt(chatMessageId);
}
/**
* Sample code listing read receipts using the sync chat thread client.
*/
public void listReadReceipts() {
ChatThreadClient chatThreadClient = getChatThreadClient();
PagedIterable<ChatMessageReadReceipt> readReceiptsResponse = chatThreadClient.listReadReceipts();
readReceiptsResponse.iterableByPage().forEach(resp -> {
System.out.printf("Response headers are %s. Url %s and status code %d %n", resp.getHeaders(),
resp.getRequest().getUrl(), resp.getStatusCode());
resp.getItems().forEach(readReceipt -> {
System.out.printf("Read message id is %s.", readReceipt.getChatMessageId());
});
});
}
/**
* Sample code sending a read receipt using the sync chat thread client.
*/
public void sendTypingNotification() {
ChatThreadClient chatThreadClient = getChatThreadClient();
chatThreadClient.sendTypingNotification();
}
} | class ReadmeSamples {
/**
* Sample code for creating a sync chat client.
*
* @return the chat client.
*/
public ChatClient createChatClient() {
String endpoint = "https:
NettyAsyncHttpClientBuilder httpClientBuilder = new NettyAsyncHttpClientBuilder();
HttpClient httpClient = httpClientBuilder.build();
String token = "SECRET";
CommunicationTokenCredential credential = new CommunicationTokenCredential(token);
final ChatClientBuilder builder = new ChatClientBuilder();
builder.endpoint(endpoint)
.credential(credential)
.httpClient(httpClient);
ChatClient chatClient = builder.buildClient();
return chatClient;
}
/**
* Sample code for creating a chat thread using the sync chat client.
*/
public void createChatThread() {
ChatClient chatClient = createChatClient();
CommunicationUserIdentifier user1 = new CommunicationUserIdentifier("Id 1");
CommunicationUserIdentifier user2 = new CommunicationUserIdentifier("Id 2");
List<ChatParticipant> participants = new ArrayList<ChatParticipant>();
ChatParticipant firstParticipant = new ChatParticipant()
.setCommunicationIdentifier(user1)
.setDisplayName("Participant Display Name 1");
ChatParticipant secondParticipant = new ChatParticipant()
.setCommunicationIdentifier(user2)
.setDisplayName("Participant Display Name 2");
participants.add(firstParticipant);
participants.add(secondParticipant);
CreateChatThreadOptions createChatThreadOptions = new CreateChatThreadOptions("Topic")
.setParticipants(participants);
CreateChatThreadResult result = chatClient.createChatThread(createChatThreadOptions);
String chatThreadId = result.getChatThread().getId();
}
/**
* Sample code for getting a chat thread using the sync chat client.
*/
/**
* Sample code for deleting a chat thread using the sync chat client.
*/
public void deleteChatThread() {
ChatClient chatClient = createChatClient();
String chatThreadId = "Id";
chatClient.deleteChatThread(chatThreadId);
}
/**
* Sample code for getting a sync chat thread client using the sync chat client.
*
* @return the chat thread client.
*/
public ChatThreadClient getChatThreadClient() {
ChatClient chatClient = createChatClient();
String chatThreadId = "Id";
ChatThreadClient chatThreadClient = chatClient.getChatThreadClient(chatThreadId);
return chatThreadClient;
}
/**
* Sample code for updating a chat thread topic using the sync chat thread client.
*/
public void updateTopic() {
ChatThreadClient chatThreadClient = getChatThreadClient();
chatThreadClient.updateTopic("New Topic");
}
/**
* Sample code for sending a chat message using the sync chat thread client.
*/
public void sendChatMessage() {
ChatThreadClient chatThreadClient = getChatThreadClient();
SendChatMessageOptions sendChatMessageOptions = new SendChatMessageOptions()
.setContent("Message content")
.setSenderDisplayName("Sender Display Name");
SendChatMessageResult sendResult = chatThreadClient.sendMessage(sendChatMessageOptions);
}
/**
* Sample code for getting a chat message using the sync chat thread client.
*/
public void getChatMessage() {
ChatThreadClient chatThreadClient = getChatThreadClient();
String chatMessageId = "Id";
ChatMessage chatMessage = chatThreadClient.getMessage(chatMessageId);
}
/**
* Sample code getting the thread messages using the sync chat thread client.
*/
public void getChatMessages() {
ChatThreadClient chatThreadClient = getChatThreadClient();
PagedIterable<ChatMessage> chatMessagesResponse = chatThreadClient.listMessages();
chatMessagesResponse.iterableByPage().forEach(resp -> {
System.out.printf("Response headers are %s. Url %s and status code %d %n", resp.getHeaders(),
resp.getRequest().getUrl(), resp.getStatusCode());
resp.getItems().forEach(message -> {
System.out.printf("Message id is %s.", message.getId());
});
});
}
/**
* Sample code updating a thread message using the sync chat thread client.
*/
public void updateChatMessage() {
ChatThreadClient chatThreadClient = getChatThreadClient();
String chatMessageId = "Id";
UpdateChatMessageOptions updateChatMessageOptions = new UpdateChatMessageOptions()
.setContent("Updated message content");
chatThreadClient.updateMessage(chatMessageId, updateChatMessageOptions);
}
/**
* Sample code deleting a thread message using the sync chat thread client.
*/
public void deleteChatMessage() {
ChatThreadClient chatThreadClient = getChatThreadClient();
String chatMessageId = "Id";
chatThreadClient.deleteMessage(chatMessageId);
}
/**
* Sample code listing chat participants using the sync chat thread client.
*/
public void listChatParticipants() {
ChatThreadClient chatThreadClient = getChatThreadClient();
PagedIterable<ChatParticipant> chatParticipantsResponse = chatThreadClient.listParticipants();
chatParticipantsResponse.iterableByPage().forEach(resp -> {
System.out.printf("Response headers are %s. Url %s and status code %d %n", resp.getHeaders(),
resp.getRequest().getUrl(), resp.getStatusCode());
resp.getItems().forEach(chatParticipant -> {
System.out.printf("Participant id is %s.", ((CommunicationUserIdentifier) chatParticipant.getCommunicationIdentifier()).getId());
});
});
}
/**
* Sample code adding chat participants using the sync chat thread client.
*/
public void addChatParticipants() {
ChatThreadClient chatThreadClient = getChatThreadClient();
CommunicationUserIdentifier user1 = new CommunicationUserIdentifier("Id 1");
CommunicationUserIdentifier user2 = new CommunicationUserIdentifier("Id 2");
List<ChatParticipant> participants = new ArrayList<ChatParticipant>();
ChatParticipant firstParticipant = new ChatParticipant()
.setCommunicationIdentifier(user1)
.setDisplayName("Display Name 1");
ChatParticipant secondParticipant = new ChatParticipant()
.setCommunicationIdentifier(user2)
.setDisplayName("Display Name 2");
participants.add(firstParticipant);
participants.add(secondParticipant);
chatThreadClient.addParticipants(participants);
}
/**
* Sample code removing a chat participant using the sync chat thread client.
*/
public void removeChatParticipant() {
ChatThreadClient chatThreadClient = getChatThreadClient();
CommunicationUserIdentifier user = new CommunicationUserIdentifier("Id");
chatThreadClient.removeParticipant(user);
}
/**
* Sample code sending a read receipt using the sync chat thread client.
*/
public void sendReadReceipt() {
ChatThreadClient chatThreadClient = getChatThreadClient();
String chatMessageId = "Id";
chatThreadClient.sendReadReceipt(chatMessageId);
}
/**
* Sample code listing read receipts using the sync chat thread client.
*/
public void listReadReceipts() {
ChatThreadClient chatThreadClient = getChatThreadClient();
PagedIterable<ChatMessageReadReceipt> readReceiptsResponse = chatThreadClient.listReadReceipts();
readReceiptsResponse.iterableByPage().forEach(resp -> {
System.out.printf("Response headers are %s. Url %s and status code %d %n", resp.getHeaders(),
resp.getRequest().getUrl(), resp.getStatusCode());
resp.getItems().forEach(readReceipt -> {
System.out.printf("Read message id is %s.", readReceipt.getChatMessageId());
});
});
}
/**
* Sample code sending a read receipt using the sync chat thread client.
*/
public void sendTypingNotification() {
ChatThreadClient chatThreadClient = getChatThreadClient();
chatThreadClient.sendTypingNotification();
}
} |
`APPROLE_PREFIX` | public OidcUser loadUser(OidcUserRequest userRequest) throws OAuth2AuthenticationException {
OidcUser oidcUser = oidcUserService.loadUser(userRequest);
OidcIdToken idToken = oidcUser.getIdToken();
Set<String> roles = new HashSet<>();
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
ServletRequestAttributes attr = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
HttpSession session = attr.getRequest().getSession(true);
if (authentication != null) {
return (DefaultOidcUser) session.getAttribute(DEFAULT_OIDC_USER);
}
if (idToken.containsClaim(ROLES)) {
roles = idToken.getClaimAsStringList(ROLES)
.stream()
.filter(s -> StringUtils.hasText(s))
.map(role -> ROLE_PREFIX + role)
.collect(Collectors.toSet());
}
Set<String> groups = Optional.of(userRequest)
.filter(notUsed -> properties.allowedGroupsConfigured())
.map(OAuth2UserRequest::getAccessToken)
.map(AbstractOAuth2Token::getTokenValue)
.map(graphClient::getGroupsFromGraph)
.orElseGet(Collections::emptySet);
Set<String> groupRoles = groups.stream()
.filter(properties::isAllowedGroup)
.map(group -> ROLE_PREFIX + group)
.collect(Collectors.toSet());
roles.addAll(groupRoles);
Set<SimpleGrantedAuthority> authorities = roles.stream()
.map(SimpleGrantedAuthority::new)
.collect(Collectors.toSet());
if (authorities.isEmpty()) {
authorities = DEFAULT_AUTHORITY_SET;
}
String nameAttributeKey =
Optional.of(userRequest)
.map(OAuth2UserRequest::getClientRegistration)
.map(ClientRegistration::getProviderDetails)
.map(ClientRegistration.ProviderDetails::getUserInfoEndpoint)
.map(ClientRegistration.ProviderDetails.UserInfoEndpoint::getUserNameAttributeName)
.filter(StringUtils::hasText)
.orElse(AADTokenClaim.NAME);
DefaultOidcUser defaultOidcUser = new DefaultOidcUser(authorities, idToken, nameAttributeKey);
session.setAttribute(DEFAULT_OIDC_USER, defaultOidcUser);
return defaultOidcUser;
} | .map(role -> ROLE_PREFIX + role) | public OidcUser loadUser(OidcUserRequest userRequest) throws OAuth2AuthenticationException {
OidcUser oidcUser = oidcUserService.loadUser(userRequest);
OidcIdToken idToken = oidcUser.getIdToken();
Set<String> authorityStrings = new HashSet<>();
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
ServletRequestAttributes attr = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
HttpSession session = attr.getRequest().getSession(true);
if (authentication != null) {
return (DefaultOidcUser) session.getAttribute(DEFAULT_OIDC_USER);
}
authorityStrings.addAll(extractRolesFromIdToken(idToken));
authorityStrings.addAll(extractGroupRolesFromAccessToken(userRequest.getAccessToken()));
Set<SimpleGrantedAuthority> authorities = authorityStrings.stream()
.map(SimpleGrantedAuthority::new)
.collect(Collectors.toSet());
if (authorities.isEmpty()) {
authorities = DEFAULT_AUTHORITY_SET;
}
String nameAttributeKey =
Optional.of(userRequest)
.map(OAuth2UserRequest::getClientRegistration)
.map(ClientRegistration::getProviderDetails)
.map(ClientRegistration.ProviderDetails::getUserInfoEndpoint)
.map(ClientRegistration.ProviderDetails.UserInfoEndpoint::getUserNameAttributeName)
.filter(StringUtils::hasText)
.orElse(AADTokenClaim.NAME);
DefaultOidcUser defaultOidcUser = new DefaultOidcUser(authorities, idToken, nameAttributeKey);
session.setAttribute(DEFAULT_OIDC_USER, defaultOidcUser);
return defaultOidcUser;
} | class AADOAuth2UserService implements OAuth2UserService<OidcUserRequest, OidcUser> {
private final OidcUserService oidcUserService;
private final AADAuthenticationProperties properties;
private final GraphClient graphClient;
private static final String DEFAULT_OIDC_USER = "defaultOidcUser";
private static final String ROLES = "roles";
public AADOAuth2UserService(
AADAuthenticationProperties properties
) {
this.properties = properties;
this.oidcUserService = new OidcUserService();
this.graphClient = new GraphClient(properties);
}
@Override
} | class AADOAuth2UserService implements OAuth2UserService<OidcUserRequest, OidcUser> {
private final OidcUserService oidcUserService;
private final AADAuthenticationProperties properties;
private final GraphClient graphClient;
private static final String DEFAULT_OIDC_USER = "defaultOidcUser";
private static final String ROLES = "roles";
public AADOAuth2UserService(
AADAuthenticationProperties properties
) {
this.properties = properties;
this.oidcUserService = new OidcUserService();
this.graphClient = new GraphClient(properties);
}
@Override
Set<String> extractRolesFromIdToken(OidcIdToken idToken) {
Set<String> roles = Optional.ofNullable(idToken)
.map(token -> (Collection<?>) token.getClaim(ROLES))
.filter(obj -> obj instanceof List<?>)
.map(Collection::stream)
.orElseGet(Stream::empty)
.filter(s -> StringUtils.hasText(s.toString()))
.map(role -> APPROLE_PREFIX + role)
.collect(Collectors.toSet());
return roles;
}
Set<String> extractGroupRolesFromAccessToken(OAuth2AccessToken accessToken) {
Set<String> roles = Optional.of(accessToken)
.filter(notUsed -> properties.allowedGroupsConfigured())
.map(AbstractOAuth2Token::getTokenValue)
.map(graphClient::getGroupsFromGraph)
.orElseGet(Collections::emptySet)
.stream()
.filter(properties::isAllowedGroup)
.map(group -> ROLE_PREFIX + group)
.collect(Collectors.toSet());
return roles;
}
} |
nit: ``` .filter(StringUtils::hasText) ``` | public OidcUser loadUser(OidcUserRequest userRequest) throws OAuth2AuthenticationException {
OidcUser oidcUser = oidcUserService.loadUser(userRequest);
OidcIdToken idToken = oidcUser.getIdToken();
Set<String> roles = new HashSet<>();
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
ServletRequestAttributes attr = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
HttpSession session = attr.getRequest().getSession(true);
if (authentication != null) {
return (DefaultOidcUser) session.getAttribute(DEFAULT_OIDC_USER);
}
if (idToken.containsClaim(ROLES)) {
roles = idToken.getClaimAsStringList(ROLES)
.stream()
.filter(s -> StringUtils.hasText(s))
.map(role -> APPROLE_PREFIX + role)
.collect(Collectors.toSet());
}
Set<String> groups = Optional.of(userRequest)
.filter(notUsed -> properties.allowedGroupsConfigured())
.map(OAuth2UserRequest::getAccessToken)
.map(AbstractOAuth2Token::getTokenValue)
.map(graphClient::getGroupsFromGraph)
.orElseGet(Collections::emptySet);
Set<String> groupRoles = groups.stream()
.filter(properties::isAllowedGroup)
.map(group -> ROLE_PREFIX + group)
.collect(Collectors.toSet());
roles.addAll(groupRoles);
Set<SimpleGrantedAuthority> authorities = roles.stream()
.map(SimpleGrantedAuthority::new)
.collect(Collectors.toSet());
if (authorities.isEmpty()) {
authorities = DEFAULT_AUTHORITY_SET;
}
String nameAttributeKey =
Optional.of(userRequest)
.map(OAuth2UserRequest::getClientRegistration)
.map(ClientRegistration::getProviderDetails)
.map(ClientRegistration.ProviderDetails::getUserInfoEndpoint)
.map(ClientRegistration.ProviderDetails.UserInfoEndpoint::getUserNameAttributeName)
.filter(StringUtils::hasText)
.orElse(AADTokenClaim.NAME);
DefaultOidcUser defaultOidcUser = new DefaultOidcUser(authorities, idToken, nameAttributeKey);
session.setAttribute(DEFAULT_OIDC_USER, defaultOidcUser);
return defaultOidcUser;
} | .filter(s -> StringUtils.hasText(s)) | public OidcUser loadUser(OidcUserRequest userRequest) throws OAuth2AuthenticationException {
OidcUser oidcUser = oidcUserService.loadUser(userRequest);
OidcIdToken idToken = oidcUser.getIdToken();
Set<String> authorityStrings = new HashSet<>();
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
ServletRequestAttributes attr = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
HttpSession session = attr.getRequest().getSession(true);
if (authentication != null) {
return (DefaultOidcUser) session.getAttribute(DEFAULT_OIDC_USER);
}
authorityStrings.addAll(extractRolesFromIdToken(idToken));
authorityStrings.addAll(extractGroupRolesFromAccessToken(userRequest.getAccessToken()));
Set<SimpleGrantedAuthority> authorities = authorityStrings.stream()
.map(SimpleGrantedAuthority::new)
.collect(Collectors.toSet());
if (authorities.isEmpty()) {
authorities = DEFAULT_AUTHORITY_SET;
}
String nameAttributeKey =
Optional.of(userRequest)
.map(OAuth2UserRequest::getClientRegistration)
.map(ClientRegistration::getProviderDetails)
.map(ClientRegistration.ProviderDetails::getUserInfoEndpoint)
.map(ClientRegistration.ProviderDetails.UserInfoEndpoint::getUserNameAttributeName)
.filter(StringUtils::hasText)
.orElse(AADTokenClaim.NAME);
DefaultOidcUser defaultOidcUser = new DefaultOidcUser(authorities, idToken, nameAttributeKey);
session.setAttribute(DEFAULT_OIDC_USER, defaultOidcUser);
return defaultOidcUser;
} | class AADOAuth2UserService implements OAuth2UserService<OidcUserRequest, OidcUser> {
private final OidcUserService oidcUserService;
private final AADAuthenticationProperties properties;
private final GraphClient graphClient;
private static final String DEFAULT_OIDC_USER = "defaultOidcUser";
private static final String ROLES = "roles";
public AADOAuth2UserService(
AADAuthenticationProperties properties
) {
this.properties = properties;
this.oidcUserService = new OidcUserService();
this.graphClient = new GraphClient(properties);
}
@Override
} | class AADOAuth2UserService implements OAuth2UserService<OidcUserRequest, OidcUser> {
private final OidcUserService oidcUserService;
private final AADAuthenticationProperties properties;
private final GraphClient graphClient;
private static final String DEFAULT_OIDC_USER = "defaultOidcUser";
private static final String ROLES = "roles";
public AADOAuth2UserService(
AADAuthenticationProperties properties
) {
this.properties = properties;
this.oidcUserService = new OidcUserService();
this.graphClient = new GraphClient(properties);
}
@Override
Set<String> extractRolesFromIdToken(OidcIdToken idToken) {
Set<String> roles = Optional.ofNullable(idToken)
.map(token -> (Collection<?>) token.getClaim(ROLES))
.filter(obj -> obj instanceof List<?>)
.map(Collection::stream)
.orElseGet(Stream::empty)
.filter(s -> StringUtils.hasText(s.toString()))
.map(role -> APPROLE_PREFIX + role)
.collect(Collectors.toSet());
return roles;
}
Set<String> extractGroupRolesFromAccessToken(OAuth2AccessToken accessToken) {
Set<String> roles = Optional.of(accessToken)
.filter(notUsed -> properties.allowedGroupsConfigured())
.map(AbstractOAuth2Token::getTokenValue)
.map(graphClient::getGroupsFromGraph)
.orElseGet(Collections::emptySet)
.stream()
.filter(properties::isAllowedGroup)
.map(group -> ROLE_PREFIX + group)
.collect(Collectors.toSet());
return roles;
}
} |
Please also check for NULL. According to [docs](https://docs.spring.io/spring-security/site/docs/current/api/org/springframework/security/oauth2/core/ClaimAccessor.html#getClaimAsStringList-java.lang.String-) `getClaimAsStringList` may return NULL if the claim doesn't exist or is not a list. | public OidcUser loadUser(OidcUserRequest userRequest) throws OAuth2AuthenticationException {
OidcUser oidcUser = oidcUserService.loadUser(userRequest);
OidcIdToken idToken = oidcUser.getIdToken();
Set<String> roles = new HashSet<>();
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
ServletRequestAttributes attr = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
HttpSession session = attr.getRequest().getSession(true);
if (authentication != null) {
return (DefaultOidcUser) session.getAttribute(DEFAULT_OIDC_USER);
}
if (idToken.containsClaim(ROLES)) {
roles = idToken.getClaimAsStringList(ROLES)
.stream()
.filter(s -> StringUtils.hasText(s))
.map(role -> APPROLE_PREFIX + role)
.collect(Collectors.toSet());
}
Set<String> groups = Optional.of(userRequest)
.filter(notUsed -> properties.allowedGroupsConfigured())
.map(OAuth2UserRequest::getAccessToken)
.map(AbstractOAuth2Token::getTokenValue)
.map(graphClient::getGroupsFromGraph)
.orElseGet(Collections::emptySet);
Set<String> groupRoles = groups.stream()
.filter(properties::isAllowedGroup)
.map(group -> ROLE_PREFIX + group)
.collect(Collectors.toSet());
roles.addAll(groupRoles);
Set<SimpleGrantedAuthority> authorities = roles.stream()
.map(SimpleGrantedAuthority::new)
.collect(Collectors.toSet());
if (authorities.isEmpty()) {
authorities = DEFAULT_AUTHORITY_SET;
}
String nameAttributeKey =
Optional.of(userRequest)
.map(OAuth2UserRequest::getClientRegistration)
.map(ClientRegistration::getProviderDetails)
.map(ClientRegistration.ProviderDetails::getUserInfoEndpoint)
.map(ClientRegistration.ProviderDetails.UserInfoEndpoint::getUserNameAttributeName)
.filter(StringUtils::hasText)
.orElse(AADTokenClaim.NAME);
DefaultOidcUser defaultOidcUser = new DefaultOidcUser(authorities, idToken, nameAttributeKey);
session.setAttribute(DEFAULT_OIDC_USER, defaultOidcUser);
return defaultOidcUser;
} | roles = idToken.getClaimAsStringList(ROLES) | public OidcUser loadUser(OidcUserRequest userRequest) throws OAuth2AuthenticationException {
OidcUser oidcUser = oidcUserService.loadUser(userRequest);
OidcIdToken idToken = oidcUser.getIdToken();
Set<String> authorityStrings = new HashSet<>();
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
ServletRequestAttributes attr = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
HttpSession session = attr.getRequest().getSession(true);
if (authentication != null) {
return (DefaultOidcUser) session.getAttribute(DEFAULT_OIDC_USER);
}
authorityStrings.addAll(extractRolesFromIdToken(idToken));
authorityStrings.addAll(extractGroupRolesFromAccessToken(userRequest.getAccessToken()));
Set<SimpleGrantedAuthority> authorities = authorityStrings.stream()
.map(SimpleGrantedAuthority::new)
.collect(Collectors.toSet());
if (authorities.isEmpty()) {
authorities = DEFAULT_AUTHORITY_SET;
}
String nameAttributeKey =
Optional.of(userRequest)
.map(OAuth2UserRequest::getClientRegistration)
.map(ClientRegistration::getProviderDetails)
.map(ClientRegistration.ProviderDetails::getUserInfoEndpoint)
.map(ClientRegistration.ProviderDetails.UserInfoEndpoint::getUserNameAttributeName)
.filter(StringUtils::hasText)
.orElse(AADTokenClaim.NAME);
DefaultOidcUser defaultOidcUser = new DefaultOidcUser(authorities, idToken, nameAttributeKey);
session.setAttribute(DEFAULT_OIDC_USER, defaultOidcUser);
return defaultOidcUser;
} | class AADOAuth2UserService implements OAuth2UserService<OidcUserRequest, OidcUser> {
private final OidcUserService oidcUserService;
private final AADAuthenticationProperties properties;
private final GraphClient graphClient;
private static final String DEFAULT_OIDC_USER = "defaultOidcUser";
private static final String ROLES = "roles";
public AADOAuth2UserService(
AADAuthenticationProperties properties
) {
this.properties = properties;
this.oidcUserService = new OidcUserService();
this.graphClient = new GraphClient(properties);
}
@Override
} | class AADOAuth2UserService implements OAuth2UserService<OidcUserRequest, OidcUser> {
private final OidcUserService oidcUserService;
private final AADAuthenticationProperties properties;
private final GraphClient graphClient;
private static final String DEFAULT_OIDC_USER = "defaultOidcUser";
private static final String ROLES = "roles";
public AADOAuth2UserService(
AADAuthenticationProperties properties
) {
this.properties = properties;
this.oidcUserService = new OidcUserService();
this.graphClient = new GraphClient(properties);
}
@Override
Set<String> extractRolesFromIdToken(OidcIdToken idToken) {
Set<String> roles = Optional.ofNullable(idToken)
.map(token -> (Collection<?>) token.getClaim(ROLES))
.filter(obj -> obj instanceof List<?>)
.map(Collection::stream)
.orElseGet(Stream::empty)
.filter(s -> StringUtils.hasText(s.toString()))
.map(role -> APPROLE_PREFIX + role)
.collect(Collectors.toSet());
return roles;
}
Set<String> extractGroupRolesFromAccessToken(OAuth2AccessToken accessToken) {
Set<String> roles = Optional.of(accessToken)
.filter(notUsed -> properties.allowedGroupsConfigured())
.map(AbstractOAuth2Token::getTokenValue)
.map(graphClient::getGroupsFromGraph)
.orElseGet(Collections::emptySet)
.stream()
.filter(properties::isAllowedGroup)
.map(group -> ROLE_PREFIX + group)
.collect(Collectors.toSet());
return roles;
}
} |
@yiliuTo How about write like this: ``` Optional.ofNullable(idToken) .map(token -> token.getClaimAsStringList(ROLES)) .map(Collection::stream) .orElseGet(Stream::empty) .filter(StringUtils::hasText) .map(role -> APPROLE_PREFIX + role) .forEach(roles::add); ``` And please add test about: 1. claim does not exist. 2. cannot be assigned to a list | public OidcUser loadUser(OidcUserRequest userRequest) throws OAuth2AuthenticationException {
OidcUser oidcUser = oidcUserService.loadUser(userRequest);
OidcIdToken idToken = oidcUser.getIdToken();
Set<String> roles = new HashSet<>();
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
ServletRequestAttributes attr = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
HttpSession session = attr.getRequest().getSession(true);
if (authentication != null) {
return (DefaultOidcUser) session.getAttribute(DEFAULT_OIDC_USER);
}
if (idToken.containsClaim(ROLES)) {
roles = idToken.getClaimAsStringList(ROLES)
.stream()
.filter(s -> StringUtils.hasText(s))
.map(role -> APPROLE_PREFIX + role)
.collect(Collectors.toSet());
}
Set<String> groups = Optional.of(userRequest)
.filter(notUsed -> properties.allowedGroupsConfigured())
.map(OAuth2UserRequest::getAccessToken)
.map(AbstractOAuth2Token::getTokenValue)
.map(graphClient::getGroupsFromGraph)
.orElseGet(Collections::emptySet);
Set<String> groupRoles = groups.stream()
.filter(properties::isAllowedGroup)
.map(group -> ROLE_PREFIX + group)
.collect(Collectors.toSet());
roles.addAll(groupRoles);
Set<SimpleGrantedAuthority> authorities = roles.stream()
.map(SimpleGrantedAuthority::new)
.collect(Collectors.toSet());
if (authorities.isEmpty()) {
authorities = DEFAULT_AUTHORITY_SET;
}
String nameAttributeKey =
Optional.of(userRequest)
.map(OAuth2UserRequest::getClientRegistration)
.map(ClientRegistration::getProviderDetails)
.map(ClientRegistration.ProviderDetails::getUserInfoEndpoint)
.map(ClientRegistration.ProviderDetails.UserInfoEndpoint::getUserNameAttributeName)
.filter(StringUtils::hasText)
.orElse(AADTokenClaim.NAME);
DefaultOidcUser defaultOidcUser = new DefaultOidcUser(authorities, idToken, nameAttributeKey);
session.setAttribute(DEFAULT_OIDC_USER, defaultOidcUser);
return defaultOidcUser;
} | roles = idToken.getClaimAsStringList(ROLES) | public OidcUser loadUser(OidcUserRequest userRequest) throws OAuth2AuthenticationException {
OidcUser oidcUser = oidcUserService.loadUser(userRequest);
OidcIdToken idToken = oidcUser.getIdToken();
Set<String> authorityStrings = new HashSet<>();
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
ServletRequestAttributes attr = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
HttpSession session = attr.getRequest().getSession(true);
if (authentication != null) {
return (DefaultOidcUser) session.getAttribute(DEFAULT_OIDC_USER);
}
authorityStrings.addAll(extractRolesFromIdToken(idToken));
authorityStrings.addAll(extractGroupRolesFromAccessToken(userRequest.getAccessToken()));
Set<SimpleGrantedAuthority> authorities = authorityStrings.stream()
.map(SimpleGrantedAuthority::new)
.collect(Collectors.toSet());
if (authorities.isEmpty()) {
authorities = DEFAULT_AUTHORITY_SET;
}
String nameAttributeKey =
Optional.of(userRequest)
.map(OAuth2UserRequest::getClientRegistration)
.map(ClientRegistration::getProviderDetails)
.map(ClientRegistration.ProviderDetails::getUserInfoEndpoint)
.map(ClientRegistration.ProviderDetails.UserInfoEndpoint::getUserNameAttributeName)
.filter(StringUtils::hasText)
.orElse(AADTokenClaim.NAME);
DefaultOidcUser defaultOidcUser = new DefaultOidcUser(authorities, idToken, nameAttributeKey);
session.setAttribute(DEFAULT_OIDC_USER, defaultOidcUser);
return defaultOidcUser;
} | class AADOAuth2UserService implements OAuth2UserService<OidcUserRequest, OidcUser> {
private final OidcUserService oidcUserService;
private final AADAuthenticationProperties properties;
private final GraphClient graphClient;
private static final String DEFAULT_OIDC_USER = "defaultOidcUser";
private static final String ROLES = "roles";
public AADOAuth2UserService(
AADAuthenticationProperties properties
) {
this.properties = properties;
this.oidcUserService = new OidcUserService();
this.graphClient = new GraphClient(properties);
}
@Override
} | class AADOAuth2UserService implements OAuth2UserService<OidcUserRequest, OidcUser> {
private final OidcUserService oidcUserService;
private final AADAuthenticationProperties properties;
private final GraphClient graphClient;
private static final String DEFAULT_OIDC_USER = "defaultOidcUser";
private static final String ROLES = "roles";
public AADOAuth2UserService(
AADAuthenticationProperties properties
) {
this.properties = properties;
this.oidcUserService = new OidcUserService();
this.graphClient = new GraphClient(properties);
}
@Override
Set<String> extractRolesFromIdToken(OidcIdToken idToken) {
Set<String> roles = Optional.ofNullable(idToken)
.map(token -> (Collection<?>) token.getClaim(ROLES))
.filter(obj -> obj instanceof List<?>)
.map(Collection::stream)
.orElseGet(Stream::empty)
.filter(s -> StringUtils.hasText(s.toString()))
.map(role -> APPROLE_PREFIX + role)
.collect(Collectors.toSet());
return roles;
}
Set<String> extractGroupRolesFromAccessToken(OAuth2AccessToken accessToken) {
Set<String> roles = Optional.of(accessToken)
.filter(notUsed -> properties.allowedGroupsConfigured())
.map(AbstractOAuth2Token::getTokenValue)
.map(graphClient::getGroupsFromGraph)
.orElseGet(Collections::emptySet)
.stream()
.filter(properties::isAllowedGroup)
.map(group -> ROLE_PREFIX + group)
.collect(Collectors.toSet());
return roles;
}
} |
`roles` -> `authorityStrings` | public OidcUser loadUser(OidcUserRequest userRequest) throws OAuth2AuthenticationException {
OidcUser oidcUser = oidcUserService.loadUser(userRequest);
OidcIdToken idToken = oidcUser.getIdToken();
Set<String> roles = new HashSet<>();
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
ServletRequestAttributes attr = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
HttpSession session = attr.getRequest().getSession(true);
if (authentication != null) {
return (DefaultOidcUser) session.getAttribute(DEFAULT_OIDC_USER);
}
extractRolesFromIdToken(idToken, roles);
extractGroupRolesFromAccessToken(userRequest.getAccessToken(), roles);
Set<SimpleGrantedAuthority> authorities = roles.stream()
.map(SimpleGrantedAuthority::new)
.collect(Collectors.toSet());
if (authorities.isEmpty()) {
authorities = DEFAULT_AUTHORITY_SET;
}
String nameAttributeKey =
Optional.of(userRequest)
.map(OAuth2UserRequest::getClientRegistration)
.map(ClientRegistration::getProviderDetails)
.map(ClientRegistration.ProviderDetails::getUserInfoEndpoint)
.map(ClientRegistration.ProviderDetails.UserInfoEndpoint::getUserNameAttributeName)
.filter(StringUtils::hasText)
.orElse(AADTokenClaim.NAME);
DefaultOidcUser defaultOidcUser = new DefaultOidcUser(authorities, idToken, nameAttributeKey);
session.setAttribute(DEFAULT_OIDC_USER, defaultOidcUser);
return defaultOidcUser;
} | Set<String> roles = new HashSet<>(); | public OidcUser loadUser(OidcUserRequest userRequest) throws OAuth2AuthenticationException {
OidcUser oidcUser = oidcUserService.loadUser(userRequest);
OidcIdToken idToken = oidcUser.getIdToken();
Set<String> authorityStrings = new HashSet<>();
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
ServletRequestAttributes attr = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
HttpSession session = attr.getRequest().getSession(true);
if (authentication != null) {
return (DefaultOidcUser) session.getAttribute(DEFAULT_OIDC_USER);
}
authorityStrings.addAll(extractRolesFromIdToken(idToken));
authorityStrings.addAll(extractGroupRolesFromAccessToken(userRequest.getAccessToken()));
Set<SimpleGrantedAuthority> authorities = authorityStrings.stream()
.map(SimpleGrantedAuthority::new)
.collect(Collectors.toSet());
if (authorities.isEmpty()) {
authorities = DEFAULT_AUTHORITY_SET;
}
String nameAttributeKey =
Optional.of(userRequest)
.map(OAuth2UserRequest::getClientRegistration)
.map(ClientRegistration::getProviderDetails)
.map(ClientRegistration.ProviderDetails::getUserInfoEndpoint)
.map(ClientRegistration.ProviderDetails.UserInfoEndpoint::getUserNameAttributeName)
.filter(StringUtils::hasText)
.orElse(AADTokenClaim.NAME);
DefaultOidcUser defaultOidcUser = new DefaultOidcUser(authorities, idToken, nameAttributeKey);
session.setAttribute(DEFAULT_OIDC_USER, defaultOidcUser);
return defaultOidcUser;
} | class AADOAuth2UserService implements OAuth2UserService<OidcUserRequest, OidcUser> {
private final OidcUserService oidcUserService;
private final AADAuthenticationProperties properties;
private final GraphClient graphClient;
private static final String DEFAULT_OIDC_USER = "defaultOidcUser";
private static final String ROLES = "roles";
public AADOAuth2UserService(
AADAuthenticationProperties properties
) {
this.properties = properties;
this.oidcUserService = new OidcUserService();
this.graphClient = new GraphClient(properties);
}
@Override
void extractRolesFromIdToken(OidcIdToken idToken, Set<String> rolesClaim) {
Optional.ofNullable(idToken)
.map(token -> (Collection<?>) token.getClaim(ROLES))
.filter(obj -> obj instanceof List<?>)
.map(Collection::stream)
.orElseGet(Stream::empty)
.filter(s -> StringUtils.hasText(s.toString()))
.map(role -> APPROLE_PREFIX + role)
.forEach(rolesClaim::add);
}
void extractGroupRolesFromAccessToken(OAuth2AccessToken accessToken, Set<String> rolesClaim) {
Optional.of(accessToken)
.filter(notUsed -> properties.allowedGroupsConfigured())
.map(AbstractOAuth2Token::getTokenValue)
.map(graphClient::getGroupsFromGraph)
.orElseGet(Collections::emptySet)
.stream()
.filter(properties::isAllowedGroup)
.map(group -> ROLE_PREFIX + group)
.forEach(rolesClaim::add);
}
} | class AADOAuth2UserService implements OAuth2UserService<OidcUserRequest, OidcUser> {
private final OidcUserService oidcUserService;
private final AADAuthenticationProperties properties;
private final GraphClient graphClient;
private static final String DEFAULT_OIDC_USER = "defaultOidcUser";
private static final String ROLES = "roles";
public AADOAuth2UserService(
AADAuthenticationProperties properties
) {
this.properties = properties;
this.oidcUserService = new OidcUserService();
this.graphClient = new GraphClient(properties);
}
@Override
Set<String> extractRolesFromIdToken(OidcIdToken idToken) {
Set<String> roles = Optional.ofNullable(idToken)
.map(token -> (Collection<?>) token.getClaim(ROLES))
.filter(obj -> obj instanceof List<?>)
.map(Collection::stream)
.orElseGet(Stream::empty)
.filter(s -> StringUtils.hasText(s.toString()))
.map(role -> APPROLE_PREFIX + role)
.collect(Collectors.toSet());
return roles;
}
Set<String> extractGroupRolesFromAccessToken(OAuth2AccessToken accessToken) {
Set<String> roles = Optional.of(accessToken)
.filter(notUsed -> properties.allowedGroupsConfigured())
.map(AbstractOAuth2Token::getTokenValue)
.map(graphClient::getGroupsFromGraph)
.orElseGet(Collections::emptySet)
.stream()
.filter(properties::isAllowedGroup)
.map(group -> ROLE_PREFIX + group)
.collect(Collectors.toSet());
return roles;
}
} |
``` authorityStrings.addAll(getAuthorityFromIdtoken(idToken)). ``` | public OidcUser loadUser(OidcUserRequest userRequest) throws OAuth2AuthenticationException {
OidcUser oidcUser = oidcUserService.loadUser(userRequest);
OidcIdToken idToken = oidcUser.getIdToken();
Set<String> roles = new HashSet<>();
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
ServletRequestAttributes attr = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
HttpSession session = attr.getRequest().getSession(true);
if (authentication != null) {
return (DefaultOidcUser) session.getAttribute(DEFAULT_OIDC_USER);
}
extractRolesFromIdToken(idToken, roles);
extractGroupRolesFromAccessToken(userRequest.getAccessToken(), roles);
Set<SimpleGrantedAuthority> authorities = roles.stream()
.map(SimpleGrantedAuthority::new)
.collect(Collectors.toSet());
if (authorities.isEmpty()) {
authorities = DEFAULT_AUTHORITY_SET;
}
String nameAttributeKey =
Optional.of(userRequest)
.map(OAuth2UserRequest::getClientRegistration)
.map(ClientRegistration::getProviderDetails)
.map(ClientRegistration.ProviderDetails::getUserInfoEndpoint)
.map(ClientRegistration.ProviderDetails.UserInfoEndpoint::getUserNameAttributeName)
.filter(StringUtils::hasText)
.orElse(AADTokenClaim.NAME);
DefaultOidcUser defaultOidcUser = new DefaultOidcUser(authorities, idToken, nameAttributeKey);
session.setAttribute(DEFAULT_OIDC_USER, defaultOidcUser);
return defaultOidcUser;
} | extractRolesFromIdToken(idToken, roles); | public OidcUser loadUser(OidcUserRequest userRequest) throws OAuth2AuthenticationException {
OidcUser oidcUser = oidcUserService.loadUser(userRequest);
OidcIdToken idToken = oidcUser.getIdToken();
Set<String> authorityStrings = new HashSet<>();
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
ServletRequestAttributes attr = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
HttpSession session = attr.getRequest().getSession(true);
if (authentication != null) {
return (DefaultOidcUser) session.getAttribute(DEFAULT_OIDC_USER);
}
authorityStrings.addAll(extractRolesFromIdToken(idToken));
authorityStrings.addAll(extractGroupRolesFromAccessToken(userRequest.getAccessToken()));
Set<SimpleGrantedAuthority> authorities = authorityStrings.stream()
.map(SimpleGrantedAuthority::new)
.collect(Collectors.toSet());
if (authorities.isEmpty()) {
authorities = DEFAULT_AUTHORITY_SET;
}
String nameAttributeKey =
Optional.of(userRequest)
.map(OAuth2UserRequest::getClientRegistration)
.map(ClientRegistration::getProviderDetails)
.map(ClientRegistration.ProviderDetails::getUserInfoEndpoint)
.map(ClientRegistration.ProviderDetails.UserInfoEndpoint::getUserNameAttributeName)
.filter(StringUtils::hasText)
.orElse(AADTokenClaim.NAME);
DefaultOidcUser defaultOidcUser = new DefaultOidcUser(authorities, idToken, nameAttributeKey);
session.setAttribute(DEFAULT_OIDC_USER, defaultOidcUser);
return defaultOidcUser;
} | class AADOAuth2UserService implements OAuth2UserService<OidcUserRequest, OidcUser> {
private final OidcUserService oidcUserService;
private final AADAuthenticationProperties properties;
private final GraphClient graphClient;
private static final String DEFAULT_OIDC_USER = "defaultOidcUser";
private static final String ROLES = "roles";
public AADOAuth2UserService(
AADAuthenticationProperties properties
) {
this.properties = properties;
this.oidcUserService = new OidcUserService();
this.graphClient = new GraphClient(properties);
}
@Override
void extractRolesFromIdToken(OidcIdToken idToken, Set<String> rolesClaim) {
Optional.ofNullable(idToken)
.map(token -> (Collection<?>) token.getClaim(ROLES))
.filter(obj -> obj instanceof List<?>)
.map(Collection::stream)
.orElseGet(Stream::empty)
.filter(s -> StringUtils.hasText(s.toString()))
.map(role -> APPROLE_PREFIX + role)
.forEach(rolesClaim::add);
}
void extractGroupRolesFromAccessToken(OAuth2AccessToken accessToken, Set<String> rolesClaim) {
Optional.of(accessToken)
.filter(notUsed -> properties.allowedGroupsConfigured())
.map(AbstractOAuth2Token::getTokenValue)
.map(graphClient::getGroupsFromGraph)
.orElseGet(Collections::emptySet)
.stream()
.filter(properties::isAllowedGroup)
.map(group -> ROLE_PREFIX + group)
.forEach(rolesClaim::add);
}
} | class AADOAuth2UserService implements OAuth2UserService<OidcUserRequest, OidcUser> {
private final OidcUserService oidcUserService;
private final AADAuthenticationProperties properties;
private final GraphClient graphClient;
private static final String DEFAULT_OIDC_USER = "defaultOidcUser";
private static final String ROLES = "roles";
public AADOAuth2UserService(
AADAuthenticationProperties properties
) {
this.properties = properties;
this.oidcUserService = new OidcUserService();
this.graphClient = new GraphClient(properties);
}
@Override
Set<String> extractRolesFromIdToken(OidcIdToken idToken) {
Set<String> roles = Optional.ofNullable(idToken)
.map(token -> (Collection<?>) token.getClaim(ROLES))
.filter(obj -> obj instanceof List<?>)
.map(Collection::stream)
.orElseGet(Stream::empty)
.filter(s -> StringUtils.hasText(s.toString()))
.map(role -> APPROLE_PREFIX + role)
.collect(Collectors.toSet());
return roles;
}
Set<String> extractGroupRolesFromAccessToken(OAuth2AccessToken accessToken) {
Set<String> roles = Optional.of(accessToken)
.filter(notUsed -> properties.allowedGroupsConfigured())
.map(AbstractOAuth2Token::getTokenValue)
.map(graphClient::getGroupsFromGraph)
.orElseGet(Collections::emptySet)
.stream()
.filter(properties::isAllowedGroup)
.map(group -> ROLE_PREFIX + group)
.collect(Collectors.toSet());
return roles;
}
} |
Same here. | public OidcUser loadUser(OidcUserRequest userRequest) throws OAuth2AuthenticationException {
OidcUser oidcUser = oidcUserService.loadUser(userRequest);
OidcIdToken idToken = oidcUser.getIdToken();
Set<String> roles = new HashSet<>();
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
ServletRequestAttributes attr = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
HttpSession session = attr.getRequest().getSession(true);
if (authentication != null) {
return (DefaultOidcUser) session.getAttribute(DEFAULT_OIDC_USER);
}
extractRolesFromIdToken(idToken, roles);
extractGroupRolesFromAccessToken(userRequest.getAccessToken(), roles);
Set<SimpleGrantedAuthority> authorities = roles.stream()
.map(SimpleGrantedAuthority::new)
.collect(Collectors.toSet());
if (authorities.isEmpty()) {
authorities = DEFAULT_AUTHORITY_SET;
}
String nameAttributeKey =
Optional.of(userRequest)
.map(OAuth2UserRequest::getClientRegistration)
.map(ClientRegistration::getProviderDetails)
.map(ClientRegistration.ProviderDetails::getUserInfoEndpoint)
.map(ClientRegistration.ProviderDetails.UserInfoEndpoint::getUserNameAttributeName)
.filter(StringUtils::hasText)
.orElse(AADTokenClaim.NAME);
DefaultOidcUser defaultOidcUser = new DefaultOidcUser(authorities, idToken, nameAttributeKey);
session.setAttribute(DEFAULT_OIDC_USER, defaultOidcUser);
return defaultOidcUser;
} | extractGroupRolesFromAccessToken(userRequest.getAccessToken(), roles); | public OidcUser loadUser(OidcUserRequest userRequest) throws OAuth2AuthenticationException {
OidcUser oidcUser = oidcUserService.loadUser(userRequest);
OidcIdToken idToken = oidcUser.getIdToken();
Set<String> authorityStrings = new HashSet<>();
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
ServletRequestAttributes attr = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
HttpSession session = attr.getRequest().getSession(true);
if (authentication != null) {
return (DefaultOidcUser) session.getAttribute(DEFAULT_OIDC_USER);
}
authorityStrings.addAll(extractRolesFromIdToken(idToken));
authorityStrings.addAll(extractGroupRolesFromAccessToken(userRequest.getAccessToken()));
Set<SimpleGrantedAuthority> authorities = authorityStrings.stream()
.map(SimpleGrantedAuthority::new)
.collect(Collectors.toSet());
if (authorities.isEmpty()) {
authorities = DEFAULT_AUTHORITY_SET;
}
String nameAttributeKey =
Optional.of(userRequest)
.map(OAuth2UserRequest::getClientRegistration)
.map(ClientRegistration::getProviderDetails)
.map(ClientRegistration.ProviderDetails::getUserInfoEndpoint)
.map(ClientRegistration.ProviderDetails.UserInfoEndpoint::getUserNameAttributeName)
.filter(StringUtils::hasText)
.orElse(AADTokenClaim.NAME);
DefaultOidcUser defaultOidcUser = new DefaultOidcUser(authorities, idToken, nameAttributeKey);
session.setAttribute(DEFAULT_OIDC_USER, defaultOidcUser);
return defaultOidcUser;
} | class AADOAuth2UserService implements OAuth2UserService<OidcUserRequest, OidcUser> {
private final OidcUserService oidcUserService;
private final AADAuthenticationProperties properties;
private final GraphClient graphClient;
private static final String DEFAULT_OIDC_USER = "defaultOidcUser";
private static final String ROLES = "roles";
public AADOAuth2UserService(
AADAuthenticationProperties properties
) {
this.properties = properties;
this.oidcUserService = new OidcUserService();
this.graphClient = new GraphClient(properties);
}
@Override
void extractRolesFromIdToken(OidcIdToken idToken, Set<String> rolesClaim) {
Optional.ofNullable(idToken)
.map(token -> (Collection<?>) token.getClaim(ROLES))
.filter(obj -> obj instanceof List<?>)
.map(Collection::stream)
.orElseGet(Stream::empty)
.filter(s -> StringUtils.hasText(s.toString()))
.map(role -> APPROLE_PREFIX + role)
.forEach(rolesClaim::add);
}
void extractGroupRolesFromAccessToken(OAuth2AccessToken accessToken, Set<String> rolesClaim) {
Optional.of(accessToken)
.filter(notUsed -> properties.allowedGroupsConfigured())
.map(AbstractOAuth2Token::getTokenValue)
.map(graphClient::getGroupsFromGraph)
.orElseGet(Collections::emptySet)
.stream()
.filter(properties::isAllowedGroup)
.map(group -> ROLE_PREFIX + group)
.forEach(rolesClaim::add);
}
} | class AADOAuth2UserService implements OAuth2UserService<OidcUserRequest, OidcUser> {
private final OidcUserService oidcUserService;
private final AADAuthenticationProperties properties;
private final GraphClient graphClient;
private static final String DEFAULT_OIDC_USER = "defaultOidcUser";
private static final String ROLES = "roles";
public AADOAuth2UserService(
AADAuthenticationProperties properties
) {
this.properties = properties;
this.oidcUserService = new OidcUserService();
this.graphClient = new GraphClient(properties);
}
@Override
Set<String> extractRolesFromIdToken(OidcIdToken idToken) {
Set<String> roles = Optional.ofNullable(idToken)
.map(token -> (Collection<?>) token.getClaim(ROLES))
.filter(obj -> obj instanceof List<?>)
.map(Collection::stream)
.orElseGet(Stream::empty)
.filter(s -> StringUtils.hasText(s.toString()))
.map(role -> APPROLE_PREFIX + role)
.collect(Collectors.toSet());
return roles;
}
Set<String> extractGroupRolesFromAccessToken(OAuth2AccessToken accessToken) {
Set<String> roles = Optional.of(accessToken)
.filter(notUsed -> properties.allowedGroupsConfigured())
.map(AbstractOAuth2Token::getTokenValue)
.map(graphClient::getGroupsFromGraph)
.orElseGet(Collections::emptySet)
.stream()
.filter(properties::isAllowedGroup)
.map(group -> ROLE_PREFIX + group)
.collect(Collectors.toSet());
return roles;
}
} |
please try to refactor the code to make it easier to read | private PartitionSupplier toPartitionSupplier(Message<?> message) {
PartitionSupplier partitionSupplier = new PartitionSupplier();
String partitionId = message.getHeaders().get(AzureHeaders.PARTITION_ID, String.class);
if (!StringUtils.hasText(partitionId) && message.getHeaders().containsKey(AzureHeaders.PARTITION_OVERRIDE)) {
partitionId = String.valueOf(message.getHeaders().get(AzureHeaders.PARTITION_OVERRIDE));
} else if (!StringUtils.hasText(partitionId) && message.getHeaders().containsKey(AzureHeaders.PARTITION_HEADER)) {
partitionId = String.valueOf(message.getHeaders().get(AzureHeaders.PARTITION_HEADER, Integer.class));
}
if (StringUtils.hasText(partitionId)) {
partitionSupplier.setPartitionId(partitionId);
} else {
if (this.partitionKeyExpression != null) {
String partitionKey = this.partitionKeyExpression.getValue(this.evaluationContext, message, String.class);
if (StringUtils.hasText(partitionKey)) {
partitionSupplier.setPartitionKey(partitionKey);
}
}
}
return partitionSupplier;
} | } | private PartitionSupplier toPartitionSupplier(Message<?> message) {
PartitionSupplier partitionSupplier = new PartitionSupplier();
String partitionId = getHeaderValue(message.getHeaders(), AzureHeaders.PARTITION_ID);
if (!StringUtils.hasText(partitionId) && this.partitionIdExpression != null) {
partitionId = this.partitionIdExpression.getValue(this.evaluationContext, message, String.class);
}
if (StringUtils.hasText(partitionId)) {
partitionSupplier.setPartitionId(partitionId);
} else {
String partitionKey = getHeaderValue(message.getHeaders(), AzureHeaders.PARTITION_KEY);
if (!StringUtils.hasText(partitionKey) && this.partitionKeyExpression != null) {
partitionKey = this.partitionKeyExpression.getValue(this.evaluationContext, message, String.class);
}
if (StringUtils.hasText(partitionKey)) {
partitionSupplier.setPartitionKey(partitionKey);
}
}
return partitionSupplier;
} | class DefaultMessageHandler extends AbstractMessageProducingHandler {
private static final Logger LOGGER = LoggerFactory.getLogger(DefaultMessageHandler.class);
private static final long DEFAULT_SEND_TIMEOUT = 10000;
private final String destination;
private final SendOperation sendOperation;
private boolean sync = false;
private ListenableFutureCallback<Void> sendCallback;
private EvaluationContext evaluationContext;
private Expression sendTimeoutExpression = new ValueExpression<>(DEFAULT_SEND_TIMEOUT);
private ErrorMessageStrategy errorMessageStrategy = new DefaultErrorMessageStrategy();
private Expression partitionKeyExpression;
private MessageChannel sendFailureChannel;
private String sendFailureChannelName;
public DefaultMessageHandler(String destination, @NonNull SendOperation sendOperation) {
Assert.hasText(destination, "destination can't be null or empty");
this.destination = destination;
this.sendOperation = sendOperation;
}
@Override
protected void onInit() {
super.onInit();
this.evaluationContext = ExpressionUtils.createStandardEvaluationContext(getBeanFactory());
LOGGER.info("Started DefaultMessageHandler with properties: {}", buildPropertiesMap());
}
@Override
protected void handleMessageInternal(Message<?> message) {
PartitionSupplier partitionSupplier = toPartitionSupplier(message);
String destination = toDestination(message);
final Mono<Void> mono = this.sendOperation.sendAsync(destination, message, partitionSupplier);
if (this.sync) {
waitingSendResponse(mono, message);
} else {
handleSendResponseAsync(mono, message);
}
}
private <T> void handleSendResponseAsync(Mono<T> mono, Message<?> message) {
mono.doOnError(ex -> {
if (LOGGER.isWarnEnabled()) {
LOGGER.warn("{} sent failed in async mode due to {}", message, ex.getMessage());
}
if (this.sendCallback != null) {
this.sendCallback.onFailure(ex);
}
if (getSendFailureChannel() != null) {
this.messagingTemplate.send(getSendFailureChannel(), getErrorMessageStrategy()
.buildErrorMessage(new AzureSendFailureException(message, ex), null));
}
}).doOnSuccess(t -> {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("{} sent successfully in async mode", message);
}
if (this.sendCallback != null) {
this.sendCallback.onSuccess((Void) t);
}
}).subscribe();
}
private <T> void waitingSendResponse(Mono<T> mono, Message<?> message) {
Long sendTimeout = this.sendTimeoutExpression.getValue(this.evaluationContext, message, Long.class);
if (sendTimeout == null || sendTimeout < 0) {
try {
mono.block();
} catch (Exception e) {
throw new MessageDeliveryException(e.getMessage());
}
} else {
try {
mono.block(Duration.of(sendTimeout, ChronoUnit.MILLIS));
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("{} sent successfully in sync mode", message);
}
} catch (Exception e) {
if (e.getCause() instanceof TimeoutException) {
throw new MessageTimeoutException(message, "Timeout waiting for send event hub response");
}
throw new MessageDeliveryException(e.getMessage());
}
}
}
public void setSync(boolean sync) {
this.sync = sync;
LOGGER.info("DefaultMessageHandler sync becomes: {}", sync);
}
public void setSendTimeout(long sendTimeout) {
setSendTimeoutExpression(new ValueExpression<>(sendTimeout));
}
public void setPartitionKey(String partitionKey) {
setPartitionKeyExpression(new LiteralExpression(partitionKey));
}
public void setPartitionKeyExpression(Expression partitionKeyExpression) {
this.partitionKeyExpression = partitionKeyExpression;
}
public void setPartitionKeyExpressionString(String partitionKeyExpression) {
setPartitionKeyExpression(EXPRESSION_PARSER.parseExpression(partitionKeyExpression));
}
private String toDestination(Message<?> message) {
if (message.getHeaders().containsKey(AzureHeaders.NAME)) {
return message.getHeaders().get(AzureHeaders.NAME, String.class);
}
return this.destination;
}
private Map<String, Object> buildPropertiesMap() {
Map<String, Object> properties = new HashMap<>();
properties.put("sync", sync);
properties.put("sendTimeout", sendTimeoutExpression);
properties.put("destination", destination);
return properties;
}
public void setSendCallback(ListenableFutureCallback<Void> callback) {
this.sendCallback = callback;
}
public Expression getSendTimeoutExpression() {
return sendTimeoutExpression;
}
public void setSendTimeoutExpression(Expression sendTimeoutExpression) {
Assert.notNull(sendTimeoutExpression, "'sendTimeoutExpression' must not be null");
this.sendTimeoutExpression = sendTimeoutExpression;
LOGGER.info("DefaultMessageHandler syncTimeout becomes: {}", sendTimeoutExpression);
}
protected MessageChannel getSendFailureChannel() {
if (this.sendFailureChannel != null) {
return this.sendFailureChannel;
} else if (this.sendFailureChannelName != null) {
this.sendFailureChannel = getChannelResolver().resolveDestination(this.sendFailureChannelName);
return this.sendFailureChannel;
}
return null;
}
public void setSendFailureChannel(MessageChannel sendFailureChannel) {
this.sendFailureChannel = sendFailureChannel;
}
public void setSendFailureChannelName(String sendFailureChannelName) {
this.sendFailureChannelName = sendFailureChannelName;
}
protected ErrorMessageStrategy getErrorMessageStrategy() {
return this.errorMessageStrategy;
}
public void setErrorMessageStrategy(ErrorMessageStrategy errorMessageStrategy) {
Assert.notNull(errorMessageStrategy, "'errorMessageStrategy' must not be null");
this.errorMessageStrategy = errorMessageStrategy;
}
} | class DefaultMessageHandler extends AbstractMessageProducingHandler {
private static final Logger LOGGER = LoggerFactory.getLogger(DefaultMessageHandler.class);
private static final long DEFAULT_SEND_TIMEOUT = 10000;
private final String destination;
private final SendOperation sendOperation;
private boolean sync = false;
private ListenableFutureCallback<Void> sendCallback;
private EvaluationContext evaluationContext;
private Expression sendTimeoutExpression = new ValueExpression<>(DEFAULT_SEND_TIMEOUT);
private ErrorMessageStrategy errorMessageStrategy = new DefaultErrorMessageStrategy();
private Expression partitionKeyExpression;
private Expression partitionIdExpression;
private MessageChannel sendFailureChannel;
private String sendFailureChannelName;
public DefaultMessageHandler(String destination, @NonNull SendOperation sendOperation) {
Assert.hasText(destination, "destination can't be null or empty");
this.destination = destination;
this.sendOperation = sendOperation;
}
@Override
protected void onInit() {
super.onInit();
this.evaluationContext = ExpressionUtils.createStandardEvaluationContext(getBeanFactory());
LOGGER.info("Started DefaultMessageHandler with properties: {}", buildPropertiesMap());
}
@Override
protected void handleMessageInternal(Message<?> message) {
PartitionSupplier partitionSupplier = toPartitionSupplier(message);
String destination = toDestination(message);
final Mono<Void> mono = this.sendOperation.sendAsync(destination, message, partitionSupplier);
if (this.sync) {
waitingSendResponse(mono, message);
} else {
handleSendResponseAsync(mono, message);
}
}
private <T> void handleSendResponseAsync(Mono<T> mono, Message<?> message) {
mono.doOnError(ex -> {
if (LOGGER.isWarnEnabled()) {
LOGGER.warn("{} sent failed in async mode due to {}", message, ex.getMessage());
}
if (this.sendCallback != null) {
this.sendCallback.onFailure(ex);
}
if (getSendFailureChannel() != null) {
this.messagingTemplate.send(getSendFailureChannel(), getErrorMessageStrategy()
.buildErrorMessage(new AzureSendFailureException(message, ex), null));
}
}).doOnSuccess(t -> {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("{} sent successfully in async mode", message);
}
if (this.sendCallback != null) {
this.sendCallback.onSuccess((Void) t);
}
}).subscribe();
}
private <T> void waitingSendResponse(Mono<T> mono, Message<?> message) {
Long sendTimeout = this.sendTimeoutExpression.getValue(this.evaluationContext, message, Long.class);
if (sendTimeout == null || sendTimeout < 0) {
try {
mono.block();
} catch (Exception e) {
throw new MessageDeliveryException(e.getMessage());
}
} else {
try {
mono.block(Duration.of(sendTimeout, ChronoUnit.MILLIS));
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("{} sent successfully in sync mode", message);
}
} catch (Exception e) {
if (e.getCause() instanceof TimeoutException) {
throw new MessageTimeoutException(message, "Timeout waiting for send event hub response");
}
throw new MessageDeliveryException(e.getMessage());
}
}
}
public void setSync(boolean sync) {
this.sync = sync;
LOGGER.info("DefaultMessageHandler sync becomes: {}", sync);
}
public void setSendTimeout(long sendTimeout) {
setSendTimeoutExpression(new ValueExpression<>(sendTimeout));
}
public void setPartitionKey(String partitionKey) {
setPartitionKeyExpression(new LiteralExpression(partitionKey));
}
public void setPartitionKeyExpression(Expression partitionKeyExpression) {
this.partitionKeyExpression = partitionKeyExpression;
}
public void setPartitionIdExpression(Expression partitionIdExpression) {
this.partitionIdExpression = partitionIdExpression;
}
private String toDestination(Message<?> message) {
if (message.getHeaders().containsKey(AzureHeaders.NAME)) {
return message.getHeaders().get(AzureHeaders.NAME, String.class);
}
return this.destination;
}
/**
* Get header value from MessageHeaders
* @param headers MessageHeaders
* @param keyName Key name
* @return String header value
*/
private String getHeaderValue(MessageHeaders headers, String keyName) {
return headers.keySet().stream()
.filter(header -> keyName.equals(header))
.map(key -> String.valueOf(headers.get(key)))
.findAny()
.orElse(null);
}
private Map<String, Object> buildPropertiesMap() {
Map<String, Object> properties = new HashMap<>();
properties.put("sync", sync);
properties.put("sendTimeout", sendTimeoutExpression);
properties.put("destination", destination);
return properties;
}
public void setSendCallback(ListenableFutureCallback<Void> callback) {
this.sendCallback = callback;
}
public Expression getSendTimeoutExpression() {
return sendTimeoutExpression;
}
public void setSendTimeoutExpression(Expression sendTimeoutExpression) {
Assert.notNull(sendTimeoutExpression, "'sendTimeoutExpression' must not be null");
this.sendTimeoutExpression = sendTimeoutExpression;
LOGGER.info("DefaultMessageHandler syncTimeout becomes: {}", sendTimeoutExpression);
}
protected MessageChannel getSendFailureChannel() {
if (this.sendFailureChannel != null) {
return this.sendFailureChannel;
} else if (this.sendFailureChannelName != null) {
this.sendFailureChannel = getChannelResolver().resolveDestination(this.sendFailureChannelName);
return this.sendFailureChannel;
}
return null;
}
public void setSendFailureChannel(MessageChannel sendFailureChannel) {
this.sendFailureChannel = sendFailureChannel;
}
public void setSendFailureChannelName(String sendFailureChannelName) {
this.sendFailureChannelName = sendFailureChannelName;
}
protected ErrorMessageStrategy getErrorMessageStrategy() {
return this.errorMessageStrategy;
}
public void setErrorMessageStrategy(ErrorMessageStrategy errorMessageStrategy) {
Assert.notNull(errorMessageStrategy, "'errorMessageStrategy' must not be null");
this.errorMessageStrategy = errorMessageStrategy;
}
} |
Refactored. | private PartitionSupplier toPartitionSupplier(Message<?> message) {
PartitionSupplier partitionSupplier = new PartitionSupplier();
String partitionId = message.getHeaders().get(AzureHeaders.PARTITION_ID, String.class);
if (!StringUtils.hasText(partitionId) && message.getHeaders().containsKey(AzureHeaders.PARTITION_OVERRIDE)) {
partitionId = String.valueOf(message.getHeaders().get(AzureHeaders.PARTITION_OVERRIDE));
} else if (!StringUtils.hasText(partitionId) && message.getHeaders().containsKey(AzureHeaders.PARTITION_HEADER)) {
partitionId = String.valueOf(message.getHeaders().get(AzureHeaders.PARTITION_HEADER, Integer.class));
}
if (StringUtils.hasText(partitionId)) {
partitionSupplier.setPartitionId(partitionId);
} else {
if (this.partitionKeyExpression != null) {
String partitionKey = this.partitionKeyExpression.getValue(this.evaluationContext, message, String.class);
if (StringUtils.hasText(partitionKey)) {
partitionSupplier.setPartitionKey(partitionKey);
}
}
}
return partitionSupplier;
} | } | private PartitionSupplier toPartitionSupplier(Message<?> message) {
PartitionSupplier partitionSupplier = new PartitionSupplier();
String partitionId = getHeaderValue(message.getHeaders(), AzureHeaders.PARTITION_ID);
if (!StringUtils.hasText(partitionId) && this.partitionIdExpression != null) {
partitionId = this.partitionIdExpression.getValue(this.evaluationContext, message, String.class);
}
if (StringUtils.hasText(partitionId)) {
partitionSupplier.setPartitionId(partitionId);
} else {
String partitionKey = getHeaderValue(message.getHeaders(), AzureHeaders.PARTITION_KEY);
if (!StringUtils.hasText(partitionKey) && this.partitionKeyExpression != null) {
partitionKey = this.partitionKeyExpression.getValue(this.evaluationContext, message, String.class);
}
if (StringUtils.hasText(partitionKey)) {
partitionSupplier.setPartitionKey(partitionKey);
}
}
return partitionSupplier;
} | class DefaultMessageHandler extends AbstractMessageProducingHandler {
private static final Logger LOGGER = LoggerFactory.getLogger(DefaultMessageHandler.class);
private static final long DEFAULT_SEND_TIMEOUT = 10000;
private final String destination;
private final SendOperation sendOperation;
private boolean sync = false;
private ListenableFutureCallback<Void> sendCallback;
private EvaluationContext evaluationContext;
private Expression sendTimeoutExpression = new ValueExpression<>(DEFAULT_SEND_TIMEOUT);
private ErrorMessageStrategy errorMessageStrategy = new DefaultErrorMessageStrategy();
private Expression partitionKeyExpression;
private MessageChannel sendFailureChannel;
private String sendFailureChannelName;
public DefaultMessageHandler(String destination, @NonNull SendOperation sendOperation) {
Assert.hasText(destination, "destination can't be null or empty");
this.destination = destination;
this.sendOperation = sendOperation;
}
@Override
protected void onInit() {
super.onInit();
this.evaluationContext = ExpressionUtils.createStandardEvaluationContext(getBeanFactory());
LOGGER.info("Started DefaultMessageHandler with properties: {}", buildPropertiesMap());
}
@Override
protected void handleMessageInternal(Message<?> message) {
PartitionSupplier partitionSupplier = toPartitionSupplier(message);
String destination = toDestination(message);
final Mono<Void> mono = this.sendOperation.sendAsync(destination, message, partitionSupplier);
if (this.sync) {
waitingSendResponse(mono, message);
} else {
handleSendResponseAsync(mono, message);
}
}
private <T> void handleSendResponseAsync(Mono<T> mono, Message<?> message) {
mono.doOnError(ex -> {
if (LOGGER.isWarnEnabled()) {
LOGGER.warn("{} sent failed in async mode due to {}", message, ex.getMessage());
}
if (this.sendCallback != null) {
this.sendCallback.onFailure(ex);
}
if (getSendFailureChannel() != null) {
this.messagingTemplate.send(getSendFailureChannel(), getErrorMessageStrategy()
.buildErrorMessage(new AzureSendFailureException(message, ex), null));
}
}).doOnSuccess(t -> {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("{} sent successfully in async mode", message);
}
if (this.sendCallback != null) {
this.sendCallback.onSuccess((Void) t);
}
}).subscribe();
}
private <T> void waitingSendResponse(Mono<T> mono, Message<?> message) {
Long sendTimeout = this.sendTimeoutExpression.getValue(this.evaluationContext, message, Long.class);
if (sendTimeout == null || sendTimeout < 0) {
try {
mono.block();
} catch (Exception e) {
throw new MessageDeliveryException(e.getMessage());
}
} else {
try {
mono.block(Duration.of(sendTimeout, ChronoUnit.MILLIS));
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("{} sent successfully in sync mode", message);
}
} catch (Exception e) {
if (e.getCause() instanceof TimeoutException) {
throw new MessageTimeoutException(message, "Timeout waiting for send event hub response");
}
throw new MessageDeliveryException(e.getMessage());
}
}
}
public void setSync(boolean sync) {
this.sync = sync;
LOGGER.info("DefaultMessageHandler sync becomes: {}", sync);
}
public void setSendTimeout(long sendTimeout) {
setSendTimeoutExpression(new ValueExpression<>(sendTimeout));
}
public void setPartitionKey(String partitionKey) {
setPartitionKeyExpression(new LiteralExpression(partitionKey));
}
public void setPartitionKeyExpression(Expression partitionKeyExpression) {
this.partitionKeyExpression = partitionKeyExpression;
}
public void setPartitionKeyExpressionString(String partitionKeyExpression) {
setPartitionKeyExpression(EXPRESSION_PARSER.parseExpression(partitionKeyExpression));
}
private String toDestination(Message<?> message) {
if (message.getHeaders().containsKey(AzureHeaders.NAME)) {
return message.getHeaders().get(AzureHeaders.NAME, String.class);
}
return this.destination;
}
private Map<String, Object> buildPropertiesMap() {
Map<String, Object> properties = new HashMap<>();
properties.put("sync", sync);
properties.put("sendTimeout", sendTimeoutExpression);
properties.put("destination", destination);
return properties;
}
public void setSendCallback(ListenableFutureCallback<Void> callback) {
this.sendCallback = callback;
}
public Expression getSendTimeoutExpression() {
return sendTimeoutExpression;
}
public void setSendTimeoutExpression(Expression sendTimeoutExpression) {
Assert.notNull(sendTimeoutExpression, "'sendTimeoutExpression' must not be null");
this.sendTimeoutExpression = sendTimeoutExpression;
LOGGER.info("DefaultMessageHandler syncTimeout becomes: {}", sendTimeoutExpression);
}
protected MessageChannel getSendFailureChannel() {
if (this.sendFailureChannel != null) {
return this.sendFailureChannel;
} else if (this.sendFailureChannelName != null) {
this.sendFailureChannel = getChannelResolver().resolveDestination(this.sendFailureChannelName);
return this.sendFailureChannel;
}
return null;
}
public void setSendFailureChannel(MessageChannel sendFailureChannel) {
this.sendFailureChannel = sendFailureChannel;
}
public void setSendFailureChannelName(String sendFailureChannelName) {
this.sendFailureChannelName = sendFailureChannelName;
}
protected ErrorMessageStrategy getErrorMessageStrategy() {
return this.errorMessageStrategy;
}
public void setErrorMessageStrategy(ErrorMessageStrategy errorMessageStrategy) {
Assert.notNull(errorMessageStrategy, "'errorMessageStrategy' must not be null");
this.errorMessageStrategy = errorMessageStrategy;
}
} | class DefaultMessageHandler extends AbstractMessageProducingHandler {
private static final Logger LOGGER = LoggerFactory.getLogger(DefaultMessageHandler.class);
private static final long DEFAULT_SEND_TIMEOUT = 10000;
private final String destination;
private final SendOperation sendOperation;
private boolean sync = false;
private ListenableFutureCallback<Void> sendCallback;
private EvaluationContext evaluationContext;
private Expression sendTimeoutExpression = new ValueExpression<>(DEFAULT_SEND_TIMEOUT);
private ErrorMessageStrategy errorMessageStrategy = new DefaultErrorMessageStrategy();
private Expression partitionKeyExpression;
private Expression partitionIdExpression;
private MessageChannel sendFailureChannel;
private String sendFailureChannelName;
public DefaultMessageHandler(String destination, @NonNull SendOperation sendOperation) {
Assert.hasText(destination, "destination can't be null or empty");
this.destination = destination;
this.sendOperation = sendOperation;
}
@Override
protected void onInit() {
super.onInit();
this.evaluationContext = ExpressionUtils.createStandardEvaluationContext(getBeanFactory());
LOGGER.info("Started DefaultMessageHandler with properties: {}", buildPropertiesMap());
}
@Override
protected void handleMessageInternal(Message<?> message) {
PartitionSupplier partitionSupplier = toPartitionSupplier(message);
String destination = toDestination(message);
final Mono<Void> mono = this.sendOperation.sendAsync(destination, message, partitionSupplier);
if (this.sync) {
waitingSendResponse(mono, message);
} else {
handleSendResponseAsync(mono, message);
}
}
private <T> void handleSendResponseAsync(Mono<T> mono, Message<?> message) {
mono.doOnError(ex -> {
if (LOGGER.isWarnEnabled()) {
LOGGER.warn("{} sent failed in async mode due to {}", message, ex.getMessage());
}
if (this.sendCallback != null) {
this.sendCallback.onFailure(ex);
}
if (getSendFailureChannel() != null) {
this.messagingTemplate.send(getSendFailureChannel(), getErrorMessageStrategy()
.buildErrorMessage(new AzureSendFailureException(message, ex), null));
}
}).doOnSuccess(t -> {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("{} sent successfully in async mode", message);
}
if (this.sendCallback != null) {
this.sendCallback.onSuccess((Void) t);
}
}).subscribe();
}
private <T> void waitingSendResponse(Mono<T> mono, Message<?> message) {
Long sendTimeout = this.sendTimeoutExpression.getValue(this.evaluationContext, message, Long.class);
if (sendTimeout == null || sendTimeout < 0) {
try {
mono.block();
} catch (Exception e) {
throw new MessageDeliveryException(e.getMessage());
}
} else {
try {
mono.block(Duration.of(sendTimeout, ChronoUnit.MILLIS));
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("{} sent successfully in sync mode", message);
}
} catch (Exception e) {
if (e.getCause() instanceof TimeoutException) {
throw new MessageTimeoutException(message, "Timeout waiting for send event hub response");
}
throw new MessageDeliveryException(e.getMessage());
}
}
}
public void setSync(boolean sync) {
this.sync = sync;
LOGGER.info("DefaultMessageHandler sync becomes: {}", sync);
}
public void setSendTimeout(long sendTimeout) {
setSendTimeoutExpression(new ValueExpression<>(sendTimeout));
}
public void setPartitionKey(String partitionKey) {
setPartitionKeyExpression(new LiteralExpression(partitionKey));
}
public void setPartitionKeyExpression(Expression partitionKeyExpression) {
this.partitionKeyExpression = partitionKeyExpression;
}
public void setPartitionIdExpression(Expression partitionIdExpression) {
this.partitionIdExpression = partitionIdExpression;
}
private String toDestination(Message<?> message) {
if (message.getHeaders().containsKey(AzureHeaders.NAME)) {
return message.getHeaders().get(AzureHeaders.NAME, String.class);
}
return this.destination;
}
/**
* Get header value from MessageHeaders
* @param headers MessageHeaders
* @param keyName Key name
* @return String header value
*/
private String getHeaderValue(MessageHeaders headers, String keyName) {
return headers.keySet().stream()
.filter(header -> keyName.equals(header))
.map(key -> String.valueOf(headers.get(key)))
.findAny()
.orElse(null);
}
private Map<String, Object> buildPropertiesMap() {
Map<String, Object> properties = new HashMap<>();
properties.put("sync", sync);
properties.put("sendTimeout", sendTimeoutExpression);
properties.put("destination", destination);
return properties;
}
public void setSendCallback(ListenableFutureCallback<Void> callback) {
this.sendCallback = callback;
}
public Expression getSendTimeoutExpression() {
return sendTimeoutExpression;
}
public void setSendTimeoutExpression(Expression sendTimeoutExpression) {
Assert.notNull(sendTimeoutExpression, "'sendTimeoutExpression' must not be null");
this.sendTimeoutExpression = sendTimeoutExpression;
LOGGER.info("DefaultMessageHandler syncTimeout becomes: {}", sendTimeoutExpression);
}
protected MessageChannel getSendFailureChannel() {
if (this.sendFailureChannel != null) {
return this.sendFailureChannel;
} else if (this.sendFailureChannelName != null) {
this.sendFailureChannel = getChannelResolver().resolveDestination(this.sendFailureChannelName);
return this.sendFailureChannel;
}
return null;
}
public void setSendFailureChannel(MessageChannel sendFailureChannel) {
this.sendFailureChannel = sendFailureChannel;
}
public void setSendFailureChannelName(String sendFailureChannelName) {
this.sendFailureChannelName = sendFailureChannelName;
}
protected ErrorMessageStrategy getErrorMessageStrategy() {
return this.errorMessageStrategy;
}
public void setErrorMessageStrategy(ErrorMessageStrategy errorMessageStrategy) {
Assert.notNull(errorMessageStrategy, "'errorMessageStrategy' must not be null");
this.errorMessageStrategy = errorMessageStrategy;
}
} |
can we directly get a string value from the expression? | private PartitionSupplier toPartitionSupplier(Message<?> message) {
PartitionSupplier partitionSupplier = new PartitionSupplier();
MessageHeaders headers = message.getHeaders();
String partitionId = this.partitionIdExpression != null
? String.valueOf(this.partitionIdExpression.getValue(this.evaluationContext, message, Integer.class))
: headers.get(AzureHeaders.PARTITION_ID, String.class);
if (StringUtils.hasText(partitionId)) {
partitionSupplier.setPartitionId(partitionId);
} else {
if (this.partitionKeyExpression != null) {
String partitionKey = this.partitionKeyExpression.getValue(this.evaluationContext,
message, String.class);
if (StringUtils.hasText(partitionKey)) {
partitionSupplier.setPartitionKey(partitionKey);
}
}
}
return partitionSupplier;
} | ? String.valueOf(this.partitionIdExpression.getValue(this.evaluationContext, message, Integer.class)) | private PartitionSupplier toPartitionSupplier(Message<?> message) {
PartitionSupplier partitionSupplier = new PartitionSupplier();
String partitionId = getHeaderValue(message.getHeaders(), AzureHeaders.PARTITION_ID);
if (!StringUtils.hasText(partitionId) && this.partitionIdExpression != null) {
partitionId = this.partitionIdExpression.getValue(this.evaluationContext, message, String.class);
}
if (StringUtils.hasText(partitionId)) {
partitionSupplier.setPartitionId(partitionId);
} else {
String partitionKey = getHeaderValue(message.getHeaders(), AzureHeaders.PARTITION_KEY);
if (!StringUtils.hasText(partitionKey) && this.partitionKeyExpression != null) {
partitionKey = this.partitionKeyExpression.getValue(this.evaluationContext, message, String.class);
}
if (StringUtils.hasText(partitionKey)) {
partitionSupplier.setPartitionKey(partitionKey);
}
}
return partitionSupplier;
} | class DefaultMessageHandler extends AbstractMessageProducingHandler {
private static final Logger LOGGER = LoggerFactory.getLogger(DefaultMessageHandler.class);
private static final long DEFAULT_SEND_TIMEOUT = 10000;
private final String destination;
private final SendOperation sendOperation;
private boolean sync = false;
private ListenableFutureCallback<Void> sendCallback;
private EvaluationContext evaluationContext;
private Expression sendTimeoutExpression = new ValueExpression<>(DEFAULT_SEND_TIMEOUT);
private ErrorMessageStrategy errorMessageStrategy = new DefaultErrorMessageStrategy();
private Expression partitionKeyExpression;
private Expression partitionIdExpression;
private MessageChannel sendFailureChannel;
private String sendFailureChannelName;
public DefaultMessageHandler(String destination, @NonNull SendOperation sendOperation) {
Assert.hasText(destination, "destination can't be null or empty");
this.destination = destination;
this.sendOperation = sendOperation;
}
@Override
protected void onInit() {
super.onInit();
this.evaluationContext = ExpressionUtils.createStandardEvaluationContext(getBeanFactory());
LOGGER.info("Started DefaultMessageHandler with properties: {}", buildPropertiesMap());
}
@Override
protected void handleMessageInternal(Message<?> message) {
PartitionSupplier partitionSupplier = toPartitionSupplier(message);
String destination = toDestination(message);
final Mono<Void> mono = this.sendOperation.sendAsync(destination, message, partitionSupplier);
if (this.sync) {
waitingSendResponse(mono, message);
} else {
handleSendResponseAsync(mono, message);
}
}
private <T> void handleSendResponseAsync(Mono<T> mono, Message<?> message) {
mono.doOnError(ex -> {
if (LOGGER.isWarnEnabled()) {
LOGGER.warn("{} sent failed in async mode due to {}", message, ex.getMessage());
}
if (this.sendCallback != null) {
this.sendCallback.onFailure(ex);
}
if (getSendFailureChannel() != null) {
this.messagingTemplate.send(getSendFailureChannel(), getErrorMessageStrategy()
.buildErrorMessage(new AzureSendFailureException(message, ex), null));
}
}).doOnSuccess(t -> {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("{} sent successfully in async mode", message);
}
if (this.sendCallback != null) {
this.sendCallback.onSuccess((Void) t);
}
}).subscribe();
}
private <T> void waitingSendResponse(Mono<T> mono, Message<?> message) {
Long sendTimeout = this.sendTimeoutExpression.getValue(this.evaluationContext, message, Long.class);
if (sendTimeout == null || sendTimeout < 0) {
try {
mono.block();
} catch (Exception e) {
throw new MessageDeliveryException(e.getMessage());
}
} else {
try {
mono.block(Duration.of(sendTimeout, ChronoUnit.MILLIS));
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("{} sent successfully in sync mode", message);
}
} catch (Exception e) {
if (e.getCause() instanceof TimeoutException) {
throw new MessageTimeoutException(message, "Timeout waiting for send event hub response");
}
throw new MessageDeliveryException(e.getMessage());
}
}
}
public void setSync(boolean sync) {
this.sync = sync;
LOGGER.info("DefaultMessageHandler sync becomes: {}", sync);
}
public void setSendTimeout(long sendTimeout) {
setSendTimeoutExpression(new ValueExpression<>(sendTimeout));
}
public void setPartitionKey(String partitionKey) {
setPartitionKeyExpression(new LiteralExpression(partitionKey));
}
public void setPartitionKeyExpression(Expression partitionKeyExpression) {
this.partitionKeyExpression = partitionKeyExpression;
}
public void setPartitionIdExpression(Expression partitionIdExpression) {
this.partitionIdExpression = partitionIdExpression;
}
public void setPartitionIdExpressionString(String partitionIdExpressionString) {
setPartitionIdExpression(EXPRESSION_PARSER.parseExpression(partitionIdExpressionString));
}
private String toDestination(Message<?> message) {
if (message.getHeaders().containsKey(AzureHeaders.NAME)) {
return message.getHeaders().get(AzureHeaders.NAME, String.class);
}
return this.destination;
}
private Map<String, Object> buildPropertiesMap() {
Map<String, Object> properties = new HashMap<>();
properties.put("sync", sync);
properties.put("sendTimeout", sendTimeoutExpression);
properties.put("destination", destination);
return properties;
}
public void setSendCallback(ListenableFutureCallback<Void> callback) {
this.sendCallback = callback;
}
public Expression getSendTimeoutExpression() {
return sendTimeoutExpression;
}
public void setSendTimeoutExpression(Expression sendTimeoutExpression) {
Assert.notNull(sendTimeoutExpression, "'sendTimeoutExpression' must not be null");
this.sendTimeoutExpression = sendTimeoutExpression;
LOGGER.info("DefaultMessageHandler syncTimeout becomes: {}", sendTimeoutExpression);
}
protected MessageChannel getSendFailureChannel() {
if (this.sendFailureChannel != null) {
return this.sendFailureChannel;
} else if (this.sendFailureChannelName != null) {
this.sendFailureChannel = getChannelResolver().resolveDestination(this.sendFailureChannelName);
return this.sendFailureChannel;
}
return null;
}
public void setSendFailureChannel(MessageChannel sendFailureChannel) {
this.sendFailureChannel = sendFailureChannel;
}
public void setSendFailureChannelName(String sendFailureChannelName) {
this.sendFailureChannelName = sendFailureChannelName;
}
protected ErrorMessageStrategy getErrorMessageStrategy() {
return this.errorMessageStrategy;
}
public void setErrorMessageStrategy(ErrorMessageStrategy errorMessageStrategy) {
Assert.notNull(errorMessageStrategy, "'errorMessageStrategy' must not be null");
this.errorMessageStrategy = errorMessageStrategy;
}
} | class DefaultMessageHandler extends AbstractMessageProducingHandler {
private static final Logger LOGGER = LoggerFactory.getLogger(DefaultMessageHandler.class);
private static final long DEFAULT_SEND_TIMEOUT = 10000;
private final String destination;
private final SendOperation sendOperation;
private boolean sync = false;
private ListenableFutureCallback<Void> sendCallback;
private EvaluationContext evaluationContext;
private Expression sendTimeoutExpression = new ValueExpression<>(DEFAULT_SEND_TIMEOUT);
private ErrorMessageStrategy errorMessageStrategy = new DefaultErrorMessageStrategy();
private Expression partitionKeyExpression;
private Expression partitionIdExpression;
private MessageChannel sendFailureChannel;
private String sendFailureChannelName;
public DefaultMessageHandler(String destination, @NonNull SendOperation sendOperation) {
Assert.hasText(destination, "destination can't be null or empty");
this.destination = destination;
this.sendOperation = sendOperation;
}
@Override
protected void onInit() {
super.onInit();
this.evaluationContext = ExpressionUtils.createStandardEvaluationContext(getBeanFactory());
LOGGER.info("Started DefaultMessageHandler with properties: {}", buildPropertiesMap());
}
@Override
protected void handleMessageInternal(Message<?> message) {
PartitionSupplier partitionSupplier = toPartitionSupplier(message);
String destination = toDestination(message);
final Mono<Void> mono = this.sendOperation.sendAsync(destination, message, partitionSupplier);
if (this.sync) {
waitingSendResponse(mono, message);
} else {
handleSendResponseAsync(mono, message);
}
}
private <T> void handleSendResponseAsync(Mono<T> mono, Message<?> message) {
mono.doOnError(ex -> {
if (LOGGER.isWarnEnabled()) {
LOGGER.warn("{} sent failed in async mode due to {}", message, ex.getMessage());
}
if (this.sendCallback != null) {
this.sendCallback.onFailure(ex);
}
if (getSendFailureChannel() != null) {
this.messagingTemplate.send(getSendFailureChannel(), getErrorMessageStrategy()
.buildErrorMessage(new AzureSendFailureException(message, ex), null));
}
}).doOnSuccess(t -> {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("{} sent successfully in async mode", message);
}
if (this.sendCallback != null) {
this.sendCallback.onSuccess((Void) t);
}
}).subscribe();
}
private <T> void waitingSendResponse(Mono<T> mono, Message<?> message) {
Long sendTimeout = this.sendTimeoutExpression.getValue(this.evaluationContext, message, Long.class);
if (sendTimeout == null || sendTimeout < 0) {
try {
mono.block();
} catch (Exception e) {
throw new MessageDeliveryException(e.getMessage());
}
} else {
try {
mono.block(Duration.of(sendTimeout, ChronoUnit.MILLIS));
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("{} sent successfully in sync mode", message);
}
} catch (Exception e) {
if (e.getCause() instanceof TimeoutException) {
throw new MessageTimeoutException(message, "Timeout waiting for send event hub response");
}
throw new MessageDeliveryException(e.getMessage());
}
}
}
public void setSync(boolean sync) {
this.sync = sync;
LOGGER.info("DefaultMessageHandler sync becomes: {}", sync);
}
public void setSendTimeout(long sendTimeout) {
setSendTimeoutExpression(new ValueExpression<>(sendTimeout));
}
public void setPartitionKey(String partitionKey) {
setPartitionKeyExpression(new LiteralExpression(partitionKey));
}
public void setPartitionKeyExpression(Expression partitionKeyExpression) {
this.partitionKeyExpression = partitionKeyExpression;
}
public void setPartitionIdExpression(Expression partitionIdExpression) {
this.partitionIdExpression = partitionIdExpression;
}
private String toDestination(Message<?> message) {
if (message.getHeaders().containsKey(AzureHeaders.NAME)) {
return message.getHeaders().get(AzureHeaders.NAME, String.class);
}
return this.destination;
}
/**
* Get header value from MessageHeaders
* @param headers MessageHeaders
* @param keyName Key name
* @return String header value
*/
private String getHeaderValue(MessageHeaders headers, String keyName) {
return headers.keySet().stream()
.filter(header -> keyName.equals(header))
.map(key -> String.valueOf(headers.get(key)))
.findAny()
.orElse(null);
}
private Map<String, Object> buildPropertiesMap() {
Map<String, Object> properties = new HashMap<>();
properties.put("sync", sync);
properties.put("sendTimeout", sendTimeoutExpression);
properties.put("destination", destination);
return properties;
}
public void setSendCallback(ListenableFutureCallback<Void> callback) {
this.sendCallback = callback;
}
public Expression getSendTimeoutExpression() {
return sendTimeoutExpression;
}
public void setSendTimeoutExpression(Expression sendTimeoutExpression) {
Assert.notNull(sendTimeoutExpression, "'sendTimeoutExpression' must not be null");
this.sendTimeoutExpression = sendTimeoutExpression;
LOGGER.info("DefaultMessageHandler syncTimeout becomes: {}", sendTimeoutExpression);
}
protected MessageChannel getSendFailureChannel() {
if (this.sendFailureChannel != null) {
return this.sendFailureChannel;
} else if (this.sendFailureChannelName != null) {
this.sendFailureChannel = getChannelResolver().resolveDestination(this.sendFailureChannelName);
return this.sendFailureChannel;
}
return null;
}
public void setSendFailureChannel(MessageChannel sendFailureChannel) {
this.sendFailureChannel = sendFailureChannel;
}
public void setSendFailureChannelName(String sendFailureChannelName) {
this.sendFailureChannelName = sendFailureChannelName;
}
protected ErrorMessageStrategy getErrorMessageStrategy() {
return this.errorMessageStrategy;
}
public void setErrorMessageStrategy(ErrorMessageStrategy errorMessageStrategy) {
Assert.notNull(errorMessageStrategy, "'errorMessageStrategy' must not be null");
this.errorMessageStrategy = errorMessageStrategy;
}
} |
Can this be done just once and cache the ByteBuffer instead of wrapping the data each time? | public ByteBuffer toByteBuffer() {
return ByteBuffer.wrap(this.data).asReadOnlyBuffer();
} | return ByteBuffer.wrap(this.data).asReadOnlyBuffer(); | public ByteBuffer toByteBuffer() {
return ByteBuffer.wrap(this.data).asReadOnlyBuffer();
} | class BinaryData {
private static final ClientLogger LOGGER = new ClientLogger(BinaryData.class);
private static final BinaryData EMPTY_DATA = new BinaryData(new byte[0]);
private static final int STREAM_READ_SIZE = 1024;
private static final Object LOCK = new Object();
private static volatile JsonSerializer defaultJsonSerializer;
private final byte[] data;
private String dataAsStringCache;
/**
* Create an instance of {@link BinaryData} from the given byte array.
*
* @param data The byte array that {@link BinaryData} will represent.
*/
BinaryData(byte[] data) {
this.data = data;
}
/**
* Creates an instance of {@link BinaryData} from the given {@link InputStream}.
* <p>
* If {@code inputStream} is null or empty an empty {@link BinaryData} is returned.
* <p>
* <b>NOTE:</b> The {@link InputStream} is not closed by this function.
*
* <p><strong>Create an instance from an InputStream</strong></p>
*
* {@codesnippet com.azure.core.util.BinaryData.fromStream
*
* @param inputStream The {@link InputStream} that {@link BinaryData} will represent.
* @return A {@link BinaryData} representing the {@link InputStream}.
* @throws UncheckedIOException If any error happens while reading the {@link InputStream}.
*/
public static BinaryData fromStream(InputStream inputStream) {
if (Objects.isNull(inputStream)) {
return EMPTY_DATA;
}
try {
ByteArrayOutputStream dataOutputBuffer = new ByteArrayOutputStream();
int nRead;
byte[] data = new byte[STREAM_READ_SIZE];
while ((nRead = inputStream.read(data, 0, data.length)) != -1) {
dataOutputBuffer.write(data, 0, nRead);
}
return new BinaryData(dataOutputBuffer.toByteArray());
} catch (IOException ex) {
throw LOGGER.logExceptionAsError(new UncheckedIOException(ex));
}
}
/**
* Creates an instance of {@link BinaryData} from the given {@link InputStream}.
* <p>
* If {@code inputStream} is null or empty an empty {@link BinaryData} is returned.
* <p>
* <b>NOTE:</b> The {@link InputStream} is not closed by this function.
*
* <p><strong>Create an instance from an InputStream</strong></p>
*
* {@codesnippet com.azure.core.util.BinaryData.fromStreamAsync
*
* @param inputStream The {@link InputStream} that {@link BinaryData} will represent.
* @return A {@link Mono} of {@link BinaryData} representing the {@link InputStream}.
* @throws UncheckedIOException If any error happens while reading the {@link InputStream}.
*/
public static Mono<BinaryData> fromStreamAsync(InputStream inputStream) {
return Mono.fromCallable(() -> fromStream(inputStream));
}
/**
* Creates an instance of {@link BinaryData} from the given {@link Flux} of {@link ByteBuffer}.
* <p>
* If the {@code data} is null an empty {@link BinaryData} will be returned.
* <p>
* <b>Note:</b> This will collect all bytes from the {@link ByteBuffer ByteBuffers} resulting in {@link
* ByteBuffer
*
* <p><strong>Create an instance from a Flux of ByteBuffer</strong></p>
*
* {@codesnippet com.azure.core.util.BinaryData.fromFlux
*
* @param data The {@link Flux} of {@link ByteBuffer} that {@link BinaryData} will represent.
* @return A {@link Mono} of {@link BinaryData} representing the {@link Flux} of {@link ByteBuffer}.
*/
public static Mono<BinaryData> fromFlux(Flux<ByteBuffer> data) {
if (Objects.isNull(data)) {
return Mono.just(EMPTY_DATA);
}
return FluxUtil.collectBytesInByteBufferStream(data)
.flatMap(bytes -> Mono.just(new BinaryData(bytes)));
}
/**
* Creates an instance of {@link BinaryData} from the given {@link String}.
* <p>
* The {@link String} is converted into bytes using {@link String
* StandardCharsets
* <p>
* If the {@code data} is null or a zero length string an empty {@link BinaryData} will be returned.
*
* <p><strong>Create an instance from a String</strong></p>
*
* {@codesnippet com.azure.core.util.BinaryData.fromString
*
* @param data The {@link String} that {@link BinaryData} will represent.
* @return A {@link BinaryData} representing the {@link String}.
*/
public static BinaryData fromString(String data) {
if (CoreUtils.isNullOrEmpty(data)) {
return EMPTY_DATA;
}
return new BinaryData(data.getBytes(StandardCharsets.UTF_8));
}
/**
* Creates an instance of {@link BinaryData} from the given byte array.
* <p>
* If the byte array is null or zero length an empty {@link BinaryData} will be returned.
*
* <p><strong>Create an instance from a byte array</strong></p>
*
* {@codesnippet com.azure.core.util.BinaryData.fromBytes
*
* @param data The byte array that {@link BinaryData} will represent.
* @return A {@link BinaryData} representing the byte array.
*/
public static BinaryData fromBytes(byte[] data) {
if (Objects.isNull(data) || data.length == 0) {
return EMPTY_DATA;
}
return new BinaryData(Arrays.copyOf(data, data.length));
}
/**
* Creates an instance of {@link BinaryData} by serializing the {@link Object} using the default {@link
* JsonSerializer}.
* <p>
* If {@code data} is null an empty {@link BinaryData} will be returned.
* <p>
* <b>Note:</b> A {@link JsonSerializer} implementation must be available on the classpath.
*
* <p><strong>Creating an instance from an Object</strong></p>
*
* {@codesnippet com.azure.core.util.BinaryData.fromObject
*
* @param data The object that will be JSON serialized that {@link BinaryData} will represent.
* @return A {@link BinaryData} representing the JSON serialized object.
* @throws IllegalStateException If a {@link JsonSerializer} implementation cannot be found on the classpath.
* @see JsonSerializer
*/
public static BinaryData fromObject(Object data) {
return fromObject(data, getDefaultSerializer());
}
/**
* Creates an instance of {@link BinaryData} by serializing the {@link Object} using the default {@link
* JsonSerializer}.
* <p>
* If {@code data} is null an empty {@link BinaryData} will be returned.
* <p>
* <b>Note:</b> A {@link JsonSerializer} implementation must be available on the classpath.
*
* <p><strong>Creating an instance from an Object</strong></p>
*
* {@codesnippet com.azure.core.util.BinaryData.fromObjectAsync
*
* @param data The object that will be JSON serialized that {@link BinaryData} will represent.
* @return A {@link Mono} of {@link BinaryData} representing the JSON serialized object.
* @throws IllegalStateException If a {@link JsonSerializer} implementation cannot be found on the classpath.
* @see JsonSerializer
*/
public static Mono<BinaryData> fromObjectAsync(Object data) {
return fromObjectAsync(data, getDefaultSerializer());
}
/**
* Creates an instance of {@link BinaryData} by serializing the {@link Object} using the passed {@link
* ObjectSerializer}.
* <p>
* If {@code data} is null an empty {@link BinaryData} will be returned.
* <p>
* The passed {@link ObjectSerializer} can either be one of the implementations offered by the Azure SDKs or your
* own implementation.
*
* <p><strong>Azure SDK implementations</strong></p>
* <ul>
* <li><a href="https:
* <li><a href="https:
* </ul>
*
* <p><strong>Create an instance from an Object</strong></p>
*
* {@codesnippet com.azure.core.util.BinaryData.fromObject
*
* @param data The object that will be serialized that {@link BinaryData} will represent.
* @param serializer The {@link ObjectSerializer} used to serialize object.
* @return A {@link BinaryData} representing the serialized object.
* @throws NullPointerException If {@code serializer} is null and {@code data} is not null.
* @see ObjectSerializer
* @see JsonSerializer
* @see <a href="https:
*/
public static BinaryData fromObject(Object data, ObjectSerializer serializer) {
if (Objects.isNull(data)) {
return EMPTY_DATA;
}
Objects.requireNonNull(serializer, "'serializer' cannot be null.");
return new BinaryData(serializer.serializeToBytes(data));
}
/**
* Creates an instance of {@link BinaryData} by serializing the {@link Object} using the passed {@link
* ObjectSerializer}.
* <p>
* If {@code data} is null an empty {@link BinaryData} will be returned.
* <p>
* The passed {@link ObjectSerializer} can either be one of the implementations offered by the Azure SDKs or your
* own implementation.
*
* <p><strong>Azure SDK implementations</strong></p>
* <ul>
* <li><a href="https:
* <li><a href="https:
* </ul>
*
* <p><strong>Create an instance from an Object</strong></p>
*
* {@codesnippet com.azure.core.util.BinaryData.fromObjectAsync
*
* @param data The object that will be serialized that {@link BinaryData} will represent.
* @param serializer The {@link ObjectSerializer} used to serialize object.
* @return A {@link Mono} of {@link BinaryData} representing the serialized object.
* @throws NullPointerException If {@code serializer} is null and {@code data} is not null.
* @see ObjectSerializer
* @see JsonSerializer
* @see <a href="https:
*/
public static Mono<BinaryData> fromObjectAsync(Object data, ObjectSerializer serializer) {
return Mono.fromCallable(() -> fromObject(data, serializer));
}
/**
* Returns a byte array representation of this {@link BinaryData}.
*
* @return A byte array representing this {@link BinaryData}.
*/
public byte[] toBytes() {
return Arrays.copyOf(this.data, this.data.length);
}
/**
* Returns a {@link String} representation of this {@link BinaryData} by converting its data using the UTF-8
* character set.
*
* @return A {@link String} representing this {@link BinaryData}.
*/
public String toString() {
if (this.dataAsStringCache == null) {
this.dataAsStringCache = new String(this.data, StandardCharsets.UTF_8);
}
return this.dataAsStringCache;
}
/**
* Returns an {@link Object} representation of this {@link BinaryData} by deserializing its data using the default
* {@link JsonSerializer}.
* <p>
* The type, represented by {@link Class}, should be a non-generic class, for generic classes use {@link
*
* <p>
* <b>Note:</b> A {@link JsonSerializer} implementation must be available on the classpath.
*
* <p><strong>Get a non-generic Object from the BinaryData</strong></p>
*
* {@codesnippet com.azure.core.util.BinaryData.toObject
*
* @param clazz The {@link Class} representing the Object's type.
* @param <T> Type of the deserialized Object.
* @return An {@link Object} representing the JSON deserialized {@link BinaryData}.
* @throws NullPointerException If {@code clazz} is null.
* @throws IllegalStateException If a {@link JsonSerializer} implementation cannot be found on the classpath.
* @see JsonSerializer
*/
public <T> T toObject(Class<T> clazz) {
return toObject(TypeReference.createInstance(clazz), getDefaultSerializer());
}
/**
* Returns an {@link Object} representation of this {@link BinaryData} by deserializing its data using the default
* {@link JsonSerializer}.
* <p>
* The type, represented by {@link TypeReference}, can either be a generic or non-generic type. If the type is
* generic create a sub-type of {@link TypeReference}, if the type is non-generic use {@link
* TypeReference
* <p>
* <b>Note:</b> A {@link JsonSerializer} implementation must be available on the classpath.
*
* <p><strong>Get a non-generic Object from the BinaryData</strong></p>
*
* {@codesnippet com.azure.core.util.BinaryData.toObject
*
* <p><strong>Get a generic Object from the BinaryData</strong></p>
*
* {@codesnippet com.azure.core.util.BinaryData.toObject
*
* @param typeReference The {@link TypeReference} representing the Object's type.
* @param <T> Type of the deserialized Object.
* @return An {@link Object} representing the JSON deserialized {@link BinaryData}.
* @throws NullPointerException If {@code typeReference} is null.
* @throws IllegalStateException If a {@link JsonSerializer} implementation cannot be found on the classpath.
* @see JsonSerializer
*/
public <T> T toObject(TypeReference<T> typeReference) {
return toObject(typeReference, getDefaultSerializer());
}
/**
* Returns an {@link Object} representation of this {@link BinaryData} by deserializing its data using the passed
* {@link ObjectSerializer}.
* <p>
* The type, represented by {@link Class}, should be a non-generic class, for generic classes use {@link
*
* <p>
* The passed {@link ObjectSerializer} can either be one of the implementations offered by the Azure SDKs or your
* own implementation.
*
* <p><strong>Azure SDK implementations</strong></p>
* <ul>
* <li><a href="https:
* <li><a href="https:
* </ul>
*
* <p><strong>Get a non-generic Object from the BinaryData</strong></p>
*
* {@codesnippet com.azure.core.util.BinaryData.toObject
*
* @param clazz The {@link Class} representing the Object's type.
* @param serializer The {@link ObjectSerializer} used to deserialize object.
* @param <T> Type of the deserialized Object.
* @return An {@link Object} representing the deserialized {@link BinaryData}.
* @throws NullPointerException If {@code clazz} or {@code serializer} is null.
* @see ObjectSerializer
* @see JsonSerializer
* @see <a href="https:
*/
public <T> T toObject(Class<T> clazz, ObjectSerializer serializer) {
return toObject(TypeReference.createInstance(clazz), serializer);
}
/**
* Returns an {@link Object} representation of this {@link BinaryData} by deserializing its data using the passed
* {@link ObjectSerializer}.
* <p>
* The type, represented by {@link TypeReference}, can either be a generic or non-generic type. If the type is
* generic create a sub-type of {@link TypeReference}, if the type is non-generic use {@link
* TypeReference
* <p>
* The passed {@link ObjectSerializer} can either be one of the implementations offered by the Azure SDKs or your
* own implementation.
*
* <p><strong>Azure SDK implementations</strong></p>
* <ul>
* <li><a href="https:
* <li><a href="https:
* </ul>
*
* <p><strong>Get a non-generic Object from the BinaryData</strong></p>
*
* {@codesnippet com.azure.core.util.BinaryData.toObject
*
* <p><strong>Get a generic Object from the BinaryData</strong></p>
*
* {@codesnippet com.azure.core.util.BinaryData.toObject
*
* @param typeReference The {@link TypeReference} representing the Object's type.
* @param serializer The {@link ObjectSerializer} used to deserialize object.
* @param <T> Type of the deserialized Object.
* @return An {@link Object} representing the deserialized {@link BinaryData}.
* @throws NullPointerException If {@code typeReference} or {@code serializer} is null.
* @see ObjectSerializer
* @see JsonSerializer
* @see <a href="https:
*/
public <T> T toObject(TypeReference<T> typeReference, ObjectSerializer serializer) {
Objects.requireNonNull(typeReference, "'typeReference' cannot be null.");
Objects.requireNonNull(serializer, "'serializer' cannot be null.");
return serializer.deserializeFromBytes(this.data, typeReference);
}
/**
* Returns an {@link Object} representation of this {@link BinaryData} by deserializing its data using the default
* {@link JsonSerializer}.
* <p>
* The type, represented by {@link Class}, should be a non-generic class, for generic classes use {@link
*
* <p>
* <b>Note:</b> A {@link JsonSerializer} implementation must be available on the classpath.
*
* <p><strong>Get a non-generic Object from the BinaryData</strong></p>
*
* {@codesnippet com.azure.core.util.BinaryData.toObjectAsync
*
* @param clazz The {@link Class} representing the Object's type.
* @param <T> Type of the deserialized Object.
* @return A {@link Mono} of {@link Object} representing the JSON deserialized {@link BinaryData}.
* @throws NullPointerException If {@code clazz} is null.
* @throws IllegalStateException If a {@link JsonSerializer} implementation cannot be found on the classpath.
* @see JsonSerializer
*/
public <T> Mono<T> toObjectAsync(Class<T> clazz) {
return toObjectAsync(TypeReference.createInstance(clazz), getDefaultSerializer());
}
/**
* Returns an {@link Object} representation of this {@link BinaryData} by deserializing its data using the default
* {@link JsonSerializer}.
* <p>
* The type, represented by {@link TypeReference}, can either be a generic or non-generic type. If the type is
* generic create a sub-type of {@link TypeReference}, if the type is non-generic use {@link
* TypeReference
* <p>
* <b>Note:</b> A {@link JsonSerializer} implementation must be available on the classpath.
*
* <p><strong>Get a non-generic Object from the BinaryData</strong></p>
*
* {@codesnippet com.azure.core.util.BinaryData.toObjectAsync
*
* <p><strong>Get a generic Object from the BinaryData</strong></p>
*
* {@codesnippet com.azure.core.util.BinaryData.toObjectAsync
*
* @param typeReference The {@link TypeReference} representing the Object's type.
* @param <T> Type of the deserialized Object.
* @return A {@link Mono} of {@link Object} representing the JSON deserialized {@link BinaryData}.
* @throws NullPointerException If {@code typeReference} is null.
* @throws IllegalStateException If a {@link JsonSerializer} implementation cannot be found on the classpath.
* @see JsonSerializer
*/
public <T> Mono<T> toObjectAsync(TypeReference<T> typeReference) {
return toObjectAsync(typeReference, getDefaultSerializer());
}
/**
* Returns an {@link Object} representation of this {@link BinaryData} by deserializing its data using the passed
* {@link ObjectSerializer}.
* <p>
* The type, represented by {@link Class}, should be a non-generic class, for generic classes use {@link
*
* <p>
* The passed {@link ObjectSerializer} can either be one of the implementations offered by the Azure SDKs or your
* own implementation.
*
* <p><strong>Azure SDK implementations</strong></p>
* <ul>
* <li><a href="https:
* <li><a href="https:
* </ul>
*
* <p><strong>Get a non-generic Object from the BinaryData</strong></p>
*
* {@codesnippet com.azure.core.util.BinaryData.toObjectAsync
*
* @param clazz The {@link Class} representing the Object's type.
* @param serializer The {@link ObjectSerializer} used to deserialize object.
* @param <T> Type of the deserialized Object.
* @return A {@link Mono} of {@link Object} representing the deserialized {@link BinaryData}.
* @throws NullPointerException If {@code clazz} or {@code serializer} is null.
* @see ObjectSerializer
* @see JsonSerializer
* @see <a href="https:
*/
public <T> Mono<T> toObjectAsync(Class<T> clazz, ObjectSerializer serializer) {
return toObjectAsync(TypeReference.createInstance(clazz), serializer);
}
/**
* Returns an {@link Object} representation of this {@link BinaryData} by deserializing its data using the passed
* {@link ObjectSerializer}.
* <p>
* The type, represented by {@link TypeReference}, can either be a generic or non-generic type. If the type is
* generic create a sub-type of {@link TypeReference}, if the type is non-generic use {@link
* TypeReference
* <p>
* The passed {@link ObjectSerializer} can either be one of the implementations offered by the Azure SDKs or your
* own implementation.
*
* <p><strong>Azure SDK implementations</strong></p>
* <ul>
* <li><a href="https:
* <li><a href="https:
* </ul>
*
* <p><strong>Get a non-generic Object from the BinaryData</strong></p>
*
* {@codesnippet com.azure.core.util.BinaryData.toObjectAsync
*
* <p><strong>Get a generic Object from the BinaryData</strong></p>
*
* {@codesnippet com.azure.core.util.BinaryData.toObjectAsync
*
* @param typeReference The {@link TypeReference} representing the Object's type.
* @param serializer The {@link ObjectSerializer} used to deserialize object.
* @param <T> Type of the deserialized Object.
* @return A {@link Mono} of {@link Object} representing the deserialized {@link BinaryData}.
* @throws NullPointerException If {@code typeReference} or {@code serializer} is null.
* @see ObjectSerializer
* @see JsonSerializer
* @see <a href="https:
*/
public <T> Mono<T> toObjectAsync(TypeReference<T> typeReference, ObjectSerializer serializer) {
return Mono.fromCallable(() -> toObject(typeReference, serializer));
}
/**
* Returns an {@link InputStream} representation of this {@link BinaryData}.
*
* <p><strong>Get an InputStream from the BinaryData</strong></p>
*
* {@codesnippet com.azure.core.util.BinaryData.toStream}
*
* @return An {@link InputStream} representing the {@link BinaryData}.
*/
public InputStream toStream() {
return new ByteArrayInputStream(this.data);
}
/**
* Returns a read-only {@link ByteBuffer} representation of this {@link BinaryData}.
* <p>
* Attempting to mutate the returned {@link ByteBuffer} will throw a {@link ReadOnlyBufferException}.
*
* <p><strong>Get a read-only ByteBuffer from the BinaryData</strong></p>
*
* {@codesnippet com.azure.util.BinaryData.toByteBuffer}
*
* @return A read-only {@link ByteBuffer} representing the {@link BinaryData}.
*/
/* This will ensure lazy instantiation to avoid hard dependency on Json Serializer. */
private static JsonSerializer getDefaultSerializer() {
if (defaultJsonSerializer == null) {
synchronized (LOCK) {
if (defaultJsonSerializer == null) {
defaultJsonSerializer = JsonSerializerProviders.createInstance();
}
}
}
return defaultJsonSerializer;
}
} | class BinaryData {
private static final ClientLogger LOGGER = new ClientLogger(BinaryData.class);
private static final BinaryData EMPTY_DATA = new BinaryData(new byte[0]);
private static final int STREAM_READ_SIZE = 1024;
private static final Object LOCK = new Object();
private static volatile JsonSerializer defaultJsonSerializer;
private final byte[] data;
private String dataAsStringCache;
/**
* Create an instance of {@link BinaryData} from the given byte array.
*
* @param data The byte array that {@link BinaryData} will represent.
*/
BinaryData(byte[] data) {
this.data = data;
}
/**
* Creates an instance of {@link BinaryData} from the given {@link InputStream}.
* <p>
* If {@code inputStream} is null or empty an empty {@link BinaryData} is returned.
* <p>
* <b>NOTE:</b> The {@link InputStream} is not closed by this function.
*
* <p><strong>Create an instance from an InputStream</strong></p>
*
* {@codesnippet com.azure.core.util.BinaryData.fromStream
*
* @param inputStream The {@link InputStream} that {@link BinaryData} will represent.
* @return A {@link BinaryData} representing the {@link InputStream}.
* @throws UncheckedIOException If any error happens while reading the {@link InputStream}.
*/
public static BinaryData fromStream(InputStream inputStream) {
if (Objects.isNull(inputStream)) {
return EMPTY_DATA;
}
try {
ByteArrayOutputStream dataOutputBuffer = new ByteArrayOutputStream();
int nRead;
byte[] data = new byte[STREAM_READ_SIZE];
while ((nRead = inputStream.read(data, 0, data.length)) != -1) {
dataOutputBuffer.write(data, 0, nRead);
}
return new BinaryData(dataOutputBuffer.toByteArray());
} catch (IOException ex) {
throw LOGGER.logExceptionAsError(new UncheckedIOException(ex));
}
}
/**
* Creates an instance of {@link BinaryData} from the given {@link InputStream}.
* <p>
* If {@code inputStream} is null or empty an empty {@link BinaryData} is returned.
* <p>
* <b>NOTE:</b> The {@link InputStream} is not closed by this function.
*
* <p><strong>Create an instance from an InputStream</strong></p>
*
* {@codesnippet com.azure.core.util.BinaryData.fromStreamAsync
*
* @param inputStream The {@link InputStream} that {@link BinaryData} will represent.
* @return A {@link Mono} of {@link BinaryData} representing the {@link InputStream}.
* @throws UncheckedIOException If any error happens while reading the {@link InputStream}.
*/
public static Mono<BinaryData> fromStreamAsync(InputStream inputStream) {
return Mono.fromCallable(() -> fromStream(inputStream));
}
/**
* Creates an instance of {@link BinaryData} from the given {@link Flux} of {@link ByteBuffer}.
* <p>
* If the {@code data} is null an empty {@link BinaryData} will be returned.
* <p>
* <b>Note:</b> This will collect all bytes from the {@link ByteBuffer ByteBuffers} resulting in {@link
* ByteBuffer
*
* <p><strong>Create an instance from a Flux of ByteBuffer</strong></p>
*
* {@codesnippet com.azure.core.util.BinaryData.fromFlux
*
* @param data The {@link Flux} of {@link ByteBuffer} that {@link BinaryData} will represent.
* @return A {@link Mono} of {@link BinaryData} representing the {@link Flux} of {@link ByteBuffer}.
*/
public static Mono<BinaryData> fromFlux(Flux<ByteBuffer> data) {
if (Objects.isNull(data)) {
return Mono.just(EMPTY_DATA);
}
return FluxUtil.collectBytesInByteBufferStream(data)
.flatMap(bytes -> Mono.just(new BinaryData(bytes)));
}
/**
* Creates an instance of {@link BinaryData} from the given {@link String}.
* <p>
* The {@link String} is converted into bytes using {@link String
* StandardCharsets
* <p>
* If the {@code data} is null or a zero length string an empty {@link BinaryData} will be returned.
*
* <p><strong>Create an instance from a String</strong></p>
*
* {@codesnippet com.azure.core.util.BinaryData.fromString
*
* @param data The {@link String} that {@link BinaryData} will represent.
* @return A {@link BinaryData} representing the {@link String}.
*/
public static BinaryData fromString(String data) {
if (CoreUtils.isNullOrEmpty(data)) {
return EMPTY_DATA;
}
return new BinaryData(data.getBytes(StandardCharsets.UTF_8));
}
/**
* Creates an instance of {@link BinaryData} from the given byte array.
* <p>
* If the byte array is null or zero length an empty {@link BinaryData} will be returned.
*
* <p><strong>Create an instance from a byte array</strong></p>
*
* {@codesnippet com.azure.core.util.BinaryData.fromBytes
*
* @param data The byte array that {@link BinaryData} will represent.
* @return A {@link BinaryData} representing the byte array.
*/
public static BinaryData fromBytes(byte[] data) {
if (Objects.isNull(data) || data.length == 0) {
return EMPTY_DATA;
}
return new BinaryData(Arrays.copyOf(data, data.length));
}
/**
* Creates an instance of {@link BinaryData} by serializing the {@link Object} using the default {@link
* JsonSerializer}.
* <p>
* If {@code data} is null an empty {@link BinaryData} will be returned.
* <p>
* <b>Note:</b> A {@link JsonSerializer} implementation must be available on the classpath.
*
* <p><strong>Creating an instance from an Object</strong></p>
*
* {@codesnippet com.azure.core.util.BinaryData.fromObject
*
* @param data The object that will be JSON serialized that {@link BinaryData} will represent.
* @return A {@link BinaryData} representing the JSON serialized object.
* @throws IllegalStateException If a {@link JsonSerializer} implementation cannot be found on the classpath.
* @see JsonSerializer
*/
public static BinaryData fromObject(Object data) {
return fromObject(data, getDefaultSerializer());
}
/**
* Creates an instance of {@link BinaryData} by serializing the {@link Object} using the default {@link
* JsonSerializer}.
* <p>
* If {@code data} is null an empty {@link BinaryData} will be returned.
* <p>
* <b>Note:</b> A {@link JsonSerializer} implementation must be available on the classpath.
*
* <p><strong>Creating an instance from an Object</strong></p>
*
* {@codesnippet com.azure.core.util.BinaryData.fromObjectAsync
*
* @param data The object that will be JSON serialized that {@link BinaryData} will represent.
* @return A {@link Mono} of {@link BinaryData} representing the JSON serialized object.
* @throws IllegalStateException If a {@link JsonSerializer} implementation cannot be found on the classpath.
* @see JsonSerializer
*/
public static Mono<BinaryData> fromObjectAsync(Object data) {
return fromObjectAsync(data, getDefaultSerializer());
}
/**
* Creates an instance of {@link BinaryData} by serializing the {@link Object} using the passed {@link
* ObjectSerializer}.
* <p>
* If {@code data} is null an empty {@link BinaryData} will be returned.
* <p>
* The passed {@link ObjectSerializer} can either be one of the implementations offered by the Azure SDKs or your
* own implementation.
*
* <p><strong>Azure SDK implementations</strong></p>
* <ul>
* <li><a href="https:
* <li><a href="https:
* </ul>
*
* <p><strong>Create an instance from an Object</strong></p>
*
* {@codesnippet com.azure.core.util.BinaryData.fromObject
*
* @param data The object that will be serialized that {@link BinaryData} will represent.
* @param serializer The {@link ObjectSerializer} used to serialize object.
* @return A {@link BinaryData} representing the serialized object.
* @throws NullPointerException If {@code serializer} is null and {@code data} is not null.
* @see ObjectSerializer
* @see JsonSerializer
* @see <a href="https:
*/
public static BinaryData fromObject(Object data, ObjectSerializer serializer) {
if (Objects.isNull(data)) {
return EMPTY_DATA;
}
Objects.requireNonNull(serializer, "'serializer' cannot be null.");
return new BinaryData(serializer.serializeToBytes(data));
}
/**
* Creates an instance of {@link BinaryData} by serializing the {@link Object} using the passed {@link
* ObjectSerializer}.
* <p>
* If {@code data} is null an empty {@link BinaryData} will be returned.
* <p>
* The passed {@link ObjectSerializer} can either be one of the implementations offered by the Azure SDKs or your
* own implementation.
*
* <p><strong>Azure SDK implementations</strong></p>
* <ul>
* <li><a href="https:
* <li><a href="https:
* </ul>
*
* <p><strong>Create an instance from an Object</strong></p>
*
* {@codesnippet com.azure.core.util.BinaryData.fromObjectAsync
*
* @param data The object that will be serialized that {@link BinaryData} will represent.
* @param serializer The {@link ObjectSerializer} used to serialize object.
* @return A {@link Mono} of {@link BinaryData} representing the serialized object.
* @throws NullPointerException If {@code serializer} is null and {@code data} is not null.
* @see ObjectSerializer
* @see JsonSerializer
* @see <a href="https:
*/
public static Mono<BinaryData> fromObjectAsync(Object data, ObjectSerializer serializer) {
return Mono.fromCallable(() -> fromObject(data, serializer));
}
/**
* Returns a byte array representation of this {@link BinaryData}.
*
* @return A byte array representing this {@link BinaryData}.
*/
public byte[] toBytes() {
return Arrays.copyOf(this.data, this.data.length);
}
/**
* Returns a {@link String} representation of this {@link BinaryData} by converting its data using the UTF-8
* character set.
*
* @return A {@link String} representing this {@link BinaryData}.
*/
public String toString() {
if (this.dataAsStringCache == null) {
this.dataAsStringCache = new String(this.data, StandardCharsets.UTF_8);
}
return this.dataAsStringCache;
}
/**
* Returns an {@link Object} representation of this {@link BinaryData} by deserializing its data using the default
* {@link JsonSerializer}.
* <p>
* The type, represented by {@link Class}, should be a non-generic class, for generic classes use {@link
*
* <p>
* <b>Note:</b> A {@link JsonSerializer} implementation must be available on the classpath.
*
* <p><strong>Get a non-generic Object from the BinaryData</strong></p>
*
* {@codesnippet com.azure.core.util.BinaryData.toObject
*
* @param clazz The {@link Class} representing the Object's type.
* @param <T> Type of the deserialized Object.
* @return An {@link Object} representing the JSON deserialized {@link BinaryData}.
* @throws NullPointerException If {@code clazz} is null.
* @throws IllegalStateException If a {@link JsonSerializer} implementation cannot be found on the classpath.
* @see JsonSerializer
*/
public <T> T toObject(Class<T> clazz) {
return toObject(TypeReference.createInstance(clazz), getDefaultSerializer());
}
/**
* Returns an {@link Object} representation of this {@link BinaryData} by deserializing its data using the default
* {@link JsonSerializer}.
* <p>
* The type, represented by {@link TypeReference}, can either be a generic or non-generic type. If the type is
* generic create a sub-type of {@link TypeReference}, if the type is non-generic use {@link
* TypeReference
* <p>
* <b>Note:</b> A {@link JsonSerializer} implementation must be available on the classpath.
*
* <p><strong>Get a non-generic Object from the BinaryData</strong></p>
*
* {@codesnippet com.azure.core.util.BinaryData.toObject
*
* <p><strong>Get a generic Object from the BinaryData</strong></p>
*
* {@codesnippet com.azure.core.util.BinaryData.toObject
*
* @param typeReference The {@link TypeReference} representing the Object's type.
* @param <T> Type of the deserialized Object.
* @return An {@link Object} representing the JSON deserialized {@link BinaryData}.
* @throws NullPointerException If {@code typeReference} is null.
* @throws IllegalStateException If a {@link JsonSerializer} implementation cannot be found on the classpath.
* @see JsonSerializer
*/
public <T> T toObject(TypeReference<T> typeReference) {
return toObject(typeReference, getDefaultSerializer());
}
/**
* Returns an {@link Object} representation of this {@link BinaryData} by deserializing its data using the passed
* {@link ObjectSerializer}.
* <p>
* The type, represented by {@link Class}, should be a non-generic class, for generic classes use {@link
*
* <p>
* The passed {@link ObjectSerializer} can either be one of the implementations offered by the Azure SDKs or your
* own implementation.
*
* <p><strong>Azure SDK implementations</strong></p>
* <ul>
* <li><a href="https:
* <li><a href="https:
* </ul>
*
* <p><strong>Get a non-generic Object from the BinaryData</strong></p>
*
* {@codesnippet com.azure.core.util.BinaryData.toObject
*
* @param clazz The {@link Class} representing the Object's type.
* @param serializer The {@link ObjectSerializer} used to deserialize object.
* @param <T> Type of the deserialized Object.
* @return An {@link Object} representing the deserialized {@link BinaryData}.
* @throws NullPointerException If {@code clazz} or {@code serializer} is null.
* @see ObjectSerializer
* @see JsonSerializer
* @see <a href="https:
*/
public <T> T toObject(Class<T> clazz, ObjectSerializer serializer) {
return toObject(TypeReference.createInstance(clazz), serializer);
}
/**
* Returns an {@link Object} representation of this {@link BinaryData} by deserializing its data using the passed
* {@link ObjectSerializer}.
* <p>
* The type, represented by {@link TypeReference}, can either be a generic or non-generic type. If the type is
* generic create a sub-type of {@link TypeReference}, if the type is non-generic use {@link
* TypeReference
* <p>
* The passed {@link ObjectSerializer} can either be one of the implementations offered by the Azure SDKs or your
* own implementation.
*
* <p><strong>Azure SDK implementations</strong></p>
* <ul>
* <li><a href="https:
* <li><a href="https:
* </ul>
*
* <p><strong>Get a non-generic Object from the BinaryData</strong></p>
*
* {@codesnippet com.azure.core.util.BinaryData.toObject
*
* <p><strong>Get a generic Object from the BinaryData</strong></p>
*
* {@codesnippet com.azure.core.util.BinaryData.toObject
*
* @param typeReference The {@link TypeReference} representing the Object's type.
* @param serializer The {@link ObjectSerializer} used to deserialize object.
* @param <T> Type of the deserialized Object.
* @return An {@link Object} representing the deserialized {@link BinaryData}.
* @throws NullPointerException If {@code typeReference} or {@code serializer} is null.
* @see ObjectSerializer
* @see JsonSerializer
* @see <a href="https:
*/
public <T> T toObject(TypeReference<T> typeReference, ObjectSerializer serializer) {
Objects.requireNonNull(typeReference, "'typeReference' cannot be null.");
Objects.requireNonNull(serializer, "'serializer' cannot be null.");
return serializer.deserializeFromBytes(this.data, typeReference);
}
/**
* Returns an {@link Object} representation of this {@link BinaryData} by deserializing its data using the default
* {@link JsonSerializer}.
* <p>
* The type, represented by {@link Class}, should be a non-generic class, for generic classes use {@link
*
* <p>
* <b>Note:</b> A {@link JsonSerializer} implementation must be available on the classpath.
*
* <p><strong>Get a non-generic Object from the BinaryData</strong></p>
*
* {@codesnippet com.azure.core.util.BinaryData.toObjectAsync
*
* @param clazz The {@link Class} representing the Object's type.
* @param <T> Type of the deserialized Object.
* @return A {@link Mono} of {@link Object} representing the JSON deserialized {@link BinaryData}.
* @throws NullPointerException If {@code clazz} is null.
* @throws IllegalStateException If a {@link JsonSerializer} implementation cannot be found on the classpath.
* @see JsonSerializer
*/
public <T> Mono<T> toObjectAsync(Class<T> clazz) {
return toObjectAsync(TypeReference.createInstance(clazz), getDefaultSerializer());
}
/**
* Returns an {@link Object} representation of this {@link BinaryData} by deserializing its data using the default
* {@link JsonSerializer}.
* <p>
* The type, represented by {@link TypeReference}, can either be a generic or non-generic type. If the type is
* generic create a sub-type of {@link TypeReference}, if the type is non-generic use {@link
* TypeReference
* <p>
* <b>Note:</b> A {@link JsonSerializer} implementation must be available on the classpath.
*
* <p><strong>Get a non-generic Object from the BinaryData</strong></p>
*
* {@codesnippet com.azure.core.util.BinaryData.toObjectAsync
*
* <p><strong>Get a generic Object from the BinaryData</strong></p>
*
* {@codesnippet com.azure.core.util.BinaryData.toObjectAsync
*
* @param typeReference The {@link TypeReference} representing the Object's type.
* @param <T> Type of the deserialized Object.
* @return A {@link Mono} of {@link Object} representing the JSON deserialized {@link BinaryData}.
* @throws NullPointerException If {@code typeReference} is null.
* @throws IllegalStateException If a {@link JsonSerializer} implementation cannot be found on the classpath.
* @see JsonSerializer
*/
public <T> Mono<T> toObjectAsync(TypeReference<T> typeReference) {
return toObjectAsync(typeReference, getDefaultSerializer());
}
/**
* Returns an {@link Object} representation of this {@link BinaryData} by deserializing its data using the passed
* {@link ObjectSerializer}.
* <p>
* The type, represented by {@link Class}, should be a non-generic class, for generic classes use {@link
*
* <p>
* The passed {@link ObjectSerializer} can either be one of the implementations offered by the Azure SDKs or your
* own implementation.
*
* <p><strong>Azure SDK implementations</strong></p>
* <ul>
* <li><a href="https:
* <li><a href="https:
* </ul>
*
* <p><strong>Get a non-generic Object from the BinaryData</strong></p>
*
* {@codesnippet com.azure.core.util.BinaryData.toObjectAsync
*
* @param clazz The {@link Class} representing the Object's type.
* @param serializer The {@link ObjectSerializer} used to deserialize object.
* @param <T> Type of the deserialized Object.
* @return A {@link Mono} of {@link Object} representing the deserialized {@link BinaryData}.
* @throws NullPointerException If {@code clazz} or {@code serializer} is null.
* @see ObjectSerializer
* @see JsonSerializer
* @see <a href="https:
*/
public <T> Mono<T> toObjectAsync(Class<T> clazz, ObjectSerializer serializer) {
return toObjectAsync(TypeReference.createInstance(clazz), serializer);
}
/**
* Returns an {@link Object} representation of this {@link BinaryData} by deserializing its data using the passed
* {@link ObjectSerializer}.
* <p>
* The type, represented by {@link TypeReference}, can either be a generic or non-generic type. If the type is
* generic create a sub-type of {@link TypeReference}, if the type is non-generic use {@link
* TypeReference
* <p>
* The passed {@link ObjectSerializer} can either be one of the implementations offered by the Azure SDKs or your
* own implementation.
*
* <p><strong>Azure SDK implementations</strong></p>
* <ul>
* <li><a href="https:
* <li><a href="https:
* </ul>
*
* <p><strong>Get a non-generic Object from the BinaryData</strong></p>
*
* {@codesnippet com.azure.core.util.BinaryData.toObjectAsync
*
* <p><strong>Get a generic Object from the BinaryData</strong></p>
*
* {@codesnippet com.azure.core.util.BinaryData.toObjectAsync
*
* @param typeReference The {@link TypeReference} representing the Object's type.
* @param serializer The {@link ObjectSerializer} used to deserialize object.
* @param <T> Type of the deserialized Object.
* @return A {@link Mono} of {@link Object} representing the deserialized {@link BinaryData}.
* @throws NullPointerException If {@code typeReference} or {@code serializer} is null.
* @see ObjectSerializer
* @see JsonSerializer
* @see <a href="https:
*/
public <T> Mono<T> toObjectAsync(TypeReference<T> typeReference, ObjectSerializer serializer) {
return Mono.fromCallable(() -> toObject(typeReference, serializer));
}
/**
* Returns an {@link InputStream} representation of this {@link BinaryData}.
*
* <p><strong>Get an InputStream from the BinaryData</strong></p>
*
* {@codesnippet com.azure.core.util.BinaryData.toStream}
*
* @return An {@link InputStream} representing the {@link BinaryData}.
*/
public InputStream toStream() {
return new ByteArrayInputStream(this.data);
}
/**
* Returns a read-only {@link ByteBuffer} representation of this {@link BinaryData}.
* <p>
* Attempting to mutate the returned {@link ByteBuffer} will throw a {@link ReadOnlyBufferException}.
*
* <p><strong>Get a read-only ByteBuffer from the BinaryData</strong></p>
*
* {@codesnippet com.azure.util.BinaryData.toByteBuffer}
*
* @return A read-only {@link ByteBuffer} representing the {@link BinaryData}.
*/
/* This will ensure lazy instantiation to avoid hard dependency on Json Serializer. */
private static JsonSerializer getDefaultSerializer() {
if (defaultJsonSerializer == null) {
synchronized (LOCK) {
if (defaultJsonSerializer == null) {
defaultJsonSerializer = JsonSerializerProviders.createInstance();
}
}
}
return defaultJsonSerializer;
}
} |
The logic here is not correct, in your case, the grant type could only be null or client_credential, but users could also set it to obo. | public List<ClientRegistration> createClients() {
List<ClientRegistration> result = new ArrayList<>();
for (String id : properties.getAuthorizationClients().keySet()) {
AuthorizationClientProperties authorizationProperties = properties.getAuthorizationClients().get(id);
if (authorizationProperties.getAuthorizationGrantType() == null) {
authorizationProperties.setAuthorizationGrantType(AADAuthorizationGrantType.ON_BEHALF_OF
.getValue());
result.add(createOboClientBuilder(id, authorizationProperties));
} else if (authorizationProperties.getAuthorizationGrantType().equals(AADAuthorizationGrantType
.CLIENT_CREDENTIALS.getValue())) {
result.add(createWebClientBuilder(id, authorizationProperties));
}
}
return result;
} | } | public List<ClientRegistration> createClients() {
List<ClientRegistration> result = new ArrayList<>();
for (String id : properties.getAuthorizationClients().keySet()) {
AuthorizationClientProperties authorizationProperties = properties.getAuthorizationClients().get(id);
if (authorizationProperties.getAuthorizationGrantType() == null || AADAuthorizationGrantType.ON_BEHALF_OF
.equals(authorizationProperties.getAuthorizationGrantType())) {
result.add(createOboClientBuilder(id, authorizationProperties));
} else if (AADAuthorizationGrantType.CLIENT_CREDENTIALS
.equals(authorizationProperties.getAuthorizationGrantType())) {
result.add(createWebClientBuilder(id, authorizationProperties));
}
}
return result;
} | class })
public ClientRegistrationRepository clientRegistrationRepository() {
final List<ClientRegistration> oboClients = createClients();
if (oboClients.isEmpty()) {
LOGGER.warn("No client registrations are found for AAD Client.");
return registrationId -> null;
}
return new InMemoryClientRegistrationRepository(oboClients);
} | class })
public ClientRegistrationRepository clientRegistrationRepository() {
final List<ClientRegistration> clients = createClients();
if (clients.isEmpty()) {
LOGGER.warn("No client registrations are found for AAD Client.");
return registrationId -> null;
}
return new InMemoryClientRegistrationRepository(clients);
} |
It could be cached but each return would need to be a `duplicate` (another `ByteBuffer` view on top of the current one) and that would effectively be the same cost as this. | public ByteBuffer toByteBuffer() {
return ByteBuffer.wrap(this.data).asReadOnlyBuffer();
} | return ByteBuffer.wrap(this.data).asReadOnlyBuffer(); | public ByteBuffer toByteBuffer() {
return ByteBuffer.wrap(this.data).asReadOnlyBuffer();
} | class BinaryData {
private static final ClientLogger LOGGER = new ClientLogger(BinaryData.class);
private static final BinaryData EMPTY_DATA = new BinaryData(new byte[0]);
private static final int STREAM_READ_SIZE = 1024;
private static final Object LOCK = new Object();
private static volatile JsonSerializer defaultJsonSerializer;
private final byte[] data;
private String dataAsStringCache;
/**
* Create an instance of {@link BinaryData} from the given byte array.
*
* @param data The byte array that {@link BinaryData} will represent.
*/
BinaryData(byte[] data) {
this.data = data;
}
/**
* Creates an instance of {@link BinaryData} from the given {@link InputStream}.
* <p>
* If {@code inputStream} is null or empty an empty {@link BinaryData} is returned.
* <p>
* <b>NOTE:</b> The {@link InputStream} is not closed by this function.
*
* <p><strong>Create an instance from an InputStream</strong></p>
*
* {@codesnippet com.azure.core.util.BinaryData.fromStream
*
* @param inputStream The {@link InputStream} that {@link BinaryData} will represent.
* @return A {@link BinaryData} representing the {@link InputStream}.
* @throws UncheckedIOException If any error happens while reading the {@link InputStream}.
*/
public static BinaryData fromStream(InputStream inputStream) {
if (Objects.isNull(inputStream)) {
return EMPTY_DATA;
}
try {
ByteArrayOutputStream dataOutputBuffer = new ByteArrayOutputStream();
int nRead;
byte[] data = new byte[STREAM_READ_SIZE];
while ((nRead = inputStream.read(data, 0, data.length)) != -1) {
dataOutputBuffer.write(data, 0, nRead);
}
return new BinaryData(dataOutputBuffer.toByteArray());
} catch (IOException ex) {
throw LOGGER.logExceptionAsError(new UncheckedIOException(ex));
}
}
/**
* Creates an instance of {@link BinaryData} from the given {@link InputStream}.
* <p>
* If {@code inputStream} is null or empty an empty {@link BinaryData} is returned.
* <p>
* <b>NOTE:</b> The {@link InputStream} is not closed by this function.
*
* <p><strong>Create an instance from an InputStream</strong></p>
*
* {@codesnippet com.azure.core.util.BinaryData.fromStreamAsync
*
* @param inputStream The {@link InputStream} that {@link BinaryData} will represent.
* @return A {@link Mono} of {@link BinaryData} representing the {@link InputStream}.
* @throws UncheckedIOException If any error happens while reading the {@link InputStream}.
*/
public static Mono<BinaryData> fromStreamAsync(InputStream inputStream) {
return Mono.fromCallable(() -> fromStream(inputStream));
}
/**
* Creates an instance of {@link BinaryData} from the given {@link Flux} of {@link ByteBuffer}.
* <p>
* If the {@code data} is null an empty {@link BinaryData} will be returned.
* <p>
* <b>Note:</b> This will collect all bytes from the {@link ByteBuffer ByteBuffers} resulting in {@link
* ByteBuffer
*
* <p><strong>Create an instance from a Flux of ByteBuffer</strong></p>
*
* {@codesnippet com.azure.core.util.BinaryData.fromFlux
*
* @param data The {@link Flux} of {@link ByteBuffer} that {@link BinaryData} will represent.
* @return A {@link Mono} of {@link BinaryData} representing the {@link Flux} of {@link ByteBuffer}.
*/
public static Mono<BinaryData> fromFlux(Flux<ByteBuffer> data) {
if (Objects.isNull(data)) {
return Mono.just(EMPTY_DATA);
}
return FluxUtil.collectBytesInByteBufferStream(data)
.flatMap(bytes -> Mono.just(new BinaryData(bytes)));
}
/**
* Creates an instance of {@link BinaryData} from the given {@link String}.
* <p>
* The {@link String} is converted into bytes using {@link String
* StandardCharsets
* <p>
* If the {@code data} is null or a zero length string an empty {@link BinaryData} will be returned.
*
* <p><strong>Create an instance from a String</strong></p>
*
* {@codesnippet com.azure.core.util.BinaryData.fromString
*
* @param data The {@link String} that {@link BinaryData} will represent.
* @return A {@link BinaryData} representing the {@link String}.
*/
public static BinaryData fromString(String data) {
if (CoreUtils.isNullOrEmpty(data)) {
return EMPTY_DATA;
}
return new BinaryData(data.getBytes(StandardCharsets.UTF_8));
}
/**
* Creates an instance of {@link BinaryData} from the given byte array.
* <p>
* If the byte array is null or zero length an empty {@link BinaryData} will be returned.
*
* <p><strong>Create an instance from a byte array</strong></p>
*
* {@codesnippet com.azure.core.util.BinaryData.fromBytes
*
* @param data The byte array that {@link BinaryData} will represent.
* @return A {@link BinaryData} representing the byte array.
*/
public static BinaryData fromBytes(byte[] data) {
if (Objects.isNull(data) || data.length == 0) {
return EMPTY_DATA;
}
return new BinaryData(Arrays.copyOf(data, data.length));
}
/**
* Creates an instance of {@link BinaryData} by serializing the {@link Object} using the default {@link
* JsonSerializer}.
* <p>
* If {@code data} is null an empty {@link BinaryData} will be returned.
* <p>
* <b>Note:</b> A {@link JsonSerializer} implementation must be available on the classpath.
*
* <p><strong>Creating an instance from an Object</strong></p>
*
* {@codesnippet com.azure.core.util.BinaryData.fromObject
*
* @param data The object that will be JSON serialized that {@link BinaryData} will represent.
* @return A {@link BinaryData} representing the JSON serialized object.
* @throws IllegalStateException If a {@link JsonSerializer} implementation cannot be found on the classpath.
* @see JsonSerializer
*/
public static BinaryData fromObject(Object data) {
return fromObject(data, getDefaultSerializer());
}
/**
* Creates an instance of {@link BinaryData} by serializing the {@link Object} using the default {@link
* JsonSerializer}.
* <p>
* If {@code data} is null an empty {@link BinaryData} will be returned.
* <p>
* <b>Note:</b> A {@link JsonSerializer} implementation must be available on the classpath.
*
* <p><strong>Creating an instance from an Object</strong></p>
*
* {@codesnippet com.azure.core.util.BinaryData.fromObjectAsync
*
* @param data The object that will be JSON serialized that {@link BinaryData} will represent.
* @return A {@link Mono} of {@link BinaryData} representing the JSON serialized object.
* @throws IllegalStateException If a {@link JsonSerializer} implementation cannot be found on the classpath.
* @see JsonSerializer
*/
public static Mono<BinaryData> fromObjectAsync(Object data) {
return fromObjectAsync(data, getDefaultSerializer());
}
/**
* Creates an instance of {@link BinaryData} by serializing the {@link Object} using the passed {@link
* ObjectSerializer}.
* <p>
* If {@code data} is null an empty {@link BinaryData} will be returned.
* <p>
* The passed {@link ObjectSerializer} can either be one of the implementations offered by the Azure SDKs or your
* own implementation.
*
* <p><strong>Azure SDK implementations</strong></p>
* <ul>
* <li><a href="https:
* <li><a href="https:
* </ul>
*
* <p><strong>Create an instance from an Object</strong></p>
*
* {@codesnippet com.azure.core.util.BinaryData.fromObject
*
* @param data The object that will be serialized that {@link BinaryData} will represent.
* @param serializer The {@link ObjectSerializer} used to serialize object.
* @return A {@link BinaryData} representing the serialized object.
* @throws NullPointerException If {@code serializer} is null and {@code data} is not null.
* @see ObjectSerializer
* @see JsonSerializer
* @see <a href="https:
*/
public static BinaryData fromObject(Object data, ObjectSerializer serializer) {
if (Objects.isNull(data)) {
return EMPTY_DATA;
}
Objects.requireNonNull(serializer, "'serializer' cannot be null.");
return new BinaryData(serializer.serializeToBytes(data));
}
/**
* Creates an instance of {@link BinaryData} by serializing the {@link Object} using the passed {@link
* ObjectSerializer}.
* <p>
* If {@code data} is null an empty {@link BinaryData} will be returned.
* <p>
* The passed {@link ObjectSerializer} can either be one of the implementations offered by the Azure SDKs or your
* own implementation.
*
* <p><strong>Azure SDK implementations</strong></p>
* <ul>
* <li><a href="https:
* <li><a href="https:
* </ul>
*
* <p><strong>Create an instance from an Object</strong></p>
*
* {@codesnippet com.azure.core.util.BinaryData.fromObjectAsync
*
* @param data The object that will be serialized that {@link BinaryData} will represent.
* @param serializer The {@link ObjectSerializer} used to serialize object.
* @return A {@link Mono} of {@link BinaryData} representing the serialized object.
* @throws NullPointerException If {@code serializer} is null and {@code data} is not null.
* @see ObjectSerializer
* @see JsonSerializer
* @see <a href="https:
*/
public static Mono<BinaryData> fromObjectAsync(Object data, ObjectSerializer serializer) {
return Mono.fromCallable(() -> fromObject(data, serializer));
}
/**
* Returns a byte array representation of this {@link BinaryData}.
*
* @return A byte array representing this {@link BinaryData}.
*/
public byte[] toBytes() {
return Arrays.copyOf(this.data, this.data.length);
}
/**
* Returns a {@link String} representation of this {@link BinaryData} by converting its data using the UTF-8
* character set.
*
* @return A {@link String} representing this {@link BinaryData}.
*/
public String toString() {
if (this.dataAsStringCache == null) {
this.dataAsStringCache = new String(this.data, StandardCharsets.UTF_8);
}
return this.dataAsStringCache;
}
/**
* Returns an {@link Object} representation of this {@link BinaryData} by deserializing its data using the default
* {@link JsonSerializer}.
* <p>
* The type, represented by {@link Class}, should be a non-generic class, for generic classes use {@link
*
* <p>
* <b>Note:</b> A {@link JsonSerializer} implementation must be available on the classpath.
*
* <p><strong>Get a non-generic Object from the BinaryData</strong></p>
*
* {@codesnippet com.azure.core.util.BinaryData.toObject
*
* @param clazz The {@link Class} representing the Object's type.
* @param <T> Type of the deserialized Object.
* @return An {@link Object} representing the JSON deserialized {@link BinaryData}.
* @throws NullPointerException If {@code clazz} is null.
* @throws IllegalStateException If a {@link JsonSerializer} implementation cannot be found on the classpath.
* @see JsonSerializer
*/
public <T> T toObject(Class<T> clazz) {
return toObject(TypeReference.createInstance(clazz), getDefaultSerializer());
}
/**
* Returns an {@link Object} representation of this {@link BinaryData} by deserializing its data using the default
* {@link JsonSerializer}.
* <p>
* The type, represented by {@link TypeReference}, can either be a generic or non-generic type. If the type is
* generic create a sub-type of {@link TypeReference}, if the type is non-generic use {@link
* TypeReference
* <p>
* <b>Note:</b> A {@link JsonSerializer} implementation must be available on the classpath.
*
* <p><strong>Get a non-generic Object from the BinaryData</strong></p>
*
* {@codesnippet com.azure.core.util.BinaryData.toObject
*
* <p><strong>Get a generic Object from the BinaryData</strong></p>
*
* {@codesnippet com.azure.core.util.BinaryData.toObject
*
* @param typeReference The {@link TypeReference} representing the Object's type.
* @param <T> Type of the deserialized Object.
* @return An {@link Object} representing the JSON deserialized {@link BinaryData}.
* @throws NullPointerException If {@code typeReference} is null.
* @throws IllegalStateException If a {@link JsonSerializer} implementation cannot be found on the classpath.
* @see JsonSerializer
*/
public <T> T toObject(TypeReference<T> typeReference) {
return toObject(typeReference, getDefaultSerializer());
}
/**
* Returns an {@link Object} representation of this {@link BinaryData} by deserializing its data using the passed
* {@link ObjectSerializer}.
* <p>
* The type, represented by {@link Class}, should be a non-generic class, for generic classes use {@link
*
* <p>
* The passed {@link ObjectSerializer} can either be one of the implementations offered by the Azure SDKs or your
* own implementation.
*
* <p><strong>Azure SDK implementations</strong></p>
* <ul>
* <li><a href="https:
* <li><a href="https:
* </ul>
*
* <p><strong>Get a non-generic Object from the BinaryData</strong></p>
*
* {@codesnippet com.azure.core.util.BinaryData.toObject
*
* @param clazz The {@link Class} representing the Object's type.
* @param serializer The {@link ObjectSerializer} used to deserialize object.
* @param <T> Type of the deserialized Object.
* @return An {@link Object} representing the deserialized {@link BinaryData}.
* @throws NullPointerException If {@code clazz} or {@code serializer} is null.
* @see ObjectSerializer
* @see JsonSerializer
* @see <a href="https:
*/
public <T> T toObject(Class<T> clazz, ObjectSerializer serializer) {
return toObject(TypeReference.createInstance(clazz), serializer);
}
/**
* Returns an {@link Object} representation of this {@link BinaryData} by deserializing its data using the passed
* {@link ObjectSerializer}.
* <p>
* The type, represented by {@link TypeReference}, can either be a generic or non-generic type. If the type is
* generic create a sub-type of {@link TypeReference}, if the type is non-generic use {@link
* TypeReference
* <p>
* The passed {@link ObjectSerializer} can either be one of the implementations offered by the Azure SDKs or your
* own implementation.
*
* <p><strong>Azure SDK implementations</strong></p>
* <ul>
* <li><a href="https:
* <li><a href="https:
* </ul>
*
* <p><strong>Get a non-generic Object from the BinaryData</strong></p>
*
* {@codesnippet com.azure.core.util.BinaryData.toObject
*
* <p><strong>Get a generic Object from the BinaryData</strong></p>
*
* {@codesnippet com.azure.core.util.BinaryData.toObject
*
* @param typeReference The {@link TypeReference} representing the Object's type.
* @param serializer The {@link ObjectSerializer} used to deserialize object.
* @param <T> Type of the deserialized Object.
* @return An {@link Object} representing the deserialized {@link BinaryData}.
* @throws NullPointerException If {@code typeReference} or {@code serializer} is null.
* @see ObjectSerializer
* @see JsonSerializer
* @see <a href="https:
*/
public <T> T toObject(TypeReference<T> typeReference, ObjectSerializer serializer) {
Objects.requireNonNull(typeReference, "'typeReference' cannot be null.");
Objects.requireNonNull(serializer, "'serializer' cannot be null.");
return serializer.deserializeFromBytes(this.data, typeReference);
}
/**
* Returns an {@link Object} representation of this {@link BinaryData} by deserializing its data using the default
* {@link JsonSerializer}.
* <p>
* The type, represented by {@link Class}, should be a non-generic class, for generic classes use {@link
*
* <p>
* <b>Note:</b> A {@link JsonSerializer} implementation must be available on the classpath.
*
* <p><strong>Get a non-generic Object from the BinaryData</strong></p>
*
* {@codesnippet com.azure.core.util.BinaryData.toObjectAsync
*
* @param clazz The {@link Class} representing the Object's type.
* @param <T> Type of the deserialized Object.
* @return A {@link Mono} of {@link Object} representing the JSON deserialized {@link BinaryData}.
* @throws NullPointerException If {@code clazz} is null.
* @throws IllegalStateException If a {@link JsonSerializer} implementation cannot be found on the classpath.
* @see JsonSerializer
*/
public <T> Mono<T> toObjectAsync(Class<T> clazz) {
return toObjectAsync(TypeReference.createInstance(clazz), getDefaultSerializer());
}
/**
* Returns an {@link Object} representation of this {@link BinaryData} by deserializing its data using the default
* {@link JsonSerializer}.
* <p>
* The type, represented by {@link TypeReference}, can either be a generic or non-generic type. If the type is
* generic create a sub-type of {@link TypeReference}, if the type is non-generic use {@link
* TypeReference
* <p>
* <b>Note:</b> A {@link JsonSerializer} implementation must be available on the classpath.
*
* <p><strong>Get a non-generic Object from the BinaryData</strong></p>
*
* {@codesnippet com.azure.core.util.BinaryData.toObjectAsync
*
* <p><strong>Get a generic Object from the BinaryData</strong></p>
*
* {@codesnippet com.azure.core.util.BinaryData.toObjectAsync
*
* @param typeReference The {@link TypeReference} representing the Object's type.
* @param <T> Type of the deserialized Object.
* @return A {@link Mono} of {@link Object} representing the JSON deserialized {@link BinaryData}.
* @throws NullPointerException If {@code typeReference} is null.
* @throws IllegalStateException If a {@link JsonSerializer} implementation cannot be found on the classpath.
* @see JsonSerializer
*/
public <T> Mono<T> toObjectAsync(TypeReference<T> typeReference) {
return toObjectAsync(typeReference, getDefaultSerializer());
}
/**
* Returns an {@link Object} representation of this {@link BinaryData} by deserializing its data using the passed
* {@link ObjectSerializer}.
* <p>
* The type, represented by {@link Class}, should be a non-generic class, for generic classes use {@link
*
* <p>
* The passed {@link ObjectSerializer} can either be one of the implementations offered by the Azure SDKs or your
* own implementation.
*
* <p><strong>Azure SDK implementations</strong></p>
* <ul>
* <li><a href="https:
* <li><a href="https:
* </ul>
*
* <p><strong>Get a non-generic Object from the BinaryData</strong></p>
*
* {@codesnippet com.azure.core.util.BinaryData.toObjectAsync
*
* @param clazz The {@link Class} representing the Object's type.
* @param serializer The {@link ObjectSerializer} used to deserialize object.
* @param <T> Type of the deserialized Object.
* @return A {@link Mono} of {@link Object} representing the deserialized {@link BinaryData}.
* @throws NullPointerException If {@code clazz} or {@code serializer} is null.
* @see ObjectSerializer
* @see JsonSerializer
* @see <a href="https:
*/
public <T> Mono<T> toObjectAsync(Class<T> clazz, ObjectSerializer serializer) {
return toObjectAsync(TypeReference.createInstance(clazz), serializer);
}
/**
* Returns an {@link Object} representation of this {@link BinaryData} by deserializing its data using the passed
* {@link ObjectSerializer}.
* <p>
* The type, represented by {@link TypeReference}, can either be a generic or non-generic type. If the type is
* generic create a sub-type of {@link TypeReference}, if the type is non-generic use {@link
* TypeReference
* <p>
* The passed {@link ObjectSerializer} can either be one of the implementations offered by the Azure SDKs or your
* own implementation.
*
* <p><strong>Azure SDK implementations</strong></p>
* <ul>
* <li><a href="https:
* <li><a href="https:
* </ul>
*
* <p><strong>Get a non-generic Object from the BinaryData</strong></p>
*
* {@codesnippet com.azure.core.util.BinaryData.toObjectAsync
*
* <p><strong>Get a generic Object from the BinaryData</strong></p>
*
* {@codesnippet com.azure.core.util.BinaryData.toObjectAsync
*
* @param typeReference The {@link TypeReference} representing the Object's type.
* @param serializer The {@link ObjectSerializer} used to deserialize object.
* @param <T> Type of the deserialized Object.
* @return A {@link Mono} of {@link Object} representing the deserialized {@link BinaryData}.
* @throws NullPointerException If {@code typeReference} or {@code serializer} is null.
* @see ObjectSerializer
* @see JsonSerializer
* @see <a href="https:
*/
public <T> Mono<T> toObjectAsync(TypeReference<T> typeReference, ObjectSerializer serializer) {
return Mono.fromCallable(() -> toObject(typeReference, serializer));
}
/**
* Returns an {@link InputStream} representation of this {@link BinaryData}.
*
* <p><strong>Get an InputStream from the BinaryData</strong></p>
*
* {@codesnippet com.azure.core.util.BinaryData.toStream}
*
* @return An {@link InputStream} representing the {@link BinaryData}.
*/
public InputStream toStream() {
return new ByteArrayInputStream(this.data);
}
/**
* Returns a read-only {@link ByteBuffer} representation of this {@link BinaryData}.
* <p>
* Attempting to mutate the returned {@link ByteBuffer} will throw a {@link ReadOnlyBufferException}.
*
* <p><strong>Get a read-only ByteBuffer from the BinaryData</strong></p>
*
* {@codesnippet com.azure.util.BinaryData.toByteBuffer}
*
* @return A read-only {@link ByteBuffer} representing the {@link BinaryData}.
*/
/* This will ensure lazy instantiation to avoid hard dependency on Json Serializer. */
private static JsonSerializer getDefaultSerializer() {
if (defaultJsonSerializer == null) {
synchronized (LOCK) {
if (defaultJsonSerializer == null) {
defaultJsonSerializer = JsonSerializerProviders.createInstance();
}
}
}
return defaultJsonSerializer;
}
} | class BinaryData {
private static final ClientLogger LOGGER = new ClientLogger(BinaryData.class);
private static final BinaryData EMPTY_DATA = new BinaryData(new byte[0]);
private static final int STREAM_READ_SIZE = 1024;
private static final Object LOCK = new Object();
private static volatile JsonSerializer defaultJsonSerializer;
private final byte[] data;
private String dataAsStringCache;
/**
* Create an instance of {@link BinaryData} from the given byte array.
*
* @param data The byte array that {@link BinaryData} will represent.
*/
BinaryData(byte[] data) {
this.data = data;
}
/**
* Creates an instance of {@link BinaryData} from the given {@link InputStream}.
* <p>
* If {@code inputStream} is null or empty an empty {@link BinaryData} is returned.
* <p>
* <b>NOTE:</b> The {@link InputStream} is not closed by this function.
*
* <p><strong>Create an instance from an InputStream</strong></p>
*
* {@codesnippet com.azure.core.util.BinaryData.fromStream
*
* @param inputStream The {@link InputStream} that {@link BinaryData} will represent.
* @return A {@link BinaryData} representing the {@link InputStream}.
* @throws UncheckedIOException If any error happens while reading the {@link InputStream}.
*/
public static BinaryData fromStream(InputStream inputStream) {
if (Objects.isNull(inputStream)) {
return EMPTY_DATA;
}
try {
ByteArrayOutputStream dataOutputBuffer = new ByteArrayOutputStream();
int nRead;
byte[] data = new byte[STREAM_READ_SIZE];
while ((nRead = inputStream.read(data, 0, data.length)) != -1) {
dataOutputBuffer.write(data, 0, nRead);
}
return new BinaryData(dataOutputBuffer.toByteArray());
} catch (IOException ex) {
throw LOGGER.logExceptionAsError(new UncheckedIOException(ex));
}
}
/**
* Creates an instance of {@link BinaryData} from the given {@link InputStream}.
* <p>
* If {@code inputStream} is null or empty an empty {@link BinaryData} is returned.
* <p>
* <b>NOTE:</b> The {@link InputStream} is not closed by this function.
*
* <p><strong>Create an instance from an InputStream</strong></p>
*
* {@codesnippet com.azure.core.util.BinaryData.fromStreamAsync
*
* @param inputStream The {@link InputStream} that {@link BinaryData} will represent.
* @return A {@link Mono} of {@link BinaryData} representing the {@link InputStream}.
* @throws UncheckedIOException If any error happens while reading the {@link InputStream}.
*/
public static Mono<BinaryData> fromStreamAsync(InputStream inputStream) {
return Mono.fromCallable(() -> fromStream(inputStream));
}
/**
* Creates an instance of {@link BinaryData} from the given {@link Flux} of {@link ByteBuffer}.
* <p>
* If the {@code data} is null an empty {@link BinaryData} will be returned.
* <p>
* <b>Note:</b> This will collect all bytes from the {@link ByteBuffer ByteBuffers} resulting in {@link
* ByteBuffer
*
* <p><strong>Create an instance from a Flux of ByteBuffer</strong></p>
*
* {@codesnippet com.azure.core.util.BinaryData.fromFlux
*
* @param data The {@link Flux} of {@link ByteBuffer} that {@link BinaryData} will represent.
* @return A {@link Mono} of {@link BinaryData} representing the {@link Flux} of {@link ByteBuffer}.
*/
public static Mono<BinaryData> fromFlux(Flux<ByteBuffer> data) {
if (Objects.isNull(data)) {
return Mono.just(EMPTY_DATA);
}
return FluxUtil.collectBytesInByteBufferStream(data)
.flatMap(bytes -> Mono.just(new BinaryData(bytes)));
}
/**
* Creates an instance of {@link BinaryData} from the given {@link String}.
* <p>
* The {@link String} is converted into bytes using {@link String
* StandardCharsets
* <p>
* If the {@code data} is null or a zero length string an empty {@link BinaryData} will be returned.
*
* <p><strong>Create an instance from a String</strong></p>
*
* {@codesnippet com.azure.core.util.BinaryData.fromString
*
* @param data The {@link String} that {@link BinaryData} will represent.
* @return A {@link BinaryData} representing the {@link String}.
*/
public static BinaryData fromString(String data) {
if (CoreUtils.isNullOrEmpty(data)) {
return EMPTY_DATA;
}
return new BinaryData(data.getBytes(StandardCharsets.UTF_8));
}
/**
* Creates an instance of {@link BinaryData} from the given byte array.
* <p>
* If the byte array is null or zero length an empty {@link BinaryData} will be returned.
*
* <p><strong>Create an instance from a byte array</strong></p>
*
* {@codesnippet com.azure.core.util.BinaryData.fromBytes
*
* @param data The byte array that {@link BinaryData} will represent.
* @return A {@link BinaryData} representing the byte array.
*/
public static BinaryData fromBytes(byte[] data) {
if (Objects.isNull(data) || data.length == 0) {
return EMPTY_DATA;
}
return new BinaryData(Arrays.copyOf(data, data.length));
}
/**
* Creates an instance of {@link BinaryData} by serializing the {@link Object} using the default {@link
* JsonSerializer}.
* <p>
* If {@code data} is null an empty {@link BinaryData} will be returned.
* <p>
* <b>Note:</b> A {@link JsonSerializer} implementation must be available on the classpath.
*
* <p><strong>Creating an instance from an Object</strong></p>
*
* {@codesnippet com.azure.core.util.BinaryData.fromObject
*
* @param data The object that will be JSON serialized that {@link BinaryData} will represent.
* @return A {@link BinaryData} representing the JSON serialized object.
* @throws IllegalStateException If a {@link JsonSerializer} implementation cannot be found on the classpath.
* @see JsonSerializer
*/
public static BinaryData fromObject(Object data) {
return fromObject(data, getDefaultSerializer());
}
/**
* Creates an instance of {@link BinaryData} by serializing the {@link Object} using the default {@link
* JsonSerializer}.
* <p>
* If {@code data} is null an empty {@link BinaryData} will be returned.
* <p>
* <b>Note:</b> A {@link JsonSerializer} implementation must be available on the classpath.
*
* <p><strong>Creating an instance from an Object</strong></p>
*
* {@codesnippet com.azure.core.util.BinaryData.fromObjectAsync
*
* @param data The object that will be JSON serialized that {@link BinaryData} will represent.
* @return A {@link Mono} of {@link BinaryData} representing the JSON serialized object.
* @throws IllegalStateException If a {@link JsonSerializer} implementation cannot be found on the classpath.
* @see JsonSerializer
*/
public static Mono<BinaryData> fromObjectAsync(Object data) {
return fromObjectAsync(data, getDefaultSerializer());
}
/**
* Creates an instance of {@link BinaryData} by serializing the {@link Object} using the passed {@link
* ObjectSerializer}.
* <p>
* If {@code data} is null an empty {@link BinaryData} will be returned.
* <p>
* The passed {@link ObjectSerializer} can either be one of the implementations offered by the Azure SDKs or your
* own implementation.
*
* <p><strong>Azure SDK implementations</strong></p>
* <ul>
* <li><a href="https:
* <li><a href="https:
* </ul>
*
* <p><strong>Create an instance from an Object</strong></p>
*
* {@codesnippet com.azure.core.util.BinaryData.fromObject
*
* @param data The object that will be serialized that {@link BinaryData} will represent.
* @param serializer The {@link ObjectSerializer} used to serialize object.
* @return A {@link BinaryData} representing the serialized object.
* @throws NullPointerException If {@code serializer} is null and {@code data} is not null.
* @see ObjectSerializer
* @see JsonSerializer
* @see <a href="https:
*/
public static BinaryData fromObject(Object data, ObjectSerializer serializer) {
if (Objects.isNull(data)) {
return EMPTY_DATA;
}
Objects.requireNonNull(serializer, "'serializer' cannot be null.");
return new BinaryData(serializer.serializeToBytes(data));
}
/**
* Creates an instance of {@link BinaryData} by serializing the {@link Object} using the passed {@link
* ObjectSerializer}.
* <p>
* If {@code data} is null an empty {@link BinaryData} will be returned.
* <p>
* The passed {@link ObjectSerializer} can either be one of the implementations offered by the Azure SDKs or your
* own implementation.
*
* <p><strong>Azure SDK implementations</strong></p>
* <ul>
* <li><a href="https:
* <li><a href="https:
* </ul>
*
* <p><strong>Create an instance from an Object</strong></p>
*
* {@codesnippet com.azure.core.util.BinaryData.fromObjectAsync
*
* @param data The object that will be serialized that {@link BinaryData} will represent.
* @param serializer The {@link ObjectSerializer} used to serialize object.
* @return A {@link Mono} of {@link BinaryData} representing the serialized object.
* @throws NullPointerException If {@code serializer} is null and {@code data} is not null.
* @see ObjectSerializer
* @see JsonSerializer
* @see <a href="https:
*/
public static Mono<BinaryData> fromObjectAsync(Object data, ObjectSerializer serializer) {
return Mono.fromCallable(() -> fromObject(data, serializer));
}
/**
* Returns a byte array representation of this {@link BinaryData}.
*
* @return A byte array representing this {@link BinaryData}.
*/
public byte[] toBytes() {
return Arrays.copyOf(this.data, this.data.length);
}
/**
* Returns a {@link String} representation of this {@link BinaryData} by converting its data using the UTF-8
* character set.
*
* @return A {@link String} representing this {@link BinaryData}.
*/
public String toString() {
if (this.dataAsStringCache == null) {
this.dataAsStringCache = new String(this.data, StandardCharsets.UTF_8);
}
return this.dataAsStringCache;
}
/**
* Returns an {@link Object} representation of this {@link BinaryData} by deserializing its data using the default
* {@link JsonSerializer}.
* <p>
* The type, represented by {@link Class}, should be a non-generic class, for generic classes use {@link
*
* <p>
* <b>Note:</b> A {@link JsonSerializer} implementation must be available on the classpath.
*
* <p><strong>Get a non-generic Object from the BinaryData</strong></p>
*
* {@codesnippet com.azure.core.util.BinaryData.toObject
*
* @param clazz The {@link Class} representing the Object's type.
* @param <T> Type of the deserialized Object.
* @return An {@link Object} representing the JSON deserialized {@link BinaryData}.
* @throws NullPointerException If {@code clazz} is null.
* @throws IllegalStateException If a {@link JsonSerializer} implementation cannot be found on the classpath.
* @see JsonSerializer
*/
public <T> T toObject(Class<T> clazz) {
return toObject(TypeReference.createInstance(clazz), getDefaultSerializer());
}
/**
* Returns an {@link Object} representation of this {@link BinaryData} by deserializing its data using the default
* {@link JsonSerializer}.
* <p>
* The type, represented by {@link TypeReference}, can either be a generic or non-generic type. If the type is
* generic create a sub-type of {@link TypeReference}, if the type is non-generic use {@link
* TypeReference
* <p>
* <b>Note:</b> A {@link JsonSerializer} implementation must be available on the classpath.
*
* <p><strong>Get a non-generic Object from the BinaryData</strong></p>
*
* {@codesnippet com.azure.core.util.BinaryData.toObject
*
* <p><strong>Get a generic Object from the BinaryData</strong></p>
*
* {@codesnippet com.azure.core.util.BinaryData.toObject
*
* @param typeReference The {@link TypeReference} representing the Object's type.
* @param <T> Type of the deserialized Object.
* @return An {@link Object} representing the JSON deserialized {@link BinaryData}.
* @throws NullPointerException If {@code typeReference} is null.
* @throws IllegalStateException If a {@link JsonSerializer} implementation cannot be found on the classpath.
* @see JsonSerializer
*/
public <T> T toObject(TypeReference<T> typeReference) {
return toObject(typeReference, getDefaultSerializer());
}
/**
* Returns an {@link Object} representation of this {@link BinaryData} by deserializing its data using the passed
* {@link ObjectSerializer}.
* <p>
* The type, represented by {@link Class}, should be a non-generic class, for generic classes use {@link
*
* <p>
* The passed {@link ObjectSerializer} can either be one of the implementations offered by the Azure SDKs or your
* own implementation.
*
* <p><strong>Azure SDK implementations</strong></p>
* <ul>
* <li><a href="https:
* <li><a href="https:
* </ul>
*
* <p><strong>Get a non-generic Object from the BinaryData</strong></p>
*
* {@codesnippet com.azure.core.util.BinaryData.toObject
*
* @param clazz The {@link Class} representing the Object's type.
* @param serializer The {@link ObjectSerializer} used to deserialize object.
* @param <T> Type of the deserialized Object.
* @return An {@link Object} representing the deserialized {@link BinaryData}.
* @throws NullPointerException If {@code clazz} or {@code serializer} is null.
* @see ObjectSerializer
* @see JsonSerializer
* @see <a href="https:
*/
public <T> T toObject(Class<T> clazz, ObjectSerializer serializer) {
return toObject(TypeReference.createInstance(clazz), serializer);
}
/**
* Returns an {@link Object} representation of this {@link BinaryData} by deserializing its data using the passed
* {@link ObjectSerializer}.
* <p>
* The type, represented by {@link TypeReference}, can either be a generic or non-generic type. If the type is
* generic create a sub-type of {@link TypeReference}, if the type is non-generic use {@link
* TypeReference
* <p>
* The passed {@link ObjectSerializer} can either be one of the implementations offered by the Azure SDKs or your
* own implementation.
*
* <p><strong>Azure SDK implementations</strong></p>
* <ul>
* <li><a href="https:
* <li><a href="https:
* </ul>
*
* <p><strong>Get a non-generic Object from the BinaryData</strong></p>
*
* {@codesnippet com.azure.core.util.BinaryData.toObject
*
* <p><strong>Get a generic Object from the BinaryData</strong></p>
*
* {@codesnippet com.azure.core.util.BinaryData.toObject
*
* @param typeReference The {@link TypeReference} representing the Object's type.
* @param serializer The {@link ObjectSerializer} used to deserialize object.
* @param <T> Type of the deserialized Object.
* @return An {@link Object} representing the deserialized {@link BinaryData}.
* @throws NullPointerException If {@code typeReference} or {@code serializer} is null.
* @see ObjectSerializer
* @see JsonSerializer
* @see <a href="https:
*/
public <T> T toObject(TypeReference<T> typeReference, ObjectSerializer serializer) {
Objects.requireNonNull(typeReference, "'typeReference' cannot be null.");
Objects.requireNonNull(serializer, "'serializer' cannot be null.");
return serializer.deserializeFromBytes(this.data, typeReference);
}
/**
* Returns an {@link Object} representation of this {@link BinaryData} by deserializing its data using the default
* {@link JsonSerializer}.
* <p>
* The type, represented by {@link Class}, should be a non-generic class, for generic classes use {@link
*
* <p>
* <b>Note:</b> A {@link JsonSerializer} implementation must be available on the classpath.
*
* <p><strong>Get a non-generic Object from the BinaryData</strong></p>
*
* {@codesnippet com.azure.core.util.BinaryData.toObjectAsync
*
* @param clazz The {@link Class} representing the Object's type.
* @param <T> Type of the deserialized Object.
* @return A {@link Mono} of {@link Object} representing the JSON deserialized {@link BinaryData}.
* @throws NullPointerException If {@code clazz} is null.
* @throws IllegalStateException If a {@link JsonSerializer} implementation cannot be found on the classpath.
* @see JsonSerializer
*/
public <T> Mono<T> toObjectAsync(Class<T> clazz) {
return toObjectAsync(TypeReference.createInstance(clazz), getDefaultSerializer());
}
/**
* Returns an {@link Object} representation of this {@link BinaryData} by deserializing its data using the default
* {@link JsonSerializer}.
* <p>
* The type, represented by {@link TypeReference}, can either be a generic or non-generic type. If the type is
* generic create a sub-type of {@link TypeReference}, if the type is non-generic use {@link
* TypeReference
* <p>
* <b>Note:</b> A {@link JsonSerializer} implementation must be available on the classpath.
*
* <p><strong>Get a non-generic Object from the BinaryData</strong></p>
*
* {@codesnippet com.azure.core.util.BinaryData.toObjectAsync
*
* <p><strong>Get a generic Object from the BinaryData</strong></p>
*
* {@codesnippet com.azure.core.util.BinaryData.toObjectAsync
*
* @param typeReference The {@link TypeReference} representing the Object's type.
* @param <T> Type of the deserialized Object.
* @return A {@link Mono} of {@link Object} representing the JSON deserialized {@link BinaryData}.
* @throws NullPointerException If {@code typeReference} is null.
* @throws IllegalStateException If a {@link JsonSerializer} implementation cannot be found on the classpath.
* @see JsonSerializer
*/
public <T> Mono<T> toObjectAsync(TypeReference<T> typeReference) {
return toObjectAsync(typeReference, getDefaultSerializer());
}
/**
* Returns an {@link Object} representation of this {@link BinaryData} by deserializing its data using the passed
* {@link ObjectSerializer}.
* <p>
* The type, represented by {@link Class}, should be a non-generic class, for generic classes use {@link
*
* <p>
* The passed {@link ObjectSerializer} can either be one of the implementations offered by the Azure SDKs or your
* own implementation.
*
* <p><strong>Azure SDK implementations</strong></p>
* <ul>
* <li><a href="https:
* <li><a href="https:
* </ul>
*
* <p><strong>Get a non-generic Object from the BinaryData</strong></p>
*
* {@codesnippet com.azure.core.util.BinaryData.toObjectAsync
*
* @param clazz The {@link Class} representing the Object's type.
* @param serializer The {@link ObjectSerializer} used to deserialize object.
* @param <T> Type of the deserialized Object.
* @return A {@link Mono} of {@link Object} representing the deserialized {@link BinaryData}.
* @throws NullPointerException If {@code clazz} or {@code serializer} is null.
* @see ObjectSerializer
* @see JsonSerializer
* @see <a href="https:
*/
public <T> Mono<T> toObjectAsync(Class<T> clazz, ObjectSerializer serializer) {
return toObjectAsync(TypeReference.createInstance(clazz), serializer);
}
/**
* Returns an {@link Object} representation of this {@link BinaryData} by deserializing its data using the passed
* {@link ObjectSerializer}.
* <p>
* The type, represented by {@link TypeReference}, can either be a generic or non-generic type. If the type is
* generic create a sub-type of {@link TypeReference}, if the type is non-generic use {@link
* TypeReference
* <p>
* The passed {@link ObjectSerializer} can either be one of the implementations offered by the Azure SDKs or your
* own implementation.
*
* <p><strong>Azure SDK implementations</strong></p>
* <ul>
* <li><a href="https:
* <li><a href="https:
* </ul>
*
* <p><strong>Get a non-generic Object from the BinaryData</strong></p>
*
* {@codesnippet com.azure.core.util.BinaryData.toObjectAsync
*
* <p><strong>Get a generic Object from the BinaryData</strong></p>
*
* {@codesnippet com.azure.core.util.BinaryData.toObjectAsync
*
* @param typeReference The {@link TypeReference} representing the Object's type.
* @param serializer The {@link ObjectSerializer} used to deserialize object.
* @param <T> Type of the deserialized Object.
* @return A {@link Mono} of {@link Object} representing the deserialized {@link BinaryData}.
* @throws NullPointerException If {@code typeReference} or {@code serializer} is null.
* @see ObjectSerializer
* @see JsonSerializer
* @see <a href="https:
*/
public <T> Mono<T> toObjectAsync(TypeReference<T> typeReference, ObjectSerializer serializer) {
return Mono.fromCallable(() -> toObject(typeReference, serializer));
}
/**
* Returns an {@link InputStream} representation of this {@link BinaryData}.
*
* <p><strong>Get an InputStream from the BinaryData</strong></p>
*
* {@codesnippet com.azure.core.util.BinaryData.toStream}
*
* @return An {@link InputStream} representing the {@link BinaryData}.
*/
public InputStream toStream() {
return new ByteArrayInputStream(this.data);
}
/**
* Returns a read-only {@link ByteBuffer} representation of this {@link BinaryData}.
* <p>
* Attempting to mutate the returned {@link ByteBuffer} will throw a {@link ReadOnlyBufferException}.
*
* <p><strong>Get a read-only ByteBuffer from the BinaryData</strong></p>
*
* {@codesnippet com.azure.util.BinaryData.toByteBuffer}
*
* @return A read-only {@link ByteBuffer} representing the {@link BinaryData}.
*/
/* This will ensure lazy instantiation to avoid hard dependency on Json Serializer. */
private static JsonSerializer getDefaultSerializer() {
if (defaultJsonSerializer == null) {
synchronized (LOCK) {
if (defaultJsonSerializer == null) {
defaultJsonSerializer = JsonSerializerProviders.createInstance();
}
}
}
return defaultJsonSerializer;
}
} |
the local variable is still named `oboClients`, I suppose you also want to change this. | public ClientRegistrationRepository clientRegistrationRepository() {
final List<ClientRegistration> oboClients = createClients();
if (oboClients.isEmpty()) {
LOGGER.warn("No client registrations are found for AAD Client.");
return registrationId -> null;
}
return new InMemoryClientRegistrationRepository(oboClients);
} | final List<ClientRegistration> oboClients = createClients(); | public ClientRegistrationRepository clientRegistrationRepository() {
final List<ClientRegistration> clients = createClients();
if (clients.isEmpty()) {
LOGGER.warn("No client registrations are found for AAD Client.");
return registrationId -> null;
}
return new InMemoryClientRegistrationRepository(clients);
} | class }) | class }) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.